Coverage Report

Created: 2026-06-13 06:23

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