Coverage Report

Created: 2026-07-16 06:35

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/llama.cpp/src/llama-memory-recurrent.cpp
Line
Count
Source
1
#include "llama-memory-recurrent.h"
2
3
#include "ggml-backend.h"
4
#include "llama-impl.h"
5
#include "llama-io.h"
6
#include "llama-batch.h"
7
#include "llama-model.h"
8
9
#include <algorithm>
10
#include <cassert>
11
#include <cstring>
12
#include <limits>
13
#include <map>
14
#include <stdexcept>
15
16
//
17
// llama_memory_recurrent
18
//
19
20
llama_memory_recurrent::llama_memory_recurrent(
21
        const llama_model & model,
22
                ggml_type   type_r,
23
                ggml_type   type_s,
24
                     bool   offload,
25
                 uint32_t   mem_size,
26
                 uint32_t   n_seq_max,
27
                 uint32_t   n_rs_seq,
28
0
    const layer_filter_cb & filter) : hparams(model.hparams), n_seq_max(n_seq_max) {
29
0
    const int32_t n_layer = hparams.n_layer();
30
31
0
    head = 0;
32
0
    size = mem_size;
33
0
    used = 0;
34
35
0
    this->n_rs_seq = n_rs_seq;
36
0
    rs_idx.assign(n_seq_max, 0);
37
38
0
    cells.clear();
39
0
    cells.resize(mem_size);
40
41
    // define a comparator for the buft -> ctx map to ensure that the order is well-defined:
42
0
    struct ggml_backend_buft_comparator {
43
0
        bool operator()(const ggml_backend_buffer_type_t & lhs, const ggml_backend_buffer_type_t & rhs) const {
44
0
            return strcmp(ggml_backend_buft_name(lhs), ggml_backend_buft_name(rhs)) < 0;
45
0
        }
46
0
    };
47
0
    std::map<ggml_backend_buffer_type_t, ggml_context_ptr, ggml_backend_buft_comparator> ctx_map;
48
49
    // create a context for each buffer type
50
0
    auto ctx_for_buft = [&](ggml_backend_buffer_type_t buft) -> ggml_context * {
51
0
        auto it = ctx_map.find(buft);
52
0
        if (it == ctx_map.end()) {
53
0
            ggml_init_params params = {
54
0
                /*.mem_size   =*/ size_t(2u*n_layer*ggml_tensor_overhead()),
55
0
                /*.mem_buffer =*/ NULL,
56
0
                /*.no_alloc   =*/ true,
57
0
            };
58
59
0
            ggml_context * ctx = ggml_init(params);
60
0
            if (!ctx) {
61
0
                return nullptr;
62
0
            }
63
64
0
            ctx_map.emplace(buft, ctx);
65
66
0
            return ctx;
67
0
        }
68
69
0
        return it->second.get();
70
0
    };
71
72
0
    r_l.resize(n_layer);
73
0
    s_l.resize(n_layer);
74
75
0
    for (int i = 0; i < n_layer; i++) {
76
0
        if (filter && !filter(i)) {
77
0
            LLAMA_LOG_DEBUG("%s: layer %3d: skipped\n", __func__, i);
78
0
            continue;
79
0
        }
80
81
0
        const char * dev_name = "CPU";
82
83
0
        ggml_backend_buffer_type_t buft = ggml_backend_cpu_buffer_type();
84
85
0
        if (offload) {
86
0
            auto * dev = model.dev_layer(i);
87
0
            buft = ggml_backend_dev_buffer_type(dev);
88
89
0
            dev_name = ggml_backend_dev_name(dev);
90
0
        }
91
92
0
        LLAMA_LOG_DEBUG("%s, layer %3d: dev = %s\n", __func__, i, dev_name);
93
94
0
        ggml_context * ctx = ctx_for_buft(buft);
95
0
        if (!ctx) {
96
0
            throw std::runtime_error("failed to create ggml context for rs cache");
97
0
        }
98
99
0
        const uint32_t n_rows = mem_size * (1 + n_rs_seq);
100
0
        ggml_tensor * r = ggml_new_tensor_2d(ctx, type_r, hparams.n_embd_r(), n_rows);
101
0
        ggml_tensor * s = ggml_new_tensor_2d(ctx, type_s, hparams.n_embd_s(), n_rows);
102
0
        ggml_format_name(r, "cache_r_l%d", i);
103
0
        ggml_format_name(s, "cache_s_l%d", i);
104
0
        r_l[i] = r;
105
0
        s_l[i] = s;
106
0
    }
107
108
    // allocate tensors and initialize the buffers to avoid NaNs in the padding
109
0
    for (auto & [buft, ctx] : ctx_map) {
110
0
        ggml_backend_buffer_t buf = ggml_backend_alloc_ctx_tensors_from_buft(ctx.get(), buft);
111
0
        if (!buf) {
112
0
            throw std::runtime_error("failed to allocate buffer for rs cache");
113
0
        }
114
0
        ggml_backend_buffer_clear(buf, 0);
115
0
        LLAMA_LOG_INFO("%s: %10s RS buffer size = %8.2f MiB\n", __func__, ggml_backend_buffer_name(buf), ggml_backend_buffer_get_size(buf)/1024.0/1024.0);
116
0
        ctxs_bufs.emplace_back(std::move(ctx), buf);
117
0
    }
118
119
0
    {
120
0
        const size_t memory_size_r = size_r_bytes();
121
0
        const size_t memory_size_s = size_s_bytes();
122
123
0
        LLAMA_LOG_INFO("%s: size = %7.2f MiB (%6u cells, %3d layers, %2u seqs %2u rs_seq), R (%s): %7.2f MiB, S (%s): %7.2f MiB\n", __func__,
124
0
                (float)(memory_size_r + memory_size_s) / (1024.0f * 1024.0f), mem_size, n_layer, n_seq_max, n_rs_seq,
125
0
                ggml_type_name(type_r), (float)memory_size_r / (1024.0f * 1024.0f),
126
0
                ggml_type_name(type_s), (float)memory_size_s / (1024.0f * 1024.0f));
127
0
    }
128
0
}
129
130
0
void llama_memory_recurrent::clear(bool data) {
131
0
    for (int32_t i = 0; i < (int32_t) size; ++i) {
132
0
        cells[i].pos = -1;
133
0
        cells[i].seq_id.clear();
134
0
        cells[i].src = -1;
135
0
        cells[i].tail = -1;
136
0
    }
137
138
0
    head = 0;
139
0
    used = 0;
140
141
0
    if (data) {
142
0
        for (auto & [_, buf] : ctxs_bufs) {
143
0
            ggml_backend_buffer_clear(buf.get(), 0);
144
0
        }
145
0
    }
146
147
0
    std::fill(rs_idx.begin(), rs_idx.end(), 0);
148
0
}
149
150
0
bool llama_memory_recurrent::seq_rm(llama_seq_id seq_id, llama_pos p0, llama_pos p1) {
151
0
    uint32_t new_head = size;
152
153
0
    if (p0 < 0) {
154
0
        p0 = 0;
155
0
    }
156
157
0
    if (p1 < 0) {
158
0
        p1 = std::numeric_limits<llama_pos>::max();
159
0
    }
160
161
0
    const bool rm_all = p0 == 0 && p1 == std::numeric_limits<llama_pos>::max();
162
0
    if (rm_all) {
163
0
        if (seq_id >= 0) {
164
0
            set_rs_idx(seq_id, 0);
165
0
        } else {
166
0
            std::fill(rs_idx.begin(), rs_idx.end(), 0);
167
0
        }
168
0
    }
169
170
    // models like Mamba or RWKV can't have a state partially erased at the end
171
    // of the sequence because their state isn't preserved for previous tokens
172
0
    if (seq_id >= (int64_t) size) {
173
        // could be fatal
174
0
        return false;
175
0
    }
176
0
    if (0 <= seq_id) {
177
0
        int32_t & tail_id = cells[seq_id].tail;
178
0
        if (tail_id >= 0) {
179
0
            auto & cell = cells[tail_id];
180
181
            // partial rollback via per-token snapshot index (bounded by n_rs_seq)
182
0
            if (0 < p0 && p0 <= cell.pos && p1 > cell.pos) {
183
0
                const llama_pos rollback = cell.pos - (p0 - 1);
184
0
                if (rollback >= 1 && rollback <= (llama_pos) n_rs_seq) {
185
0
                    set_rs_idx(seq_id, (uint32_t) rollback);
186
0
                    cell.pos = p0 - 1;
187
0
                    return true;
188
0
                }
189
0
                return false;
190
0
            }
191
            // invalidate tails which will be cleared
192
0
            if (p0 <= cell.pos && cell.pos < p1) {
193
0
                tail_id = -1;
194
0
            }
195
0
        }
196
0
    } else {
197
        // seq_id is negative, then the range should include everything or nothing
198
0
        if (p0 != p1 && (p0 != 0 || p1 != std::numeric_limits<llama_pos>::max())) {
199
            //printf("[DEBUG] inside `llama_memory_recurrent::seq_rm`: `seq_id` is negative, so returning false\n");
200
0
            return false;
201
0
        }
202
0
    }
203
204
0
    for (uint32_t i = 0; i < size; ++i) {
205
0
        if (cells[i].pos >= p0 && cells[i].pos < p1) {
206
0
            if (seq_id < 0) {
207
0
                cells[i].seq_id.clear();
208
0
            } else if (cells[i].has_seq_id(seq_id)) {
209
0
                cells[i].seq_id.erase(seq_id);
210
0
            } else {
211
0
                continue;
212
0
            }
213
0
            if (cells[i].is_empty()) {
214
                // keep count of the number of used cells
215
0
                if (cells[i].pos >= 0) {
216
0
                    used--;
217
0
                }
218
0
                cells[i].pos = -1;
219
0
                cells[i].src = -1;
220
0
                if (new_head == size) {
221
0
                    new_head = i;
222
0
                }
223
0
            }
224
0
        }
225
0
    }
226
227
    // If we freed up a slot, set head to it so searching can start there.
228
0
    if (new_head != size && new_head < head) {
229
0
        head = new_head;
230
0
    }
231
232
0
    return true;
233
0
}
234
235
0
void llama_memory_recurrent::seq_cp(llama_seq_id seq_id_src, llama_seq_id seq_id_dst, llama_pos p0, llama_pos p1) {
236
0
    if (seq_id_src == seq_id_dst) {
237
0
        return;
238
0
    }
239
240
0
    if (p0 < 0) {
241
0
        p0 = 0;
242
0
    }
243
244
0
    if (p1 < 0) {
245
0
        p1 = std::numeric_limits<llama_pos>::max();
246
0
    }
247
248
0
    if ((uint32_t) seq_id_dst < size && (uint32_t) seq_id_src < size) {
249
0
        auto & tail_src = cells[seq_id_src];
250
0
        auto & tail_dst = cells[seq_id_dst];
251
0
        if (tail_dst.tail >= 0) {
252
            // clear destination seq_id if it wasn't empty
253
0
            auto & cell_dst = cells[tail_dst.tail];
254
255
0
            cell_dst.seq_id.erase(seq_id_dst);
256
0
            tail_dst.tail = -1;
257
0
            if (cell_dst.seq_id.empty()) {
258
0
                cell_dst.pos = -1;
259
0
                cell_dst.src = -1;
260
0
                used -= 1;
261
0
            }
262
0
        }
263
0
        if (tail_src.tail >= 0) {
264
0
            auto & cell_src = cells[tail_src.tail];
265
266
0
            cell_src.seq_id.insert(seq_id_dst);
267
0
            tail_dst.tail = tail_src.tail;
268
0
        }
269
0
    }
270
0
}
271
272
0
void llama_memory_recurrent::seq_keep(llama_seq_id seq_id) {
273
0
    uint32_t new_head = size;
274
275
0
    for (uint32_t i = 0; i < size; ++i) {
276
0
        if ((llama_seq_id) i != seq_id) {
277
0
            cells[i].tail = -1;
278
0
        }
279
280
0
        if (!cells[i].has_seq_id(seq_id)) {
281
0
            if (cells[i].pos >= 0) {
282
0
                used--;
283
0
            }
284
285
0
            cells[i].pos = -1;
286
0
            cells[i].src = -1;
287
0
            cells[i].seq_id.clear();
288
289
0
            if (new_head == size){
290
0
                new_head = i;
291
0
            }
292
0
        } else {
293
0
            cells[i].seq_id.clear();
294
0
            cells[i].seq_id.insert(seq_id);
295
0
        }
296
0
    }
297
298
    // If we freed up a slot, set head to it so searching can start there.
299
0
    if (new_head != size && new_head < head) {
300
0
        head = new_head;
301
0
    }
302
0
}
303
304
0
void llama_memory_recurrent::seq_add(llama_seq_id seq_id, llama_pos p0, llama_pos p1, llama_pos shift) {
305
0
    if (shift == 0) {
306
0
        return;
307
0
    }
308
309
0
    if (p0 < 0) {
310
0
        p0 = 0;
311
0
    }
312
313
0
    if (p1 < 0) {
314
0
        p1 = std::numeric_limits<llama_pos>::max();
315
0
    }
316
317
    // If there is no range then return early to avoid looping over the
318
0
    if (p0 == p1) {
319
0
        return;
320
0
    }
321
322
    // for Mamba-like or RWKV models, only the pos needs to be shifted
323
0
    if (0 <= seq_id && seq_id < (int64_t) size) {
324
0
        const int32_t tail_id = cells[seq_id].tail;
325
0
        if (tail_id >= 0) {
326
0
            auto & cell = cells[tail_id];
327
0
            if (cell.has_seq_id(seq_id) && p0 <= cell.pos && cell.pos < p1) {
328
0
                cell.pos += shift;
329
0
            }
330
0
        }
331
0
    }
332
0
}
333
334
0
void llama_memory_recurrent::seq_div(llama_seq_id seq_id, llama_pos p0, llama_pos p1, int d) {
335
0
    if (d == 1) {
336
0
        return;
337
0
    }
338
339
0
    if (p0 < 0) {
340
0
        p0 = 0;
341
0
    }
342
343
0
    if (p1 < 0) {
344
0
        p1 = std::numeric_limits<llama_pos>::max();
345
0
    }
346
347
    // If there is no range then return early to avoid looping over the cache.
348
0
    if (p0 == p1) {
349
0
        return;
350
0
    }
351
352
    // for Mamba-like or RWKV models, only the pos needs to be changed
353
0
    if (0 <= seq_id && seq_id < (int64_t) size) {
354
0
        const int32_t tail_id = cells[seq_id].tail;
355
0
        if (tail_id >= 0) {
356
0
            auto & cell = cells[tail_id];
357
0
            if (cell.has_seq_id(seq_id) && p0 <= cell.pos && cell.pos < p1) {
358
0
                cell.pos /= d;
359
0
            }
360
0
        }
361
0
    }
362
0
}
363
364
0
llama_pos llama_memory_recurrent::seq_pos_min(llama_seq_id seq_id) const {
365
0
    llama_pos result = std::numeric_limits<llama_pos>::max();
366
367
0
    for (uint32_t i = 0; i < size; ++i) {
368
0
        if (cells[i].has_seq_id(seq_id)) {
369
0
            result = std::min(result, cells[i].pos);
370
0
        }
371
0
    }
372
373
0
    if (result == std::numeric_limits<llama_pos>::max()) {
374
0
        result = -1;
375
0
    }
376
377
0
    return result;
378
0
}
379
380
0
llama_pos llama_memory_recurrent::seq_pos_max(llama_seq_id seq_id) const {
381
0
    llama_pos result = -1;
382
383
0
    for (uint32_t i = 0; i < size; ++i) {
384
0
        if (cells[i].has_seq_id(seq_id)) {
385
0
            result = std::max(result, cells[i].pos);
386
0
        }
387
0
    }
388
389
0
    return result;
390
0
}
391
392
0
void llama_memory_recurrent::set_rs_idx(llama_seq_id seq_id, uint32_t idx) {
393
0
    if (seq_id < 0 || (size_t) seq_id >= rs_idx.size()) {
394
0
        return;
395
0
    }
396
0
    rs_idx[seq_id] = (idx > n_rs_seq) ? n_rs_seq : idx;
397
0
}
398
399
0
std::map<ggml_backend_buffer_type_t, size_t> llama_memory_recurrent::memory_breakdown() const {
400
0
    std::map<ggml_backend_buffer_type_t, size_t> ret;
401
0
    for (const auto & [_, buf] : ctxs_bufs) {
402
0
        ret[ggml_backend_buffer_get_type(buf.get())] += ggml_backend_buffer_get_size(buf.get());
403
0
    }
404
0
    return ret;
405
0
}
406
407
0
llama_memory_context_ptr llama_memory_recurrent::init_batch(llama_batch_allocr & balloc, uint32_t n_ubatch, bool embd_all) {
408
0
    do {
409
0
        balloc.split_reset();
410
411
0
        std::vector<llama_ubatch> ubatches;
412
0
        while (true) {
413
0
            llama_ubatch ubatch;
414
415
0
            if (embd_all) {
416
                // if all tokens are output, split by sequence
417
0
                ubatch = balloc.split_seq(n_ubatch);
418
0
            } else {
419
                // TODO: non-sequential equal split can be done if using unified KV cache
420
                //       for simplicity, we always use sequential equal split for now
421
                // [TAG_RECURRENT_ROLLBACK_SPLITS]
422
                // the trailing (1 + n_rs_seq) tokens of each seq must stay in the same ubatch
423
                //   so that the rollback snapshots remain valid
424
0
                ubatch = balloc.split_equal(n_ubatch, true, n_rs_seq > 0 ? n_rs_seq + 1 : 0);
425
0
            }
426
427
0
            if (ubatch.n_tokens == 0) {
428
0
                break;
429
0
            }
430
431
0
            ubatches.push_back(std::move(ubatch)); // NOLINT
432
0
        }
433
434
0
        if (balloc.get_n_used() < balloc.get_n_tokens()) {
435
            // failed to find a suitable split
436
0
            break;
437
0
        }
438
439
0
        if (!prepare(ubatches)) {
440
0
            break;
441
0
        }
442
443
0
        return std::make_unique<llama_memory_recurrent_context>(this, std::move(ubatches));
444
0
    } while (false);
445
446
0
    return std::make_unique<llama_memory_recurrent_context>(LLAMA_MEMORY_STATUS_FAILED_PREPARE);
447
0
}
448
449
0
llama_memory_context_ptr llama_memory_recurrent::init_full() {
450
0
    return std::make_unique<llama_memory_recurrent_context>(this);
451
0
}
452
453
0
llama_memory_context_ptr llama_memory_recurrent::init_update(llama_context * lctx, bool optimize) {
454
0
    GGML_UNUSED(lctx);
455
0
    GGML_UNUSED(optimize);
456
457
0
    return std::make_unique<llama_memory_recurrent_context>(LLAMA_MEMORY_STATUS_NO_UPDATE);
458
0
}
459
460
0
bool llama_memory_recurrent::prepare(const std::vector<llama_ubatch> & ubatches) {
461
    // simply remember the full state because it is very small for this type of cache
462
    // TODO: optimize
463
0
    auto org_cells = cells;
464
0
    auto org_used = used;
465
0
    auto org_head = head;
466
467
0
    bool success = true;
468
469
0
    for (const auto & ubatch : ubatches) {
470
0
        if (!find_slot(ubatch)) {
471
0
            success = false;
472
0
            break;
473
0
        }
474
0
    }
475
476
    // restore the original state
477
0
    cells = std::move(org_cells);
478
0
    used = org_used;
479
0
    head = org_head;
480
481
0
    return success;
482
0
}
483
484
0
bool llama_memory_recurrent::find_slot(const llama_ubatch & ubatch) {
485
0
    const uint32_t n_seq_tokens = ubatch.n_seq_tokens;
486
0
    const uint32_t n_seqs       = ubatch.n_seqs;
487
488
    // if we have enough unused cells before the current head ->
489
    //   better to start searching from the beginning of the cache, hoping to fill it
490
0
    if (head > used + 2*n_seqs) {
491
0
        head = 0;
492
0
    }
493
494
    // For recurrent state architectures (like Mamba or RWKV),
495
    // each cache cell can store the state for a whole sequence.
496
    // A slot should be always be contiguous.
497
498
    // can only process batches with an equal number of new tokens in each sequence
499
0
    GGML_ASSERT(ubatch.equal_seqs());
500
501
0
    int32_t min = size - 1;
502
0
    int32_t max = 0;
503
504
    // everything should fit if all seq_ids are smaller than the max
505
0
    for (uint32_t s = 0; s < n_seqs; ++s) {
506
0
        const uint32_t i = s*n_seq_tokens; // first token of sequence set s
507
0
        const uint32_t n_seq_id = ubatch.n_seq_id[i];
508
509
0
        for (uint32_t j = 0; j < n_seq_id; ++j) {
510
0
            const llama_seq_id seq_id = ubatch.seq_id[i][j];
511
512
0
            if (seq_id < 0 || (uint32_t) seq_id >= size) {
513
                // too big seq_id
514
                // TODO: would it be possible to resize the cache instead?
515
0
                LLAMA_LOG_ERROR("%s: seq_id=%d >= n_seq_max=%u Try using a bigger --parallel value\n", __func__, seq_id, n_seq_max);
516
0
                return false;
517
0
            }
518
0
            if (j > 0) {
519
0
                auto & seq = cells[seq_id];
520
0
                if (seq.tail >= 0) {
521
0
                    auto & cell = cells[seq.tail];
522
                    // clear cells from seq_ids that become shared
523
                    // (should not normally happen, but let's handle it anyway)
524
0
                    cell.seq_id.erase(seq_id);
525
0
                    seq.tail = -1;
526
0
                    if (cell.seq_id.empty()) {
527
0
                        cell.pos = -1;
528
0
                        cell.src = -1;
529
0
                        used -= 1;
530
0
                    }
531
0
                }
532
0
            }
533
0
        }
534
0
    }
535
536
#ifndef NDEBUG
537
    {
538
        std::vector<int32_t> tails_verif;
539
        tails_verif.assign(size, -1);
540
        for (uint32_t i = 0; i < size; ++i) {
541
            auto & cell = cells[i];
542
            for (llama_seq_id seq_id : cell.seq_id) {
543
                if (tails_verif[seq_id] != -1) {
544
                    LLAMA_LOG_ERROR("%s: duplicate tail for seq_id %d in cell %d and %d\n", __func__, seq_id, i, tails_verif[seq_id]);
545
                }
546
                tails_verif[seq_id] = i;
547
            }
548
        }
549
        for (uint32_t i = 0; i < size; ++i) {
550
            if (tails_verif[i] != cells[i].tail) {
551
                LLAMA_LOG_ERROR("%s: wrong tail for seq_id %d, (%d instead of %d)\n", __func__, i, cells[i].tail, tails_verif[i]);
552
            }
553
        }
554
    }
555
#endif
556
557
    // find next empty cell
558
0
    uint32_t next_empty_cell = head;
559
560
0
    for (uint32_t i = 0; i < size; ++i) {
561
0
        if (next_empty_cell >= size) { next_empty_cell -= size; }
562
0
        auto & cell = cells[next_empty_cell];
563
0
        if (cell.is_empty()) { break; }
564
0
        next_empty_cell += 1;
565
0
    }
566
567
    // find usable cell range
568
0
    for (uint32_t s = 0; s < n_seqs; ++s) {
569
0
        const uint32_t i = s*n_seq_tokens;
570
0
        const llama_seq_id seq_id = ubatch.seq_id[i][0];
571
0
        auto & seq_meta = cells[seq_id];
572
0
        bool has_cell = false;
573
0
        if (seq_meta.tail >= 0) {
574
0
            auto & cell = cells[seq_meta.tail];
575
0
            GGML_ASSERT(cell.has_seq_id(seq_id));
576
            // does this seq_id "own" the cell?
577
0
            if (cell.seq_id.size() == 1) { has_cell = true; }
578
0
        }
579
0
        if (!has_cell) {
580
0
            auto & empty_cell = cells[next_empty_cell];
581
0
            GGML_ASSERT(empty_cell.is_empty());
582
            // copy old tail into the empty cell
583
0
            if (seq_meta.tail >= 0) {
584
0
                auto & orig_cell = cells[seq_meta.tail];
585
0
                empty_cell.pos = orig_cell.pos;
586
0
                empty_cell.src = orig_cell.src;
587
0
                orig_cell.seq_id.erase(seq_id);
588
0
                empty_cell.seq_id.insert(seq_id); // will be overwritten
589
0
                GGML_ASSERT(!orig_cell.is_empty()); // has at least one remaining seq_id
590
0
            }
591
0
            seq_meta.tail = next_empty_cell;
592
            // find next empty cell
593
0
            if (s + 1 < n_seqs) {
594
0
                for (uint32_t j = 0; j < size; ++j) {
595
0
                    next_empty_cell += 1;
596
0
                    if (next_empty_cell >= size) { next_empty_cell -= size; }
597
0
                    auto & cell = cells[next_empty_cell];
598
0
                    if (cell.is_empty()) { break; }
599
0
                }
600
0
            }
601
0
        }
602
0
        if (min > seq_meta.tail) { min = seq_meta.tail; }
603
0
        if (max < seq_meta.tail) { max = seq_meta.tail; }
604
0
    }
605
606
    // gather and re-order
607
0
    for (uint32_t s = 0; s < n_seqs; ++s) {
608
0
        const uint32_t i = s*n_seq_tokens;
609
0
        const int32_t dst_id = s + min;
610
0
        const int32_t src_id = cells[ubatch.seq_id[i][0]].tail;
611
0
        if (dst_id != src_id) {
612
0
            auto & dst_cell = cells[dst_id];
613
0
            auto & src_cell = cells[src_id];
614
615
0
            std::swap(dst_cell.pos, src_cell.pos);
616
0
            std::swap(dst_cell.src, src_cell.src);
617
0
            std::swap(dst_cell.seq_id, src_cell.seq_id);
618
619
            // swap tails
620
0
            for (uint32_t j = 0; j < size; ++j) {
621
0
                int32_t & tail = cells[j].tail;
622
0
                if (tail == src_id) {
623
0
                    tail = dst_id;
624
0
                } else if (tail == dst_id) {
625
0
                    tail = src_id;
626
0
                }
627
0
            }
628
0
        }
629
0
    }
630
631
    // update the pos of the used seqs
632
0
    for (uint32_t s = 0; s < n_seqs; ++s) {
633
0
        const uint32_t i = s*n_seq_tokens;
634
0
        const llama_pos last_pos = ubatch.pos[i + n_seq_tokens - 1];
635
0
        const int32_t cell_id = s + min;
636
0
        auto & cell = cells[cell_id];
637
638
0
        if (cell.pos >= 0 && last_pos != cell.pos + (llama_pos) n_seq_tokens) {
639
            // What should happen when the pos backtracks or skips a value?
640
            // Clearing the state mid-batch would require special-casing which isn't done.
641
0
            LLAMA_LOG_WARN("%s: non-consecutive token position %d after %d for sequence %d with %u new tokens\n",
642
0
                __func__, last_pos, cell.pos, ubatch.seq_id[i][0], n_seq_tokens);
643
0
        }
644
0
        cell.pos = last_pos;
645
0
        cell.seq_id.clear();
646
0
        for (int32_t j = 0; j < ubatch.n_seq_id[i]; ++j) {
647
0
            const llama_seq_id seq_id = ubatch.seq_id[i][j];
648
0
            cell.seq_id.insert(seq_id);
649
0
            cells[seq_id].tail = cell_id;
650
0
        }
651
0
    }
652
653
    // Find first cell without src refs, to use as the zero-ed state
654
0
    {
655
        // TODO: bake-in src refcounts in the cell metadata
656
0
        std::vector<int32_t> refcounts(size, 0);
657
0
        for (size_t i = 0; i < size; ++i) {
658
0
            const int32_t src = cells[i].src;
659
0
            if (src >= 0) {
660
0
                refcounts[src] += 1;
661
0
            }
662
0
        }
663
664
0
        rs_z = -1;
665
0
        for (int i = min; i <= max; ++i) {
666
0
            if (refcounts[i] == 0) {
667
0
                rs_z = i;
668
0
                break;
669
0
            }
670
0
        }
671
672
0
        for (int i = min; i <= max; ++i) {
673
0
            if (cells[i].src < 0) {
674
0
                GGML_ASSERT(rs_z >= 0);
675
0
                cells[i].src0 = rs_z;
676
0
            } else {
677
                // Stage the source ids for all used cells to allow correct seq_* behavior
678
                // and still make these values available when setting the inputs
679
0
                cells[i].src0 = cells[i].src;
680
0
            }
681
0
            cells[i].src = i; // avoid moving or clearing twice
682
0
        }
683
0
    }
684
685
    // allow getting the range of used cells, from head to head + n
686
0
    head = min;
687
0
    n    = max - min + 1;
688
0
    used = std::count_if(cells.begin(), cells.end(),
689
0
        [](const mem_cell & cell){ return !cell.is_empty(); });
690
691
    // sanity check
692
0
    return n >= n_seqs;
693
0
}
694
695
0
bool llama_memory_recurrent::get_can_shift() const {
696
    // shifting the pos is trivial for recurrent models
697
0
    return true;
698
0
}
699
700
0
size_t llama_memory_recurrent::total_size() const {
701
0
    size_t size = 0;
702
0
    for (const auto & [_, buf] : ctxs_bufs) {
703
0
        size += ggml_backend_buffer_get_size(buf.get());
704
0
    }
705
706
0
    return size;
707
0
}
708
709
0
size_t llama_memory_recurrent::size_r_bytes() const {
710
0
    size_t size_r_bytes = 0;
711
712
0
    for (const auto & r : r_l) {
713
0
        if (r != nullptr) {
714
0
            size_r_bytes += ggml_nbytes(r);
715
0
        }
716
0
    }
717
718
0
    return size_r_bytes;
719
0
}
720
721
0
size_t llama_memory_recurrent::size_s_bytes() const {
722
0
    size_t size_s_bytes = 0;
723
724
0
    for (const auto & s : s_l) {
725
0
        if (s != nullptr) {
726
0
            size_s_bytes += ggml_nbytes(s);
727
0
        }
728
0
    }
729
730
0
    return size_s_bytes;
731
0
}
732
733
0
void llama_memory_recurrent::state_write(llama_io_write_i & io, llama_seq_id seq_id, llama_state_seq_flags flags) const {
734
0
    GGML_UNUSED(flags);
735
736
0
    std::vector<std::pair<uint32_t, uint32_t>> cell_ranges; // ranges, from inclusive, to exclusive
737
0
    std::vector<std::pair<uint32_t, uint32_t>> cell_ranges_data; // logical source row ranges
738
0
    uint32_t cell_count = 0;
739
740
    // Count the number of cells with the specified seq_id
741
    // Find all the ranges of cells with this seq id (or all, when -1)
742
0
    uint32_t cell_range_begin = size;
743
0
    for (uint32_t i = 0; i < size; ++i) {
744
0
        const auto & cell = cells[i];
745
0
        if ((seq_id == -1 && !cell.is_empty()) || cell.has_seq_id(seq_id)) {
746
0
            ++cell_count;
747
0
            uint32_t rs_idx_cur = 0;
748
749
0
            if (n_rs_seq != 0) {
750
0
                if (seq_id != -1) {
751
0
                    GGML_ASSERT(seq_id >= 0 && (size_t) seq_id < rs_idx.size());
752
0
                    rs_idx_cur = rs_idx[seq_id];
753
0
                } else {
754
0
                    bool has_rs_idx = false;
755
0
                    for (const llama_seq_id cell_seq_id : cell.seq_id) {
756
0
                        GGML_ASSERT(cell_seq_id >= 0 && (size_t) cell_seq_id < rs_idx.size());
757
758
0
                        const uint32_t seq_rs_idx = rs_idx[cell_seq_id];
759
0
                        if (!has_rs_idx) {
760
0
                            rs_idx_cur = seq_rs_idx;
761
0
                            has_rs_idx = true;
762
0
                        } else if (rs_idx_cur != seq_rs_idx) {
763
0
                            GGML_ABORT("cannot write shared recurrent state with different rollback indices");
764
0
                        }
765
0
                    }
766
0
                }
767
0
            }
768
769
0
            const uint32_t cell_id = rs_idx_cur * size + (cell.src >= 0 ? cell.src : (int32_t) i);
770
0
            if (cell_ranges_data.empty() || cell_ranges_data.back().second != cell_id) {
771
0
                cell_ranges_data.emplace_back(cell_id, cell_id + 1);
772
0
            } else {
773
0
                cell_ranges_data.back().second++;
774
0
            }
775
776
0
            if (cell_range_begin == size) {
777
0
                cell_range_begin = i;
778
0
            }
779
0
        } else {
780
0
            if (cell_range_begin != size) {
781
0
                cell_ranges.emplace_back(cell_range_begin, i);
782
0
                cell_range_begin = size;
783
0
            }
784
0
        }
785
0
    }
786
0
    if (cell_range_begin != size) {
787
0
        cell_ranges.emplace_back(cell_range_begin, size);
788
0
    }
789
790
0
    if ((flags & LLAMA_STATE_SEQ_FLAGS_ON_DEVICE) && cell_ranges.size() > 1) {
791
0
        GGML_ABORT("cannot save/load multiple ranges of cells to/from device memory\n");
792
0
    }
793
794
    // DEBUG CHECK: Sum of cell counts in ranges should equal the total cell count
795
0
    uint32_t cell_count_check = 0;
796
0
    for (const auto & range : cell_ranges) {
797
0
        cell_count_check += range.second - range.first;
798
0
    }
799
0
    GGML_ASSERT(cell_count == cell_count_check);
800
801
0
    cell_count_check = 0;
802
0
    for (const auto & range : cell_ranges_data) {
803
0
        cell_count_check += range.second - range.first;
804
0
    }
805
0
    GGML_ASSERT(cell_count == cell_count_check);
806
807
0
    io.write(&cell_count, sizeof(cell_count));
808
809
0
    state_write_meta(io, cell_ranges, seq_id);
810
0
    state_write_data(io, cell_ranges_data);
811
0
}
812
813
0
void llama_memory_recurrent::state_read(llama_io_read_i & io, llama_seq_id seq_id, llama_state_seq_flags flags) {
814
0
    GGML_UNUSED(flags);
815
816
0
    uint32_t cell_count;
817
0
    io.read(&cell_count, sizeof(cell_count));
818
819
0
    bool res = true;
820
821
0
    res = res && state_read_meta(io, cell_count, seq_id);
822
0
    res = res && state_read_data(io, cell_count);
823
824
0
    if (!res) {
825
0
        if (seq_id == -1) {
826
0
            clear(true);
827
0
        } else {
828
0
            seq_rm(seq_id, -1, -1);
829
0
        }
830
0
        throw std::runtime_error("failed to restore kv cache");
831
0
    }
832
833
0
    if (n_rs_seq != 0) {
834
0
        if (seq_id == -1) {
835
0
            std::fill(rs_idx.begin(), rs_idx.end(), 0);
836
0
        } else {
837
0
            set_rs_idx(seq_id, 0);
838
0
        }
839
0
    }
840
0
}
841
842
0
void llama_memory_recurrent::state_write_meta(llama_io_write_i & io, const std::vector<std::pair<uint32_t, uint32_t>> & cell_ranges, llama_seq_id seq_id) const {
843
0
    for (const auto & range : cell_ranges) {
844
0
        for (uint32_t i = range.first; i < range.second; ++i) {
845
0
            const auto & cell = cells[i];
846
0
            const llama_pos pos      = cell.pos;
847
0
            const uint32_t  n_seq_id = seq_id == -1 ? cell.seq_id.size() : 0;
848
849
0
            io.write(&pos,      sizeof(pos));
850
0
            io.write(&n_seq_id, sizeof(n_seq_id));
851
852
0
            if (n_seq_id) {
853
0
                for (auto seq_id : cell.seq_id) {
854
0
                    io.write(&seq_id, sizeof(seq_id));
855
0
                }
856
0
            }
857
0
        }
858
0
    }
859
0
}
860
861
0
void llama_memory_recurrent::state_write_data(llama_io_write_i & io, const std::vector<std::pair<uint32_t, uint32_t>> & cell_ranges) const {
862
0
    const uint32_t s_trans = 0;
863
0
    const uint32_t n_layer = hparams.n_layer();
864
865
0
    io.write(&s_trans, sizeof(s_trans));
866
0
    io.write(&n_layer, sizeof(n_layer));
867
868
    // Iterate and write all the R tensors first, each row is a cell
869
    // Get whole range at a time
870
0
    for (uint32_t il = 0; il < n_layer; ++il) {
871
        // skip null layers (read_data will handle this by checking "r_l" and "s_l" for null)
872
0
        if (r_l[il] == nullptr) continue;
873
874
        // Write R tensor type
875
0
        const int32_t r_type_i = (int32_t)r_l[il]->type;
876
0
        io.write(&r_type_i, sizeof(r_type_i));
877
878
        // Write row size of R tensor
879
0
        const uint64_t r_size_row = ggml_row_size(r_l[il]->type, hparams.n_embd_r());
880
0
        io.write(&r_size_row, sizeof(r_size_row));
881
882
        // Write each logical cell row range. With pending recurrent rollback,
883
        // the logical current state may live in a rollback snapshot plane.
884
0
        for (const auto & range : cell_ranges) {
885
0
            const size_t range_size = range.second - range.first;
886
0
            const size_t buf_size = range_size * r_size_row;
887
0
            io.write_tensor(r_l[il], range.first * r_size_row, buf_size);
888
0
        }
889
0
    }
890
891
0
    if (!s_trans) {
892
0
        for (uint32_t il = 0; il < n_layer; ++il) {
893
            // skip null layers (read_data will handle this by checking "r_l" and "s_l" for null)
894
0
            if (s_l[il] == nullptr) continue;
895
896
            // Write S tensor type
897
0
            const int32_t s_type_i = (int32_t)s_l[il]->type;
898
0
            io.write(&s_type_i, sizeof(s_type_i));
899
900
            // Write row size of S tensor
901
0
            const uint64_t s_size_row = ggml_row_size(s_l[il]->type, hparams.n_embd_s());
902
0
            io.write(&s_size_row, sizeof(s_size_row));
903
904
            // Write each logical cell row range. With pending recurrent rollback,
905
            // the logical current state may live in a rollback snapshot plane.
906
0
            for (const auto & range : cell_ranges) {
907
0
                const size_t range_size = range.second - range.first;
908
0
                const size_t buf_size = range_size * s_size_row;
909
0
                io.write_tensor(s_l[il], range.first * s_size_row, buf_size);
910
0
            }
911
0
        }
912
0
    } else {
913
        // When S tensor is transposed, we also need the element size and get the element ranges from each row
914
0
        const uint32_t mem_size = size;
915
0
        for (uint32_t il = 0; il < n_layer; ++il) {
916
            // skip null layers (read_data will handle this by checking "r_l" and "s_l" for null)
917
0
            if (s_l[il] == nullptr) continue;
918
919
0
            const uint32_t n_embd_s = hparams.n_embd_s();
920
921
            // Write S tensor type
922
0
            const int32_t s_type_i = (int32_t)s_l[il]->type;
923
0
            io.write(&s_type_i, sizeof(s_type_i));
924
925
            // Write element size
926
0
            const uint32_t s_size_el = ggml_type_size(s_l[il]->type);
927
0
            io.write(&s_size_el, sizeof(s_size_el));
928
929
            // Write GQA embedding size
930
0
            io.write(&n_embd_s, sizeof(n_embd_s));
931
932
            // For each row, we get the element values of each logical cell
933
0
            for (uint32_t j = 0; j < n_embd_s; ++j) {
934
0
                for (const auto & range : cell_ranges) {
935
0
                    const size_t range_size = range.second - range.first;
936
0
                    const size_t src_offset = (range.first + j * mem_size) * s_size_el;
937
0
                    const size_t buf_size = range_size * s_size_el;
938
0
                    io.write_tensor(s_l[il], src_offset, buf_size);
939
0
                }
940
0
            }
941
0
        }
942
0
    }
943
0
}
944
945
0
bool llama_memory_recurrent::state_read_meta(llama_io_read_i & io, uint32_t cell_count, llama_seq_id dest_seq_id) {
946
0
    if (dest_seq_id != -1) {
947
        // single sequence
948
0
        seq_rm(dest_seq_id, -1, -1);
949
950
0
        if (cell_count == 0) {
951
0
            return true;
952
0
        }
953
954
0
        llama_batch_allocr balloc(hparams.n_pos_per_embd());
955
956
0
        llama_ubatch ubatch = balloc.ubatch_reserve(cell_count, 1);
957
958
0
        for (uint32_t i = 0; i < cell_count; ++i) {
959
0
            llama_pos pos;
960
0
            uint32_t n_seq_id;
961
962
0
            io.read(&pos,      sizeof(pos));
963
0
            io.read(&n_seq_id, sizeof(n_seq_id));
964
965
0
            if (n_seq_id != 0) {
966
0
                LLAMA_LOG_ERROR("%s: invalid seq_id-agnostic kv cell\n", __func__);
967
0
                return false;
968
0
            }
969
970
0
            ubatch.pos[i] = pos;
971
0
        }
972
0
        ubatch.n_seq_id[0] = 1;
973
0
        ubatch.seq_id[0] = &dest_seq_id;
974
975
0
        if (!find_slot(ubatch)) {
976
0
            LLAMA_LOG_ERROR("%s: failed to find available cells in kv cache\n", __func__);
977
0
            return false;
978
0
        }
979
980
        // DEBUG CHECK: kv.head should be our first cell, kv.head + cell_count - 1 should be our last cell (verify seq_id and pos values)
981
        // Assume that this is one contiguous block of cells
982
0
        GGML_ASSERT(head + cell_count <= size);
983
0
        GGML_ASSERT(cells[head].pos == ubatch.pos[0]);
984
0
        GGML_ASSERT(cells[head + cell_count - 1].pos == ubatch.pos[cell_count - 1]);
985
0
        GGML_ASSERT(cells[head].has_seq_id(dest_seq_id));
986
0
        GGML_ASSERT(cells[head + cell_count - 1].has_seq_id(dest_seq_id));
987
0
    } else {
988
        // whole KV cache restore
989
990
0
        if (cell_count > size) {
991
0
            LLAMA_LOG_ERROR("%s: not enough cells in kv cache\n", __func__);
992
0
            return false;
993
0
        }
994
995
0
        clear(true);
996
997
0
        for (uint32_t i = 0; i < cell_count; ++i) {
998
0
            auto & cell = cells[i];
999
1000
0
            llama_pos pos;
1001
0
            uint32_t  n_seq_id;
1002
1003
0
            io.read(&pos,      sizeof(pos));
1004
0
            io.read(&n_seq_id, sizeof(n_seq_id));
1005
1006
0
            cell.pos = pos;
1007
1008
0
            for (uint32_t j = 0; j < n_seq_id; ++j) {
1009
0
                llama_seq_id seq_id;
1010
0
                io.read(&seq_id, sizeof(seq_id));
1011
1012
0
                if (seq_id < 0 || (uint32_t) seq_id >= this->n_seq_max) {
1013
0
                    LLAMA_LOG_ERROR("%s: invalid seq_id, %d is out of range [0, %u)\n", __func__, seq_id, this->n_seq_max);
1014
0
                    return false;
1015
0
                }
1016
1017
0
                cell.seq_id.insert(seq_id);
1018
1019
0
                int32_t & tail = cells[seq_id].tail;
1020
0
                if (tail != -1) {
1021
0
                    LLAMA_LOG_ERROR("%s: duplicate tail for seq_id %d in cell %d and %d\n", __func__, seq_id, i, tail);
1022
0
                    return false;
1023
0
                }
1024
0
                tail = i;
1025
0
            }
1026
0
        }
1027
1028
0
        head = 0;
1029
0
        used = cell_count;
1030
0
    }
1031
1032
0
    for (uint32_t i = 0; i < cell_count; ++i) {
1033
0
        uint32_t cell_id = head + i;
1034
        // make sure the recurrent states will keep their restored state
1035
0
        cells[cell_id].src = cell_id;
1036
0
    }
1037
1038
0
    return true;
1039
0
}
1040
1041
0
bool llama_memory_recurrent::state_read_data(llama_io_read_i & io, uint32_t cell_count) {
1042
0
    uint32_t s_trans;
1043
0
    uint32_t n_layer;
1044
0
    io.read(&s_trans, sizeof(s_trans));
1045
0
    io.read(&n_layer, sizeof(n_layer));
1046
1047
0
    if (n_layer != hparams.n_layer()) {
1048
0
        LLAMA_LOG_ERROR("%s: mismatched layer count (%u instead of %u)\n", __func__, n_layer, hparams.n_layer());
1049
0
        return false;
1050
0
    }
1051
0
    if (cell_count > size) {
1052
0
        LLAMA_LOG_ERROR("%s: not enough cells in kv cache to restore state (%u > %u)\n", __func__, cell_count, size);
1053
0
        return false;
1054
0
    }
1055
0
    if (false != (bool) s_trans) {
1056
0
        LLAMA_LOG_ERROR("%s: incompatible s transposition\n", __func__);
1057
0
        return false;
1058
0
    }
1059
1060
    // For each layer, read the keys for each cell, one row is one cell, read as one contiguous block
1061
0
    for (uint32_t il = 0; il < n_layer; ++il) {
1062
        // skip null layers
1063
0
        if (r_l[il] == nullptr) continue;
1064
1065
        // Read type of key
1066
0
        int32_t r_type_i_ref;
1067
0
        io.read(&r_type_i_ref, sizeof(r_type_i_ref));
1068
0
        const int32_t r_type_i = (int32_t) r_l[il]->type;
1069
0
        if (r_type_i != r_type_i_ref) {
1070
0
            LLAMA_LOG_ERROR("%s: mismatched r type (%d != %d, layer %d)\n", __func__, r_type_i, r_type_i_ref, il);
1071
0
            return false;
1072
0
        }
1073
1074
        // Read row size of key
1075
0
        uint64_t r_size_row_ref;
1076
0
        io.read(&r_size_row_ref, sizeof(r_size_row_ref));
1077
0
        const size_t r_size_row = ggml_row_size(r_l[il]->type, hparams.n_embd_r());
1078
0
        if (r_size_row != r_size_row_ref) {
1079
0
            LLAMA_LOG_ERROR("%s: mismatched r row size (%zu != %zu, layer %d)\n", __func__, r_size_row, (size_t) r_size_row_ref, il);
1080
0
            return false;
1081
0
        }
1082
1083
0
        if (cell_count) {
1084
            // Read and set the keys for the whole cell range
1085
0
            io.read_tensor(r_l[il], head * r_size_row, cell_count * r_size_row);
1086
0
        }
1087
0
    }
1088
1089
0
    if (!s_trans) {
1090
0
        for (uint32_t il = 0; il < n_layer; ++il) {
1091
            // skip null layers
1092
0
            if (s_l[il] == nullptr) continue;
1093
1094
            // Read type of value
1095
0
            int32_t s_type_i_ref;
1096
0
            io.read(&s_type_i_ref, sizeof(s_type_i_ref));
1097
0
            const int32_t s_type_i = (int32_t)s_l[il]->type;
1098
1099
0
            if (s_type_i != s_type_i_ref) {
1100
0
                LLAMA_LOG_ERROR("%s: mismatched s type (%d != %d, layer %d)\n", __func__, s_type_i, s_type_i_ref, il);
1101
0
                return false;
1102
0
            }
1103
1104
            // Read row size of value
1105
0
            uint64_t s_size_row_ref;
1106
0
            io.read(&s_size_row_ref, sizeof(s_size_row_ref));
1107
0
            const size_t s_size_row = ggml_row_size(s_l[il]->type, hparams.n_embd_s());
1108
0
            if (s_size_row != s_size_row_ref) {
1109
0
                LLAMA_LOG_ERROR("%s: mismatched s row size (%zu != %zu, layer %d)\n", __func__, s_size_row, (size_t) s_size_row_ref, il);
1110
0
                return false;
1111
0
            }
1112
1113
0
            if (cell_count) {
1114
                // Read and set the values for the whole cell range
1115
0
                io.read_tensor(s_l[il], head * s_size_row, cell_count * s_size_row);
1116
0
            }
1117
0
        }
1118
0
    } else {
1119
        // For each layer, read the values for each cell (transposed)
1120
0
        for (uint32_t il = 0; il < n_layer; ++il) {
1121
            // skip null layers
1122
0
            if (s_l[il] == nullptr) continue;
1123
1124
0
            const uint32_t n_embd_s = hparams.n_embd_s();
1125
1126
            // Read type of value
1127
0
            int32_t s_type_i_ref;
1128
0
            io.read(&s_type_i_ref, sizeof(s_type_i_ref));
1129
0
            const int32_t s_type_i = (int32_t)s_l[il]->type;
1130
0
            if (s_type_i != s_type_i_ref) {
1131
0
                LLAMA_LOG_ERROR("%s: mismatched s type (%d != %d, layer %d)\n", __func__, s_type_i, s_type_i_ref, il);
1132
0
                return false;
1133
0
            }
1134
1135
            // Read element size of value
1136
0
            uint32_t s_size_el_ref;
1137
0
            io.read(&s_size_el_ref, sizeof(s_size_el_ref));
1138
0
            const size_t s_size_el = ggml_type_size(s_l[il]->type);
1139
0
            if (s_size_el != s_size_el_ref) {
1140
0
                LLAMA_LOG_ERROR("%s: mismatched s element size (%zu != %zu, layer %d)\n", __func__, s_size_el, (size_t) s_size_el_ref, il);
1141
0
                return false;
1142
0
            }
1143
1144
            // Read state embedding size
1145
0
            uint32_t n_embd_s_ref;
1146
0
            io.read(&n_embd_s_ref, sizeof(n_embd_s_ref));
1147
0
            if (n_embd_s != n_embd_s_ref) {
1148
0
                LLAMA_LOG_ERROR("%s: mismatched s embedding size (%u != %u, layer %d)\n", __func__, n_embd_s, n_embd_s_ref, il);
1149
0
                return false;
1150
0
            }
1151
1152
0
            if (cell_count) {
1153
                // For each row in the transposed matrix, read the values for the whole cell range
1154
0
                for (uint32_t j = 0; j < n_embd_s; ++j) {
1155
0
                    const size_t dst_offset = (head + j * size) * s_size_el;
1156
0
                    io.read_tensor(s_l[il], dst_offset, cell_count * s_size_el);
1157
0
                }
1158
0
            }
1159
0
        }
1160
0
    }
1161
1162
0
    return true;
1163
0
}
1164
1165
//
1166
// llama_memory_recurrent_context
1167
//
1168
1169
0
llama_memory_recurrent_context::llama_memory_recurrent_context(llama_memory_status status) : status(status) {}
1170
1171
llama_memory_recurrent_context::llama_memory_recurrent_context(
1172
0
        llama_memory_recurrent * mem) : status(LLAMA_MEMORY_STATUS_SUCCESS), mem(mem), is_full(true) {
1173
0
}
1174
1175
llama_memory_recurrent_context::llama_memory_recurrent_context(
1176
        llama_memory_recurrent * mem,
1177
0
        std::vector<llama_ubatch> ubatches) : status(LLAMA_MEMORY_STATUS_SUCCESS), mem(mem), ubatches(std::move(ubatches)) {}
