char-fork/llama.cpp

git clone https://git.t4t.associates/char-fork/llama.cpp

Xuan-Son Nguyenmodel, mtmd: fix gemma4 vision handling (#28335)163a40796

char/aliceai-t5-moe
91.5 KiB2815 linesraw
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#include <unordered_map>
16
17static bool ggml_is_power_of_2(int n) {
18    return (n & (n - 1)) == 0;
19}
20
21// orthonormal Walsh-Hadamard rotation matrix
22// note: res^2 == I
23static void ggml_gen_hadamard(ggml_tensor * tensor) {
24    assert(tensor->type == GGML_TYPE_F32);
25
26    const int n = tensor->ne[0];
27
28    assert(ggml_is_power_of_2(n));
29    assert(tensor->ne[1] == n);
30    assert(tensor->ne[2] == 1);
31    assert(tensor->ne[3] == 1);
32
33    std::vector<float> data_f32;
34
35    float * data = (float *) tensor->data;
36
37    if (tensor->type != GGML_TYPE_F32) {
38        data_f32.resize(n*n);
39        data = data_f32.data();
40    }
41
42    data[0*n + 0] = 1.0 / sqrtf(n);
43
44    for (int s = 1; s < n; s *= 2) {
45        for (int i = 0; i < s; i++) {
46            for (int j = 0; j < s; j++) {
47                const float val = data[i*n + j];
48
49                data[(i + s)*n + (j    )] =  val;
50                data[(i    )*n + (j + s)] =  val;
51                data[(i + s)*n + (j + s)] = -val;
52            }
53        }
54    }
55
56    if (tensor->type != GGML_TYPE_F32) {
57        ggml_quantize_chunk(tensor->type, data, tensor->data, 0, 1, n*n, nullptr);
58    }
59}
60
61//
62// llama_kv_cache
63//
64
65llama_kv_cache::llama_kv_cache(
66        const llama_model & model,
67        const llama_hparams & hparams,
68                ggml_type   type_k,
69                ggml_type   type_v,
70                     bool   v_trans,
71                     bool   offload,
72                     bool   unified,
73                 uint32_t   kv_size,
74                 uint32_t   n_seq_max,
75                 uint32_t   n_pad,
76                 uint32_t   n_swa,
77           llama_swa_type   swa_type,
78           llama_memory_t   mem_other,
79    const layer_filter_cb & filter,
80    const  layer_reuse_cb & reuse,
81    const  layer_share_cb & share,
82             const char *   name_tag) :
83    model(model), hparams(hparams), v_trans(v_trans),
84    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),
85    other(static_cast<llama_kv_cache *>(mem_other)),
86    v_cells_impl(other ? other->v_cells_impl : std::make_shared<llama_kv_cells_vec>()),
87    v_cells(*v_cells_impl) {
88
89    // shared cells view the source cache's K/V tensors, so the cell count
90    // follows the source allocation: a fitted target can be smaller than the
91    // draft default and oversized views would overflow the source tensors
92    if (other) {
93        const uint32_t size_other = other->get_size();
94        if (kv_size != size_other) {
95            LLAMA_LOG_WARN("%s: kv_size = %u overridden to %u to match the shared source cache\n", __func__, kv_size, size_other);
96            kv_size = size_other;
97        }
98    }
99
100    GGML_ASSERT(kv_size % n_pad == 0);
101
102    const uint32_t n_layer = hparams.n_layer_all;
103
104    // define a comparator for the buft -> ctx map to ensure that the order is well-defined:
105    struct ggml_backend_buft_comparator {
106        bool operator()(const ggml_backend_buffer_type_t & lhs, const ggml_backend_buffer_type_t & rhs) const {
107            return strcmp(ggml_backend_buft_name(lhs), ggml_backend_buft_name(rhs)) < 0;
108        }
109    };
110    std::map<ggml_backend_buffer_type_t, ggml_context_ptr, ggml_backend_buft_comparator> ctx_map;
111
112    // create a context for each buffer type
113    auto ctx_for_buft = [&](ggml_backend_buffer_type_t buft) -> ggml_context * {
114        auto it = ctx_map.find(buft);
115        if (it == ctx_map.end()) {
116            ggml_init_params params = {
117                /*.mem_size   =*/ size_t(2u*(1 + n_stream)*n_layer*ggml_tensor_overhead()),
118                /*.mem_buffer =*/ NULL,
119                /*.no_alloc   =*/ true,
120            };
121
122            ggml_context * ctx = ggml_init(params);
123            if (!ctx) {
124                return nullptr;
125            }
126
127            ctx_map.emplace(buft, ctx);
128
129            return ctx;
130        }
131
132        return it->second.get();
133    };
134
135    GGML_ASSERT(n_stream == 1 || n_stream == n_seq_max);
136
137    v_heads.resize(n_stream);
138    for (uint32_t s = 0; s < n_stream; ++s) {
139        v_heads[s] = 0;
140    }
141
142    v_cells.resize(n_stream);
143    for (uint32_t s = 0; s < n_stream; ++s) {
144        v_cells[s].resize(kv_size);
145    }
146
147    // by default, all sequence ids are mapped to the 0th stream
148    seq_to_stream.resize(LLAMA_MAX_SEQ, 0);
149
150    if (n_stream > 1) {
151        seq_to_stream.resize(n_stream, 0);
152        for (uint32_t s = 0; s < n_stream; ++s) {
153            seq_to_stream[s] = s;
154        }
155    }
156
157    // [TAG_V_CACHE_VARIABLE]
158    if (v_trans && hparams.is_n_embd_v_gqa_variable()) {
159        LLAMA_LOG_WARN("%s: the V embeddings have different sizes across layers and FA is not enabled - padding V cache to %d\n",
160                __func__, hparams.n_embd_v_gqa_max());
161    }
162
163    const bool is_mla = hparams.is_mla();
164
165    for (uint32_t il = 0; il < n_layer; il++) {
166        if (!hparams.has_kv(il)) {
167            LLAMA_LOG_DEBUG("%s: layer %3d: does not have KV cache\n", __func__, il);
168            continue;
169        }
170
171        if (filter && !filter(il)) {
172            LLAMA_LOG_DEBUG("%s: layer %3d: filtered\n", __func__, il);
173            continue;
174        }
175
176        if (share && other) {
177            const int32_t il_share = share(il);
178
179            if (il_share >= 0) {
180                const auto & layer_share = other->layers[other->map_layer_ids[il_share]];
181
182                LLAMA_LOG_WARN("%s: layer %3d: sharing with layer %d. k = %p, v = %p\n", __func__, il, il_share,
183                        layer_share.k->data, layer_share.v->data);
184
185                map_layer_ids[il] = layers.size();
186
187                layers.push_back(layer_share);
188                layers.back().il = il;
189
190                continue;
191            }
192        }
193
194        if (n_embd_head_k_all == 0) {
195            n_embd_head_k_all = (int32_t) hparams.n_embd_head_k(il);
196        } else if (n_embd_head_k_all > 0 && n_embd_head_k_all != (int32_t) hparams.n_embd_head_k(il)) {
197            n_embd_head_k_all = -1;
198        }
199
200        if (!is_mla) {
201            if (n_embd_head_v_all == 0) {
202                n_embd_head_v_all = (int32_t) hparams.n_embd_head_v(il);
203            } else if (n_embd_head_v_all > 0 && n_embd_head_v_all != (int32_t) hparams.n_embd_head_v(il)) {
204                n_embd_head_v_all = -1;
205            }
206        }
207
208        // [TAG_V_CACHE_VARIABLE]
209        const uint32_t n_embd_k_gqa =            hparams.n_embd_k_gqa(il);
210        const uint32_t n_embd_v_gqa = !v_trans ? hparams.n_embd_v_gqa(il) : hparams.n_embd_v_gqa_max();
211
212        const char * dev_name = "CPU";
213
214        ggml_backend_buffer_type_t buft = ggml_backend_cpu_buffer_type();
215
216        if (offload) {
217            auto * dev = model.dev_layer(il);
218            buft = ggml_backend_dev_buffer_type(dev);
219
220            dev_name = ggml_backend_dev_name(dev);
221        }
222
223        LLAMA_LOG_DEBUG("%s: layer %3d: dev = %s\n", __func__, il, dev_name);
224
225        ggml_context * ctx = ctx_for_buft(buft);
226        if (!ctx) {
227            throw std::runtime_error("failed to create ggml context for kv cache");
228        }
229
230        const bool has_k = true;
231        const bool has_v = !is_mla;
232
233        ggml_tensor * k = has_k ? ggml_new_tensor_3d(ctx, type_k, n_embd_k_gqa, kv_size, n_stream) : nullptr;
234        ggml_tensor * v = has_v ? ggml_new_tensor_3d(ctx, type_v, n_embd_v_gqa, kv_size, n_stream) : nullptr;
235
236        has_k && ggml_format_name(k, "cache_%sk_l%d", name_tag, il);
237        has_v && ggml_format_name(v, "cache_%sv_l%d", name_tag, il);
238
239        std::vector<ggml_tensor *> k_stream;
240        std::vector<ggml_tensor *> v_stream;
241
242        for (uint32_t s = 0; s < n_stream; ++s) {
243            k_stream.push_back(has_k ? ggml_view_2d(ctx, k, n_embd_k_gqa, kv_size, k->nb[1], s*k->nb[2]) : nullptr);
244            v_stream.push_back(has_v ? ggml_view_2d(ctx, v, n_embd_v_gqa, kv_size, v->nb[1], s*v->nb[2]) : nullptr);
245        }
246
247        map_layer_ids[il] = layers.size();
248
249        layers.push_back({ il, k, v, k_stream, v_stream, });
250    }
251
252    if (reuse) {
253        LLAMA_LOG_DEBUG("%s: reusing layers:\n", __func__);
254
255        for (uint32_t il = 0; il < n_layer; il++) {
256            const int32_t il_reuse = reuse(il);
257
258            if (il_reuse < 0) {
259                LLAMA_LOG_DEBUG("%s: - layer %3d: no reuse\n", __func__, il);
260                continue;
261            }
262
263            if (filter && !filter(il)) {
264                LLAMA_LOG_DEBUG("%s: - layer %3d: filtered\n", __func__, il);
265                continue;
266            }
267
268            GGML_ASSERT(map_layer_ids.find(il_reuse) != map_layer_ids.end());
269
270            map_layer_ids[il] = map_layer_ids[il_reuse];
271
272            LLAMA_LOG_DEBUG("%s: - layer %3d: reuse layer %d, is_swa = %d\n", __func__, il, il_reuse, hparams.is_swa(il));
273        }
274    }
275
276    // allocate tensors and initialize the buffers to avoid NaNs in the padding
277    for (auto & [buft, ctx] : ctx_map) {
278        ggml_backend_buffer_t buf;
279        if (hparams.no_alloc) {
280            buf = ggml_backend_buft_alloc_buffer(buft, /*size =*/ 0); // dummy buffer
281            for (ggml_tensor * t = ggml_get_first_tensor(ctx.get()); t != nullptr; t = ggml_get_next_tensor(ctx.get(), t)) {
282                t->buffer = buf; // set dummy buffer for KV cache so that the backend scheduler won't try to allocate it
283            }
284        } else {
285            buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx.get(), buft); // real buffer
286        }
287        if (!buf) {
288            throw std::runtime_error("failed to allocate buffer for kv cache");
289        }
290
291        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);
292
293        ggml_backend_buffer_clear(buf, 0);
294        ctxs_bufs.emplace_back(std::move(ctx), buf);
295    }
296
297    {
298        const size_t memory_size_k = size_k_bytes();
299        const size_t memory_size_v = size_v_bytes();
300
301        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__,
302                (float)(memory_size_k + memory_size_v) / (1024.0f * 1024.0f), kv_size, (int) layers.size(), n_seq_max, n_stream,
303                ggml_type_name(type_k), (float)memory_size_k / (1024.0f * 1024.0f),
304                ggml_type_name(type_v), (float)memory_size_v / (1024.0f * 1024.0f));
305    }
306
307    // TODO: refactor [TAG_KV_CACHE_SHARE_CELLS]
308    if (other) {
309        n_embd_head_k_all = other->n_embd_head_k_all;
310        n_embd_head_v_all = other->n_embd_head_v_all;
311
312        attn_rot_k = other->attn_rot_k;
313        attn_rot_v = other->attn_rot_v;
314    } else {
315        const char * LLAMA_ATTN_ROT_DISABLE = getenv("LLAMA_ATTN_ROT_DISABLE");
316        const bool attn_rot_disable = LLAMA_ATTN_ROT_DISABLE ? atoi(LLAMA_ATTN_ROT_DISABLE) : false;
317        if (attn_rot_disable) {
318            LLAMA_LOG_WARN("%s: attention rotation force disabled (LLAMA_ATTN_ROT_DISABLE)\n", __func__);
319        }
320
321        attn_rot_k =
322            !attn_rot_disable &&
323            n_embd_head_k_all > 0 &&
324            ggml_is_quantized(type_k) &&
325            hparams.n_embd_head_k() % 64 == 0;
326
327        // always create Hadamard rotation tensors for DeepSeek lightning indexers
328        if ((model.arch == LLM_ARCH_DEEPSEEK32 || model.arch == LLM_ARCH_DEEPSEEK4 ||
329                model.arch == LLM_ARCH_GLM_DSA || model.arch == LLM_ARCH_DOTS3NOTE) &&
330                hparams.n_embd_head_k_full == hparams.indexer_head_size) {
331            attn_rot_k = true;
332        }
333
334        attn_rot_v =
335            !attn_rot_disable &&
336            n_embd_head_v_all > 0 &&
337            ggml_is_quantized(type_v) &&
338            hparams.n_embd_head_v() % 64 == 0;
339    }
340
341    LLAMA_LOG_INFO("%s: attn_rot_k = %d, n_embd_head_k_all = %d\n", __func__, attn_rot_k, n_embd_head_k_all);
342    LLAMA_LOG_INFO("%s: attn_rot_v = %d, n_embd_head_k_all = %d\n", __func__, attn_rot_v, n_embd_head_v_all);
343
344    // pre-compute the haramard matrices and keep them in host memory
345    // TODO: in the future, we can make copies in the backend buffers to avoid host -> device transfers
346    if (attn_rot_k || attn_rot_v) {
347        for (int64_t n = 64; n <= std::max(n_embd_head_k_all, n_embd_head_v_all); n *= 2) {
348            attn_rot_hadamard[n] = std::vector<float>(n*n);
349
350            ggml_init_params params = {
351                /* .mem_size   = */ 1*ggml_tensor_overhead(),
352                /* .mem_buffer = */ nullptr,
353                /* .no_alloc   = */ true,
354            };
355
356            ggml_context_ptr ctx { ggml_init(params) };
357
358            ggml_tensor * tmp = ggml_new_tensor_2d(ctx.get(), GGML_TYPE_F32, n, n);
359            tmp->data = attn_rot_hadamard[n].data();
360
361            ggml_gen_hadamard(tmp);
362        }
363    }
364
365    const char * LLAMA_KV_CACHE_DEBUG = getenv("LLAMA_KV_CACHE_DEBUG");
366    debug = LLAMA_KV_CACHE_DEBUG ? atoi(LLAMA_KV_CACHE_DEBUG) : 0;
367}
368
369void llama_kv_cache::clear(bool data) {
370    for (uint32_t s = 0; s < n_stream; ++s) {
371        v_cells[s].reset();
372        v_heads[s] = 0;
373    }
374
375    if (data) {
376        for (auto & [_, buf] : ctxs_bufs) {
377            ggml_backend_buffer_clear(buf.get(), 0);
378        }
379    }
380}
381
382bool llama_kv_cache::seq_rm(llama_seq_id seq_id, llama_pos p0, llama_pos p1) {
383    // TODO: refactor [TAG_KV_CACHE_SHARE_CELLS]
384    if (other) {
385        return true;
386    }
387
388    // TODO: fix incosistent handling of `seq_id < 0` and `seq_id == -1` in the codebase [TAG_LLAMA_SEQ_ID_NEG]
389    GGML_ASSERT(seq_id == -1 || (seq_id >= 0 && (size_t) seq_id < seq_to_stream.size()));
390
391    if (p0 < 0) {
392        p0 = 0;
393    }
394
395    if (p1 < 0) {
396        p1 = std::numeric_limits<llama_pos>::max();
397    }
398
399    if (seq_id >= 0) {
400        auto & cells = v_cells[seq_to_stream[seq_id]];
401        auto & head  = v_heads[seq_to_stream[seq_id]];
402
403        uint32_t new_head = cells.size();
404
405        for (uint32_t i = 0; i < cells.size(); ++i) {
406            if (!cells.pos_in(i, p0, p1)) {
407                continue;
408            }
409
410            if (cells.seq_has(i, seq_id) && cells.seq_rm(i, seq_id)) {
411                if (new_head == cells.size()) {
412                    new_head = i;
413                }
414            }
415        }
416
417        // If we freed up a slot, set head to it so searching can start there.
418        if (new_head != cells.size() && new_head < head) {
419            head = new_head;
420        }
421    } else {
422        // match any sequence
423        for (uint32_t s = 0; s < n_stream; ++s) {
424            auto & cells = v_cells[s];
425            auto & head  = v_heads[s];
426
427            uint32_t new_head = cells.size();
428
429            for (uint32_t i = 0; i < cells.size(); ++i) {
430                if (!cells.pos_in(i, p0, p1)) {
431                    continue;
432                }
433
434                cells.rm(i);
435
436                if (new_head == cells.size()) {
437                    new_head = i;
438                }
439            }
440
441            // If we freed up a slot, set head to it so searching can start there.
442            if (new_head != cells.size() && new_head < head) {
443                head = new_head;
444            }
445        }
446    }
447
448    return true;
449}
450
451void llama_kv_cache::seq_cp(llama_seq_id seq_id_src, llama_seq_id seq_id_dst, llama_pos p0, llama_pos p1) {
452    // TODO: refactor [TAG_KV_CACHE_SHARE_CELLS]
453    if (other) {
454        return;
455    }
456
457    GGML_ASSERT(seq_id_src >= 0 && (size_t) seq_id_src < seq_to_stream.size());
458    GGML_ASSERT(seq_id_dst >= 0 && (size_t) seq_id_dst < seq_to_stream.size());
459
460    const auto s0 = seq_to_stream[seq_id_src];
461    const auto s1 = seq_to_stream[seq_id_dst];
462
463    if (s0 == s1) {
464        // since both sequences are in the same stream, no data copy is necessary
465        // we just have to update the cells meta data
466
467        auto & cells = v_cells[s0];
468
469        if (seq_id_src == seq_id_dst) {
470            return;
471        }
472
473        if (p0 < 0) {
474            p0 = 0;
475        }
476
477        if (p1 < 0) {
478            p1 = std::numeric_limits<llama_pos>::max();
479        }
480
481        for (uint32_t i = 0; i < cells.size(); ++i) {
482            if (!cells.pos_in(i, p0, p1)) {
483                continue;
484            }
485
486            if (cells.seq_has(i, seq_id_src)) {
487                cells.seq_add(i, seq_id_dst);
488            }
489        }
490
491        return;
492    }
493
494    // cross-stream sequence copies require to copy the actual buffer data
495
496    bool is_full = true;
497
498    if (p0 > 0 && p0 + 1 < (int) get_size()) {
499        is_full = false;
500    }
501
502    if (p1 > 0 && p1 + 1 < (int) get_size()) {
503        is_full = false;
504    }
505
506    GGML_ASSERT(is_full && "seq_cp() is only supported for full KV buffers");
507
508    // enqueue the copy operation - the buffer copy will be performed during the next update
509    sc_info.ssrc.push_back(s0);
510    sc_info.sdst.push_back(s1);
511
512    v_cells[s1].reset();
513    for (uint32_t i = 0; i < v_cells[s0].size(); ++i) {
514        if (v_cells[s0].seq_has(i, seq_id_src)) {
515            llama_pos pos   = v_cells[s0].pos_get(i);
516            llama_pos shift = v_cells[s0].get_shift(i);
517
518            llama_kv_cell_ext ext = v_cells[s0].ext_get(i);
519
520            if (shift != 0) {
521                pos -= shift;
522                assert(pos >= 0);
523            }
524
525            v_cells[s1].pos_set(i, pos);
526            v_cells[s1].seq_add(i, seq_id_dst);
527
528            if (shift != 0) {
529                v_cells[s1].pos_add(i, shift);
530            }
531
532            v_cells[s1].ext_set(i, ext);
533        }
534    }
535
536    v_heads[s1] = v_heads[s0];
537
538    //for (uint32_t s = 0; s < n_stream; ++s) {
539    //    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));
540    //}
541}
542
543void llama_kv_cache::seq_keep(llama_seq_id seq_id) {
544    // TODO: refactor [TAG_KV_CACHE_SHARE_CELLS]
545    if (other) {
546        return;
547    }
548
549    GGML_ASSERT(seq_id >= 0 && (size_t) seq_id < seq_to_stream.size());
550
551    auto & cells = v_cells[seq_to_stream[seq_id]];
552    auto & head  = v_heads[seq_to_stream[seq_id]];
553
554    uint32_t new_head = cells.size();
555
556    for (uint32_t i = 0; i < cells.size(); ++i) {
557        if (cells.seq_keep(i, seq_id)) {
558            if (new_head == cells.size()) {
559                new_head = i;
560            }
561        }
562    }
563
564    // If we freed up a slot, set head to it so searching can start there.
565    if (new_head != cells.size() && new_head < head) {
566        head = new_head;
567    }
568}
569
570void llama_kv_cache::seq_add(llama_seq_id seq_id, llama_pos p0, llama_pos p1, llama_pos shift) {
571    // TODO: refactor [TAG_KV_CACHE_SHARE_CELLS]
572    if (other) {
573        return;
574    }
575
576    GGML_ASSERT(seq_id >= 0 && (size_t) seq_id < seq_to_stream.size());
577    GGML_ASSERT(hparams.n_pos_per_embd() == 1 && "seq_add() is only supported for n_pos_per_embd() == 1");
578
579    auto & cells = v_cells[seq_to_stream[seq_id]];
580    auto & head  = v_heads[seq_to_stream[seq_id]];
581
582    if (shift == 0) {
583        return;
584    }
585
586    uint32_t new_head = cells.size();
587
588    if (p0 < 0) {
589        p0 = 0;
590    }
591
592    if (p1 < 0) {
593        p1 = std::numeric_limits<llama_pos>::max();
594    }
595
596    // If there is no range then return early to avoid looping over all cells.
597    if (p0 == p1) {
598        return;
599    }
600
601    for (uint32_t i = 0; i < cells.size(); ++i) {
602        if (!cells.pos_in(i, p0, p1)) {
603            continue;
604        }
605
606        if (cells.seq_has(i, seq_id)) {
607            if (cells.pos_add(i, shift)) {
608                if (new_head == cells.size()) {
609                    new_head = i;
610                }
611            }
612        }
613    }
614
615    // If we freed up a slot, set head to it so searching can start there.
616    // Otherwise we just start the next search from the beginning.
617    head = new_head != cells.size() ? new_head : 0;
618}
619
620void llama_kv_cache::seq_div(llama_seq_id seq_id, llama_pos p0, llama_pos p1, int d) {
621    // TODO: refactor [TAG_KV_CACHE_SHARE_CELLS]
622    if (other) {
623        return;
624    }
625
626    GGML_ASSERT(seq_id >= 0 && (size_t) seq_id < seq_to_stream.size());
627    GGML_ASSERT(hparams.n_pos_per_embd() == 1 && "seq_div() is only supported for n_pos_per_embd() == 1");
628
629    auto & cells = v_cells[seq_to_stream[seq_id]];
630
631    if (d == 1) {
632        return;
633    }
634
635    if (p0 < 0) {
636        p0 = 0;
637    }
638
639    if (p1 < 0) {
640        p1 = std::numeric_limits<llama_pos>::max();
641    }
642
643    // If there is no range then return early to avoid looping over the cache.
644    if (p0 == p1) {
645        return;
646    }
647
648    for (uint32_t i = 0; i < cells.size(); ++i) {
649        if (!cells.pos_in(i, p0, p1)) {
650            continue;
651        }
652
653        if (cells.seq_has(i, seq_id)) {
654            cells.pos_div(i, d);
655        }
656    }
657}
658
659llama_pos llama_kv_cache::seq_pos_min(llama_seq_id seq_id) const {
660    // TODO: refactor [TAG_KV_CACHE_SHARE_CELLS]
661    if (other) {
662        return other->seq_pos_min(seq_id);
663    }
664
665    GGML_ASSERT(seq_id >= 0 && (size_t) seq_id < seq_to_stream.size());
666
667    const auto & cells = v_cells[seq_to_stream[seq_id]];
668
669    return cells.seq_pos_min(seq_id);
670}
671
672llama_pos llama_kv_cache::seq_pos_max(llama_seq_id seq_id) const {
673    // TODO: refactor [TAG_KV_CACHE_SHARE_CELLS]
674    if (other) {
675        return other->seq_pos_max(seq_id);
676    }
677
678    GGML_ASSERT(seq_id >= 0 && (size_t) seq_id < seq_to_stream.size());
679
680    const auto & cells = v_cells[seq_to_stream[seq_id]];
681
682    return cells.seq_pos_max(seq_id);
683}
684
685std::map<ggml_backend_buffer_type_t, size_t> llama_kv_cache::memory_breakdown() const {
686    std::map<ggml_backend_buffer_type_t, size_t> ret;
687    for (const auto & [ctx, buf] : ctxs_bufs) {
688        ggml_backend_buffer_type_t buft = ggml_backend_buffer_get_type(buf.get());
689
690        if (hparams.no_alloc) {
691            GGML_ASSERT(ggml_backend_buffer_get_base(buf.get()) == nullptr);
692            ret[buft] += ggml_backend_alloc_ctx_tensors_from_buft_size(ctx.get(), buft);
693        } else {
694            // GGML_ASSERT(ggml_backend_buffer_get_base(buf.get()) != nullptr); // multi_buffer does not have a defined base
695            ret[buft] += ggml_backend_buffer_get_size(buf.get());
696        }
697    }
698
699    return ret;
700}
701
702llama_memory_context_ptr llama_kv_cache::init_batch(
703            llama_batch_allocr & balloc,
704            uint32_t n_ubatch,
705            bool embd_all) {
706    GGML_UNUSED(embd_all);
707
708    do {
709        balloc.split_reset();
710
711        std::vector<llama_ubatch> ubatches;
712        while (true) {
713            auto ubatch = n_stream == 1 ? balloc.split_simple(n_ubatch) : balloc.split_equal(n_ubatch, true, 0);
714
715            if (ubatch.n_tokens == 0) {
716                break;
717            }
718
719            ubatches.push_back(std::move(ubatch)); // NOLINT
720        }
721
722        if (balloc.get_n_used() < balloc.get_n_tokens()) {
723            // failed to find a suitable split
724            break;
725        }
726
727        auto sinfos = prepare(ubatches);
728        if (sinfos.empty()) {
729            break;
730        }
731
732        return std::make_unique<llama_kv_cache_context>(
733                this, std::move(sinfos), std::move(ubatches));
734    } while (false);
735
736    return std::make_unique<llama_kv_cache_context>(LLAMA_MEMORY_STATUS_FAILED_PREPARE);
737}
738
739llama_memory_context_ptr llama_kv_cache::init_full() {
740    return std::make_unique<llama_kv_cache_context>(this);
741}
742
743llama_memory_context_ptr llama_kv_cache::init_update(llama_context * lctx, bool optimize) {
744    GGML_UNUSED(optimize);
745
746    bool do_shift = get_has_shift();
747
748    return std::make_unique<llama_kv_cache_context>(this, lctx, do_shift, std::move(sc_info));
749}
750
751llama_kv_cache::slot_info_vec_t llama_kv_cache::prepare(const std::vector<llama_ubatch> & ubatches) {
752    llama_kv_cache::slot_info_vec_t res;
753
754    struct state_t {
755        slot_info sinfo; // slot info for the ubatch
756
757        std::vector<uint32_t> v_heads_old; // old positions of the heads, before placing the ubatch
758
759        std::vector<llama_kv_cells> v_cells; // copy of the old cells, before placing the ubatch
760    };
761
762    // remember the old state of the cells so we can restore it in the end
763    std::vector<state_t> states;
764
765    bool success = true;
766
767    for (const auto & ubatch : ubatches) {
768        // only find a suitable slot for the ubatch. don't modify the cells yet
769        const auto sinfo_new = find_slot(ubatch, false);
770        if (sinfo_new.empty()) {
771            success = false;
772            break;
773        }
774
775        // remember the position that we found
776        res.push_back(sinfo_new);
777
778        // store the old state of the cells in the recovery stack
779        {
780            state_t state = { sinfo_new, v_heads, {} };
781
782            for (uint32_t s = 0; s < sinfo_new.n_stream(); ++s) {
783                auto & cells = v_cells[sinfo_new.strm[s]];
784
785                state.v_cells.push_back(cells.cp(sinfo_new.idxs[s]));
786            }
787
788            states.push_back(std::move(state));
789        }
790
791        // now emplace the ubatch
792        apply_ubatch(sinfo_new, ubatch);
793    }
794
795    GGML_ASSERT(!states.empty() || !success);
796
797    // iterate backwards and restore the cells to their original state
798    for (auto it = states.rbegin(); it != states.rend(); ++it) {
799        const auto & sinfo = it->sinfo;
800
801        for (uint32_t s = 0; s < sinfo.n_stream(); ++s) {
802            auto & cells = v_cells[sinfo.strm[s]];
803            auto & head  = v_heads[sinfo.strm[s]];
804
805            cells.set(sinfo.idxs[s], it->v_cells[s]);
806            head = it->v_heads_old[s];
807        }
808    }
809
810    if (!success) {
811        return {};
812    }
813
814    return res;
815}
816
817bool llama_kv_cache::update(llama_context * lctx, bool do_shift, const stream_copy_info & sc_info) {
818    // TODO: refactor [TAG_KV_CACHE_SHARE_CELLS]
819    if (other) {
820        return true;
821    }
822
823    bool updated = false;
824
825    auto * sched = lctx->get_sched();
826
827    if (!sc_info.empty()) {
828        assert(n_stream > 1 && "stream copy should never happen with a single stream");
829
830        llama_synchronize(lctx);
831
832        const size_t n_copy = sc_info.ssrc.size();
833
834        for (size_t i = 0; i < n_copy; ++i) {
835            const auto ssrc = sc_info.ssrc[i];
836            const auto sdst = sc_info.sdst[i];
837
838            assert(ssrc < n_stream);
839            assert(sdst < n_stream);
840
841            LLAMA_LOG_DEBUG("%s: copying KV buffer: stream %d to stream %d\n", __func__, ssrc, sdst);
842
843            assert(ssrc != sdst);
844
845            for (uint32_t il = 0; il < layers.size(); ++il) {
846                const auto & layer = layers[il];
847
848                ggml_backend_tensor_copy(layer.k_stream[ssrc], layer.k_stream[sdst]);
849
850                if (layer.v_stream[ssrc]) {
851                    ggml_backend_tensor_copy(layer.v_stream[ssrc], layer.v_stream[sdst]);
852                }
853            }
854        }
855    }
856
857    if (do_shift) {
858        if (!get_can_shift()) {
859            GGML_ABORT("The current KV cache / model configuration does not support K-shift");
860        }
861
862        LLAMA_LOG_DEBUG("%s: applying K-shift\n", __func__);
863
864        // apply K-shift if needed
865        if (hparams.rope_type != LLAMA_ROPE_TYPE_NONE) {
866            ggml_backend_sched_reset(sched);
867
868            auto * res = lctx->get_gf_res_reserve();
869
870            res->reset();
871
872            auto * gf = build_graph_shift(res, lctx);
873            if (!ggml_backend_sched_alloc_graph(sched, gf)) {
874                LLAMA_LOG_ERROR("%s: failed to allocate compute graph for K-shift\n", __func__);
875                return updated;
876            }
877
878            res->set_inputs(nullptr);
879
880            if (lctx->graph_compute(gf, false) != GGML_STATUS_SUCCESS) {
881                LLAMA_LOG_ERROR("%s: failed to compute K-shift\n", __func__);
882                return updated;
883            }
884
885            updated = true;
886        }
887
888        for (uint32_t s = 0; s < n_stream; ++s) {
889            auto & cells = v_cells[s];
890
891            cells.reset_shift();
892        }
893    }
894
895    return updated;
896}
897
898llama_kv_cache::slot_info llama_kv_cache::find_slot(const llama_ubatch & ubatch, bool cont) const {
899
900    if (debug > 0) {
901        for (uint32_t s = 0; s < ubatch.n_seqs_unq; ++s) {
902            const auto seq_id = ubatch.seq_id_unq[s];
903            const auto stream_id = seq_to_stream[seq_id];
904            const auto & cells = v_cells[stream_id];
905            const uint32_t head_cur = v_heads[stream_id];
906
907            LLAMA_LOG_DEBUG("%s: stream[%d], n = %5d, used = %5d, head = %5d, size = %5d, n_swa = %5d\n",
908                    __func__, stream_id, cells.used_max_p1(), cells.get_used(), head_cur, get_size(), n_swa);
909
910            if ((debug == 2 && n_swa > 0) || debug > 2) {
911                std::string ss;
912                for (uint32_t i = 0; i < cells.size(); ++i) {
913                    if (cells.is_empty(i)) {
914                        ss += '.';
915                    } else {
916                        assert(cells.seq_count(i) >= 1);
917
918                        if (cells.seq_count(i) == 1) {
919                            ss += std::to_string(cells.seq_get(i));
920                        } else {
921                            ss += 'M';
922                        }
923                    }
924                    if (i%256 == 255) {
925                        ss += " *";
926                        ss += '\n';
927                    }
928                }
929                LLAMA_LOG_DEBUG("\n%s\n", ss.c_str());
930            }
931
932            if ((debug == 2 && n_swa > 0) || debug > 2) {
933                std::string ss;
934                for (uint32_t i = 0; i < cells.size(); ++i) {
935                    std::string cur;
936                    if (cells.is_empty(i)) {
937                        cur = '.';
938                    } else {
939                        cur = std::to_string(cells.pos_get(i));
940                    }
941                    const int n = cur.size();
942                    for (int j = 0; j < 5 - n; ++j) {
943                        cur += ' ';
944                    }
945                    ss += cur;
946                    if (i%256 == 255) {
947                        ss += " *";
948                    }
949                    if (i%64 == 63) {
950                        ss += '\n';
951                    }
952                }
953                LLAMA_LOG_DEBUG("\n%s\n", ss.c_str());
954            }
955
956            for (int s = 0; s < LLAMA_MAX_SEQ; ++s) {
957                if (cells.seq_pos_min(s) < 0) {
958                    continue;
959                }
960
961                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));
962            }
963        }
964    }
965
966    uint32_t n_tokens = ubatch.n_tokens;
967    uint32_t n_seqs   = 1;
968
969    if (n_stream > 1) {
970        GGML_ASSERT(n_tokens % ubatch.n_seqs_unq == 0);
971
972        n_seqs   = ubatch.n_seqs_unq;
973        n_tokens = n_tokens / n_seqs;
974    }
975
976    slot_info res = {
977        /*.s0   =*/ LLAMA_MAX_SEQ,
978        /*.s1   =*/ 0,
979        /*.strm =*/ { },
980        /*.idxs =*/ { },
981    };
982
983    res.resize(n_seqs);
984
985    for (uint32_t s = 0; s < n_seqs; ++s) {
986        const auto seq_id = ubatch.seq_id_unq[s];
987
988        if (n_stream > 1) {
989            GGML_ASSERT(ubatch.n_seq_id[s*n_tokens]    == 1);
990            GGML_ASSERT(ubatch.seq_id  [s*n_tokens][0] == seq_id);
991        }
992
993        res.s0 = std::min<uint32_t>(res.s0, seq_to_stream[seq_id]);
994        res.s1 = std::max<uint32_t>(res.s1, seq_to_stream[seq_id]);
995
996        res.strm[s] = seq_to_stream[seq_id];
997        res.idxs[s].reserve(n_tokens);
998
999        const auto & cells = v_cells[seq_to_stream[seq_id]];
1000
1001        uint32_t head_cur = v_heads[seq_to_stream[seq_id]];
1002
1003        // if we have enough unused cells before the current head ->
1004        //   better to start searching from the beginning of the cache, hoping to fill it
1005        if (head_cur > cells.get_used() + 2*n_tokens) {
1006            head_cur = 0;
1007        }
1008
1009        if (n_tokens > cells.size()) {
1010            LLAMA_LOG_ERROR("%s: n_tokens = %d > size = %u\n", __func__, n_tokens, cells.size());
1011            return { };
1012        }
1013
1014        uint32_t n_tested = 0;
1015
1016        // for continuous slots, we test that all tokens in the ubatch fit, starting from the current head
1017        // for non-continuous slots, we test the tokens one by one
1018        const uint32_t n_test = cont ? n_tokens : 1;
1019
1020        while (true) {
1021            if (head_cur + n_test > cells.size()) {
1022                n_tested += cells.size() - head_cur;
1023                head_cur = 0;
1024                continue;
1025            }
1026
1027            for (uint32_t i = 0; i < n_test; i++) {
1028                const auto idx = head_cur;
1029
1030                head_cur++;
1031                n_tested++;
1032
1033                //const llama_pos    pos    = ubatch.pos[i];
1034                //const llama_seq_id seq_id = ubatch.seq_id[i][0];
1035
1036                // can we use this cell? either:
1037                //  - the cell is empty
1038                //  - the cell is occupied only by one sequence:
1039                //    - (disabled) mask causally, if the sequence is the same as the one we are inserting
1040                //    - mask SWA, using current max pos for that sequence in the cache
1041                //                always insert in the cell with minimum pos
1042                bool can_use = cells.is_empty(idx);
1043
1044                if (!can_use && cells.seq_count(idx) == 1) {
1045                    const llama_pos pos_cell = cells.pos_get(idx);
1046
1047                    // (disabled) causal mask
1048                    // note: it's better to purge any "future" tokens beforehand
1049                    //if (cells.seq_has(idx, seq_id)) {
1050                    //    can_use = pos_cell >= pos;
1051                    //}
1052
1053                    if (!can_use) {
1054                        const llama_seq_id seq_id_cell = cells.seq_get(idx);
1055
1056                        // SWA mask
1057                        if (llama_hparams::is_masked_swa(n_swa, swa_type, pos_cell, cells.seq_pos_max(seq_id_cell) + 1)) {
1058                            can_use = true;
1059                        }
1060                    }
1061                }
1062
1063                if (can_use) {
1064                    res.idxs[s].push_back(idx);
1065                } else {
1066                    if (cont) {
1067                        break;
1068                    }
1069                }
1070            }
1071
1072            if (res.idxs[s].size() == n_tokens) {
1073                break;
1074            }
1075
1076            if (cont) {
1077                res.idxs[s].clear();
1078            }
1079
1080            if (n_tested >= cells.size()) {
1081                //LLAMA_LOG_ERROR("%s: failed to find a slot for %d tokens\n", __func__, n_tokens);
1082                return { };
1083            }
1084        }
1085
1086        // we didn't find a suitable slot - return empty result
1087        if (res.idxs[s].size() < n_tokens) {
1088            return { };
1089        }
1090    }
1091
1092    assert(res.s1 >= res.s0);
1093
1094    return res;
1095}
1096
1097void llama_kv_cache::apply_ubatch(const slot_info & sinfo, const llama_ubatch & ubatch) {
1098    // TODO: refactor [TAG_KV_CACHE_SHARE_CELLS]
1099    if (other) {
1100        return;
1101    }
1102
1103    // keep track of the max sequence position that we would overwrite with this ubatch
1104    // for non-SWA cache, this would be always empty
1105    llama_seq_id seq_pos_max_rm[LLAMA_MAX_SEQ];
1106    for (uint32_t s = 0; s < LLAMA_MAX_SEQ; ++s) {
1107        seq_pos_max_rm[s] = -1;
1108    }
1109
1110    assert(ubatch.n_tokens == sinfo.n_stream()*sinfo.size());
1111
1112    for (uint32_t s = 0; s < sinfo.n_stream(); ++s) {
1113        for (uint32_t ii = 0; ii < sinfo.size(); ++ii) {
1114            const uint32_t i = s*sinfo.size() + ii;
1115
1116            auto & cells = v_cells[sinfo.strm[s]];
1117
1118            const auto idx = sinfo.idxs[s][ii];
1119
1120            if (!cells.is_empty(idx)) {
1121                assert(cells.seq_count(idx) == 1);
1122
1123                const llama_seq_id seq_id = cells.seq_get(idx);
1124                const llama_pos    pos    = cells.pos_get(idx);
1125
1126                seq_pos_max_rm[seq_id] = std::max(seq_pos_max_rm[seq_id], pos);
1127
1128                cells.rm(idx);
1129            }
1130
1131            cells.pos_set(idx, ubatch.pos[i]);
1132
1133            if (ubatch.is_pos_2d() || ubatch.token || hparams.ple_n_heads > 0) {
1134                llama_kv_cell_ext ext;
1135
1136                if (ubatch.is_pos_2d()) {
1137                    ext.x = ubatch.pos[i + ubatch.n_tokens*2];
1138                    ext.y = ubatch.pos[i + ubatch.n_tokens];
1139                }
1140
1141                if (ubatch.token) {
1142                    ext.tok = ubatch.token[i];
1143                } else if (hparams.ple_n_heads > 0) {
1144                    // embd batch (multimodal input) has no token ids, need to pad it with the correct ID for PLE layers
1145                    // TODO @ngxson : check if we can do the same as gemma 3n / gemma 4
1146                    ext.tok = hparams.ple_image_token_id != 0
1147                        ? (llama_token) hparams.ple_image_token_id
1148                        : (llama_token) hparams.ple_eos_token_id;
1149                }
1150
1151                cells.ext_set(idx, ext);
1152            }
1153
1154            for (int32_t s = 0; s < ubatch.n_seq_id[i]; s++) {
1155                cells.seq_add(idx, ubatch.seq_id[i][s]);
1156            }
1157        }
1158    }
1159
1160    // note: we want to preserve the invariant that all positions between [pos_min, pos_max] for each sequence
1161    //       will be present in the cache. so we have to purge any position which is less than those we would overwrite
1162    //       ref: https://github.com/ggml-org/llama.cpp/pull/13746#issuecomment-2916057092
1163    for (uint32_t s = 0; s < LLAMA_MAX_SEQ; ++s) {
1164        if (seq_pos_max_rm[s] == -1) {
1165            continue;
1166        }
1167
1168        GGML_ASSERT(s < seq_to_stream.size());
1169
1170        auto & cells = v_cells[seq_to_stream[s]];
1171
1172        if (cells.seq_pos_min(s) <= seq_pos_max_rm[s]) {
1173            LLAMA_LOG_DEBUG("%s: purging positions [%d, %d] of sequence %d from KV cache\n",
1174                    __func__, cells.seq_pos_min(s), seq_pos_max_rm[s], s);
1175
1176            seq_rm(s, cells.seq_pos_min(s), seq_pos_max_rm[s] + 1);
1177        }
1178    }
1179
1180    // move the head at the end of the slot
1181    for (uint32_t s = 0; s < sinfo.n_stream(); ++s) {
1182        auto & head = v_heads[sinfo.strm[s]];
1183
1184        head = sinfo.idxs[s].back() + 1;
1185    }
1186}
1187
1188bool llama_kv_cache::get_can_shift() const {
1189    // Step35 uses per-layer RoPE dims; K-shift assumes a single global n_rot.
1190    if (model.arch == LLM_ARCH_STEP35) {
1191        return false;
1192    }
1193    if (hparams.n_pos_per_embd() > 1) {
1194        return false;
1195    }
1196    return true;
1197}
1198
1199uint32_t llama_kv_cache::get_size() const {
1200    const auto & cells = v_cells[seq_to_stream[0]];
1201
1202    return cells.size();
1203}
1204
1205uint32_t llama_kv_cache::get_n_stream() const {
1206    return n_stream;
1207}
1208
1209bool llama_kv_cache::get_has_shift() const {
1210    bool result = false;
1211
1212    for (uint32_t s = 0; s < n_stream; ++s) {
1213        result |= v_cells[s].get_has_shift();
1214    }
1215
1216    return result;
1217}
1218
1219ggml_type llama_kv_cache::type_k() const {
1220    return layers[0].k->type;
1221}
1222
1223ggml_type llama_kv_cache::type_v() const {
1224    return layers[0].v->type;
1225}
1226
1227std::vector<uint32_t> llama_kv_cache::get_layer_ids() const {
1228    std::vector<uint32_t> res;
1229    res.reserve(layers.size());
1230
1231    for (const auto & layer : layers) {
1232        res.push_back(layer.il);
1233    }
1234
1235    return res;
1236}
1237
1238ggml_tensor * llama_kv_cache::get_k_storage(int32_t il) const {
1239    const int32_t ikv = map_layer_ids.at(il);
1240
1241    return layers[ikv].k;
1242}
1243
1244const llama_kv_cells & llama_kv_cache::get_cells(llama_seq_id seq_id) const {
1245    GGML_ASSERT(seq_id >= 0 && (size_t) seq_id < seq_to_stream.size());
1246
1247    return v_cells[seq_to_stream[seq_id]];
1248}
1249
1250uint32_t llama_kv_cache::get_n_kv(const slot_info & sinfo) const {
1251    uint32_t result = 0;
1252
1253    // pad the n_kv value so that the graph remains constant across batches and can be reused
1254    // note: this also helps some backends with performance (f.ex https://github.com/ggml-org/llama.cpp/pull/16812#issuecomment-3455112220)
1255    const uint32_t n_pad_cur = std::max(n_pad, 256u);
1256
1257    for (uint32_t s = 0; s < sinfo.n_stream(); ++s) {
1258        const auto & cells = v_cells[sinfo.strm[s]];
1259
1260        result = std::max(std::min(cells.size(), std::max(n_pad_cur, GGML_PAD(cells.used_max_p1(), n_pad_cur))), result);
1261    }
1262
1263    return result;
1264}
1265
1266ggml_tensor * llama_kv_cache::get_k(ggml_context * ctx, int32_t il, uint32_t n_kv, const slot_info & sinfo) const {
1267    const int32_t ikv = map_layer_ids.at(il);
1268
1269    auto * k = layers[ikv].k;
1270
1271    const uint64_t kv_size      = get_size();
1272    const uint64_t n_embd_k_gqa = k->ne[0];
1273
1274    assert(n_embd_k_gqa == hparams.n_embd_k_gqa(il));
1275
1276    const uint32_t ns = sinfo.s1 - sinfo.s0 + 1;
1277
1278    return ggml_view_4d(ctx, k,
1279            hparams.n_embd_head_k(il), hparams.n_head_kv(il), n_kv, ns,
1280            ggml_row_size(k->type, hparams.n_embd_head_k(il)),
1281            ggml_row_size(k->type, n_embd_k_gqa),
1282            ggml_row_size(k->type, n_embd_k_gqa*kv_size),
1283            ggml_row_size(k->type, n_embd_k_gqa*kv_size)*sinfo.s0);
1284}
1285
1286ggml_tensor * llama_kv_cache::get_v(ggml_context * ctx, int32_t il, uint32_t n_kv, const slot_info & sinfo) const {
1287    const int32_t ikv = map_layer_ids.at(il);
1288
1289    auto * v = layers[ikv].v;
1290
1291    const uint64_t kv_size      = get_size();
1292    const uint64_t n_embd_v_gqa = v->ne[0];
1293
1294    // [TAG_V_CACHE_VARIABLE]
1295    assert(n_embd_v_gqa >= hparams.n_embd_v_gqa(il));
1296
1297    const uint32_t ns = sinfo.s1 - sinfo.s0 + 1;
1298
1299    if (!v_trans) {
1300        // note: v->nb[1] <= v->nb[2]
1301        return ggml_view_4d(ctx, v,
1302                hparams.n_embd_head_v(il), hparams.n_head_kv(il), n_kv, ns,
1303                ggml_row_size(v->type, hparams.n_embd_head_v(il)),          // v->nb[1]
1304                ggml_row_size(v->type, n_embd_v_gqa),                   // v->nb[2]
1305                ggml_row_size(v->type, n_embd_v_gqa*kv_size),           // v->nb[3]
1306                ggml_row_size(v->type, n_embd_v_gqa*kv_size)*sinfo.s0);
1307    }
1308
1309    // note: v->nb[1] > v->nb[2]
1310    return ggml_view_4d(ctx, v,
1311            n_kv, hparams.n_head_kv(il), hparams.n_embd_head_v(il), ns,
1312            ggml_row_size(v->type, kv_size*hparams.n_embd_head_v(il)),  // v->nb[1]
1313            ggml_row_size(v->type, kv_size),                        // v->nb[2]
1314            ggml_row_size(v->type, kv_size*n_embd_v_gqa),           // v->nb[3]
1315            ggml_row_size(v->type, kv_size*n_embd_v_gqa)*sinfo.s0);
1316}
1317
1318ggml_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 {
1319    GGML_UNUSED(sinfo);
1320
1321    const int32_t ikv = map_layer_ids.at(il);
1322
1323    ggml_tensor * k = layers[ikv].k;
1324
1325    const int64_t n_embd_head = k_cur->ne[0];
1326    const int64_t n_head      = k_cur->ne[1];
1327    const int64_t n_tokens    = k_cur->ne[2];
1328
1329    const int64_t n_embd_gqa = n_embd_head*n_head;
1330
1331    // we can merge dims 0 and 1
1332    // TODO: add ggml helper function for this?
1333    GGML_ASSERT(ggml_row_size(k_cur->type, n_embd_head) == k_cur->nb[1]);
1334
1335    k_cur = ggml_view_2d(ctx, k_cur, n_embd_gqa, n_tokens, k_cur->nb[2], 0);
1336
1337    const int64_t n_stream = k->ne[2];
1338
1339    if (n_stream > 1) {
1340        const int64_t kv_size = get_size();
1341
1342        assert(n_embd_gqa == k->ne[0]);
1343        assert(kv_size    == k->ne[1]);
1344
1345        // merge the buffer across all streams because the idxs are global
1346        k = ggml_reshape_2d(ctx, k, n_embd_gqa, kv_size*n_stream);
1347    }
1348
1349    // store the current K values into the cache
1350    return ggml_set_rows(ctx, k, k_cur, k_idxs);
1351}
1352
1353ggml_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 {
1354    GGML_UNUSED(sinfo);
1355
1356    const int32_t ikv = map_layer_ids.at(il);
1357
1358    auto * v = layers[ikv].v;
1359
1360    const int64_t n_embd_head = v_cur->ne[0];
1361    const int64_t n_head      = v_cur->ne[1];
1362    const int64_t n_tokens    = v_cur->ne[2];
1363
1364    const int64_t n_embd_gqa = n_embd_head*n_head;
1365
1366    // we can merge dims 0 and 1
1367    GGML_ASSERT(ggml_row_size(v_cur->type, n_embd_head) == v_cur->nb[1]);
1368
1369    const int64_t n_stream = v->ne[2];
1370
1371    // take this branch when FA is enabled (the V cache is not transposed)
1372    if (!v_trans) {
1373        v_cur = ggml_view_2d(ctx, v_cur, n_embd_gqa, n_tokens, v_cur->nb[2], 0);
1374
1375        if (n_stream > 1) {
1376            const int64_t kv_size = get_size();
1377
1378            assert(n_embd_gqa == v->ne[0]);
1379            assert(kv_size    == v->ne[1]);
1380
1381            // merge the buffer across all streams because the idxs are global
1382            v = ggml_reshape_2d(ctx, v, n_embd_gqa, kv_size*n_stream);
1383        }
1384
1385        return ggml_set_rows(ctx, v, v_cur, v_idxs);
1386    }
1387
1388    if (ggml_row_size(v_cur->type, n_embd_gqa) == v_cur->nb[2]) {
1389        // we can merge dims 0, 1 and 2
1390        v_cur = ggml_reshape_2d(ctx, v_cur, n_embd_gqa, n_tokens);
1391    } else {
1392        // otherwise -> make a copy to get contiguous data
1393        v_cur = ggml_cont_2d   (ctx, v_cur, n_embd_gqa, n_tokens);
1394    }
1395
1396    // [TAG_V_CACHE_VARIABLE]
1397    if (n_embd_gqa < v->ne[0]) {
1398        v_cur = ggml_pad(ctx, v_cur, v->ne[0] - n_embd_gqa, 0, 0, 0);
1399    }
1400
1401    // in this branch the v_idxs are constructed in such a way that each row is a single head element
1402    ggml_tensor * v_view = ggml_reshape_2d(ctx, v, 1, ggml_nelements(v));
1403
1404    v_cur = ggml_reshape_2d(ctx, v_cur, 1, ggml_nelements(v_cur));
1405
1406    return ggml_set_rows(ctx, v_view, v_cur, v_idxs);
1407}
1408
1409ggml_tensor * llama_kv_cache::build_input_k_idxs(ggml_context * ctx, const llama_ubatch & ubatch) const {
1410    const uint32_t n_tokens = ubatch.n_tokens;
1411
1412    ggml_tensor * k_idxs = ggml_new_tensor_1d(ctx, GGML_TYPE_I64, n_tokens);
1413
1414    ggml_set_input(k_idxs);
1415
1416    return k_idxs;
1417}
1418
1419ggml_tensor * llama_kv_cache::build_input_v_idxs(ggml_context * ctx, const llama_ubatch & ubatch) const {
1420    const uint32_t n_tokens = ubatch.n_tokens;
1421
1422    ggml_tensor * v_idxs;
1423
1424    if (!v_trans) {
1425        v_idxs = ggml_new_tensor_1d(ctx, GGML_TYPE_I64, n_tokens);
1426    } else {
1427        v_idxs = ggml_new_tensor_1d(ctx, GGML_TYPE_I64, n_tokens*hparams.n_embd_v_gqa_max());
1428    }
1429
1430    ggml_set_input(v_idxs);
1431
1432    return v_idxs;
1433}
1434
1435ggml_tensor * llama_kv_cache::build_input_k_rot(ggml_context * ctx) const {
1436    ggml_tensor * res = nullptr;
1437
1438    if (attn_rot_k) {
1439        int nrot = 64;
1440
1441        // TODO: investigate if using the smallest rotation matrix is beneficial also for K (similar as for V)
1442        // ref: https://github.com/ggml-org/llama.cpp/pull/21038#issuecomment-4141323088
1443        do {
1444            nrot *= 2;
1445        } while (n_embd_head_k_all % nrot == 0);
1446        nrot /= 2;
1447
1448        res = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, nrot, nrot);
1449        ggml_set_input(res);
1450        ggml_set_name(res, "attn_inp_k_rot");
1451    }
1452
1453    return res;
1454}
1455
1456ggml_tensor * llama_kv_cache::build_input_v_rot(ggml_context * ctx) const {
1457    ggml_tensor * res = nullptr;
1458
1459    if (attn_rot_v) {
1460        int nrot = 64;
1461        // using smaller rotation matrices for V seems beneficial
1462        // ref: https://github.com/ggml-org/llama.cpp/pull/21038#issuecomment-4146397570
1463        //do {
1464        //    nrot *= 2;
1465        //} while (hparams.n_embd_head_v() % nrot == 0);
1466        //nrot /= 2;
1467
1468        res = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, nrot, nrot);
1469        ggml_set_input(res);
1470        ggml_set_name(res, "attn_inp_v_rot");
1471    }
1472
1473    return res;
1474}
1475
1476void llama_kv_cache::set_input_k_idxs(ggml_tensor * dst, const llama_ubatch * ubatch, const slot_info & sinfo) const {
1477    const uint32_t n_tokens = ubatch->n_tokens;
1478    GGML_ASSERT(n_tokens == (int64_t) sinfo.size()*sinfo.n_stream());
1479
1480    GGML_ASSERT(ggml_backend_buffer_is_host(dst->buffer));
1481    int64_t * data = (int64_t *) dst->data;
1482
1483    for (uint32_t s = 0; s < sinfo.n_stream(); ++s) {
1484        const int64_t offs = sinfo.strm[s]*get_size();
1485
1486        for (uint32_t i = 0; i < sinfo.size(); ++i) {
1487            data[s*sinfo.size() + i] = offs + sinfo.idxs[s][i];
1488        }
1489    }
1490}
1491
1492void llama_kv_cache::set_input_v_idxs(ggml_tensor * dst, const llama_ubatch * ubatch, const slot_info & sinfo) const {
1493    const uint32_t n_tokens = ubatch->n_tokens;
1494    GGML_ASSERT(n_tokens == (int64_t) sinfo.size()*sinfo.n_stream());
1495
1496    GGML_ASSERT(ggml_backend_buffer_is_host(dst->buffer));
1497    int64_t * data = (int64_t *) dst->data;
1498
1499    if (!v_trans) {
1500        for (uint32_t s = 0; s < sinfo.n_stream(); ++s) {
1501            const int64_t offs = sinfo.strm[s]*get_size();
1502
1503            for (uint32_t i = 0; i < sinfo.size(); ++i) {
1504                data[s*sinfo.size() + i] = offs + sinfo.idxs[s][i];
1505            }
1506        }
1507    } else {
1508        // note: the V cache is transposed when not using flash attention
1509        const int64_t kv_size = get_size();
1510
1511        const int64_t n_embd_v_gqa = hparams.n_embd_v_gqa_max();
1512
1513        for (uint32_t s = 0; s < sinfo.n_stream(); ++s) {
1514            const int64_t offs = sinfo.strm[s]*kv_size*n_embd_v_gqa;
1515
1516            for (uint32_t i = 0; i < sinfo.size(); ++i) {
1517                for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
1518                    data[s*sinfo.size()*n_embd_v_gqa + i*n_embd_v_gqa + j] = offs + j*kv_size + sinfo.idxs[s][i];
1519                }
1520            }
1521        }
1522    }
1523}
1524
1525void llama_kv_cache::set_input_k_shift(ggml_tensor * dst) const {
1526    GGML_ASSERT(ggml_backend_buffer_is_host(dst->buffer));
1527
1528    int32_t * data = (int32_t *) dst->data;
1529
1530    for (uint32_t s = 0; s < n_stream; ++s) {
1531        const auto & cells = v_cells[s];
1532
1533        for (uint32_t i = 0; i < cells.size(); ++i) {
1534            data[s*cells.size() + i] = cells.is_empty(i) ? 0 : cells.get_shift(i);
1535        }
1536    }
1537}
1538
1539struct args_set_input_kq_mask {
1540    const llama_hparams & hparams;
1541    const llama_ubatch  * ubatch;
1542
1543    const std::vector<llama_kv_cells> & v_cells;
1544    const std::vector<uint32_t>       & seq_to_stream;
1545
1546    uint32_t       n_swa;
1547    llama_swa_type swa_type;
1548
1549    int64_t n_kv;
1550    int64_t n_stream;
1551    int64_t n_tps;
1552};
1553
1554template<typename T, bool causal, bool swa, bool is_2d, bool alibi>
1555static void set_input_kq_mask_impl(const args_set_input_kq_mask & args, T * data) {
1556  //const auto & hparams = args.hparams;
1557    const auto & ubatch  = args.ubatch;
1558
1559    const auto & v_cells       = args.v_cells;
1560    const auto & seq_to_stream = args.seq_to_stream;
1561
1562    const uint32_t       n_swa    = args.n_swa;
1563    const llama_swa_type swa_type = args.swa_type;
1564
1565    const int64_t n_kv     = args.n_kv;
1566    const int64_t n_stream = args.n_stream;
1567    const int64_t n_tps    = args.n_tps;
1568
1569    const T mask_keep = llama_cast<T>(0.0f);
1570    const T mask_drop = llama_cast<T>(-INFINITY);
1571
1572    // the min position in the batch for each sequence
1573    llama_pos seq_pos_min[LLAMA_MAX_SEQ];
1574    std::fill(seq_pos_min, seq_pos_min + LLAMA_MAX_SEQ, INT32_MAX);
1575
1576    for (uint32_t i = 0; i < ubatch->n_tokens; ++i) {
1577        const llama_seq_id seq_id = ubatch->seq_id[i][0];
1578
1579        seq_pos_min[seq_id] = std::min(seq_pos_min[seq_id], ubatch->pos[i]);
1580    }
1581
1582    for (uint32_t s = 0; s < n_stream; ++s) {
1583        // bookkeeping of the KQ mask cells that could change for other tokens of the same sequence
1584        std::unordered_map<llama_seq_id, uint32_t>              seq_srct;
1585        std::unordered_map<llama_seq_id, std::vector<uint32_t>> seq_idxs;
1586
1587        for (uint32_t ii = 0; ii < n_tps; ++ii) {
1588            const uint32_t i = s*n_tps + ii;
1589
1590            const llama_seq_id seq_id = ubatch->seq_id[i][0];
1591
1592            const auto & cells = v_cells.at(seq_to_stream[seq_id]);
1593
1594                  llama_pos p0 = -1;
1595            const llama_pos p1 = ubatch->pos[i];
1596
1597            // for M-RoPE
1598            const llama_pos p1_x = is_2d ? ubatch->pos[i + ubatch->n_tokens*2] : 0;
1599            const llama_pos p1_y = is_2d ? ubatch->pos[i + ubatch->n_tokens]   : 0;
1600
1601            const uint64_t idst = n_kv*i;
1602
1603            // for tokens of the same sequence, the mask is mostly the same, so we can reuse it
1604            // the only cells that could change are the ones that are with similar positions as the
1605            //   ones in the batch (i.e. due to causal masking, SWA, etc.)
1606            // keep track of those cells and shortcut the loop to save time
1607            // note: this optimization is not compatible with Alibi position encoding
1608            // ref:  https://github.com/ggml-org/llama.cpp/pull/18842
1609            bool prev = false;
1610
1611            auto & idxs = seq_idxs[seq_id];
1612
1613            if (!alibi) {
1614                if (seq_srct.find(seq_id) != seq_srct.end()) {
1615                    const uint32_t srct = seq_srct[seq_id];
1616
1617                    const uint64_t idst_prev = n_kv*srct;
1618
1619                    std::copy(data + idst_prev, data + idst_prev + n_kv, data + idst);
1620
1621                    prev = true;
1622                } else {
1623                    idxs.clear();
1624                    idxs.reserve(ubatch->n_tokens + n_swa + 32);
1625
1626                    seq_srct[seq_id] = i;
1627                }
1628            }
1629
1630            for (uint32_t jj = 0; jj < n_kv; ++jj) {
1631                uint32_t j = jj;
1632
1633                // we have an exiting mask for this sequence -> update just seq_idxs
1634                if (!alibi) {
1635                    if (prev) {
1636                        if (jj >= idxs.size()) {
1637                            break;
1638                        }
1639
1640                        j = idxs[jj];
1641                    }
1642                }
1643
1644                if (cells.is_empty(j)) {
1645                    goto skip;
1646                }
1647
1648                // mask the token if not the same sequence
1649                if (!cells.seq_has(j, seq_id)) {
1650                    goto skip;
1651                }
1652
1653                p0 = cells.pos_get(j);
1654
1655                if (!alibi) {
1656                    if (!prev) {
1657                        // record all cells for which: p0 >= seq_pos_min[seq_id] - n_swa - 32
1658                        if (p0 + (int32_t) (n_swa + 32) >= seq_pos_min[seq_id]) {
1659                            idxs.push_back(j);
1660                        }
1661                    }
1662                }
1663
1664                if (causal) {
1665                    // mask future tokens
1666                    if (p0 > p1) {
1667                        goto skip;
1668                    }
1669
1670                    // M-RoPE causal mask
1671                    if (is_2d) {
1672                        if (p0 == p1) {
1673                            const auto & p0_ext = cells.ext_get(j);
1674
1675                            if (p0_ext.is_2d_gt(p1_x, p1_y)) {
1676                                goto skip;
1677                            }
1678                        }
1679                    }
1680                }
1681
1682                // apply SWA if any
1683                if (swa) {
1684                    // see llama_non_causal_type
1685                    const bool in_span = !causal && args.hparams.non_causal_type == LLAMA_NON_CAUSAL_TYPE_SWA_FULL && p0 >= seq_pos_min[seq_id];
1686                    if (!in_span && llama_hparams::is_masked_swa(n_swa, swa_type, p0, p1)) {
1687                        goto skip;
1688                    }
1689                }
1690
1691                if (alibi) {
1692                    data[idst + j] = llama_cast<T>(static_cast<float>(-std::abs(p0 - p1)));
1693                } else {
1694                    data[idst + j] = mask_keep;
1695                }
1696
1697                continue;
1698skip:
1699                data[idst + j] = mask_drop;
1700            }
1701        }
1702    }
1703}
1704
1705template<typename T, bool causal, bool swa, bool is_2d>
1706static void set_input_kq_mask_impl(const args_set_input_kq_mask & args, T * data) {
1707    const bool alibi = args.hparams.use_alibi;
1708    if (alibi) {
1709        set_input_kq_mask_impl<T, causal, swa, is_2d, true> (args, data);
1710    } else {
1711        set_input_kq_mask_impl<T, causal, swa, is_2d, false>(args, data);
1712    }
1713}
1714
1715template<typename T, bool causal, bool swa>
1716static void set_input_kq_mask_impl(const args_set_input_kq_mask & args, T * data) {
1717    const bool is_2d = args.ubatch->is_pos_2d();
1718    if (is_2d) {
1719        set_input_kq_mask_impl<T, causal, swa, true> (args, data);
1720    } else {
1721        set_input_kq_mask_impl<T, causal, swa, false>(args, data);
1722    }
1723}
1724
1725template<typename T, bool causal>
1726static void set_input_kq_mask_impl(const args_set_input_kq_mask & args, T * data) {
1727    const bool swa = args.swa_type != LLAMA_SWA_TYPE_NONE;
1728    if (swa) {
1729        set_input_kq_mask_impl<T, causal, true> (args, data);
1730    } else {
1731        set_input_kq_mask_impl<T, causal, false>(args, data);
1732    }
1733}
1734
1735template<typename T>
1736static void set_input_kq_mask_impl(const args_set_input_kq_mask & args, T * data, bool causal_attn) {
1737    if (causal_attn) {
1738        set_input_kq_mask_impl<T, true> (args, data);
1739    } else {
1740        set_input_kq_mask_impl<T, false>(args, data);
1741    }
1742}
1743
1744void llama_kv_cache::set_input_kq_mask(ggml_tensor * dst, const llama_ubatch * ubatch, bool causal_attn) const {
1745    const uint32_t n_tokens = ubatch->n_tokens;
1746
1747    GGML_ASSERT(ggml_backend_buffer_is_host(dst->buffer));
1748
1749    const int64_t n_kv     = dst->ne[0];
1750    const int64_t n_stream = dst->ne[3]; // num streams in the current ubatch
1751
1752    GGML_ASSERT(n_tokens%n_stream == 0);
1753
1754    // n_tps == n_tokens_per_stream
1755    const int64_t n_tps = n_tokens/n_stream;
1756
1757    // see llama_non_causal_type
1758    // only the SWA cache (or the SWA layers of a single cache) become non-causal
1759    if (!causal_attn && hparams.non_causal_type == LLAMA_NON_CAUSAL_TYPE_SWA_ONLY) {
1760        causal_attn = swa_type == LLAMA_SWA_TYPE_NONE;
1761    }
1762
1763    //const int64_t t_start = ggml_time_us();
1764
1765    const args_set_input_kq_mask args = {
1766        /*.hparams          =*/ hparams,
1767        /*.ubatch           =*/ ubatch,
1768        /*.v_cells          =*/ v_cells,
1769        /*.seq_to_stream    =*/ seq_to_stream,
1770        /*.n_swa            =*/ n_swa,
1771        /*.swa_type         =*/ swa_type,
1772        /*.n_kv             =*/ n_kv,
1773        /*.n_stream         =*/ n_stream,
1774        /*.n_tps            =*/ n_tps,
1775    };
1776
1777    if (dst->type == GGML_TYPE_F16) {
1778        set_input_kq_mask_impl<ggml_fp16_t>(args, (ggml_fp16_t *) dst->data, causal_attn);
1779    } else {
1780        set_input_kq_mask_impl<float>(args, (float *) dst->data, causal_attn);
1781    }
1782
1783    //const int64_t t_end = ggml_time_us();
1784
1785    //LLAMA_LOG_ERROR("%s: kq mask time: %0.3f ms\n", __func__, (t_end - t_start)/1000.0);
1786}
1787
1788void llama_kv_cache::set_input_pos_bucket(ggml_tensor * dst, const llama_ubatch * ubatch) const {
1789    const int64_t n_tokens = ubatch->n_tokens;
1790
1791    GGML_ASSERT(n_stream == 1 && "TODO: support multiple streams");
1792    const auto & cells = v_cells[0];
1793
1794    GGML_ASSERT(ggml_backend_buffer_is_host(dst->buffer));
1795    GGML_ASSERT(!ubatch->equal_seqs()); // TODO: use ubatch->n_seqs instead of failing
1796
1797    int32_t * data = (int32_t *) dst->data;
1798
1799    const int32_t n_kv = dst->ne[0];
1800
1801    for (int h = 0; h < 1; ++h) {
1802        for (int i = 0; i < n_tokens; ++i) {
1803            for (int j = 0; j < n_kv; ++j) {
1804                // the position when the cells is empty is irrelevant - it will be masked out later in the attention
1805                const llama_pos p0 = cells.is_empty(j) ? -1 : cells.pos_get(j);
1806
1807                data[h*(n_kv*n_tokens) + i*n_kv + j] = llama_relative_position_bucket(p0, ubatch->pos[i], hparams.n_rel_attn_bkts, false);
1808            }
1809        }
1810    }
1811}
1812
1813void llama_kv_cache::set_input_k_rot(ggml_tensor * dst) const {
1814    GGML_ASSERT(ggml_backend_buffer_is_host(dst->buffer));
1815
1816    const auto n_rot = dst->ne[0];
1817    GGML_ASSERT(attn_rot_hadamard.count(dst->ne[0]));
1818
1819    memcpy(dst->data, attn_rot_hadamard.at(n_rot).data(), ggml_nbytes(dst));
1820}
1821
1822void llama_kv_cache::set_input_v_rot(ggml_tensor * dst) const {
1823    GGML_ASSERT(ggml_backend_buffer_is_host(dst->buffer));
1824
1825    const auto n_rot = dst->ne[0];
1826    GGML_ASSERT(attn_rot_hadamard.count(dst->ne[0]));
1827
1828    memcpy(dst->data, attn_rot_hadamard.at(n_rot).data(), ggml_nbytes(dst));
1829}
1830
1831bool llama_kv_cache::has_cell_ext() const {
1832    // M-RoPE needs the 2D position, the PLE n-gram hash needs the token id
1833    return hparams.n_pos_per_embd() > 1 || hparams.ple_n_heads > 0;
1834}
1835
1836void llama_kv_cache::get_prev_tokens(const llama_ubatch & ubatch, uint32_t n, std::vector<llama_token> & res) const {
1837    const uint32_t n_tokens = ubatch.n_tokens;
1838
1839    res.clear();
1840    res.resize(n_tokens*n, LLAMA_TOKEN_NULL);
1841
1842    if (n == 0) {
1843        return;
1844    }
1845
1846    // note: apply_ubatch() has already stored the current ubatch, so the cells cover the tokens
1847    //       of this very ubatch as well, which is what we want
1848    // the nearest cell at or before a position also resolves M-RoPE gaps, where multiple tokens
1849    // share the same temporal pos
1850
1851    // an embd (multimodal) ubatch can repeat one position for a whole image, so positions
1852    // do not encode the token order; resolve its predecessors by ubatch order instead
1853    std::vector<uint32_t> ord; // index among the ubatch tokens of the same seq
1854    std::unordered_map<llama_seq_id, std::vector<uint32_t>> seq_idx;
1855
1856    if (!ubatch.token) {
1857        ord.resize(n_tokens);
1858        for (uint32_t i = 0; i < n_tokens; ++i) {
1859            auto & v = seq_idx[ubatch.seq_id[i][0]];
1860            ord[i] = v.size();
1861            v.push_back(i);
1862        }
1863    }
1864
1865    for (uint32_t i = 0; i < n_tokens; ++i) {
1866        // TODO: a token that belongs to more than one sequence has an ambiguous history.
1867        //       the n-gram architectures have to reject such batches
1868        const llama_seq_id seq_id = ubatch.seq_id[i][0];
1869
1870        for (uint32_t j = 0; j < n; ++j) {
1871            const llama_pos d = (llama_pos) (n - j);
1872
1873            llama_pos p;
1874            if (!ubatch.token) {
1875                const auto & v = seq_idx[seq_id];
1876                const int64_t k = (int64_t) ord[i] - d;
1877                // k >= 0: an earlier token of this very ubatch; k < 0: before the chunk
1878                p = k >= 0 ? ubatch.pos[v[k]] : ubatch.pos[v[0]] + (llama_pos) k;
1879            } else {
1880                p = ubatch.pos[i] - d;
1881            }
1882
1883            if (p < 0) {
1884                continue;
1885            }
1886
1887            res[i*n + j] = v_cells[seq_to_stream[seq_id]].seq_pos_tok_le(seq_id, p);
1888        }
1889    }
1890}
1891
1892size_t llama_kv_cache::total_size() const {
1893    size_t size = 0;
1894
1895    for (const auto & [_, buf] : ctxs_bufs) {
1896        size += ggml_backend_buffer_get_size(buf.get());
1897    }
1898
1899    return size;
1900}
1901
1902size_t llama_kv_cache::size_k_bytes() const {
1903    size_t size_k_bytes = 0;
1904
1905    for (const auto & layer : layers) {
1906        size_k_bytes += ggml_nbytes(layer.k);
1907    }
1908
1909    return size_k_bytes;
1910}
1911
1912size_t llama_kv_cache::size_v_bytes() const {
1913    size_t size_v_bytes = 0;
1914
1915    for (const auto & layer : layers) {
1916        size_v_bytes += layer.v ? ggml_nbytes(layer.v) : 0;
1917    }
1918
1919    return size_v_bytes;
1920}
1921
1922ggml_tensor * llama_kv_cache::build_rope_shift(
1923        const llama_cparams & cparams,
1924               ggml_context * ctx,
1925                ggml_tensor * cur,
1926                ggml_tensor * shift,
1927                ggml_tensor * rot,
1928                ggml_tensor * factors,
1929                      float   freq_base,
1930                      float   freq_scale,
1931                   uint32_t   il) const {
1932    const auto & n_ctx_orig = cparams.n_ctx_orig_yarn;
1933
1934    const auto & yarn_ext_factor  = cparams.yarn_ext_factor;
1935    const auto & yarn_beta_fast   = cparams.yarn_beta_fast;
1936    const auto & yarn_beta_slow   = cparams.yarn_beta_slow;
1937    const auto & yarn_attn_factor = cparams.yarn_attn_factor;
1938
1939    const auto & n_rot     = hparams.n_rot(il);
1940    const auto & rope_type = hparams.rope_type == LLAMA_ROPE_TYPE_MROPE || hparams.rope_type == LLAMA_ROPE_TYPE_IMROPE
1941                                // @ngxson : this is a workaround
1942                                // for M-RoPE, we want to rotate the whole vector when doing KV shift
1943                                // a normal RoPE should work, we just need to use the correct ordering
1944                                // ref: https://github.com/ggml-org/llama.cpp/pull/13870
1945                                ? LLAMA_ROPE_TYPE_NEOX
1946                                : hparams.rope_type;
1947    ggml_tensor * tmp;
1948
1949    if (ggml_is_quantized(cur->type)) {
1950        // dequantize to f32 -> RoPE -> quantize back
1951        tmp = ggml_cast(ctx, cur, GGML_TYPE_F32);
1952
1953        // rotate back
1954        tmp = llama_mul_mat_hadamard(ctx, tmp, rot);
1955
1956        tmp = ggml_rope_ext(ctx, tmp,
1957                shift, factors, n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
1958                yarn_ext_factor, yarn_attn_factor, yarn_beta_fast, yarn_beta_slow);
1959
1960        // rotate fwd
1961        tmp = llama_mul_mat_hadamard(ctx, tmp, rot);
1962
1963        tmp = ggml_cpy(ctx, tmp, cur);
1964    } else {
1965        // we rotate only the first n_rot dimensions
1966        tmp = ggml_rope_ext_inplace(ctx, cur,
1967                shift, factors, n_rot, rope_type, n_ctx_orig, freq_base, freq_scale,
1968                yarn_ext_factor, yarn_attn_factor, yarn_beta_fast, yarn_beta_slow);
1969    }
1970
1971    return tmp;
1972}
1973
1974class llm_graph_input_k_shift : public llm_graph_input_i {
1975public:
1976    llm_graph_input_k_shift(const llama_kv_cache * kv_self) : kv_self(kv_self) {}
1977    virtual ~llm_graph_input_k_shift() = default;
1978
1979    void set_input(const llama_ubatch * ubatch) override;
1980
1981    ggml_tensor * k_shift; // I32 [kv_size*n_stream]
1982
1983    // note: assumes k_rot^2 == I
1984    ggml_tensor * k_rot = nullptr;
1985
1986    const llama_kv_cache * kv_self;
1987};
1988
1989void llm_graph_input_k_shift::set_input(const llama_ubatch * ubatch) {
1990    GGML_UNUSED(ubatch);
1991
1992    if (k_shift) {
1993        kv_self->set_input_k_shift(k_shift);
1994    }
1995
1996    if (k_rot && k_rot->buffer) {
1997        kv_self->set_input_k_rot(k_rot);
1998    }
1999}
2000
2001ggml_cgraph * llama_kv_cache::build_graph_shift(llm_graph_result * res, llama_context * lctx) const {
2002    // TODO: refactor [TAG_KV_CACHE_SHARE_CELLS]
2003    GGML_ASSERT(!other);
2004
2005    auto * ctx = res->get_ctx();
2006    auto * gf  = res->get_gf();
2007
2008    auto inp = std::make_unique<llm_graph_input_k_shift>(this);
2009
2010    inp->k_shift = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, (int64_t) get_size()*n_stream);
2011    ggml_set_input(inp->k_shift);
2012
2013    inp->k_rot = build_input_k_rot(ctx);
2014
2015    const auto & cparams = lctx->get_cparams();
2016
2017    for (const auto & layer : layers) {
2018        const uint32_t il = layer.il;
2019
2020        if (!hparams.has_rope(il)) {
2021            continue;
2022        }
2023
2024        const int64_t n_head_kv    = hparams.n_head_kv(il);
2025        const int64_t n_embd_k_gqa = hparams.n_embd_k_gqa(il);
2026
2027        const auto n_rot         = hparams.n_rot(il);
2028        const auto n_embd_head_k = hparams.n_embd_head_k(il);
2029        const auto n_embd_nope   = hparams.n_lora_kv > 0 ? n_embd_head_k - n_rot : 0;
2030
2031        const float freq_base_l  = model.get_rope_freq_base (cparams, il);
2032        const float freq_scale_l = model.get_rope_freq_scale(cparams, il);
2033
2034        ggml_tensor * rope_factors = model.get_rope_factors(cparams, il);
2035
2036        ggml_tensor * k =
2037            ggml_view_3d(ctx, layer.k,
2038                n_rot, n_head_kv, get_size()*n_stream,
2039                ggml_row_size(layer.k->type, n_embd_head_k),
2040                ggml_row_size(layer.k->type, n_embd_k_gqa),
2041                ggml_row_size(layer.k->type, n_embd_nope));
2042
2043        ggml_tensor * cur = build_rope_shift(cparams, ctx, k, inp->k_shift, inp->k_rot, rope_factors, freq_base_l, freq_scale_l, il);
2044
2045        ggml_build_forward_expand(gf, cur);
2046    }
2047
2048    res->add_input(std::move(inp));
2049
2050    return gf;
2051}
2052
2053void llama_kv_cache::state_write(llama_io_write_i & io, llama_seq_id seq_id, llama_state_seq_flags flags) const {
2054    // TODO: refactor [TAG_KV_CACHE_SHARE_CELLS]
2055    if (other) {
2056        return;
2057    }
2058
2059    GGML_UNUSED(flags);
2060
2061    io.write(&n_stream, sizeof(n_stream));
2062
2063    for (uint32_t s = 0; s < n_stream; ++s) {
2064        cell_ranges_t cr { s, {} };
2065
2066        uint32_t cell_count = 0;
2067
2068        const auto & cells = v_cells[s];
2069
2070        // Count the number of cells with the specified seq_id
2071        // Find all the ranges of cells with this seq id (or all, when -1)
2072        uint32_t cell_range_begin = cells.size();
2073
2074        for (uint32_t i = 0; i < cells.size(); ++i) {
2075            bool add_cell = true;
2076
2077            add_cell = add_cell && !cells.is_empty(i);
2078            add_cell = add_cell && (seq_id == -1 || cells.seq_has(i, seq_id));
2079
2080            // check the cell is not SWA-masked
2081            if (add_cell && seq_id != -1) {
2082                const bool is_masked = llama_hparams::is_masked_swa(n_swa, swa_type, cells.pos_get(i), cells.seq_pos_max(seq_id));
2083
2084                add_cell = !is_masked;
2085            }
2086
2087            if (add_cell) {
2088                ++cell_count;
2089                if (cell_range_begin == cells.size()) {
2090                    cell_range_begin = i;
2091                }
2092            } else {
2093                if (cell_range_begin != cells.size()) {
2094                    cr.data.emplace_back(cell_range_begin, i);
2095                    cell_range_begin = cells.size();
2096                }
2097            }
2098        }
2099
2100        if (cell_range_begin != cells.size()) {
2101            cr.data.emplace_back(cell_range_begin, cells.size());
2102        }
2103
2104        // DEBUG CHECK: Sum of cell counts in ranges should equal the total cell count
2105        uint32_t cell_count_check = 0;
2106        for (const auto & range : cr.data) {
2107            cell_count_check += range.second - range.first;
2108        }
2109        GGML_ASSERT(cell_count == cell_count_check);
2110
2111        io.write(&cell_count, sizeof(cell_count));
2112
2113        // skip empty streams
2114        if (cell_count == 0) {
2115            continue;
2116        }
2117
2118        state_write_meta(io, cr, seq_id);
2119        state_write_data(io, cr);
2120    }
2121}
2122
2123void llama_kv_cache::state_read(llama_io_read_i & io, llama_seq_id seq_id, llama_state_seq_flags flags) {
2124    state_read_sinfo(io, seq_id, flags, nullptr, nullptr);
2125}
2126
2127void llama_kv_cache::state_read_sinfo(
2128        llama_io_read_i & io,
2129           llama_seq_id   seq_id,
2130  llama_state_seq_flags   flags,
2131      slot_info_vec_t *   sinfos_out,
2132const slot_info_vec_t *   sinfos_in) {
2133    // TODO: refactor [TAG_KV_CACHE_SHARE_CELLS]
2134    if (other) {
2135        return;
2136    }
2137
2138    GGML_UNUSED(flags);
2139
2140    // TODO: fix incosistent handling of `seq_id < 0` and `seq_id == -1` in the codebase [TAG_LLAMA_SEQ_ID_NEG]
2141    GGML_ASSERT(seq_id == -1 || (seq_id >= 0 && (size_t) seq_id < seq_to_stream.size()));
2142
2143    if (sinfos_out) {
2144        sinfos_out->assign(n_stream, slot_info{});
2145    }
2146
2147    if (sinfos_in && sinfos_in->size() != n_stream) {
2148        throw std::runtime_error("failed to restore kv cache: mirrored slot layout has the wrong stream count");
2149    }
2150
2151    uint32_t n_stream_cur;
2152    io.read(&n_stream_cur, sizeof(n_stream_cur));
2153    if (n_stream_cur != n_stream) {
2154        throw std::runtime_error("n_stream mismatch");
2155    }
2156
2157    // a whole-context restore replaces every stream, so the cache is emptied once here
2158    // clear() resets all streams at once, so doing it per stream below would keep only the last one
2159    if (seq_id == -1) {
2160        clear(true);
2161    }
2162
2163    for (uint32_t s = 0; s < n_stream; ++s) {
2164        uint32_t cell_count;
2165        io.read(&cell_count, sizeof(cell_count));
2166
2167        if (cell_count == 0) {
2168            // a mirrored cache must be empty here as well, or the two no longer agree cell for cell
2169            if (sinfos_in && !(*sinfos_in)[s].empty()) {
2170                throw std::runtime_error("failed to restore kv cache: mirrored cache holds cells this one does not");
2171            }
2172            continue;
2173        }
2174
2175        const uint32_t strm = seq_id == -1 ? s : seq_to_stream[seq_id];
2176
2177        slot_info sinfo;
2178
2179        bool res = true;
2180        res = res && state_read_meta(io, strm, cell_count, sinfo, seq_id, sinfos_in ? &(*sinfos_in)[s] : nullptr);
2181
2182        try {
2183            res = res && state_read_data(io, strm, cell_count, sinfo);
2184        } catch (...) {
2185            res = false;
2186        }
2187
2188        if (!res) {
2189            if (seq_id == -1) {
2190                clear(true);
2191            } else {
2192                seq_rm(seq_id, -1, -1);
2193            }
2194            throw std::runtime_error("failed to restore kv cache");
2195        }
2196
2197        if (sinfos_out) {
2198            (*sinfos_out)[s] = sinfo;
2199        }
2200    }
2201}
2202
2203void llama_kv_cache::state_write_meta(llama_io_write_i & io, const cell_ranges_t & cr, llama_seq_id seq_id) const {
2204    const auto & cells = v_cells[cr.strm];
2205
2206    for (const auto & range : cr.data) {
2207        for (uint32_t i = range.first; i < range.second; ++i) {
2208            std::vector<llama_seq_id> seq_ids;
2209
2210            for (llama_seq_id cur = 0; cur < (int) n_seq_max; ++cur) {
2211                if (cur == seq_id || seq_id == -1) {
2212                    if (cells.seq_has(i, cur)) {
2213                        seq_ids.push_back(cur);
2214                    }
2215                }
2216            }
2217
2218            const llama_pos pos     = cells.pos_get(i);
2219            const uint32_t n_seq_id = seq_ids.size();
2220
2221            io.write(&pos,      sizeof(pos));
2222            io.write(&n_seq_id, sizeof(n_seq_id));
2223
2224            if (has_cell_ext()) {
2225                const llama_kv_cell_ext ext = cells.ext_get(i);
2226                io.write(&ext, sizeof(ext));
2227            }
2228
2229            for (const auto & seq_id : seq_ids) {
2230                io.write(&seq_id, sizeof(seq_id));
2231            }
2232        }
2233    }
2234}
2235
2236void llama_kv_cache::state_write_data(llama_io_write_i & io, const cell_ranges_t & cr) const {
2237    const auto & cells = v_cells[cr.strm];
2238
2239    const uint32_t v_trans = this->v_trans ? 1 : 0;
2240    const uint32_t n_layer = layers.size();
2241
2242    io.write(&v_trans, sizeof(v_trans));
2243    io.write(&n_layer, sizeof(n_layer));
2244
2245    // Iterate and write all the keys first, each row is a cell
2246    // Get whole range at a time
2247    for (const auto & layer : layers) {
2248        const uint32_t il = layer.il;
2249
2250        const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa(il);
2251
2252        auto * k = layer.k_stream[cr.strm];
2253
2254        // Write key type
2255        const int32_t k_type_i = (int32_t) k->type;
2256        io.write(&k_type_i, sizeof(k_type_i));
2257
2258        // Write row size of key
2259        const uint64_t k_size_row = ggml_row_size(k->type, n_embd_k_gqa);
2260        io.write(&k_size_row, sizeof(k_size_row));
2261
2262        // Read each range of cells of k_size length and write out
2263        for (const auto & range : cr.data) {
2264            const size_t range_size = range.second - range.first;
2265            const size_t buf_size = range_size * k_size_row;
2266            io.write_tensor(k, range.first * k_size_row, buf_size);
2267        }
2268    }
2269
2270    if (!v_trans) {
2271        for (const auto & layer : layers) {
2272            const uint32_t il = layer.il;
2273
2274            const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(il);
2275
2276            auto * v = layer.v_stream[cr.strm];
2277            if (!v) {
2278                continue;
2279            }
2280
2281            // Write value type
2282            const int32_t v_type_i = (int32_t) v->type;
2283            io.write(&v_type_i, sizeof(v_type_i));
2284
2285            // Write row size of value
2286            const uint64_t v_size_row = ggml_row_size(v->type, n_embd_v_gqa);
2287            io.write(&v_size_row, sizeof(v_size_row));
2288
2289            // Read each range of cells of v_size length and write out
2290            for (const auto & range : cr.data) {
2291                const size_t range_size = range.second - range.first;
2292                const size_t buf_size = range_size * v_size_row;
2293                io.write_tensor(v, range.first * v_size_row, buf_size);
2294            }
2295        }
2296    } else {
2297        // When v is transposed, we also need the element size and get the element ranges from each row
2298        const uint32_t kv_size = cells.size();
2299
2300        for (const auto & layer : layers) {
2301            const uint32_t il = layer.il;
2302
2303            const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(il);
2304
2305            auto * v = layer.v_stream[cr.strm];
2306            if (!v) {
2307                continue;
2308            }
2309
2310            // Write value type
2311            const int32_t v_type_i = (int32_t) v->type;
2312            io.write(&v_type_i, sizeof(v_type_i));
2313
2314            // Write element size
2315            const uint32_t v_size_el = ggml_type_size(v->type);
2316            io.write(&v_size_el, sizeof(v_size_el));
2317
2318            // Write GQA embedding size
2319            io.write(&n_embd_v_gqa, sizeof(n_embd_v_gqa));
2320
2321            // For each row, we get the element values of each cell
2322            for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
2323                // Read each range of cells of v_size_el length and write out
2324                for (const auto & range : cr.data) {
2325                    const size_t range_size = range.second - range.first;
2326                    const size_t src_offset = (range.first + j * kv_size) * v_size_el;
2327                    const size_t buf_size = range_size * v_size_el;
2328                    io.write_tensor(v, src_offset, buf_size);
2329                }
2330            }
2331        }
2332    }
2333}
2334
2335bool llama_kv_cache::state_read_meta(llama_io_read_i & io, uint32_t strm, uint32_t cell_count, slot_info & sinfo, llama_seq_id dest_seq_id, const slot_info * sinfo_in) {
2336    auto & cells = v_cells[strm];
2337    auto & head  = v_heads[strm];
2338
2339    if (dest_seq_id != -1) {
2340        // single sequence
2341        seq_rm(dest_seq_id, -1, -1);
2342
2343        llama_batch_allocr balloc(hparams.n_pos_per_embd());
2344
2345        llama_ubatch ubatch = balloc.ubatch_reserve(cell_count, 1);
2346
2347        ubatch.seq_id_unq[0] = dest_seq_id;
2348
2349        // the ext as it was saved, to put back after apply_ubatch()
2350        std::vector<llama_kv_cell_ext> exts;
2351        if (has_cell_ext()) {
2352            exts.resize(cell_count);
2353        }
2354
2355        for (uint32_t i = 0; i < cell_count; ++i) {
2356            llama_pos pos;
2357            uint32_t n_seq_id;
2358
2359            io.read(&pos,      sizeof(pos));
2360            io.read(&n_seq_id, sizeof(n_seq_id));
2361
2362            if (n_seq_id != 1) {
2363                LLAMA_LOG_ERROR("%s: invalid seq_id-agnostic kv cell\n", __func__);
2364                return false;
2365            }
2366
2367            if (has_cell_ext()) {
2368                llama_kv_cell_ext ext;
2369                io.read(&ext, sizeof(ext));
2370
2371                if (hparams.n_pos_per_embd() > 1) {
2372                    ubatch.pos[i + ubatch.n_tokens]   = ext.y;
2373                    ubatch.pos[i + ubatch.n_tokens*2] = ext.x;
2374                }
2375
2376                // apply_ubatch() below restores ext.tok from the ubatch tokens
2377                ubatch.token[i] = ext.tok;
2378
2379                exts[i] = ext;
2380            }
2381
2382            // read the sequence id, but directly discard it - we will use dest_seq_id instead
2383            {
2384                llama_seq_id seq_id;
2385                io.read(&seq_id, sizeof(seq_id));
2386            }
2387
2388            ubatch.pos[i]      = pos;
2389            ubatch.n_seq_id[i] = n_seq_id;
2390            ubatch.seq_id[i]   = &dest_seq_id;
2391        }
2392
2393        if (sinfo_in) {
2394            // this cache mirrors another one, so it takes that cache's layout instead of searching for its own cells
2395            if (sinfo_in->empty() || sinfo_in->n_stream() != 1 || sinfo_in->idxs[0].size() != cell_count) {
2396                LLAMA_LOG_ERROR("%s: mirrored slot layout holds %d cells, this cache restores %d\n", __func__,
2397                        sinfo_in->empty() ? 0 : (int) sinfo_in->idxs[0].size(), cell_count);
2398                return false;
2399            }
2400
2401            sinfo = *sinfo_in;
2402
2403            // the layout is cell indices, so it means the same in both caches only while their streams line up
2404            sinfo.s0 = strm;
2405            sinfo.s1 = strm;
2406            sinfo.strm[0] = strm;
2407
2408            // seq_rm above freed exactly the cells this sequence held
2409            // anything else in the way is a cache that had already drifted, which this restore must not hide
2410            for (uint32_t i = 0; i < cell_count; ++i) {
2411                const uint32_t idx = sinfo.idxs[0][i];
2412
2413                if (idx >= cells.size() || !cells.is_empty(idx)) {
2414                    LLAMA_LOG_ERROR("%s: cell %u of the mirrored slot layout is not free\n", __func__, idx);
2415                    return false;
2416                }
2417            }
2418        } else {
2419            sinfo = find_slot(ubatch, false);
2420            if (sinfo.empty()) {
2421                LLAMA_LOG_ERROR("%s: failed to find %d available cells in kv cache\n", __func__,  cell_count);
2422                return false;
2423            }
2424        }
2425
2426        // note: apply_ubatch() rebuilds llama_kv_cell_ext from the ubatch
2427        //       only ext.tok and the M-RoPE 2D position round-trip through it
2428        //       see: https://github.com/ggml-org/llama.cpp/pull/16825#issuecomment-3460868350
2429        apply_ubatch(sinfo, ubatch);
2430
2431        // apply_ubatch() takes the 2D position from the ubatch, and that ubatch is built with this
2432        // cache's own n_pos_per_embd. a cache that does not use M-RoPE itself but mirrors one that
2433        // does (the qwen4exp QSA indexer) would drop x and y. put the saved ext back instead, which
2434        // is what the whole-context path below already does.
2435        for (uint32_t i = 0; i < (uint32_t) exts.size(); ++i) {
2436            cells.ext_set(sinfo.idxs[0][i], exts[i]);
2437        }
2438
2439        LLAMA_LOG_DEBUG("%s: cell_count = %d, dest_seq_id = %d\n", __func__, cell_count, dest_seq_id);
2440
2441        // DEBUG CHECK: verify that all cells were allocated and have correct seq_id and pos values
2442        GGML_ASSERT(sinfo.n_stream() == 1);
2443        GGML_ASSERT(sinfo.idxs[0].size() == cell_count);
2444        for (uint32_t i = 0; i < cell_count; ++i) {
2445            const uint32_t idx = sinfo.idxs[0][i];
2446            GGML_ASSERT(cells.pos_get(idx) == ubatch.pos[i]);
2447            GGML_ASSERT(cells.seq_has(idx, dest_seq_id));
2448        }
2449    } else {
2450        // whole KV cache restore
2451
2452        if (cell_count > cells.size()) {
2453            LLAMA_LOG_ERROR("%s: not enough cells in kv cache\n", __func__);
2454            return false;
2455        }
2456
2457        // the cells go in from 0, so a mirrored cache lands on the same ones as long as it restores the same count. the layout itself carries no more information here
2458        if (sinfo_in && (sinfo_in->empty() || sinfo_in->n_stream() != 1 || sinfo_in->idxs[0].size() != cell_count)) {
2459            LLAMA_LOG_ERROR("%s: mirrored slot layout holds %d cells, this cache restores %d\n", __func__,
2460                    sinfo_in->empty() ? 0 : (int) sinfo_in->idxs[0].size(), cell_count);
2461            return false;
2462        }
2463
2464        for (uint32_t i = 0; i < cell_count; ++i) {
2465            llama_pos pos;
2466            uint32_t  n_seq_id;
2467
2468            io.read(&pos,      sizeof(pos));
2469            io.read(&n_seq_id, sizeof(n_seq_id));
2470
2471            cells.pos_set(i, pos);
2472
2473            if (has_cell_ext()) {
2474                llama_kv_cell_ext ext;
2475                io.read(&ext, sizeof(ext));
2476                cells.ext_set(i, ext);
2477            }
2478
2479            for (uint32_t j = 0; j < n_seq_id; ++j) {
2480                llama_seq_id seq_id;
2481                io.read(&seq_id, sizeof(seq_id));
2482
2483                if (seq_id < 0 || (uint32_t) seq_id >= n_seq_max) {
2484                    LLAMA_LOG_ERROR("%s: invalid seq_id, %d is out of range [0, %u)\n", __func__, seq_id, n_seq_max);
2485                    return false;
2486                }
2487
2488                cells.seq_add(i, seq_id);
2489            }
2490        }
2491
2492        // Create contiguous slot_info for whole cache restore
2493        sinfo.s0 = strm;
2494        sinfo.s1 = strm;
2495        sinfo.resize(1);
2496        sinfo.strm[0] = strm;
2497        sinfo.idxs[0].resize(cell_count);
2498        for (uint32_t i = 0; i < cell_count; ++i) {
2499            sinfo.idxs[0][i] = i;
2500        }
2501
2502        head = 0;
2503    }
2504
2505    return true;
2506}
2507
2508bool llama_kv_cache::state_read_data(llama_io_read_i & io, uint32_t strm, uint32_t cell_count, const slot_info & sinfo) {
2509    auto & cells = v_cells[strm];
2510
2511    // batch the scatter reads per contiguous run of destination indices
2512    // from inclusive, to exclusive - same convention as cell_ranges_t
2513    // contiguous cells yield a single run covering the whole block
2514    struct cell_run { uint32_t from; uint32_t to; };
2515    std::vector<cell_run> runs;
2516    if (cell_count > 0) {
2517        const auto & idxs = sinfo.idxs[0];
2518        uint32_t i0 = 0;
2519        while (i0 < cell_count) {
2520            uint32_t i1 = i0 + 1;
2521            while (i1 < cell_count && idxs[i1] == idxs[i1 - 1] + 1) {
2522                ++i1;
2523            }
2524            runs.push_back({idxs[i0], idxs[i1 - 1] + 1});
2525            i0 = i1;
2526        }
2527    }
2528
2529    uint32_t v_trans;
2530    uint32_t n_layer;
2531
2532    io.read(&v_trans, sizeof(v_trans));
2533    io.read(&n_layer, sizeof(n_layer));
2534
2535    if (n_layer != layers.size()) {
2536        LLAMA_LOG_ERROR("%s: mismatched layer count (%u instead of %u)\n", __func__, n_layer, (uint32_t) layers.size());
2537        return false;
2538    }
2539
2540    if (cell_count > cells.size()) {
2541        LLAMA_LOG_ERROR("%s: not enough cells in kv cache to restore state (%u > %u)\n", __func__, cell_count, cells.size());
2542        return false;
2543    }
2544
2545    if (this->v_trans != (bool) v_trans) {
2546        LLAMA_LOG_ERROR("%s: incompatible V transposition\n", __func__);
2547        return false;
2548    }
2549
2550    // For each layer, read the keys for each cell, one row is one cell, read as one contiguous block
2551    for (const auto & layer : layers) {
2552        const uint32_t il = layer.il;
2553
2554        const uint32_t n_embd_k_gqa = hparams.n_embd_k_gqa(il);
2555
2556        auto * k = layer.k_stream[strm];
2557
2558        // Read type of key
2559        int32_t k_type_i_ref;
2560        io.read(&k_type_i_ref, sizeof(k_type_i_ref));
2561        const int32_t k_type_i = (int32_t) k->type;
2562        if (k_type_i != k_type_i_ref) {
2563            LLAMA_LOG_ERROR("%s: mismatched key type (%d != %d, layer %d)\n", __func__, k_type_i, k_type_i_ref, il);
2564            return false;
2565        }
2566
2567        // Read row size of key
2568        uint64_t k_size_row_ref;
2569        io.read(&k_size_row_ref, sizeof(k_size_row_ref));
2570        const size_t k_size_row = ggml_row_size(k->type, n_embd_k_gqa);
2571        if (k_size_row != k_size_row_ref) {
2572            LLAMA_LOG_ERROR("%s: mismatched key row size (%zu != %zu, layer %d)\n", __func__, k_size_row, (size_t) k_size_row_ref, il);
2573            return false;
2574        }
2575
2576        for (const auto & r : runs) {
2577            io.read_tensor(k, (size_t) r.from * k_size_row, (size_t) (r.to - r.from) * k_size_row);
2578        }
2579    }
2580
2581    if (!this->v_trans) {
2582        for (const auto & layer : layers) {
2583            const uint32_t il = layer.il;
2584
2585            const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(il);
2586
2587            auto * v = layer.v_stream[strm];
2588            if (!v) {
2589                continue;
2590            }
2591
2592            // Read type of value
2593            int32_t v_type_i_ref;
2594            io.read(&v_type_i_ref, sizeof(v_type_i_ref));
2595            const int32_t v_type_i = (int32_t) v->type;
2596            if (v_type_i != v_type_i_ref) {
2597                LLAMA_LOG_ERROR("%s: mismatched value type (%d != %d, layer %d)\n", __func__, v_type_i, v_type_i_ref, il);
2598                return false;
2599            }
2600
2601            // Read row size of value
2602            uint64_t v_size_row_ref;
2603            io.read(&v_size_row_ref, sizeof(v_size_row_ref));
2604            const size_t v_size_row = ggml_row_size(v->type, n_embd_v_gqa);
2605            if (v_size_row != v_size_row_ref) {
2606                LLAMA_LOG_ERROR("%s: mismatched value row size (%zu != %zu, layer %d)\n", __func__, v_size_row, (size_t) v_size_row_ref, il);
2607                return false;
2608            }
2609
2610            for (const auto & r : runs) {
2611                io.read_tensor(v, (size_t) r.from * v_size_row, (size_t) (r.to - r.from) * v_size_row);
2612            }
2613        }
2614    } else {
2615        // For each layer, read the values for each cell (transposed)
2616        for (const auto & layer : layers) {
2617            const uint32_t il = layer.il;
2618
2619            const uint32_t n_embd_v_gqa = hparams.n_embd_v_gqa(il);
2620
2621            auto * v = layer.v_stream[strm];
2622            if (!v) {
2623                continue;
2624            }
2625
2626            // Read type of value
2627            int32_t v_type_i_ref;
2628            io.read(&v_type_i_ref, sizeof(v_type_i_ref));
2629            const int32_t v_type_i = (int32_t) v->type;
2630            if (v_type_i != v_type_i_ref) {
2631                LLAMA_LOG_ERROR("%s: mismatched value type (%d != %d, layer %d)\n", __func__, v_type_i, v_type_i_ref, il);
2632                return false;
2633            }
2634
2635            // Read element size of value
2636            uint32_t v_size_el_ref;
2637            io.read(&v_size_el_ref, sizeof(v_size_el_ref));
2638            const size_t v_size_el = ggml_type_size(v->type);
2639            if (v_size_el != v_size_el_ref) {
2640                LLAMA_LOG_ERROR("%s: mismatched value element size (%zu != %zu, layer %d)\n", __func__, v_size_el, (size_t) v_size_el_ref, il);
2641                return false;
2642            }
2643
2644            // Read GQA embedding size
2645            uint32_t n_embd_v_gqa_ref;
2646            io.read(&n_embd_v_gqa_ref, sizeof(n_embd_v_gqa_ref));
2647            if (n_embd_v_gqa != n_embd_v_gqa_ref) {
2648                LLAMA_LOG_ERROR("%s: mismatched GQA embedding size (%u != %u, layer %d)\n", __func__, n_embd_v_gqa, n_embd_v_gqa_ref, il);
2649                return false;
2650            }
2651
2652            for (uint32_t j = 0; j < n_embd_v_gqa; ++j) {
2653                for (const auto & r : runs) {
2654                    const size_t dst_offset = ((size_t) r.from + j * cells.size()) * v_size_el;
2655                    io.read_tensor(v, dst_offset, (size_t) (r.to - r.from) * v_size_el);
2656                }
2657            }
2658        }
2659    }
2660
2661    return true;
2662}
2663
2664//
2665// llama_kv_cache_context
2666//
2667
2668llama_kv_cache_context::llama_kv_cache_context(llama_memory_status status) : status(status) {}
2669
2670llama_kv_cache_context::llama_kv_cache_context(
2671        llama_kv_cache * kv) : status(LLAMA_MEMORY_STATUS_SUCCESS), kv(kv) {
2672    n_kv = kv->get_size();
2673
2674    const uint32_t n_stream = kv->get_n_stream();
2675
2676    // create a dummy slot info - the actual data is irrelevant. we just need to build the graph
2677    sinfos.resize(1);
2678    sinfos[0].s0 = 0;
2679    sinfos[0].s1 = n_stream - 1;
2680    sinfos[0].idxs.resize(n_stream);
2681    for (uint32_t s = 0; s < n_stream; ++s) {
2682        sinfos[0].strm.push_back(s);
2683        sinfos[0].idxs[s].resize(1, 0);
2684    }
2685}
2686
2687llama_kv_cache_context::llama_kv_cache_context(
2688        llama_kv_cache * kv,
2689        llama_context * lctx,
2690        bool do_shift,
2691        stream_copy_info sc_info) : status(LLAMA_MEMORY_STATUS_SUCCESS), kv(kv), lctx(lctx), do_shift(do_shift), sc_info(std::move(sc_info)) {
2692    if (!do_shift && this->sc_info.empty()) {
2693        status = LLAMA_MEMORY_STATUS_NO_UPDATE;
2694    }
2695}
2696
2697llama_kv_cache_context::llama_kv_cache_context(
2698        llama_kv_cache * kv,
2699        llama_kv_cache::slot_info_vec_t sinfos,
2700        std::vector<llama_ubatch> ubatches) : status(LLAMA_MEMORY_STATUS_SUCCESS), kv(kv), sinfos(std::move(sinfos)), ubatches(std::move(ubatches)) {
2701}
2702
2703llama_kv_cache_context::~llama_kv_cache_context() = default;
2704
2705bool llama_kv_cache_context::next() {
2706    assert(status == LLAMA_MEMORY_STATUS_SUCCESS);
2707
2708    if (++i_cur >= ubatches.size()) {
2709        return false;
2710    }
2711
2712    return true;
2713}
2714
2715bool llama_kv_cache_context::apply() {
2716    assert(!llama_memory_status_is_fail(status));
2717
2718    // no ubatches -> this is a KV cache update
2719    if (ubatches.empty()) {
2720        kv->update(lctx, do_shift, sc_info);
2721
2722        return true;
2723    }
2724
2725    kv->apply_ubatch(sinfos[i_cur], ubatches[i_cur]);
2726    n_kv = kv->get_n_kv(sinfos[i_cur]);
2727
2728    return true;
2729}
2730
2731llama_memory_status llama_kv_cache_context::get_status() const {
2732    return status;
2733}
2734
2735const llama_ubatch & llama_kv_cache_context::get_ubatch() const {
2736    assert(status == LLAMA_MEMORY_STATUS_SUCCESS);
2737
2738    return ubatches[i_cur];
2739}
2740
2741uint32_t llama_kv_cache_context::get_n_kv() const {
2742    return n_kv;
2743}
2744
2745ggml_type llama_kv_cache_context::type_k() const {
2746    return kv->type_k();
2747}
2748
2749ggml_type llama_kv_cache_context::type_v() const {
2750    return kv->type_v();
2751}
2752
2753ggml_tensor * llama_kv_cache_context::get_k(ggml_context * ctx, int32_t il) const {
2754    return kv->get_k(ctx, il, n_kv, sinfos[i_cur]);
2755}
2756
2757ggml_tensor * llama_kv_cache_context::get_v(ggml_context * ctx, int32_t il) const {
2758    return kv->get_v(ctx, il, n_kv, sinfos[i_cur]);
2759}
2760
2761ggml_tensor * llama_kv_cache_context::cpy_k(ggml_context * ctx, ggml_tensor * k_cur, ggml_tensor * k_idxs, int32_t il) const {
2762    return kv->cpy_k(ctx, k_cur, k_idxs, il, sinfos[i_cur]);
2763}
2764
2765ggml_tensor * llama_kv_cache_context::cpy_v(ggml_context * ctx, ggml_tensor * v_cur, ggml_tensor * v_idxs, int32_t il) const {
2766    return kv->cpy_v(ctx, v_cur, v_idxs, il, sinfos[i_cur]);
2767}
2768
2769ggml_tensor * llama_kv_cache_context::build_input_k_idxs(ggml_context * ctx, const llama_ubatch & ubatch) const {
2770    return kv->build_input_k_idxs(ctx, ubatch);
2771}
2772
2773ggml_tensor * llama_kv_cache_context::build_input_v_idxs(ggml_context * ctx, const llama_ubatch & ubatch) const {
2774    return kv->build_input_v_idxs(ctx, ubatch);
2775}
2776
2777ggml_tensor * llama_kv_cache_context::build_input_k_rot(ggml_context * ctx) const {
2778    return kv->build_input_k_rot(ctx);
2779}
2780
2781ggml_tensor * llama_kv_cache_context::build_input_v_rot(ggml_context * ctx) const {
2782    return kv->build_input_v_rot(ctx);
2783}
2784
2785void llama_kv_cache_context::set_input_k_shift(ggml_tensor * dst) const {
2786    kv->set_input_k_shift(dst);
2787}
2788
2789void llama_kv_cache_context::set_input_k_idxs(ggml_tensor * dst, const llama_ubatch * ubatch) const {
2790    kv->set_input_k_idxs(dst, ubatch, sinfos[i_cur]);
2791}
2792
2793void llama_kv_cache_context::set_input_v_idxs(ggml_tensor * dst, const llama_ubatch * ubatch) const {
2794    kv->set_input_v_idxs(dst, ubatch, sinfos[i_cur]);
2795}
2796
2797void llama_kv_cache_context::set_input_kq_mask(ggml_tensor * dst, const llama_ubatch * ubatch, bool causal_attn) const {
2798    kv->set_input_kq_mask(dst, ubatch, causal_attn);
2799}
2800
2801void llama_kv_cache_context::set_input_pos_bucket(ggml_tensor * dst, const llama_ubatch * ubatch) const {
2802    kv->set_input_pos_bucket(dst, ubatch);
2803}
2804
2805void llama_kv_cache_context::set_input_k_rot(ggml_tensor * dst) const {
2806    kv->set_input_k_rot(dst);
2807}
2808
2809void llama_kv_cache_context::set_input_v_rot(ggml_tensor * dst) const {
2810    kv->set_input_v_rot(dst);
2811}
2812
2813void llama_kv_cache_context::get_prev_tokens(const llama_ubatch & ubatch, uint32_t n, std::vector<llama_token> & res) const {
2814    kv->get_prev_tokens(ubatch, n, res);
2815}