1178
1179
0
llama_memory_recurrent_context::~llama_memory_recurrent_context() = default;
1180
1181
0
bool llama_memory_recurrent_context::next() {
1182
0
    assert(status == LLAMA_MEMORY_STATUS_SUCCESS);
1183
1184
0
    if (++i_next >= ubatches.size()) {
1185
0
        return false;
1186
0
    }
1187
1188
0
    return true;
1189
0
}
1190
1191
0
bool llama_memory_recurrent_context::apply() {
1192
0
    assert(!llama_memory_status_is_fail(status));
1193
1194
    // no ubatches -> this is an update
1195
0
    if (ubatches.empty()) {
1196
        // recurrent cache never performs updates
1197
0
        assert(status == LLAMA_MEMORY_STATUS_NO_UPDATE);
1198
1199
0
        return true;
1200
0
    }
1201
1202
0
    mem->find_slot(ubatches[i_next]);
1203
1204
0
    return true;
1205
0
}
1206
1207
0
llama_memory_status llama_memory_recurrent_context::get_status() const {
1208
0
    return status;
1209
0
}
1210
1211
0
const llama_ubatch & llama_memory_recurrent_context::get_ubatch() const {
1212
0
    assert(status == LLAMA_MEMORY_STATUS_SUCCESS);
1213
1214
0
    return ubatches[i_next];
1215
0
}
1216
1217
0
uint32_t llama_memory_recurrent_context::get_n_rs() const {
1218
0
    return is_full ? mem->size : mem->n;
1219
0
}
1220
1221
0
uint32_t llama_memory_recurrent_context::get_head() const {
1222
0
    return is_full ? 0 : mem->head;
1223
0
}
1224
1225
0
int32_t llama_memory_recurrent_context::get_rs_z() const {
1226
0
    return is_full ? 0 : mem->rs_z;
1227
0
}
1228
1229
0
uint32_t llama_memory_recurrent_context::get_size() const {
1230
0
    return mem->size;
1231
0
}
1232
1233
0
ggml_tensor * llama_memory_recurrent_context::get_r_l(int32_t il) const {
1234
0
    return mem->r_l[il];
1235
0
}
1236
1237
0
ggml_tensor * llama_memory_recurrent_context::get_s_l(int32_t il) const {
1238
0
    return mem->s_l[il];
1239
0
}
1240
1241
0
int32_t llama_memory_recurrent_context::s_copy(int i) const {
1242
0
    const uint32_t cell_idx = i + mem->head;
1243
0
    const int32_t  src0     = mem->cells[cell_idx].src0;
1244
1245
0
    if (mem->n_rs_seq == 0) {
1246
0
        return src0;
1247
0
    }
1248
1249
0
    uint32_t idx = 0;
1250
0
    if (!mem->cells[cell_idx].seq_id.empty()) {
1251
0
        const llama_seq_id seq = *mem->cells[cell_idx].seq_id.begin();
1252
0
        if (seq >= 0 && (size_t) seq < mem->rs_idx.size()) {
1253
0
            idx = mem->rs_idx[seq];
1254
            // reset rollback idx
1255
0
            mem->rs_idx[seq] = 0;
1256
0
        }
1257
0
    }
1258
0
    return (int32_t)(idx * mem->size) + src0;
1259
0
}