Coverage Report

Created: 2026-01-18 06:10

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/llama.cpp/src/llama-context.cpp
Line
Count
Source
1
#include "llama-context.h"
2
3
#include "llama-arch.h"
4
#include "llama-impl.h"
5
#include "llama-batch.h"
6
#include "llama-io.h"
7
#include "llama-memory.h"
8
#include "llama-mmap.h"
9
#include "llama-model.h"
10
11
#include <cinttypes>
12
#include <cmath>
13
#include <cstring>
14
#include <limits>
15
#include <stdexcept>
16
17
//
18
// llama_context
19
//
20
21
llama_context::llama_context(
22
        const llama_model & model,
23
              llama_context_params params) :
24
0
    model(model),
25
0
    balloc(std::make_unique<llama_batch_allocr>(model.hparams.n_pos_per_embd())) {
26
    // TODO warning when creating llama_context with awkward ctx size that is not a power of 2,
27
    //     may need to be backend-dependent
28
0
    LLAMA_LOG_INFO("%s: constructing llama_context\n", __func__);
29
30
0
    t_start_us = model.t_start_us;
31
0
    t_load_us  = model.t_load_us;
32
33
0
    const auto & hparams = model.hparams;
34
35
0
    cparams.n_seq_max = std::max(1u, params.n_seq_max);
36
0
    if (cparams.n_seq_max > LLAMA_MAX_SEQ) {
37
0
        throw std::runtime_error("n_seq_max must be <= " + std::to_string(LLAMA_MAX_SEQ));
38
0
    }
39
40
0
    cparams.n_threads        = params.n_threads;
41
0
    cparams.n_threads_batch  = params.n_threads_batch;
42
0
    cparams.yarn_ext_factor  = params.yarn_ext_factor  >= 0.0f ? params.yarn_ext_factor  : hparams.yarn_ext_factor;
43
0
    cparams.yarn_attn_factor = params.yarn_attn_factor >= 0.0f ? params.yarn_attn_factor : hparams.yarn_attn_factor;
44
0
    cparams.yarn_beta_fast   = params.yarn_beta_fast   >= 0.0f ? params.yarn_beta_fast   : hparams.yarn_beta_fast;
45
0
    cparams.yarn_beta_slow   = params.yarn_beta_slow   >= 0.0f ? params.yarn_beta_slow   : hparams.yarn_beta_slow;
46
0
    cparams.embeddings       = params.embeddings;
47
0
    cparams.offload_kqv      = params.offload_kqv;
48
0
    cparams.no_perf          = params.no_perf;
49
0
    cparams.pooling_type     = params.pooling_type;
50
0
    cparams.warmup           = false;
51
52
0
    cparams.n_ctx            = params.n_ctx           == 0    ? hparams.n_ctx_train           : params.n_ctx;
53
0
    cparams.rope_freq_base   = params.rope_freq_base  == 0.0f ? hparams.rope_freq_base_train  : params.rope_freq_base;
54
0
    cparams.rope_freq_scale  = params.rope_freq_scale == 0.0f ? hparams.rope_freq_scale_train : params.rope_freq_scale;
55
56
0
    cparams.n_ctx_orig_yarn  = params.yarn_orig_ctx    != 0 ? params.yarn_orig_ctx    :
57
0
                               hparams.n_ctx_orig_yarn != 0 ? hparams.n_ctx_orig_yarn :
58
0
                                                              hparams.n_ctx_train;
59
60
0
    cparams.cb_eval           = params.cb_eval;
61
0
    cparams.cb_eval_user_data = params.cb_eval_user_data;
62
63
    // Initialize backend samplers here so they are part of the sampling graph
64
    // before the reserve passes run later in this function. This avoids a later
65
    // re-reserve when graph nodes change.
66
0
    if (params.samplers != nullptr && params.n_samplers > 0) {
67
0
        for (size_t i = 0; i < params.n_samplers; ++i) {
68
0
            const auto & config = params.samplers[i];
69
70
0
            if (llama_sampler_chain_get(config.sampler, -1) == nullptr) {
71
0
                throw std::runtime_error("the backend samplers must be of type llama_sampler_chain");
72
0
            }
73
74
0
            if (set_sampler(config.seq_id, config.sampler)) {
75
0
                const int n_samplers = llama_sampler_chain_n(config.sampler);
76
77
0
                LLAMA_LOG_INFO("%s: setting backend sampler for seq_id %d (n = %d)\n", __func__, config.seq_id, n_samplers);
78
0
            }
79
0
        }
80
0
    }
81
82
0
    auto rope_scaling_type = params.rope_scaling_type;
83
0
    if (rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED) {
84
0
        rope_scaling_type = hparams.rope_scaling_type_train;
85
0
    }
86
87
0
    if (rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_NONE) {
88
0
        cparams.rope_freq_scale = 1.0f; // never scale if scaling type is none
89
0
    }
90
91
0
    if (cparams.yarn_ext_factor < 0.0f) { // negative indicates 'not set'
92
0
        cparams.yarn_ext_factor = rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_YARN ? 1.0f : 0.0f;
93
0
    }
94
95
0
    if (cparams.yarn_ext_factor != 0) {
96
0
        static auto get_mscale = [](float scale, float mscale) {
97
0
            return scale <= 1.0f ? 1.0f : (0.1f * mscale * logf(scale) + 1.0f);
98
0
        };
99
100
0
        const float factor = 1.0f / cparams.rope_freq_scale;
101
102
        // ref: https://github.com/huggingface/transformers/blob/6d00f6b0a5679c36510f203e4226e36f517c3032/src/transformers/modeling_rope_utils.py#L336-L348
103
0
        if (hparams.rope_yarn_log_mul != 0.0f) {
104
            // note: here we assume `mscale == 1.0f`
105
            // TODO: start reading the actual value of mscale and handle the case where it is not 1.0f
106
0
                  float mscale          = 1.0f;
107
0
            const float mscale_all_dims = hparams.rope_yarn_log_mul;
108
109
            // [TAG_DEEPSEEK2_YARN_LOG_MUL_FIX]
110
            // special-case DEEPSEEK v2:
111
            // https://huggingface.co/deepseek-ai/DeepSeek-V2-Lite-Chat/blob/main/config.json#L42-L43
112
0
            if (model.arch == LLM_ARCH_DEEPSEEK2 && mscale_all_dims != 1.0f) {
113
0
                mscale = mscale_all_dims;
114
0
            }
115
116
0
            cparams.yarn_attn_factor = get_mscale(factor, mscale) / get_mscale(factor, mscale_all_dims);
117
118
0
            LLAMA_LOG_WARN("%s: setting new yarn_attn_factor = %.4f (mscale == %.1f, mscale_all_dim = %.1f)\n",
119
0
                    __func__, cparams.yarn_attn_factor, mscale, mscale_all_dims);
120
0
        } else {
121
0
            cparams.yarn_attn_factor = get_mscale(factor, 1.0f);
122
0
        }
123
124
        // when YARN is applied with yarn_ext_factor != 0.0f, we need to cancel this factor:
125
        // https://github.com/ggml-org/llama.cpp/blob/a81a569577cc38b32558958b048228150be63eae/ggml/src/ggml-cpu/ops.cpp#L5541-L5544
126
        //
127
        // ref: https://github.com/ggml-org/llama.cpp/discussions/7416
128
        //      https://github.com/ggml-org/llama.cpp/pull/17945
129
0
        cparams.yarn_attn_factor *= 1.0f / (1.0f + 0.1f * logf(factor));
130
0
    }
131
132
0
    cparams.yarn_attn_factor *= hparams.rope_attn_factor;
133
134
0
    if (cparams.pooling_type == LLAMA_POOLING_TYPE_UNSPECIFIED) {
135
0
        if (hparams.pooling_type == LLAMA_POOLING_TYPE_UNSPECIFIED) {
136
0
            cparams.pooling_type = LLAMA_POOLING_TYPE_NONE;
137
0
        } else {
138
0
            cparams.pooling_type = hparams.pooling_type;
139
0
        }
140
0
    }
141
142
0
    if (params.attention_type == LLAMA_ATTENTION_TYPE_UNSPECIFIED) {
143
0
        cparams.causal_attn = hparams.causal_attn;
144
0
    } else {
145
0
        cparams.causal_attn = params.attention_type == LLAMA_ATTENTION_TYPE_CAUSAL;
146
0
    }
147
148
0
    cparams.flash_attn = params.flash_attn_type != LLAMA_FLASH_ATTN_TYPE_DISABLED;
149
0
    cparams.auto_fa    = params.flash_attn_type == LLAMA_FLASH_ATTN_TYPE_AUTO;
150
151
    // with causal attention, the batch size is limited by the context size
152
0
    cparams.n_batch = cparams.causal_attn ? std::min(cparams.n_ctx, params.n_batch) : params.n_batch;
153
154
0
    cparams.n_ubatch = std::min(cparams.n_batch, params.n_ubatch == 0 ? params.n_batch : params.n_ubatch);
155
156
0
    cparams.op_offload = params.op_offload;
157
0
    cparams.kv_unified = params.kv_unified;
158
159
    // intialized later
160
0
    cparams.pipeline_parallel = false;
161
162
0
    {
163
0
        const char * LLAMA_GRAPH_REUSE_DISABLE = getenv("LLAMA_GRAPH_REUSE_DISABLE");
164
0
        graph_reuse_disable = LLAMA_GRAPH_REUSE_DISABLE ? (atoi(LLAMA_GRAPH_REUSE_DISABLE) != 0) : graph_reuse_disable;
165
166
0
        if (graph_reuse_disable) {
167
0
            LLAMA_LOG_WARN("%s: graph reuse disabled\n", __func__);
168
0
        }
169
0
    }
170
171
    // ref: https://github.com/ggml-org/llama.cpp/pull/17046#discussion_r2503085732
172
0
    cparams.n_ctx = GGML_PAD(cparams.n_ctx, 256);
173
174
0
    if (cparams.kv_unified) {
175
0
        cparams.n_ctx_seq = cparams.n_ctx;
176
0
    } else {
177
0
        cparams.n_ctx_seq = cparams.n_ctx / cparams.n_seq_max;
178
0
        cparams.n_ctx_seq = GGML_PAD(cparams.n_ctx_seq, 256);
179
180
0
        if (cparams.n_ctx_seq == 0) {
181
0
            throw std::runtime_error("n_ctx_seq == 0");
182
0
        }
183
184
0
        if (cparams.n_ctx != cparams.n_ctx_seq * cparams.n_seq_max) {
185
0
            cparams.n_ctx =  cparams.n_ctx_seq * cparams.n_seq_max;
186
0
            LLAMA_LOG_WARN("%s: n_ctx is not divisible by n_seq_max - rounding down to %u\n", __func__, cparams.n_ctx);
187
0
        }
188
0
    }
189
190
0
    LLAMA_LOG_INFO("%s: n_seq_max     = %u\n",   __func__, cparams.n_seq_max);
191
0
    LLAMA_LOG_INFO("%s: n_ctx         = %u\n",   __func__, cparams.n_ctx);
192
0
    LLAMA_LOG_INFO("%s: n_ctx_seq     = %u\n",   __func__, cparams.n_ctx_seq);
193
0
    LLAMA_LOG_INFO("%s: n_batch       = %u\n",   __func__, cparams.n_batch);
194
0
    LLAMA_LOG_INFO("%s: n_ubatch      = %u\n",   __func__, cparams.n_ubatch);
195
0
    LLAMA_LOG_INFO("%s: causal_attn   = %d\n",   __func__, cparams.causal_attn);
196
0
    LLAMA_LOG_INFO("%s: flash_attn    = %s\n",   __func__, llama_flash_attn_type_name(params.flash_attn_type));
197
0
    LLAMA_LOG_INFO("%s: kv_unified    = %s\n",   __func__, cparams.kv_unified ? "true" : "false");
198
0
    LLAMA_LOG_INFO("%s: freq_base     = %.1f\n", __func__, cparams.rope_freq_base);
199
0
    LLAMA_LOG_INFO("%s: freq_scale    = %g\n",   __func__, cparams.rope_freq_scale);
200
201
0
    if (cparams.n_ctx_seq < hparams.n_ctx_train) {
202
0
        LLAMA_LOG_WARN("%s: n_ctx_seq (%u) < n_ctx_train (%u) -- the full capacity of the model will not be utilized\n",
203
0
                __func__, cparams.n_ctx_seq, hparams.n_ctx_train);
204
0
    }
205
206
0
    if (cparams.n_ctx_seq > hparams.n_ctx_train) {
207
0
        LLAMA_LOG_WARN("%s: n_ctx_seq (%u) > n_ctx_train (%u) -- possible training context overflow\n",
208
0
                __func__, cparams.n_ctx_seq, hparams.n_ctx_train);
209
0
    }
210
211
0
    if (!hparams.vocab_only) {
212
        // GPU backends
213
0
        for (auto * dev : model.devices) {
214
0
            ggml_backend_t backend = ggml_backend_dev_init(dev, nullptr);
215
0
            if (backend == nullptr) {
216
0
                throw std::runtime_error(format("failed to initialize %s backend", ggml_backend_dev_name(dev)));
217
0
            }
218
0
            backends.emplace_back(backend);
219
0
        }
220
221
        // add ACCEL backends (such as BLAS)
222
0
        for (size_t i = 0; i < ggml_backend_dev_count(); ++i) {
223
0
            ggml_backend_dev_t dev = ggml_backend_dev_get(i);
224
0
            if (ggml_backend_dev_type(dev) == GGML_BACKEND_DEVICE_TYPE_ACCEL) {
225
0
                ggml_backend_t backend = ggml_backend_dev_init(dev, nullptr);
226
0
                if (backend == nullptr) {
227
0
                    throw std::runtime_error(format("failed to initialize %s backend", ggml_backend_dev_name(dev)));
228
0
                }
229
0
                backends.emplace_back(backend);
230
0
            }
231
0
        }
232
233
        // add CPU backend
234
0
        backend_cpu = ggml_backend_init_by_type(GGML_BACKEND_DEVICE_TYPE_CPU, nullptr);
235
0
        if (backend_cpu == nullptr) {
236
0
            throw std::runtime_error("failed to initialize CPU backend");
237
0
        }
238
0
        backends.emplace_back(backend_cpu);
239
240
        // create a list of the set_n_threads functions in the backends
241
0
        for (auto & backend : backends) {
242
0
            ggml_backend_dev_t dev = ggml_backend_get_device(backend.get());
243
0
            ggml_backend_reg_t reg = dev ? ggml_backend_dev_backend_reg(dev) : nullptr;
244
0
            if (reg) {
245
0
                auto ggml_backend_set_n_threads_fn = (ggml_backend_set_n_threads_t) ggml_backend_reg_get_proc_address(reg, "ggml_backend_set_n_threads");
246
0
                if (ggml_backend_set_n_threads_fn) {
247
0
                    set_n_threads_fns.emplace_back(backend.get(), ggml_backend_set_n_threads_fn);
248
0
                }
249
0
            }
250
0
        }
251
252
0
        llama_set_abort_callback(this, params.abort_callback, params.abort_callback_data);
253
254
        // graph outputs buffer
255
0
        {
256
            // resized during inference when a batch uses more outputs
257
            // Create a dummy batch for initialization.
258
0
            llama_batch dummy_batch = {};
259
0
            dummy_batch.n_tokens = 0;
260
0
            if (output_reserve(params.n_seq_max, dummy_batch) < params.n_seq_max) {
261
0
                throw std::runtime_error("failed to reserve initial output buffer");
262
0
            }
263
264
0
            LLAMA_LOG_INFO("%s: %10s  output buffer size = %8.2f MiB\n", __func__,
265
0
                    ggml_backend_buffer_name    (buf_output.get()),
266
0
                    ggml_backend_buffer_get_size(buf_output.get()) / 1024.0 / 1024.0);
267
0
        }
268
0
    }
269
270
    // init the memory module
271
0
    if (!hparams.vocab_only) {
272
0
        llama_memory_params params_mem = {
273
0
            /*.type_k   =*/ params.type_k,
274
0
            /*.type_v   =*/ params.type_v,
275
0
            /*.swa_full =*/ params.swa_full,
276
0
        };
277
278
0
        memory.reset(model.create_memory(params_mem, cparams));
279
0
    }
280
281
    // init backends
282
0
    if (!hparams.vocab_only) {
283
0
        LLAMA_LOG_DEBUG("%s: enumerating backends\n", __func__);
284
285
0
        backend_buft.clear();
286
0
        backend_ptrs.clear();
287
0
        backend_buf_exp_size.clear();
288
289
0
        for (auto & backend : backends) {
290
0
            auto * buft = ggml_backend_get_default_buffer_type(backend.get());
291
0
            auto backend_type = ggml_backend_dev_type(ggml_backend_get_device(backend.get()));
292
293
0
            if (backend_type == GGML_BACKEND_DEVICE_TYPE_CPU && !model.devices.empty()) {
294
                // use the host buffer of the first device CPU for faster transfer of the intermediate state
295
0
                auto * dev = model.devices[0];
296
0
                auto * host_buft = ggml_backend_dev_host_buffer_type(dev);
297
0
                if (host_buft) {
298
0
                    buft = host_buft;
299
0
                }
300
0
            }
301
302
0
            backend_buft.push_back(buft);
303
0
            backend_ptrs.push_back(backend.get());
304
0
            backend_buf_exp_size.push_back(0);
305
0
        }
306
307
0
        LLAMA_LOG_DEBUG("%s: backend_ptrs.size() = %zu\n", __func__, backend_ptrs.size());
308
309
        // TODO: move these checks to ggml_backend_sched
310
        // enabling pipeline parallelism in the scheduler increases memory usage, so it is only done when necessary
311
0
        bool pipeline_parallel =
312
0
            model.n_devices() > 1 &&
313
0
            model.n_gpu_layers() > model.hparams.n_layer &&
314
0
            model.split_mode() == LLAMA_SPLIT_MODE_LAYER &&
315
0
            cparams.offload_kqv &&
316
0
            !model.has_tensor_overrides();
317
318
        // pipeline parallelism requires support for async compute and events in all devices
319
0
        if (pipeline_parallel) {
320
0
            for (auto & backend : backends) {
321
0
                auto dev_type = ggml_backend_dev_type(ggml_backend_get_device(backend.get()));
322
0
                if (dev_type == GGML_BACKEND_DEVICE_TYPE_CPU) {
323
                    // ignore CPU backend
324
0
                    continue;
325
0
                }
326
0
                auto * dev = ggml_backend_get_device(backend.get());
327
0
                ggml_backend_dev_props props;
328
0
                ggml_backend_dev_get_props(dev, &props);
329
0
                if (!props.caps.async || !props.caps.events) {
330
                    // device does not support async compute or events
331
0
                    pipeline_parallel = false;
332
0
                    break;
333
0
                }
334
0
            }
335
0
        }
336
337
0
        cparams.pipeline_parallel = pipeline_parallel;
338
339
0
        if (cparams.pipeline_parallel) {
340
0
            LLAMA_LOG_INFO("%s: pipeline parallelism enabled\n", __func__);
341
0
        }
342
343
0
        sched_reserve();
344
345
0
        if (!cparams.flash_attn) {
346
0
            if (ggml_is_quantized(params.type_v)) {
347
0
                throw std::runtime_error("quantized V cache was requested, but this requires Flash Attention");
348
0
            }
349
0
        }
350
0
    }
351
352
    // Initialize the full vocabulary token ids for backend samplers.
353
0
    {
354
0
        const int n_vocab = model.vocab.n_tokens();
355
356
0
        sampling.token_ids_full_vocab.resize(n_vocab);
357
0
        for (int i = 0; i < n_vocab; ++i) {
358
0
            sampling.token_ids_full_vocab[i] = i;
359
0
        }
360
0
    }
361
0
}
362
363
0
llama_context::~llama_context() {
364
0
    if (!model.hparams.no_alloc) {
365
0
        for (size_t i = 0; i < backend_ptrs.size(); ++i) {
366
0
            ggml_backend_t             backend = backend_ptrs[i];
367
0
            ggml_backend_buffer_type_t buft    = backend_buft[i];
368
369
0
            const size_t size_exp = backend_buf_exp_size[i];
370
0
            const size_t size_act = ggml_backend_sched_get_buffer_size(sched.get(), backend);
371
0
            if (size_exp == size_act) {
372
0
                LLAMA_LOG_DEBUG("%s: %10s compute buffer size is %8.4f MiB, matches expectation of %8.4f MiB\n",
373
0
                    __func__, ggml_backend_buft_name(buft), size_act / (1024.0*1024.0), size_exp / (1024.0*1024.0));
374
0
            } else {
375
0
                LLAMA_LOG_WARN("%s: %10s compute buffer size of %8.4f MiB, does not match expectation of %8.4f MiB\n",
376
0
                    __func__, ggml_backend_buft_name(buft), size_act / (1024.0*1024.0), size_exp / (1024.0*1024.0));
377
0
            }
378
0
        }
379
0
    }
380
0
    ggml_opt_free(opt_ctx);
381
0
}
382
383
0
void llama_context::sched_reserve() {
384
0
    if (!sched_need_reserve) {
385
0
        return;
386
0
    }
387
388
0
    sched_need_reserve = false;
389
390
0
    LLAMA_LOG_INFO("%s: reserving ...\n", __func__);
391
392
0
    synchronize();
393
394
0
    const int64_t t_start_us = ggml_time_us();
395
396
0
    const uint32_t n_seqs = cparams.n_seq_max;
397
0
    const uint32_t n_tokens = std::min(cparams.n_ctx, cparams.n_ubatch);
398
399
0
    const size_t max_nodes = this->graph_max_nodes(n_tokens);
400
401
0
    LLAMA_LOG_DEBUG("%s: max_nodes = %zu\n", __func__, max_nodes);
402
403
0
    gf_res_prev.reset(new llm_graph_result(max_nodes));
404
0
    gf_res_reserve.reset(new llm_graph_result(max_nodes));
405
406
0
    sched.reset(ggml_backend_sched_new(backend_ptrs.data(), backend_buft.data(), backend_ptrs.size(), max_nodes, cparams.pipeline_parallel, cparams.op_offload));
407
408
0
    llama_memory_context_ptr mctx;
409
0
    if (memory) {
410
0
        LLAMA_LOG_DEBUG("%s: reserving full memory module\n", __func__);
411
0
        mctx = memory->init_full();
412
0
        if (!mctx) {
413
0
            throw std::runtime_error("failed to initialize memory module");
414
0
        }
415
0
    }
416
417
    // avoid reserving graphs with zero outputs - assume one output per sequence
418
0
    const int n_outputs = n_seqs;
419
420
0
    LLAMA_LOG_DEBUG("%s: worst-case: n_tokens = %d, n_seqs = %d, n_outputs = %d\n", __func__, n_tokens, n_seqs, n_outputs);
421
422
    // resolve automatic Flash Attention use
423
0
    if (cparams.auto_fa) {
424
0
        auto * gf = graph_reserve(1, n_seqs, n_outputs, mctx.get(), true);
425
0
        if (!gf) {
426
0
            throw std::runtime_error("failed to split graph for Flash Attention check");
427
0
        }
428
429
0
        const size_t prefix_len = strlen(LLAMA_TENSOR_NAME_FATTN) + 1;
430
0
        bool fa_device_mismatch = false;
431
0
        for (int i = 0; i < ggml_graph_n_nodes(gf); i++) {
432
0
            ggml_tensor * n = ggml_graph_node(gf, i);
433
0
            if (n->op != GGML_OP_FLASH_ATTN_EXT) {
434
0
                continue;
435
0
            }
436
0
            ggml_backend_dev_t device_fa = ggml_backend_get_device(
437
0
                    ggml_backend_sched_get_tensor_backend(sched.get(), n));
438
439
            // TODO: instead of the tensor names, use a map to keep track of which (FA) tensors belong to which layer
440
0
            GGML_ASSERT(strncmp(n->name, LLAMA_TENSOR_NAME_FATTN "-", prefix_len) == 0);
441
0
            const int il = std::stoi(n->name + prefix_len);
442
0
            ggml_backend_dev_t device_kv = model.dev_layer(il);
443
0
            if (device_fa != device_kv) {
444
0
                LLAMA_LOG_WARN("%s: layer %d is assigned to device %s but the Flash Attention tensor "
445
0
                        "is assigned to device %s (usually due to missing support)\n",
446
0
                        __func__, il, ggml_backend_dev_name(device_kv), ggml_backend_dev_name(device_fa));
447
                // FIXME: fa_device_mismatch logic is wrong for --no-kv-offload, but this is broken anyways
448
0
                fa_device_mismatch = true;
449
0
                break;
450
0
            }
451
0
        }
452
0
        if (fa_device_mismatch) {
453
0
            cparams.flash_attn = false;
454
0
            LLAMA_LOG_WARN("%s: Flash Attention was auto, set to disabled\n", __func__);
455
0
        } else {
456
0
            cparams.flash_attn = true;
457
0
            LLAMA_LOG_INFO("%s: Flash Attention was auto, set to enabled\n", __func__);
458
0
        }
459
460
0
        cparams.auto_fa = false;
461
0
    }
462
463
    // reserve worst-case graph
464
0
    int n_splits_pp = -1;
465
0
    int n_nodes_pp  = -1;
466
467
0
    int n_splits_tg = -1;
468
0
    int n_nodes_tg  = -1;
469
470
    // reserve pp (prompt processing) graph first so that buffers are only allocated once
471
0
    {
472
0
        auto * gf = graph_reserve(n_tokens, n_seqs, n_tokens, mctx.get(),
473
0
                model.hparams.no_alloc, model.hparams.no_alloc ? backend_buf_exp_size.data() : nullptr);
474
0
        if (!gf) {
475
0
            if (cparams.pipeline_parallel) {
476
0
                LLAMA_LOG_WARN("%s: compute buffer allocation failed, retrying without pipeline parallelism\n", __func__);
477
0
                cparams.pipeline_parallel = false;
478
0
                sched.reset(ggml_backend_sched_new(backend_ptrs.data(), backend_buft.data(), backend_ptrs.size(), max_nodes, false, cparams.op_offload));
479
0
                gf = graph_reserve(n_tokens, n_seqs, n_tokens, mctx.get());
480
0
            }
481
0
            if (!gf) {
482
0
                throw std::runtime_error("failed to allocate compute pp buffers");
483
0
            }
484
0
        }
485
486
0
        n_splits_pp = ggml_backend_sched_get_n_splits(sched.get());
487
0
        n_nodes_pp  = ggml_graph_n_nodes(gf);
488
0
    }
489
490
    // reserve with tg (token generation) graph to get the number of splits and nodes
491
0
    {
492
0
        auto * gf = graph_reserve(n_seqs, n_seqs, n_seqs, mctx.get(), model.hparams.no_alloc);
493
0
        if (!gf) {
494
0
            throw std::runtime_error("failed to allocate compute tg buffers");
495
0
        }
496
497
0
        n_splits_tg = ggml_backend_sched_get_n_splits(sched.get());
498
0
        n_nodes_tg  = ggml_graph_n_nodes(gf);
499
0
    }
500
501
    // reserve again with pp graph to avoid ggml-alloc reallocations during inference
502
0
    {
503
        // TODO: not sure if the following graph would be worster case for multi-stream KV caches:
504
        //
505
        // auto * gf = graph_reserve(n_tokens, 1, n_tokens, mctx.get());
506
        //
507
0
        auto * gf = graph_reserve(n_tokens, n_seqs, n_tokens, mctx.get(), model.hparams.no_alloc);
508
0
        if (!gf) {
509
0
            throw std::runtime_error("failed to allocate compute pp buffers");
510
0
        }
511
0
    }
512
513
0
    for (size_t i = 0; i < backend_ptrs.size(); ++i) {
514
0
        ggml_backend_t             backend = backend_ptrs[i];
515
0
        ggml_backend_buffer_type_t buft    = backend_buft[i];
516
0
        if (!model.hparams.no_alloc) {
517
0
            backend_buf_exp_size[i] = ggml_backend_sched_get_buffer_size(sched.get(), backend);
518
0
        }
519
0
        if (backend_buf_exp_size[i] > 1) {
520
0
            LLAMA_LOG_INFO("%s: %10s compute buffer size = %8.2f MiB\n", __func__,
521
0
                    ggml_backend_buft_name(buft),
522
0
                    backend_buf_exp_size[i] / 1024.0 / 1024.0);
523
0
        }
524
0
    }
525
526
0
    if (n_nodes_pp == n_nodes_tg) {
527
0
        LLAMA_LOG_INFO("%s: graph nodes  = %d\n", __func__, n_nodes_pp);
528
0
    } else {
529
0
        LLAMA_LOG_INFO("%s: graph nodes  = %d (with bs=%d), %d (with bs=1)\n", __func__, n_nodes_pp, n_tokens, n_nodes_tg);
530
0
    }
531
532
0
    if (n_splits_pp == n_splits_tg) {
533
0
        LLAMA_LOG_INFO("%s: graph splits = %d\n", __func__, n_splits_pp);
534
0
    } else {
535
0
        LLAMA_LOG_INFO("%s: graph splits = %d (with bs=%d), %d (with bs=1)\n", __func__, n_splits_pp, n_tokens, n_splits_tg);
536
0
    }
537
538
0
    const int64_t t_end_us = ggml_time_us();
539
540
0
    LLAMA_LOG_INFO("%s: reserve took %.2f ms, sched copies = %d\n",
541
0
            __func__, (t_end_us - t_start_us)/1000.0, ggml_backend_sched_get_n_copies(sched.get()));
542
0
}
543
544
0
void llama_context::synchronize() {
545
0
    if (!sched) {
546
0
        return;
547
0
    }
548
549
0
    ggml_backend_sched_synchronize(sched.get());
550
551
    // FIXME: if multiple single tokens are evaluated without a synchronization,
552
    // the stats will be added to the prompt evaluation stats
553
    // this should only happen when using batch size 1 to evaluate a batch
554
555
    // add the evaluation to the stats
556
0
    if (n_queued_tokens == 1) {
557
0
        if (!cparams.no_perf) {
558
0
            t_eval_us += ggml_time_us() - t_compute_start_us;
559
0
        }
560
0
        n_eval++;
561
0
    } else if (n_queued_tokens > 1) {
562
0
        if (!cparams.no_perf) {
563
0
            t_p_eval_us += ggml_time_us() - t_compute_start_us;
564
0
        }
565
0
        n_p_eval += n_queued_tokens;
566
0
    }
567
568
    // get a more accurate load time, upon first eval
569
0
    if (n_queued_tokens > 0 && !has_evaluated_once) {
570
0
        t_load_us = ggml_time_us() - t_start_us;
571
0
        has_evaluated_once = true;
572
0
    }
573
574
0
    n_queued_tokens = 0;
575
0
    t_compute_start_us = 0;
576
0
}
577
578
0
const llama_model & llama_context::get_model() const {
579
0
    return model;
580
0
}
581
582
0
const llama_cparams & llama_context::get_cparams() const {
583
0
    return cparams;
584
0
}
585
586
0
ggml_backend_sched_t llama_context::get_sched() const {
587
0
    return sched.get();
588
0
}
589
590
0
uint32_t llama_context::n_ctx() const {
591
0
    return cparams.n_ctx;
592
0
}
593
594
0
uint32_t llama_context::n_ctx_seq() const {
595
0
    return cparams.n_ctx_seq;
596
0
}
597
598
0
uint32_t llama_context::n_batch() const {
599
0
    return cparams.n_batch;
600
0
}
601
602
0
uint32_t llama_context::n_ubatch() const {
603
0
    return cparams.n_ubatch;
604
0
}
605
606
0
uint32_t llama_context::n_seq_max() const {
607
0
    return cparams.n_seq_max;
608
0
}
609
610
0
uint32_t llama_context::n_threads() const {
611
0
    return cparams.n_threads;
612
0
}
613
614
0
uint32_t llama_context::n_threads_batch() const {
615
0
    return cparams.n_threads_batch;
616
0
}
617
618
0
llama_memory_t llama_context::get_memory() const {
619
0
    return memory.get();
620
0
}
621
622
0
bool llama_context::memory_update(bool optimize) {
623
0
    if (!memory) {
624
0
        return false;
625
0
    }
626
627
0
    {
628
0
        const auto mctx = memory->init_update(this, optimize);
629
0
        switch (mctx->get_status()) {
630
0
            case LLAMA_MEMORY_STATUS_SUCCESS:
631
0
                {
632
                    // noop
633
0
                } break;
634
0
            case LLAMA_MEMORY_STATUS_NO_UPDATE:
635
0
                {
636
                    // no updates need to be performed
637
0
                    return false;
638
0
                }
639
0
            case LLAMA_MEMORY_STATUS_FAILED_PREPARE:
640
0
            case LLAMA_MEMORY_STATUS_FAILED_COMPUTE:
641
0
                {
642
0
                    LLAMA_LOG_ERROR("%s: failed to prepare memory update\n", __func__);
643
0
                    return false;
644
0
                }
645
0
        }
646
647
        // reset the previous graph result to make sure that it won't be reused
648
        // TODO: change the mctx->apply() to return information if a graph reserve is needed
649
        //       reset the graph result only if the memory module did reset the scheduler
650
0
        gf_res_prev->reset();
651
652
0
        if (!mctx->apply()) {
653
0
            LLAMA_LOG_ERROR("%s: failed to apply memory update\n", __func__);
654
0
        }
655
0
    }
656
657
    // if the memory module did any computation, we have to reserve a new worst-case graph
658
0
    {
659
0
        const auto mctx = memory->init_full();
660
0
        if (!mctx) {
661
0
            throw std::runtime_error("failed to initialize memory context");
662
0
        }
663
664
0
        const uint32_t n_seqs = cparams.n_seq_max;
665
0
        const uint32_t n_tokens = std::min(cparams.n_ctx, cparams.n_ubatch);
666
667
0
        auto * gf = graph_reserve(n_tokens, n_seqs, n_tokens, mctx.get());
668
0
        if (!gf) {
669
0
            LLAMA_LOG_ERROR("%s: failed to reserve graph after the memory update\n", __func__);
670
0
        }
671
0
    }
672
673
0
    return true;
674
0
}
675
676
0
enum llama_pooling_type llama_context::pooling_type() const {
677
0
    return cparams.pooling_type;
678
0
}
679
680
0
float * llama_context::get_logits() {
681
0
    output_reorder();
682
683
0
    return logits;
684
0
}
685
686
0
int64_t llama_context::output_resolve_row(int32_t i) const {
687
0
    int64_t j = -1;
688
689
    // support negative indices (last output row)
690
0
    if (i < 0) {
691
0
        j = n_outputs + i;
692
0
        if (j < 0) {
693
0
            throw std::runtime_error(format("negative index out of range [0, %d)", n_outputs));
694
0
        }
695
0
    } else if ((size_t) i >= output_ids.size()) {
696
0
        throw std::runtime_error(format("out of range [0, %zu)", output_ids.size()));
697
0
    } else {
698
        // use output_ids to translate the batch token index into a row number
699
        // that holds this token's data.
700
0
        j = output_ids[i];
701
0
    }
702
703
0
    if (j < 0) {
704
        // the batch token was not configured to output anything
705
0
        throw std::runtime_error(format("batch.logits[%d] != true", i));
706
0
    }
707
708
0
    if (j >= n_outputs) {
709
0
        throw std::runtime_error(format("corrupt output buffer (j=%" PRId64 ", n_outputs=%d)", j, n_outputs));
710
0
    }
711
712
0
    return j;
713
0
}
714
715
0
float * llama_context::get_logits_ith(int32_t i) {
716
0
    int64_t j = -1;
717
718
0
    output_reorder();
719
720
0
    try {
721
0
        if (logits == nullptr) {
722
0
            throw std::runtime_error("no logits");
723
0
        }
724
725
        // TODO: use output_resolve_row()
726
0
        if (i < 0) {
727
0
            j = n_outputs + i;
728
0
            if (j < 0) {
729
0
                throw std::runtime_error(format("negative index out of range [0, %d)", n_outputs));
730
0
            }
731
0
        } else if ((size_t) i >= output_ids.size()) {
732
0
            throw std::runtime_error(format("out of range [0, %zu)", output_ids.size()));
733
0
        } else {
734
0
            j = output_ids[i];
735
0
        }
736
737
0
        if (j < 0) {
738
0
            throw std::runtime_error(format("batch.logits[%d] != true", i));
739
0
        }
740
0
        if (j >= n_outputs) {
741
            // This should not happen
742
0
            throw std::runtime_error(format("corrupt output buffer (j=%" PRId64 ", n_outputs=%d)", j, n_outputs));
743
0
        }
744
745
0
        return logits + j*model.vocab.n_tokens();
746
0
    } catch (const std::exception & err) {
747
0
        LLAMA_LOG_ERROR("%s: invalid logits id %d, reason: %s\n", __func__, i, err.what());
748
#ifndef NDEBUG
749
        GGML_ABORT("fatal error");
750
#else
751
0
        return nullptr;
752
0
#endif
753
0
    }
754
0
}
755
756
0
float * llama_context::get_embeddings() {
757
0
    output_reorder();
758
759
0
    return embd;
760
0
}
761
762
0
llama_token * llama_context::get_sampled_tokens()  const{
763
0
    return sampling.sampled;
764
0
}
765
766
0
float * llama_context::get_embeddings_ith(int32_t i) {
767
0
    int64_t j = -1;
768
769
0
    output_reorder();
770
771
0
    try {
772
0
        if (embd == nullptr) {
773
0
            throw std::runtime_error("no embeddings");
774
0
        }
775
776
        // TODO: use output_resolve_row()
777
0
        if (i < 0) {
778
0
            j = n_outputs + i;
779
0
            if (j < 0) {
780
0
                throw std::runtime_error(format("negative index out of range [0, %d)", n_outputs));
781
0
            }
782
0
        } else if ((size_t) i >= output_ids.size()) {
783
0
            throw std::runtime_error(format("out of range [0, %zu)", output_ids.size()));
784
0
        } else {
785
0
            j = output_ids[i];
786
0
        }
787
788
0
        if (j < 0) {
789
0
            throw std::runtime_error(format("batch.logits[%d] != true", i));
790
0
        }
791
0
        if (j >= n_outputs) {
792
            // This should not happen
793
0
            throw std::runtime_error(format("corrupt output buffer (j=%" PRId64 ", n_outputs=%d)", j, n_outputs));
794
0
        }
795
796
0
        const uint32_t n_embd_out = model.hparams.get_n_embd_out();
797
0
        return embd + j*n_embd_out;
798
0
    } catch (const std::exception & err) {
799
0
        LLAMA_LOG_ERROR("%s: invalid embeddings id %d, reason: %s\n", __func__, i, err.what());
800
#ifndef NDEBUG
801
        GGML_ABORT("fatal error");
802
#else
803
0
        return nullptr;
804
0
#endif
805
0
    }
806
0
}
807
808
0
float * llama_context::get_embeddings_seq(llama_seq_id seq_id) {
809
0
    auto it = embd_seq.find(seq_id);
810
0
    if (it == embd_seq.end()) {
811
0
        return nullptr;
812
0
    }
813
814
0
    return it->second.data();
815
0
}
816
817
0
llama_token llama_context::get_sampled_token_ith(int32_t idx) {
818
0
    output_reorder();
819
820
0
    if (sampling.sampled == nullptr) {
821
0
        return LLAMA_TOKEN_NULL;
822
0
    }
823
824
0
    try {
825
0
        const int64_t row = output_resolve_row(idx);
826
0
        GGML_ASSERT(row < (int64_t) sampling.sampled_size);
827
0
        return sampling.sampled[row];
828
0
    } catch (const std::exception & err) {
829
0
        LLAMA_LOG_ERROR("%s: invalid backend sampled token id %d, reason: %s\n", __func__, idx, err.what());
830
0
        return LLAMA_TOKEN_NULL;
831
0
    }
832
0
}
833
834
0
float * llama_context::get_sampled_probs_ith(int32_t idx) {
835
0
    output_reorder();
836
837
0
    if (sampling.probs == nullptr) {
838
0
        return nullptr;
839
0
    }
840
841
0
    try {
842
0
        const int64_t row = output_resolve_row(idx);
843
0
        if ((size_t) row >= sampling.probs_count.size() || sampling.probs_count[row] == 0) {
844
0
            return nullptr;
845
0
        }
846
0
        return sampling.probs + row*model.vocab.n_tokens();
847
0
    } catch (const std::exception & err) {
848
0
        LLAMA_LOG_ERROR("%s: invalid backend sampled probs id %d, reason: %s\n", __func__, idx, err.what());
849
0
        return nullptr;
850
0
    }
851
0
}
852
853
0
float * llama_context::get_sampled_logits_ith(int32_t idx) {
854
0
    output_reorder();
855
856
0
    if (sampling.logits == nullptr) {
857
0
        return nullptr;
858
0
    }
859
860
0
    try {
861
0
        const int64_t row = output_resolve_row(idx);
862
0
        if ((size_t) row >= sampling.logits_count.size() || sampling.logits_count[row] == 0) {
863
0
            return nullptr;
864
0
        }
865
0
        return sampling.logits + row*model.vocab.n_tokens();
866
0
    } catch (const std::exception & err) {
867
0
        LLAMA_LOG_ERROR("%s: invalid backend sampled logits id %d, reason: %s\n", __func__, idx, err.what());
868
0
        return nullptr;
869
0
    }
870
0
}
871
872
0
const llama_token * llama_context::get_sampled_candidates_ith(int32_t idx) {
873
0
    output_reorder();
874
875
0
    try {
876
0
        const int64_t row = output_resolve_row(idx);
877
0
        if (sampling.candidates != nullptr &&
878
0
            (size_t) row < sampling.candidates_count.size() &&
879
0
            sampling.candidates_count[row] > 0) {
880
0
            return sampling.candidates + row*model.vocab.n_tokens();
881
0
        }
882
0
    } catch (const std::exception & err) {
883
        // fallback to full vocab list
884
0
    }
885
886
0
    return sampling.token_ids_full_vocab.data();
887
0
}
888
889
0
size_t llama_context::get_sampled_candidates_count(int32_t idx) {
890
0
    output_reorder();
891
892
0
    if (sampling.candidates == nullptr) {
893
0
        return 0;
894
0
    }
895
896
0
    try {
897
0
        const int64_t row = output_resolve_row(idx);
898
0
        if ((size_t) row >= sampling.candidates_count.size()) {
899
0
            return 0;
900
0
        }
901
0
        return sampling.candidates_count[row];
902
0
    } catch (const std::exception & err) {
903
0
        LLAMA_LOG_ERROR("%s: invalid backend sampled candidates count id %d, reason: %s\n", __func__, idx, err.what());
904
0
        return 0;
905
0
    }
906
0
}
907
908
0
size_t llama_context::get_sampled_logits_count(int32_t idx) {
909
0
    output_reorder();
910
911
0
    if (sampling.logits == nullptr) {
912
0
        return model.vocab.n_tokens();
913
0
    }
914
915
0
    try {
916
0
        const int64_t row = output_resolve_row(idx);
917
0
        if ((size_t) row >= sampling.logits_count.size()) {
918
0
            return 0;
919
0
        }
920
0
        return sampling.logits_count[row];
921
0
    } catch (const std::exception & err) {
922
0
        LLAMA_LOG_ERROR("%s: invalid backend sampled logits count id %d, reason: %s\n", __func__, idx, err.what());
923
0
        return 0;
924
0
    }
925
0
}
926
927
0
size_t llama_context::get_sampled_probs_count(int32_t idx) {
928
0
    output_reorder();
929
930
0
    if (sampling.probs == nullptr) {
931
0
        return 0;
932
0
    }
933
934
0
    try {
935
0
        const int64_t row = output_resolve_row(idx);
936
0
        if ((size_t) row >= sampling.probs_count.size()) {
937
0
            return 0;
938
0
        }
939
0
        return sampling.probs_count[row];
940
0
    } catch (const std::exception & err) {
941
0
        LLAMA_LOG_ERROR("%s: invalid backend sampled probs count id %d, reason: %s\n", __func__, idx, err.what());
942
0
        return 0;
943
0
    }
944
0
}
945
946
947
void llama_context::attach_threadpool(
948
           ggml_threadpool_t threadpool,
949
0
           ggml_threadpool_t threadpool_batch) {
950
0
    LLAMA_LOG_DEBUG("%s: call\n", __func__);
951
952
0
    this->threadpool       = threadpool;
953
0
    this->threadpool_batch = threadpool_batch ? threadpool_batch : threadpool;
954
0
}
955
956
0
void llama_context::detach_threadpool() {
957
0
    LLAMA_LOG_DEBUG("%s: call\n", __func__);
958
959
0
    this->threadpool       = nullptr;
960
0
    this->threadpool_batch = nullptr;
961
0
}
962
963
0
void llama_context::set_n_threads(int32_t n_threads, int32_t n_threads_batch) {
964
0
    LLAMA_LOG_DEBUG("%s: n_threads = %d, n_threads_batch = %d\n", __func__, n_threads, n_threads_batch);
965
966
0
    cparams.n_threads       = n_threads;
967
0
    cparams.n_threads_batch = n_threads_batch;
968
0
}
969
970
0
void llama_context::set_abort_callback(bool (*abort_callback)(void * data), void * abort_callback_data) {
971
0
    LLAMA_LOG_DEBUG("%s: call\n", __func__);
972
973
0
    this->abort_callback      = abort_callback;
974
0
    this->abort_callback_data = abort_callback_data;
975
976
0
    for (auto & backend : backends) {
977
0
        auto * reg = ggml_backend_dev_backend_reg(ggml_backend_get_device(backend.get()));
978
0
        auto * set_abort_callback_fn = (ggml_backend_set_abort_callback_t) ggml_backend_reg_get_proc_address(reg, "ggml_backend_set_abort_callback");
979
0
        if (set_abort_callback_fn) {
980
0
            set_abort_callback_fn(backend.get(), this->abort_callback, this->abort_callback_data);
981
0
        }
982
0
    }
983
0
}
984
985
0
void llama_context::set_embeddings(bool value) {
986
0
    LLAMA_LOG_DEBUG("%s: value = %d\n", __func__, value);
987
988
0
    cparams.embeddings = value;
989
990
    // TODO: not sure yet if we want to reserve here
991
    //sched_need_reserve = true;
992
0
}
993
994
0
void llama_context::set_causal_attn(bool value) {
995
0
    LLAMA_LOG_DEBUG("%s: value = %d\n", __func__, value);
996
997
0
    if (cparams.causal_attn == value) {
998
0
        return;
999
0
    }
1000
1001
0
    cparams.causal_attn = value;
1002
1003
0
    sched_need_reserve = true;
1004
0
}
1005
1006
0
void llama_context::set_warmup(bool value) {
1007
0
    LLAMA_LOG_DEBUG("%s: value = %d\n", __func__, value);
1008
1009
0
    if (cparams.warmup == value) {
1010
0
        return;
1011
0
    }
1012
1013
0
    cparams.warmup = value;
1014
1015
    // warmups are usually with small batches, so no need to reserve
1016
    //sched_need_reserve = true;
1017
0
}
1018
1019
0
bool llama_context::set_sampler(llama_seq_id seq_id, llama_sampler * sampler) {
1020
0
    if (!sampler && sampling.samplers.count(seq_id) == 0) {
1021
0
        return true;
1022
0
    }
1023
1024
0
    LLAMA_LOG_DEBUG("%s: seq_id = %d, sampler = %p\n", __func__, (int) seq_id, (void *) sampler);
1025
1026
0
    const bool can_offload =
1027
0
        sampler &&
1028
0
        sampler->iface->backend_init &&
1029
0
        sampler->iface->backend_apply &&
1030
0
        llama_sampler_chain_n(sampler) > 0;
1031
1032
0
    if (sampler && can_offload) {
1033
0
        ggml_backend_buffer_type_t buft = ggml_backend_dev_buffer_type(model.dev_output());
1034
0
        auto * host_buft = ggml_backend_dev_host_buffer_type(model.dev_output());
1035
0
        if (host_buft) {
1036
0
            buft = host_buft;
1037
0
        }
1038
1039
0
        sampler->iface->backend_init(sampler, buft);
1040
1041
0
        sampling.samplers[seq_id] = sampler;
1042
1043
0
        sched_need_reserve = true;
1044
1045
0
        return true;
1046
0
    }
1047
1048
0
    if (sampler && !can_offload) {
1049
0
        LLAMA_LOG_WARN("%s: sampler '%s' for seq_id = %d, cannot be offloaded to the backend\n", __func__, llama_sampler_name(sampler), seq_id);
1050
1051
0
        if (sampling.samplers.count(seq_id) > 0) {
1052
0
            sched_need_reserve = true;
1053
0
        }
1054
1055
0
        sampling.samplers.erase(seq_id);
1056
1057
0
        return false;
1058
0
    }
1059
1060
0
    sampling.samplers.erase(seq_id);
1061
1062
0
    sched_need_reserve = true;
1063
1064
0
    return true;
1065
0
}
1066
1067
void llama_context::set_adapter_lora(
1068
            llama_adapter_lora * adapter,
1069
0
            float scale) {
1070
0
    LLAMA_LOG_DEBUG("%s: adapter = %p, scale = %f\n", __func__, (void *) adapter, scale);
1071
1072
0
    if (auto it = loras.find(adapter); it != loras.end()) {
1073
0
        if (it->second == scale) {
1074
0
            return;
1075
0
        }
1076
0
    }
1077
1078
0
    loras[adapter] = scale;
1079
1080
0
    sched_need_reserve = true;
1081
0
}
1082
1083
bool llama_context::rm_adapter_lora(
1084
0
            llama_adapter_lora * adapter) {
1085
0
    LLAMA_LOG_DEBUG("%s: adapter = %p\n", __func__, (void *) adapter);
1086
1087
0
    auto it = loras.find(adapter);
1088
0
    if (it != loras.end()) {
1089
0
        loras.erase(it);
1090
1091
0
        sched_need_reserve = true;
1092
1093
0
        return true;
1094
0
    }
1095
1096
0
    return false;
1097
0
}
1098
1099
0
void llama_context::clear_adapter_lora() {
1100
0
    LLAMA_LOG_DEBUG("%s: call\n", __func__);
1101
1102
0
    if (loras.empty()) {
1103
0
        return;
1104
0
    }
1105
1106
0
    loras.clear();
1107
1108
0
    sched_need_reserve = true;
1109
0
}
1110
1111
bool llama_context::apply_adapter_cvec(
1112
            const float * data,
1113
                 size_t   len,
1114
                int32_t   n_embd,
1115
                int32_t   il_start,
1116
0
                int32_t   il_end) {
1117
0
    LLAMA_LOG_DEBUG("%s: il_start = %d, il_end = %d\n", __func__, il_start, il_end);
1118
1119
    // TODO: should we reserve?
1120
1121
0
    return cvec.apply(model, data, len, n_embd, il_start, il_end);
1122
0
}
1123
1124
0
llm_graph_result * llama_context::process_ubatch(const llama_ubatch & ubatch, llm_graph_type gtype, llama_memory_context_i * mctx, ggml_status & ret) {
1125
0
    if (mctx && !mctx->apply()) {
1126
0
        LLAMA_LOG_ERROR("%s: failed to apply memory context\n", __func__);
1127
0
        ret = GGML_STATUS_FAILED;
1128
0
        return nullptr;
1129
0
    }
1130
1131
0
    auto * res = gf_res_prev.get();
1132
0
    auto * gf  = res->get_gf();
1133
1134
    // the new graph parameters
1135
    // in order to correctly reuse a graph, it's full topology has to be uniquely determined by these parameters
1136
0
    const auto gparams = graph_params(res, ubatch, mctx, gtype);
1137
1138
0
    if (!graph_reuse_disable && res->can_reuse(gparams)) {
1139
        //LLAMA_LOG_DEBUG("%s: reusing previous graph\n", __func__);
1140
1141
0
        n_reused++;
1142
0
    } else {
1143
0
        res->reset();
1144
1145
0
        ggml_backend_sched_reset(sched.get());
1146
0
        ggml_backend_sched_set_eval_callback(sched.get(), cparams.cb_eval, cparams.cb_eval_user_data);
1147
1148
        //const auto t_start_us = ggml_time_us();
1149
1150
0
        gf = model.build_graph(gparams);
1151
1152
        //LLAMA_LOG_INFO("graph build time: %.3f ms\n", (ggml_time_us() - t_start_us)/1000.0);
1153
1154
0
        if (!gf) {
1155
0
            LLAMA_LOG_ERROR("%s: failed to initialize graph\n", __func__);
1156
0
            ret = GGML_STATUS_FAILED;
1157
0
            return nullptr;
1158
0
        }
1159
1160
0
        if (!ggml_backend_sched_alloc_graph(sched.get(), gf)) {
1161
0
            LLAMA_LOG_ERROR("%s: failed to allocate graph\n", __func__);
1162
0
            ret = GGML_STATUS_ALLOC_FAILED;
1163
0
            return nullptr;
1164
0
        }
1165
0
    }
1166
1167
    // set the input data for the input tensors
1168
0
    {
1169
        //const auto t_start_us = ggml_time_us();
1170
1171
0
        res->set_inputs(&ubatch);
1172
1173
        //LLAMA_LOG_INFO("graph set inputs time: %.3f ms\n", (ggml_time_us() - t_start_us)/1000.0);
1174
0
    }
1175
1176
0
    const auto status = graph_compute(res->get_gf(), ubatch.n_tokens > 1);
1177
0
    if (status != GGML_STATUS_SUCCESS) {
1178
0
        LLAMA_LOG_ERROR("%s: failed to compute graph, compute status: %d\n", __func__, status);
1179
0
        ret = status;
1180
0
        return nullptr;
1181
0
    }
1182
1183
0
    ret = GGML_STATUS_SUCCESS;
1184
1185
0
    return res;
1186
0
}
1187
1188
0
int llama_context::encode(const llama_batch & batch_inp) {
1189
0
    GGML_ASSERT((!batch_inp.token && batch_inp.embd) || (batch_inp.token && !batch_inp.embd)); // NOLINT
1190
1191
0
    if (batch_inp.n_tokens == 0) {
1192
0
        LLAMA_LOG_ERROR("%s: n_tokens == 0\n", __func__);
1193
0
        return -1;
1194
0
    }
1195
1196
0
    const auto & hparams = model.hparams;
1197
1198
0
    const int64_t n_embd  = hparams.n_embd_inp();
1199
0
    const int64_t n_vocab = model.vocab.n_tokens();
1200
1201
    // note: during encode, we always pass the full sequence starting from pos = 0
1202
0
    if (!balloc->init(batch_inp, model.vocab, nullptr, n_embd, cparams.kv_unified ? LLAMA_MAX_SEQ : cparams.n_seq_max, true)) {
1203
0
        LLAMA_LOG_ERROR("%s: failed to initialize batch\n", __func__);
1204
0
        return -1;
1205
0
    }
1206
1207
0
    const uint32_t n_tokens = balloc->get_n_tokens();
1208
1209
    // [TAG_NO_CACHE_PAD]
1210
    // TODO: add new split mode where we pad the input sequences so that ubatch.equal_seqs == true
1211
0
    const llama_ubatch ubatch = balloc->split_simple(n_tokens);
1212
1213
    // micro-batching is not possible for non-causal encoding, so we process the batch in a single shot
1214
0
    GGML_ASSERT(cparams.n_ubatch >= n_tokens && "encoder requires n_ubatch >= n_tokens");
1215
1216
0
    if (t_compute_start_us == 0) {
1217
0
        t_compute_start_us = ggml_time_us();
1218
0
    }
1219
1220
    // TODO: this clear of the buffer can easily be forgotten - need something better
1221
0
    embd_seq.clear();
1222
1223
0
    sched_reserve();
1224
1225
0
    n_queued_tokens += n_tokens;
1226
1227
    // reserve output buffer
1228
0
    if (output_reserve(n_tokens, batch_inp) < n_tokens) {
1229
0
        LLAMA_LOG_ERROR("%s: could not reserve space for batch with %u outputs\n", __func__, n_tokens);
1230
0
        return -2;
1231
0
    };
1232
1233
0
    for (uint32_t i = 0; i < n_tokens; ++i) {
1234
0
        output_ids[i] = i;
1235
0
    }
1236
1237
0
    n_outputs = n_tokens;
1238
1239
0
    const auto causal_attn_org = cparams.causal_attn;
1240
1241
    // always use non-causal attention for encoder graphs
1242
    // TODO: this is a tmp solution until we have a proper way to support enc-dec models
1243
    //       ref: https://github.com/ggml-org/llama.cpp/pull/12181#issuecomment-2730451223
1244
0
    cparams.causal_attn = false;
1245
1246
0
    ggml_status status;
1247
0
    const auto * res = process_ubatch(ubatch, LLM_GRAPH_TYPE_ENCODER, nullptr, status);
1248
1249
0
    cparams.causal_attn = causal_attn_org;
1250
1251
0
    if (!res) {
1252
0
        switch (status) {
1253
0
            case GGML_STATUS_ABORTED:      return  2;
1254
0
            case GGML_STATUS_ALLOC_FAILED: return -2;
1255
0
            case GGML_STATUS_FAILED:       return -3;
1256
0
            case GGML_STATUS_SUCCESS:      GGML_ABORT("should not happen");
1257
0
        }
1258
0
    }
1259
1260
0
    auto * t_logits = res->get_logits();
1261
0
    auto * t_embd = res->get_embd_pooled() ? res->get_embd_pooled() : res->get_embd();
1262
1263
    // extract logits
1264
0
    if (logits && t_logits) {
1265
0
        ggml_backend_t backend_res = ggml_backend_sched_get_tensor_backend(sched.get(), t_logits);
1266
0
        GGML_ASSERT(backend_res != nullptr);
1267
0
        GGML_ASSERT(logits != nullptr);
1268
1269
0
        ggml_backend_tensor_get_async(backend_res, t_logits, logits, 0, n_tokens*n_vocab*sizeof(float));
1270
0
    }
1271
1272
    // extract embeddings
1273
0
    if (embd && t_embd) {
1274
0
        ggml_backend_t backend_embd = ggml_backend_sched_get_tensor_backend(sched.get(), t_embd);
1275
0
        GGML_ASSERT(backend_embd != nullptr);
1276
1277
0
        switch (cparams.pooling_type) {
1278
0
            case LLAMA_POOLING_TYPE_NONE:
1279
0
                {
1280
                    // extract token embeddings
1281
0
                    GGML_ASSERT(embd != nullptr);
1282
0
                    const uint32_t n_embd_out = hparams.get_n_embd_out();
1283
1284
0
                    GGML_ASSERT(n_tokens*n_embd_out <= (int64_t) embd_size);
1285
0
                    ggml_backend_tensor_get_async(backend_embd, t_embd, embd, 0, n_tokens*n_embd_out*sizeof(float));
1286
0
                } break;
1287
0
            case LLAMA_POOLING_TYPE_MEAN:
1288
0
            case LLAMA_POOLING_TYPE_CLS:
1289
0
            case LLAMA_POOLING_TYPE_LAST:
1290
0
                {
1291
                    // extract sequence embeddings
1292
0
                    auto & embd_seq_out = embd_seq;
1293
1294
0
                    for (uint32_t s = 0; s < ubatch.n_seqs_unq; ++s) {
1295
0
                        const llama_seq_id seq_id  = ubatch.seq_id_unq[s];
1296
0
                        const int32_t      seq_idx = ubatch.seq_idx[seq_id];
1297
1298
0
                        embd_seq_out[seq_id].resize(n_embd);
1299
0
                        ggml_backend_tensor_get_async(backend_embd, t_embd, embd_seq_out[seq_id].data(), (n_embd*seq_idx)*sizeof(float), n_embd*sizeof(float));
1300
0
                    }
1301
0
                } break;
1302
0
            case LLAMA_POOLING_TYPE_RANK:
1303
0
                {
1304
                    // extract the rerank score - n_cls_out floats per sequence
1305
0
                    auto & embd_seq_out = embd_seq;
1306
1307
0
                    const uint32_t n_cls_out = hparams.n_cls_out;
1308
1309
0
                    for (uint32_t s = 0; s < ubatch.n_seqs_unq; ++s) {
1310
0
                        const llama_seq_id seq_id  = ubatch.seq_id_unq[s];
1311
0
                        const int32_t      seq_idx = ubatch.seq_idx[seq_id];
1312
1313
0
                        embd_seq_out[seq_id].resize(n_cls_out);
1314
0
                        ggml_backend_tensor_get_async(backend_embd, t_embd, embd_seq_out[seq_id].data(), (n_cls_out*seq_idx)*sizeof(float), n_cls_out*sizeof(float));
1315
0
                    }
1316
0
                } break;
1317
0
            case LLAMA_POOLING_TYPE_UNSPECIFIED:
1318
0
                {
1319
0
                    GGML_ABORT("unknown pooling type");
1320
0
                }
1321
0
        }
1322
0
    }
1323
1324
    // TODO: hacky solution
1325
0
    if (model.arch == LLM_ARCH_T5 && t_embd) {
1326
        //cross.t_embd = t_embd;
1327
1328
0
        synchronize();
1329
1330
0
        cross.n_embd = t_embd->ne[0];
1331
0
        cross.n_enc  = t_embd->ne[1];
1332
0
        cross.v_embd.resize(cross.n_embd*cross.n_enc);
1333
0
        memcpy(cross.v_embd.data(), embd, ggml_nbytes(t_embd));
1334
1335
0
        const auto & batch = balloc->get_batch();
1336
1337
        // remember the sequence ids used during the encoding - needed for cross attention later
1338
0
        cross.seq_ids_enc.resize(n_tokens);
1339
0
        for (uint32_t i = 0; i < n_tokens; i++) {
1340
0
            cross.seq_ids_enc[i].clear();
1341
1342
0
            for (int s = 0; s < batch.n_seq_id[i]; s++) {
1343
0
                const llama_seq_id seq_id = batch.seq_id[i][s];
1344
1345
0
                cross.seq_ids_enc[i].insert(seq_id);
1346
0
            }
1347
0
        }
1348
0
    }
1349
1350
0
    return 0;
1351
0
}
1352
1353
0
static std::map<llama_seq_id, uint32_t> build_seq_to_output_row(const llama_ubatch & ubatch, uint32_t row_offset) {
1354
0
    std::map<llama_seq_id, uint32_t> seq_to_row;
1355
    // how many output tokens we have seen so far for this ubatch.
1356
0
    uint32_t local = 0;
1357
0
    for (uint32_t i = 0; i < ubatch.n_tokens; ++i) {
1358
        // skip tokens that are not output.
1359
0
        if (!ubatch.output[i]) {
1360
0
            continue;
1361
0
        }
1362
1363
0
        const llama_seq_id seq_id = ubatch.seq_id[i][0];
1364
        // row_offset is the number of output tokens before this ubatch.
1365
0
        seq_to_row[seq_id] = row_offset + local;
1366
0
        ++local;
1367
0
    }
1368
0
    return seq_to_row;
1369
0
}
1370
1371
static void copy_tensor_async_ints(
1372
    const std::map<llama_seq_id, ggml_tensor*> & tensor_map,
1373
    llama_token * sampled,
1374
    size_t sampled_size,
1375
    const std::map<llama_seq_id, uint32_t> & seq_to_row,
1376
0
    ggml_backend_sched_t sched) {
1377
0
    if (sampled == nullptr) {
1378
0
        return;
1379
0
    }
1380
1381
0
    for (const auto & [seq_id, tensor] : tensor_map) {
1382
0
        auto it = seq_to_row.find(seq_id);
1383
0
        if (it == seq_to_row.end()) {
1384
0
            continue;
1385
0
        }
1386
1387
0
        const uint32_t row = it->second;
1388
0
        GGML_ASSERT(row < sampled_size);
1389
1390
0
        GGML_ASSERT(ggml_is_contiguous(tensor) && "sampled tokens tensor must be contiguous for async copy");
1391
1392
0
        ggml_backend_t backend = ggml_backend_sched_get_tensor_backend(sched, tensor);
1393
0
        ggml_backend_tensor_get_async(backend, tensor, sampled + row, 0, sizeof(sampled[row]));
1394
0
    }
1395
0
}
1396
1397
static void copy_tensor_async_floats(
1398
    const std::map<llama_seq_id, ggml_tensor*> & tensor_map,
1399
    float * dst,
1400
    size_t stride,
1401
    std::vector<uint32_t> & counts,
1402
    const std::map<llama_seq_id, uint32_t> & seq_to_row,
1403
0
    ggml_backend_sched_t sched) {
1404
0
    if (dst == nullptr) {
1405
0
        return;
1406
0
    }
1407
1408
0
    for (const auto & [seq_id, tensor] : tensor_map) {
1409
0
        auto it = seq_to_row.find(seq_id);
1410
0
        if (it == seq_to_row.end()) {
1411
0
            continue;
1412
0
        }
1413
1414
0
        const uint32_t row = it->second;
1415
0
        GGML_ASSERT(row < counts.size());
1416
1417
0
        GGML_ASSERT(ggml_is_contiguous(tensor) && "logits/probs tensor must be contiguous for async copy");
1418
1419
0
        ggml_backend_t backend = ggml_backend_sched_get_tensor_backend(sched, tensor);
1420
0
        float * row_ptr = dst + (size_t) row * stride;
1421
0
        ggml_backend_tensor_get_async(backend, tensor, row_ptr, 0, ggml_nbytes(tensor));
1422
1423
        // Update the actual number of logits/probabilities that were written for this row.
1424
0
        counts[row] = ggml_nelements(tensor);
1425
0
    }
1426
0
}
1427
1428
static void copy_tensor_async_candidates(
1429
    const std::map<llama_seq_id, ggml_tensor*> & tensor_map,
1430
    llama_token * dst,
1431
    size_t stride,
1432
    std::vector<uint32_t> & counts,
1433
    const std::map<llama_seq_id, uint32_t> & seq_to_row,
1434
0
    ggml_backend_sched_t sched) {
1435
0
    if (dst == nullptr) {
1436
0
        return;
1437
0
    }
1438
1439
0
    for (const auto & [seq_id, tensor] : tensor_map) {
1440
0
        auto it = seq_to_row.find(seq_id);
1441
0
        if (it == seq_to_row.end()) {
1442
0
            continue;
1443
0
        }
1444
1445
0
        const uint32_t row = it->second;
1446
0
        GGML_ASSERT(row < counts.size());
1447
1448
0
        GGML_ASSERT(ggml_is_contiguous(tensor) && "candidates tensor must be contiguous for async copy");
1449
1450
0
        ggml_backend_t backend = ggml_backend_sched_get_tensor_backend(sched, tensor);
1451
0
        llama_token * row_ptr = dst + (size_t) row * stride;
1452
0
        ggml_backend_tensor_get_async(backend, tensor, row_ptr, 0, ggml_nbytes(tensor));
1453
1454
        // Update the actual number of candidates that were written.
1455
0
        counts[row] = ggml_nelements(tensor);
1456
0
    }
1457
0
}
1458
1459
0
int llama_context::decode(const llama_batch & batch_inp) {
1460
0
    GGML_ASSERT((!batch_inp.token && batch_inp.embd) || (batch_inp.token && !batch_inp.embd)); // NOLINT
1461
1462
0
    if (!memory) {
1463
0
        LLAMA_LOG_DEBUG("%s: cannot decode batches with this context (calling encode() instead)\n", __func__);
1464
0
        return encode(batch_inp);
1465
0
    }
1466
1467
0
    if (batch_inp.n_tokens == 0) {
1468
0
        LLAMA_LOG_ERROR("%s: n_tokens == 0\n", __func__);
1469
0
        return -1;
1470
0
    }
1471
1472
0
    const auto & vocab   = model.vocab;
1473
0
    const auto & hparams = model.hparams;
1474
1475
0
    const int64_t n_vocab = vocab.n_tokens();
1476
0
    const int64_t n_embd  = hparams.n_embd_inp();
1477
1478
    // when computing embeddings, all tokens are output
1479
0
    const bool output_all   = cparams.embeddings;
1480
0
    const bool has_samplers = !sampling.samplers.empty();
1481
1482
0
    const uint32_t n_seq_max = cparams.kv_unified ? LLAMA_MAX_SEQ : cparams.n_seq_max;
1483
1484
    // TODO: avoid this workaround in the future
1485
0
    if (has_samplers && batch_inp.logits) {
1486
0
        std::vector<int32_t> seq_output_count(n_seq_max, 0);
1487
1488
0
        for (int32_t i = 0; i < batch_inp.n_tokens; ++i) {
1489
0
            if (batch_inp.logits[i] == 0) {
1490
0
                continue;
1491
0
            }
1492
1493
0
            const int ns = batch_inp.n_seq_id ? batch_inp.n_seq_id[i] : 1;
1494
1495
0
            for (int32_t s = 0; s < ns; ++s) {
1496
0
                const llama_seq_id seq_id = batch_inp.seq_id ? batch_inp.seq_id[i][s] : 0;
1497
1498
0
                seq_output_count[seq_id]++;
1499
0
                if (seq_output_count[seq_id] > 1) {
1500
0
                    LLAMA_LOG_ERROR("%s: backend sampling requires at most one output token per sequence (seq_id %d had %d)\n",
1501
0
                            __func__, seq_id, seq_output_count[seq_id]);
1502
0
                    return -1;
1503
0
                }
1504
0
            }
1505
0
        }
1506
0
    }
1507
1508
0
    if (!balloc->init(batch_inp, vocab, memory.get(), n_embd, n_seq_max, output_all)) {
1509
0
        LLAMA_LOG_ERROR("%s: failed to initialize batch\n", __func__);
1510
0
        return -1;
1511
0
    }
1512
1513
0
    const uint32_t n_tokens_all  = balloc->get_n_tokens();
1514
0
    const uint32_t n_outputs_all = balloc->get_n_outputs();
1515
1516
0
    if (output_all) {
1517
        // require that all tokens are output
1518
0
        if (n_outputs_all != n_tokens_all) {
1519
0
            LLAMA_LOG_ERROR("%s: pooled embedding requires that all tokens are output (n_outputs_all = %d, n_tokens_all = %d)\n",
1520
0
                    __func__, n_outputs_all, n_tokens_all);
1521
0
            return -1;
1522
0
        }
1523
0
    }
1524
1525
0
    GGML_ASSERT(n_tokens_all <= cparams.n_batch);
1526
1527
0
    GGML_ASSERT((cparams.causal_attn || cparams.n_ubatch >= n_tokens_all) && "non-causal attention requires n_ubatch >= n_tokens");
1528
1529
0
    if (t_compute_start_us == 0) {
1530
0
        t_compute_start_us = ggml_time_us();
1531
0
    }
1532
0
    n_queued_tokens += n_tokens_all;
1533
1534
    // TODO: this clear of the buffer can easily be forgotten - need something better
1535
0
    embd_seq.clear();
1536
0
    output_swaps.clear();
1537
1538
0
    sched_reserve();
1539
1540
0
    bool did_optimize = false;
1541
1542
    // handle any pending shifts/copies
1543
0
    memory_update(false);
1544
1545
0
    llama_memory_context_ptr mctx;
1546
1547
0
    while (true) {
1548
0
        mctx = memory->init_batch(*balloc, cparams.n_ubatch, output_all);
1549
0
        if (!mctx) {
1550
0
            return -2;
1551
0
        }
1552
1553
0
        switch (mctx->get_status()) {
1554
0
            case LLAMA_MEMORY_STATUS_SUCCESS:
1555
0
                {
1556
0
                } break;
1557
0
            case LLAMA_MEMORY_STATUS_NO_UPDATE:
1558
0
                {
1559
0
                    LLAMA_LOG_ERROR("%s: unexpected memory context status: %d\n", __func__, mctx->get_status());
1560
1561
0
                    return -2;
1562
0
                }
1563
0
            case LLAMA_MEMORY_STATUS_FAILED_PREPARE:
1564
0
                {
1565
0
                    if (!did_optimize) {
1566
0
                        did_optimize = true;
1567
1568
0
                        if (memory_update(true)) {
1569
0
                            LLAMA_LOG_DEBUG("%s: retrying batch size %d after cache optimization\n", __func__, balloc->get_n_tokens());
1570
1571
0
                            continue;
1572
0
                        }
1573
0
                    }
1574
1575
0
                    LLAMA_LOG_WARN("%s: failed to find a memory slot for batch of size %d\n", __func__, balloc->get_n_tokens());
1576
1577
0
                    return 1;
1578
0
                }
1579
0
            case LLAMA_MEMORY_STATUS_FAILED_COMPUTE:
1580
0
                {
1581
0
                    LLAMA_LOG_ERROR("%s: compute failed while preparing batch of size %d\n", __func__, balloc->get_n_tokens());
1582
1583
0
                    return -2;
1584
0
                }
1585
0
        }
1586
1587
0
        break;
1588
0
    }
1589
1590
    // reserve output buffer
1591
0
    if (output_reserve(n_outputs_all, balloc->get_batch()) < n_outputs_all) {
1592
0
        LLAMA_LOG_ERROR("%s: could not reserve space for batch with %d outputs\n", __func__, n_outputs_all);
1593
0
        return -2;
1594
0
    };
1595
1596
0
    int64_t n_outputs_prev = 0;
1597
1598
0
    do {
1599
0
        const auto & ubatch = mctx->get_ubatch();
1600
1601
        // count the outputs in this ubatch
1602
0
        {
1603
0
            int32_t n_outputs_new = 0;
1604
1605
0
            if (n_outputs_all == n_tokens_all) {
1606
0
                n_outputs_new = ubatch.n_tokens;
1607
0
            } else {
1608
0
                for (uint32_t i = 0; i < ubatch.n_tokens; i++) {
1609
0
                    n_outputs_new += (int32_t) (ubatch.output[i] != 0);
1610
0
                }
1611
0
            }
1612
1613
            // needs to happen before the graph is built
1614
0
            n_outputs = n_outputs_new;
1615
0
        }
1616
1617
0
        ggml_status status;
1618
0
        const auto * res = process_ubatch(ubatch, LLM_GRAPH_TYPE_DECODER, mctx.get(), status);
1619
1620
0
        if (!res) {
1621
            // the last ubatch failed or was aborted -> remove all positions of that ubatch from the memory module
1622
0
            llama_pos pos_min[LLAMA_MAX_SEQ];
1623
0
            for (int s = 0; s < LLAMA_MAX_SEQ; ++s) {
1624
0
                pos_min[s] = std::numeric_limits<llama_pos>::max();
1625
0
            }
1626
1627
0
            for (uint32_t i = 0; i < ubatch.n_tokens; ++i) {
1628
0
                const auto & seq_id = ubatch.seq_id[i][0];
1629
1630
0
                pos_min[seq_id] = std::min(pos_min[seq_id], ubatch.pos[i]);
1631
0
            }
1632
1633
0
            for (int s = 0; s < LLAMA_MAX_SEQ; ++s) {
1634
0
                if (pos_min[s] == std::numeric_limits<llama_pos>::max()) {
1635
0
                    continue;
1636
0
                }
1637
1638
0
                LLAMA_LOG_WARN("%s: removing memory module entries for seq_id = %d, pos = [%d, +inf)\n", __func__, s, pos_min[s]);
1639
1640
0
                memory->seq_rm(s, pos_min[s], -1);
1641
0
            }
1642
1643
0
            switch (status) {
1644
0
                case GGML_STATUS_ABORTED:      return  2;
1645
0
                case GGML_STATUS_ALLOC_FAILED: return -2;
1646
0
                case GGML_STATUS_FAILED:       return -3;
1647
0
                case GGML_STATUS_SUCCESS:      GGML_ABORT("should not happen");
1648
0
            }
1649
0
        }
1650
1651
        // plot the computation graph in dot format (for debugging purposes)
1652
        //if (n_past%100 == 0) {
1653
        //    ggml_graph_dump_dot(gf, NULL, "llama.dot");
1654
        //}
1655
1656
0
        auto * t_logits = res->get_logits();
1657
0
        auto * t_embd   = cparams.embeddings ? res->get_embd() : nullptr;
1658
1659
0
        if (t_embd && res->get_embd_pooled()) {
1660
0
            t_embd = res->get_embd_pooled();
1661
0
        }
1662
1663
        // extract logits
1664
        // For multi-sequence batches that mix backend samplers and CPU sampler
1665
        // this is currently inefficient as we copy all logits even for the
1666
        // backend sampled tokens.
1667
0
        if (logits && t_logits && n_outputs > 0) {
1668
0
            ggml_backend_t backend_res = ggml_backend_sched_get_tensor_backend(sched.get(), t_logits);
1669
0
            GGML_ASSERT(backend_res != nullptr);
1670
0
            GGML_ASSERT(logits != nullptr);
1671
1672
0
            float * logits_out = logits + n_outputs_prev*n_vocab;
1673
1674
0
            if (n_outputs) {
1675
0
                GGML_ASSERT( n_outputs_prev + n_outputs <= n_outputs_all);
1676
0
                GGML_ASSERT((n_outputs_prev + n_outputs)*n_vocab <= (int64_t) logits_size);
1677
0
                ggml_backend_tensor_get_async(backend_res, t_logits, logits_out, 0, n_outputs*n_vocab*sizeof(float));
1678
0
            }
1679
0
        }
1680
1681
        // extract embeddings
1682
0
        if (embd && t_embd && n_outputs > 0) {
1683
0
            ggml_backend_t backend_embd = ggml_backend_sched_get_tensor_backend(sched.get(), t_embd);
1684
0
            GGML_ASSERT(backend_embd != nullptr);
1685
1686
0
            switch (cparams.pooling_type) {
1687
0
                case LLAMA_POOLING_TYPE_NONE:
1688
0
                    {
1689
                        // extract token embeddings
1690
0
                        GGML_ASSERT(embd != nullptr);
1691
0
                        const uint32_t n_embd_out = hparams.get_n_embd_out();
1692
0
                        float * embd_out = embd + n_outputs_prev*n_embd_out;
1693
1694
0
                        if (n_outputs) {
1695
0
                            GGML_ASSERT( n_outputs_prev + n_outputs <= n_outputs_all);
1696
0
                            GGML_ASSERT((n_outputs_prev + n_outputs)*n_embd_out <= (int64_t) embd_size);
1697
0
                            ggml_backend_tensor_get_async(backend_embd, t_embd, embd_out, 0, n_outputs*n_embd_out*sizeof(float));
1698
0
                        }
1699
0
                    } break;
1700
0
                case LLAMA_POOLING_TYPE_MEAN:
1701
0
                case LLAMA_POOLING_TYPE_CLS:
1702
0
                case LLAMA_POOLING_TYPE_LAST:
1703
0
                    {
1704
                        // extract sequence embeddings (cleared before processing each batch)
1705
0
                        auto & embd_seq_out = embd_seq;
1706
1707
0
                        for (uint32_t s = 0; s < ubatch.n_seqs_unq; ++s) {
1708
0
                            const llama_seq_id seq_id  = ubatch.seq_id_unq[s];
1709
0
                            const int32_t      seq_idx = ubatch.seq_idx[seq_id];
1710
1711
0
                            embd_seq_out[seq_id].resize(n_embd);
1712
0
                            ggml_backend_tensor_get_async(backend_embd, t_embd, embd_seq_out[seq_id].data(), (n_embd*seq_idx)*sizeof(float), n_embd*sizeof(float));
1713
0
                        }
1714
0
                    } break;
1715
0
                case LLAMA_POOLING_TYPE_RANK:
1716
0
                    {
1717
                        // extract the rerank score - n_cls_out floats per sequence
1718
0
                        auto & embd_seq_out = embd_seq;
1719
1720
0
                        const uint32_t n_cls_out = hparams.n_cls_out;
1721
1722
0
                        for (uint32_t s = 0; s < ubatch.n_seqs_unq; ++s) {
1723
0
                            const llama_seq_id seq_id  = ubatch.seq_id_unq[s];
1724
0
                            const int32_t      seq_idx = ubatch.seq_idx[seq_id];
1725
1726
0
                            embd_seq_out[seq_id].resize(n_cls_out);
1727
0
                            ggml_backend_tensor_get_async(backend_embd, t_embd, embd_seq_out[seq_id].data(), (n_cls_out*seq_idx)*sizeof(float), n_cls_out*sizeof(float));
1728
0
                        }
1729
0
                    } break;
1730
0
                case LLAMA_POOLING_TYPE_UNSPECIFIED:
1731
0
                    {
1732
0
                        GGML_ABORT("unknown pooling type");
1733
0
                    }
1734
0
            }
1735
0
        }
1736
1737
        // This flag indicates whether a backend sampler has actually sampled a specific
1738
        // token, or if it has produced probabilites. If true, we can skip the normal copying of logits and embeddings.
1739
0
        const bool has_sampled = !res->t_sampled.empty() || !res->t_sampled_probs.empty() || !res->t_sampled_logits.empty();
1740
1741
0
        if (has_samplers && has_sampled) {
1742
0
            const auto seq_to_output_row = build_seq_to_output_row(ubatch, n_outputs_prev);
1743
0
            const auto stride = n_vocab;
1744
1745
            // async copy the sampling data from the backend to the host
1746
0
            copy_tensor_async_ints(res->t_sampled, sampling.sampled, sampling.sampled_size, seq_to_output_row, sched.get());
1747
1748
0
            copy_tensor_async_floats    (res->t_sampled_logits, sampling.logits,     stride, sampling.logits_count,     seq_to_output_row, sched.get());
1749
0
            copy_tensor_async_floats    (res->t_sampled_probs,  sampling.probs,      stride, sampling.probs_count,      seq_to_output_row, sched.get());
1750
0
            copy_tensor_async_candidates(res->t_candidates,     sampling.candidates, stride, sampling.candidates_count, seq_to_output_row, sched.get());
1751
0
        }
1752
1753
0
        n_outputs_prev += n_outputs;
1754
0
    } while (mctx->next());
1755
1756
    // set to total number of outputs in the batch, for use in llama_get_logits_ith
1757
0
    n_outputs = n_outputs_all;
1758
1759
    // set output mappings
1760
0
    if (n_outputs > 0) {
1761
0
        bool sorted_output = true;
1762
1763
0
        auto & out_ids = balloc->get_out_ids();
1764
1765
0
        GGML_ASSERT(out_ids.size() == (size_t) n_outputs);
1766
1767
0
        for (int64_t i = 0; i < n_outputs; ++i) {
1768
0
            int64_t out_id = out_ids[i];
1769
0
            output_ids[out_id] = i;
1770
0
            if (out_id != i) {
1771
0
                sorted_output = false;
1772
0
            }
1773
0
        }
1774
1775
        // make the outputs have the same order they had in the user-provided batch
1776
        // note: this is mostly relevant for recurrent models atm
1777
0
        if (!sorted_output && n_outputs > 1) {
1778
0
            GGML_ASSERT((size_t) n_outputs == out_ids.size());
1779
1780
            // TODO: is there something more efficient which also minimizes swaps?
1781
            // selection sort, to minimize swaps (from https://en.wikipedia.org/wiki/Selection_sort)
1782
0
            for (uint32_t i = 0; i < n_outputs - 1; ++i) {
1783
0
                uint32_t j_min = i;
1784
0
                for (uint32_t j = i + 1; j < n_outputs; ++j) {
1785
0
                    if (out_ids[j] < out_ids[j_min]) {
1786
0
                        j_min = j;
1787
0
                    }
1788
0
                }
1789
0
                if (j_min == i) {
1790
0
                    continue;
1791
0
                }
1792
0
                std::swap(out_ids[i], out_ids[j_min]);
1793
1794
                // remember the swaps and apply them lazily upon logits/embeddings access
1795
0
                output_swaps.push_back({ i, j_min });
1796
0
            }
1797
1798
0
            std::fill(output_ids.begin(), output_ids.end(), -1);
1799
1800
0
            for (uint32_t i = 0; i < n_outputs; ++i) {
1801
0
                output_ids[out_ids[i]] = i;
1802
0
            }
1803
0
        }
1804
0
    }
1805
1806
    // wait for the computation to finish (automatically done when obtaining the model output)
1807
    //synchronize();
1808
1809
0
    return 0;
1810
0
}
1811
1812
//
1813
// output
1814
//
1815
1816
0
uint32_t llama_context::output_reserve(int32_t n_outputs, const llama_batch & batch) {
1817
0
    const auto & hparams = model.hparams;
1818
0
    const auto & vocab   = model.vocab;
1819
1820
0
    const int64_t n_outputs_max = std::max<int64_t>(n_outputs, n_seq_max());
1821
1822
0
    const auto n_batch    = cparams.n_batch;
1823
0
    const auto n_vocab    = vocab.n_tokens();
1824
0
    const auto n_embd_out = hparams.get_n_embd_out();
1825
1826
0
    bool has_logits = true;
1827
0
    bool has_embd   = cparams.embeddings;
1828
1829
    // TODO: hacky enc-dec support
1830
0
    if (model.arch == LLM_ARCH_T5) {
1831
0
        has_logits = true;
1832
0
        has_embd   = true;
1833
0
    }
1834
1835
    // Check which sampling modes are needed for the current batch.
1836
    // TODO: avoid this branching by working with the worst-case
1837
0
    bool has_sampling = false;
1838
0
    bool cpu_logits   = false;
1839
1840
0
    if (batch.logits) {
1841
0
        for (int32_t i = 0; i < batch.n_tokens; i++) {
1842
0
            if (!batch.logits[i]) {
1843
0
                continue;
1844
0
            }
1845
0
            for (int32_t j = 0; j < batch.n_seq_id[i]; j++) {
1846
0
                llama_seq_id seq_id = batch.seq_id[i][j];
1847
0
                if (sampling.samplers.find(seq_id) != sampling.samplers.end()) {
1848
0
                    has_sampling = true;
1849
0
                } else {
1850
0
                    cpu_logits = true;
1851
0
                }
1852
0
            }
1853
0
        }
1854
0
    } else {
1855
        // When batch.logits is nullptr (when loading state with a dummy batch),
1856
        // allocate CPU logits.
1857
0
        cpu_logits = true;
1858
0
    }
1859
1860
0
    size_t backend_float_count = 0;
1861
0
    size_t backend_token_count = 0;
1862
1863
    // Allocate CPU logits buffer only if needed by sequences in this batch
1864
0
    logits_size = (has_logits && cpu_logits) ? n_vocab*n_outputs_max : 0;
1865
0
    embd_size   = has_embd ? n_embd_out*n_outputs_max : 0;
1866
1867
    // TODO: avoid this branching by working with the worst-case
1868
0
    if (!has_sampling) {
1869
0
        sampling.logits_size     = 0;
1870
0
        sampling.probs_size      = 0;
1871
0
        sampling.sampled_size    = 0;
1872
0
        sampling.candidates_size = 0;
1873
0
    } else {
1874
0
        sampling.logits_size     = n_vocab*n_outputs_max;
1875
0
        sampling.probs_size      = n_vocab*n_outputs_max;
1876
0
        sampling.sampled_size    =         n_outputs_max;
1877
0
        sampling.candidates_size = n_vocab*n_outputs_max;
1878
1879
0
        backend_float_count = sampling.logits_size  + sampling.probs_size;
1880
0
        backend_token_count = sampling.sampled_size + sampling.candidates_size;
1881
0
    }
1882
1883
0
    if (output_ids.empty()) {
1884
        // init, never resized afterwards
1885
0
        output_ids.resize(n_batch);
1886
0
    }
1887
1888
0
    const size_t prev_size = buf_output ? ggml_backend_buffer_get_size(buf_output.get()) : 0;
1889
0
    const size_t new_size  =
1890
0
        (logits_size + embd_size + backend_float_count) * sizeof(float) +
1891
0
        (                          backend_token_count) * sizeof(llama_token);
1892
1893
    // alloc only when more than the current capacity is required
1894
    // TODO: also consider shrinking the buffer
1895
0
    if (!buf_output || prev_size < new_size) {
1896
0
        if (buf_output) {
1897
#ifndef NDEBUG
1898
            // This doesn't happen often, but may be annoying in some cases (like the HellaSwag benchmark)
1899
            LLAMA_LOG_DEBUG("%s: reallocating output buffer from size %.02f MiB to %.02f MiB\n", __func__, prev_size / 1024.0 / 1024.0, new_size / 1024.0 / 1024.0);
1900
#endif
1901
0
            synchronize();
1902
1903
            // TODO: not needed?
1904
0
            buf_output = nullptr;
1905
0
            logits = nullptr;
1906
0
            embd = nullptr;
1907
0
        }
1908
1909
0
        auto * buft = ggml_backend_cpu_buffer_type();
1910
        // try to use the host buffer of the device where the output tensor is allocated for faster transfer to system memory
1911
0
        auto * output_dev = model.dev_output();
1912
0
        auto * output_dev_host_buft = output_dev ? ggml_backend_dev_host_buffer_type(output_dev) : nullptr;
1913
0
        if (output_dev_host_buft) {
1914
0
            buft = output_dev_host_buft;
1915
0
        }
1916
0
        buf_output.reset(ggml_backend_buft_alloc_buffer(buft, new_size));
1917
0
        if (buf_output == nullptr) {
1918
0
            LLAMA_LOG_ERROR("%s: failed to allocate output buffer of size %.2f MiB\n", __func__, new_size / (1024.0 * 1024.0));
1919
0
            return 0;
1920
0
        }
1921
0
    }
1922
1923
0
    float * output_base = (float *) ggml_backend_buffer_get_base(buf_output.get());
1924
1925
0
    logits = nullptr;
1926
0
    embd   = nullptr;
1927
1928
0
    size_t offset = 0;
1929
0
    uint8_t * base = (uint8_t *) output_base;
1930
1931
0
    logits = (has_logits && cpu_logits) ? output_base : nullptr;
1932
0
    offset += logits_size * sizeof(float);
1933
1934
0
    embd = has_embd ? (float *) (base + offset) : nullptr;
1935
0
    offset += embd_size * sizeof(float);
1936
1937
0
    sampling.logits     = nullptr;
1938
0
    sampling.probs      = nullptr;
1939
0
    sampling.sampled    = nullptr;
1940
0
    sampling.candidates = nullptr;
1941
1942
0
    if (has_sampling) {
1943
0
        sampling.logits = (float *) (base + offset);
1944
0
        offset += sampling.logits_size * sizeof(float);
1945
1946
0
        sampling.probs = (float *) (base + offset);
1947
0
        offset += sampling.probs_size * sizeof(float);
1948
1949
0
        sampling.sampled = (llama_token *) (base + offset);
1950
0
        offset += sampling.sampled_size * sizeof(llama_token);
1951
1952
0
        sampling.candidates = (llama_token *) (base + offset);
1953
0
        offset += sampling.candidates_size * sizeof(llama_token);
1954
1955
        // The count vectors keep track of the actual number of logits/probs/candidates
1956
        // copied from the backend for each output row.
1957
1958
0
        sampling.logits_count.resize(n_outputs_max);
1959
0
        sampling.probs_count.resize(n_outputs_max);
1960
0
        sampling.candidates_count.resize(n_outputs_max);
1961
1962
0
        std::fill(sampling.logits_count.begin(),     sampling.logits_count.end(),     0);
1963
0
        std::fill(sampling.probs_count.begin(),      sampling.probs_count.end(),      0);
1964
0
        std::fill(sampling.candidates_count.begin(), sampling.candidates_count.end(), 0);
1965
1966
0
        std::fill_n(sampling.sampled, sampling.sampled_size, LLAMA_TOKEN_NULL);
1967
0
    }
1968
1969
    // set all ids as invalid (negative)
1970
0
    std::fill(output_ids.begin(), output_ids.end(), -1);
1971
1972
0
    this->n_outputs = 0;
1973
1974
0
    return n_outputs_max;
1975
0
}
1976
1977
0
void llama_context::output_reorder() {
1978
0
    const uint64_t n_vocab = model.vocab.n_tokens();
1979
0
    const uint64_t n_embd  = model.hparams.n_embd;
1980
1981
0
    for (size_t s = 0; s < output_swaps.size(); ++s) {
1982
0
        const uint64_t i0 = output_swaps[s].i0;
1983
0
        const uint64_t i1 = output_swaps[s].i1;
1984
1985
0
        if (logits_size > 0) {
1986
0
            for (uint64_t k = 0; k < n_vocab; k++) {
1987
0
                std::swap(logits[i0*n_vocab + k], logits[i1*n_vocab + k]);
1988
0
            }
1989
0
        }
1990
1991
0
        if (embd_size > 0) {
1992
0
            for (uint64_t k = 0; k < n_embd; k++) {
1993
0
                std::swap(embd[i0*n_embd + k], embd[i1*n_embd + k]);
1994
0
            }
1995
0
        }
1996
1997
0
        if (sampling.logits && sampling.logits_size > 0) {
1998
0
            for (uint64_t k = 0; k < n_vocab; ++k) {
1999
0
                std::swap(sampling.logits[i0*n_vocab + k], sampling.logits[i1*n_vocab + k]);
2000
0
            }
2001
0
        }
2002
2003
0
        if (sampling.probs && sampling.probs_size > 0) {
2004
0
            for (uint64_t k = 0; k < n_vocab; ++k) {
2005
0
                std::swap(sampling.probs[i0*n_vocab + k], sampling.probs[i1*n_vocab + k]);
2006
0
            }
2007
0
        }
2008
2009
0
        if (sampling.candidates && sampling.candidates_size > 0) {
2010
0
            for (uint64_t k = 0; k < n_vocab; ++k) {
2011
0
                std::swap(sampling.candidates[i0*n_vocab + k], sampling.candidates[i1*n_vocab + k]);
2012
0
            }
2013
0
        }
2014
2015
0
        if (sampling.sampled && sampling.sampled_size > 0) {
2016
0
            std::swap(sampling.sampled[i0], sampling.sampled[i1]);
2017
0
        }
2018
2019
0
        if (!sampling.logits_count.empty()) {
2020
0
            std::swap(sampling.logits_count[i0], sampling.logits_count[i1]);
2021
0
        }
2022
2023
0
        if (!sampling.probs_count.empty()) {
2024
0
            std::swap(sampling.probs_count[i0], sampling.probs_count[i1]);
2025
0
        }
2026
2027
0
        if (!sampling.candidates_count.empty()) {
2028
0
            std::swap(sampling.candidates_count[i0], sampling.candidates_count[i1]);
2029
0
        }
2030
0
    }
2031
2032
0
    output_swaps.clear();
2033
0
}
2034
2035
//
2036
// graph
2037
//
2038
2039
0
uint32_t llama_context::graph_max_nodes(uint32_t n_tokens) const {
2040
0
    if (model.arch == LLM_ARCH_QWEN3NEXT) {
2041
0
        return std::max<uint32_t>(n_tokens * 40, 32u * model.n_tensors());
2042
0
    }
2043
0
    uint32_t res = std::max<uint32_t>(1024u, 8u*model.n_tensors());
2044
0
    for (const auto & lora : model.loras) {
2045
0
        res += lora->get_n_nodes();
2046
0
    }
2047
0
    return res;
2048
0
}
2049
2050
0
llm_graph_result * llama_context::get_gf_res_reserve() const {
2051
0
    return static_cast<llm_graph_result *>(gf_res_reserve.get());
2052
0
}
2053
2054
ggml_cgraph * llama_context::graph_reserve(
2055
0
        uint32_t n_tokens, uint32_t n_seqs, uint32_t n_outputs, const llama_memory_context_i * mctx, bool split_only, size_t * sizes) {
2056
0
    LLAMA_LOG_DEBUG("%s: reserving a graph for ubatch with n_tokens = %4u, n_seqs = %2u, n_outputs = %4u\n", __func__, n_tokens, n_seqs, n_outputs);
2057
0
    GGML_ASSERT(n_outputs >= 1);
2058
2059
0
    if (n_tokens % n_seqs != 0) {
2060
0
        n_tokens = ((n_tokens + (n_seqs - 1)) / n_seqs) * n_seqs; // round to next multiple of n_seqs
2061
0
        n_outputs = std::max(n_outputs, n_tokens);
2062
2063
0
        LLAMA_LOG_DEBUG("%s: making n_tokens a multiple of n_seqs - n_tokens = %u, n_seqs = %u, n_outputs = %u\n", __func__, n_tokens, n_seqs, n_outputs);
2064
0
    }
2065
2066
0
    ggml_backend_sched_reset(sched.get());
2067
2068
    // when the scheduler is reset, we cannnot reuse the old graph, so we reset the previous graph result to prevent that
2069
0
    gf_res_prev->reset();
2070
2071
    // store the n_outputs as it is, and restore it afterwards
2072
    // TODO: not sure if needed, might simplify in the future by removing this
2073
0
    const auto save_n_outputs = this->n_outputs;
2074
2075
0
    this->n_outputs = n_outputs;
2076
2077
0
    llama_batch_allocr balloc(model.hparams.n_pos_per_embd());
2078
0
    llama_ubatch ubatch = balloc.ubatch_reserve(n_tokens/n_seqs, n_seqs);
2079
2080
    // set one output token per sequence in order to activate all backend samplers
2081
0
    std::vector<llama_seq_id> seq_ids(n_seqs);
2082
0
    for (uint32_t i = 0; i < n_seqs; ++i) {
2083
0
        seq_ids[i] = i;
2084
0
        ubatch.n_seq_id[i] = 1;
2085
0
        ubatch.seq_id[i] = &seq_ids[i];
2086
0
        ubatch.output[i] = true;
2087
0
    }
2088
2089
0
    auto * res = gf_res_reserve.get();
2090
2091
0
    const auto gparams = graph_params(res, ubatch, mctx, LLM_GRAPH_TYPE_DEFAULT);
2092
2093
0
    res->reset();
2094
2095
0
    auto * gf = model.build_graph(gparams);
2096
2097
0
    this->n_outputs = save_n_outputs;
2098
2099
    // initialize scheduler with the specified graph
2100
0
    if (split_only) {
2101
0
        if (sizes) {
2102
0
            ggml_backend_sched_reserve_size(sched.get(), gf, sizes);
2103
0
        } else {
2104
0
            ggml_backend_sched_split_graph(sched.get(), gf);
2105
0
        }
2106
0
    } else if (!ggml_backend_sched_reserve(sched.get(), gf)) {
2107
0
        GGML_ASSERT(!sizes);
2108
0
        LLAMA_LOG_ERROR("%s: failed to allocate compute buffers\n", __func__);
2109
0
        return nullptr;
2110
0
    }
2111
2112
0
    return gf;
2113
0
}
2114
2115
llm_graph_params llama_context::graph_params(
2116
                        llm_graph_result * res,
2117
                      const llama_ubatch & ubatch,
2118
            const llama_memory_context_i * mctx,
2119
0
                          llm_graph_type   gtype) const {
2120
0
    return {
2121
0
        /*.arch        =*/ model.arch,
2122
0
        /*.hparams     =*/ model.hparams,
2123
0
        /*.cparams     =*/ cparams,
2124
0
        /*.ubatch      =*/ ubatch,
2125
0
        /*.gtype       =*/ gtype,
2126
0
        /*.sched       =*/ sched.get(),
2127
0
        /*.backend_cpu =*/ backend_cpu,
2128
0
        /*.cvec        =*/ &cvec,
2129
0
        /*.loras       =*/ &loras,
2130
0
        /*.mctx        =*/ mctx,
2131
0
        /*.cross       =*/ &cross,
2132
0
        /*.samplers    =*/ sampling.samplers,
2133
0
        /*.n_outputs   =*/ n_outputs,
2134
0
        /*.cb          =*/ graph_get_cb(),
2135
0
        /*.res         =*/ res,
2136
0
    };
2137
0
}
2138
2139
ggml_status llama_context::graph_compute(
2140
            ggml_cgraph * gf,
2141
0
                   bool   batched) {
2142
0
    int n_threads        = batched ? cparams.n_threads_batch : cparams.n_threads;
2143
0
    ggml_threadpool_t tp = batched ? threadpool_batch        : threadpool;
2144
2145
0
    if (backend_cpu != nullptr) {
2146
0
        auto * reg = ggml_backend_dev_backend_reg(ggml_backend_get_device(backend_cpu));
2147
0
        auto * set_threadpool_fn = (decltype(ggml_backend_cpu_set_threadpool) *) ggml_backend_reg_get_proc_address(reg, "ggml_backend_cpu_set_threadpool");
2148
0
        if (set_threadpool_fn) {
2149
0
            set_threadpool_fn(backend_cpu, tp);
2150
0
        }
2151
0
    }
2152
2153
    // set the number of threads for all the backends
2154
0
    for (const auto & set_n_threads_fn : set_n_threads_fns) {
2155
0
        set_n_threads_fn.second(set_n_threads_fn.first, n_threads);
2156
0
    }
2157
2158
0
    auto status = ggml_backend_sched_graph_compute_async(sched.get(), gf);
2159
0
    if (status != GGML_STATUS_SUCCESS) {
2160
0
        LLAMA_LOG_ERROR("%s: ggml_backend_sched_graph_compute_async failed with error %d\n", __func__, status);
2161
0
    }
2162
2163
    // fprintf(stderr, "splits: %d\n", ggml_backend_sched_get_n_splits(sched));
2164
2165
0
    return status;
2166
0
}
2167
2168
0
llm_graph_cb llama_context::graph_get_cb() const {
2169
0
    return [&](const llama_ubatch & ubatch, ggml_tensor * cur, const char * name, int il) {
2170
0
        if (il >= 0) {
2171
0
            ggml_format_name(cur, "%s-%d", name, il);
2172
0
        } else {
2173
0
            ggml_set_name(cur, name);
2174
0
        }
2175
2176
0
        if (!cparams.offload_kqv) {
2177
0
            if (strcmp(name, "kqv_merged_cont") == 0) {
2178
                // all nodes between the KV store and the attention output are run on the CPU
2179
0
                ggml_backend_sched_set_tensor_backend(sched.get(), cur, backend_cpu);
2180
0
            }
2181
0
        }
2182
2183
        // norm may be automatically assigned to the backend of the previous layer, increasing data transfer between backends
2184
        // FIXME: fix in ggml_backend_sched
2185
0
        const bool full_offload = model.n_gpu_layers() > model.hparams.n_layer;
2186
0
        if (ubatch.n_tokens < 32 || full_offload) {
2187
0
            if (il != -1 && strcmp(name, "norm") == 0) {
2188
0
                const auto & dev_layer = model.dev_layer(il);
2189
0
                for (const auto & backend : backends) {
2190
0
                    if (ggml_backend_get_device(backend.get()) == dev_layer) {
2191
0
                        if (ggml_backend_supports_op(backend.get(), cur)) {
2192
0
                            ggml_backend_sched_set_tensor_backend(sched.get(), cur, backend.get());
2193
0
                        }
2194
0
                    }
2195
0
                }
2196
0
            }
2197
0
        }
2198
0
    };
2199
0
}
2200
2201
//
2202
// state save/load
2203
//
2204
2205
class llama_io_write_dummy : public llama_io_write_i {
2206
public:
2207
0
    llama_io_write_dummy() = default;
2208
2209
0
    void write(const void * /* src */, size_t size) override {
2210
0
        size_written += size;
2211
0
    }
2212
2213
0
    void write_tensor(const ggml_tensor * /* tensor */, size_t /* offset */, size_t size) override {
2214
0
        size_written += size;
2215
0
    }
2216
2217
0
    size_t n_bytes() override {
2218
0
        return size_written;
2219
0
    }
2220
2221
private:
2222
    size_t size_written = 0;
2223
};
2224
2225
class llama_io_write_buffer : public llama_io_write_i {
2226
public:
2227
    llama_io_write_buffer(
2228
0
            uint8_t * p, size_t len) : ptr(p), buf_size(len) {}
2229
2230
0
    void write(const void * src, size_t size) override {
2231
0
        if (size > buf_size) {
2232
0
            throw std::runtime_error("unexpectedly reached end of buffer");
2233
0
        }
2234
0
        memcpy(ptr, src, size);
2235
0
        ptr += size;
2236
0
        size_written += size;
2237
0
        buf_size -= size;
2238
0
    }
2239
2240
0
    void write_tensor(const ggml_tensor * tensor, size_t offset, size_t size) override {
2241
0
        if (size > buf_size) {
2242
0
            throw std::runtime_error("unexpectedly reached end of buffer");
2243
0
        }
2244
0
        ggml_backend_tensor_get(tensor, ptr, offset, size);
2245
0
        ptr += size;
2246
0
        size_written += size;
2247
0
        buf_size -= size;
2248
0
    }
2249
2250
0
    size_t n_bytes() override {
2251
0
        return size_written;
2252
0
    }
2253
2254
private:
2255
    uint8_t * ptr;
2256
    size_t buf_size = 0;
2257
    size_t size_written = 0;
2258
};
2259
2260
class llama_io_read_buffer : public llama_io_read_i {
2261
public:
2262
0
    llama_io_read_buffer(const uint8_t * p, size_t len) : ptr(p), buf_size(len) {}
2263
2264
0
    const uint8_t * read(size_t size) override {
2265
0
        const uint8_t * base_ptr = ptr;
2266
0
        if (size > buf_size) {
2267
0
            throw std::runtime_error("unexpectedly reached end of buffer");
2268
0
        }
2269
0
        ptr += size;
2270
0
        size_read += size;
2271
0
        buf_size -= size;
2272
0
        return base_ptr;
2273
0
    }
2274
2275
0
    void read_to(void * dst, size_t size) override {
2276
0
        memcpy(dst, read(size), size);
2277
0
    }
2278
2279
0
    size_t n_bytes() override {
2280
0
        return size_read;
2281
0
    }
2282
2283
private:
2284
    const uint8_t * ptr;
2285
    size_t buf_size = 0;
2286
    size_t size_read = 0;
2287
};
2288
2289
class llama_io_write_file : public llama_io_write_i {
2290
public:
2291
0
    llama_io_write_file(llama_file * f) : file(f) {}
2292
2293
0
    void write(const void * src, size_t size) override {
2294
0
        file->write_raw(src, size);
2295
0
        size_written += size;
2296
0
    }
2297
2298
0
    void write_tensor(const ggml_tensor * tensor, size_t offset, size_t size) override {
2299
0
        temp_buffer.resize(size);
2300
0
        ggml_backend_tensor_get(tensor, temp_buffer.data(), offset, size);
2301
0
        write(temp_buffer.data(), temp_buffer.size());
2302
0
    }
2303
2304
0
    size_t n_bytes() override {
2305
0
        return size_written;
2306
0
    }
2307
2308
private:
2309
    llama_file * file;
2310
    size_t size_written = 0;
2311
    std::vector<uint8_t> temp_buffer;
2312
};
2313
2314
class llama_io_read_file : public llama_io_read_i {
2315
public:
2316
0
    llama_io_read_file(llama_file * f) : file(f) {}
2317
2318
0
    void read_to(void * dst, size_t size) override {
2319
0
        file->read_raw(dst, size);
2320
0
        size_read += size;
2321
0
    }
2322
2323
0
    const uint8_t * read(size_t size) override {
2324
0
        temp_buffer.resize(size);
2325
0
        read_to(temp_buffer.data(), size);
2326
0
        return temp_buffer.data();
2327
0
    }
2328
2329
0
    size_t n_bytes() override {
2330
0
        return size_read;
2331
0
    }
2332
2333
private:
2334
    llama_file * file;
2335
    size_t size_read = 0;
2336
    std::vector<uint8_t> temp_buffer;
2337
};
2338
2339
0
size_t llama_context::state_get_size() {
2340
0
    llama_io_write_dummy io;
2341
0
    try {
2342
0
        return state_write_data(io);
2343
0
    } catch (const std::exception & err) {
2344
0
        LLAMA_LOG_ERROR("%s: error getting state size: %s\n", __func__, err.what());
2345
0
        return 0;
2346
0
    }
2347
0
}
2348
2349
0
size_t llama_context::state_get_data(uint8_t * dst, size_t size) {
2350
0
    llama_io_write_buffer io(dst, size);
2351
0
    try {
2352
0
        return state_write_data(io);
2353
0
    } catch (const std::exception & err) {
2354
0
        LLAMA_LOG_ERROR("%s: error saving state: %s\n", __func__, err.what());
2355
0
        return 0;
2356
0
    }
2357
0
}
2358
2359
0
size_t llama_context::state_set_data(const uint8_t * src, size_t size) {
2360
0
    llama_io_read_buffer io(src, size);
2361
0
    try {
2362
0
        return state_read_data(io);
2363
0
    } catch (const std::exception & err) {
2364
0
        LLAMA_LOG_ERROR("%s: error loading state: %s\n", __func__, err.what());
2365
0
        return 0;
2366
0
    }
2367
0
}
2368
2369
0
size_t llama_context::state_seq_get_size(llama_seq_id seq_id, llama_state_seq_flags flags) {
2370
0
    llama_io_write_dummy io;
2371
0
    try {
2372
0
        return state_seq_write_data(io, seq_id, flags);
2373
0
    } catch (const std::exception & err) {
2374
0
        LLAMA_LOG_ERROR("%s: error getting state size: %s\n", __func__, err.what());
2375
0
        return 0;
2376
0
    }
2377
0
}
2378
2379
0
size_t llama_context::state_seq_get_data(llama_seq_id seq_id, uint8_t * dst, size_t size, llama_state_seq_flags flags) {
2380
0
    llama_io_write_buffer io(dst, size);
2381
0
    try {
2382
0
        return state_seq_write_data(io, seq_id, flags);
2383
0
    } catch (const std::exception & err) {
2384
0
        LLAMA_LOG_ERROR("%s: error saving state: %s\n", __func__, err.what());
2385
0
        return 0;
2386
0
    }
2387
0
}
2388
2389
0
size_t llama_context::state_seq_set_data(llama_seq_id seq_id, const uint8_t * src, size_t size, llama_state_seq_flags flags) {
2390
0
    llama_io_read_buffer io(src, size);
2391
0
    try {
2392
0
        return state_seq_read_data(io, seq_id, flags);
2393
0
    } catch (const std::exception & err) {
2394
0
        LLAMA_LOG_ERROR("%s: error loading state: %s\n", __func__, err.what());
2395
0
        return 0;
2396
0
    }
2397
0
}
2398
2399
0
bool llama_context::state_load_file(const char * filepath, llama_token * tokens_out, size_t n_token_capacity, size_t * n_token_count_out) {
2400
0
    llama_file file(filepath, "rb");
2401
2402
    // sanity checks
2403
0
    {
2404
0
        const uint32_t magic   = file.read_u32();
2405
0
        const uint32_t version = file.read_u32();
2406
2407
0
        if (magic != LLAMA_SESSION_MAGIC || version != LLAMA_SESSION_VERSION) {
2408
0
            LLAMA_LOG_ERROR("%s: unknown (magic, version) for session file: %08x, %08x\n", __func__, magic, version);
2409
0
            return false;
2410
0
        }
2411
0
    }
2412
2413
    // load the prompt
2414
0
    {
2415
0
        const uint32_t n_token_count = file.read_u32();
2416
2417
0
        if (n_token_count > n_token_capacity) {
2418
0
            LLAMA_LOG_ERROR("%s: token count in session file exceeded capacity! %u > %zu\n", __func__, n_token_count, n_token_capacity);
2419
0
            return false;
2420
0
        }
2421
2422
0
        file.read_raw(tokens_out, sizeof(llama_token) * n_token_count);
2423
0
        *n_token_count_out = n_token_count;
2424
0
    }
2425
2426
    // restore the context state
2427
0
    {
2428
0
        const size_t n_state_size_cur = file.size() - file.tell();
2429
2430
0
        llama_io_read_file io( &file);
2431
0
        const size_t n_read = state_read_data(io);
2432
2433
0
        if (n_read != n_state_size_cur) {
2434
0
            LLAMA_LOG_ERROR("%s: did not read all of the session file data! size %zu, got %zu\n", __func__, n_state_size_cur, n_read);
2435
0
            return false;
2436
0
        }
2437
0
    }
2438
2439
0
    return true;
2440
0
}
2441
2442
0
bool llama_context::state_save_file(const char * filepath, const llama_token * tokens, size_t n_token_count) {
2443
0
    llama_file file(filepath, "wb");
2444
2445
0
    file.write_u32(LLAMA_SESSION_MAGIC);
2446
0
    file.write_u32(LLAMA_SESSION_VERSION);
2447
2448
    // save the prompt
2449
0
    file.write_u32((uint32_t) n_token_count);
2450
0
    file.write_raw(tokens, sizeof(llama_token) * n_token_count);
2451
2452
    // save the context state using stream saving
2453
0
    llama_io_write_file io(&file);
2454
0
    state_write_data(io);
2455
2456
0
    return true;
2457
0
}
2458
2459
0
size_t llama_context::state_seq_load_file(llama_seq_id seq_id, const char * filepath, llama_token * tokens_out, size_t n_token_capacity, size_t * n_token_count_out) {
2460
0
    llama_file file(filepath, "rb");
2461
2462
    // version checks
2463
0
    {
2464
0
        const uint32_t magic   = file.read_u32();
2465
0
        const uint32_t version = file.read_u32();
2466
2467
0
        if (magic != LLAMA_STATE_SEQ_MAGIC || version != LLAMA_STATE_SEQ_VERSION) {
2468
0
            LLAMA_LOG_ERROR("%s: unknown (magic, version) for sequence state file: %08x, %08x\n", __func__, magic, version);
2469
0
            return 0;
2470
0
        }
2471
0
    }
2472
2473
    // load the prompt
2474
0
    {
2475
0
        const uint32_t n_token_count = file.read_u32();
2476
2477
0
        if (n_token_count > n_token_capacity) {
2478
0
            LLAMA_LOG_ERROR("%s: token count in sequence state file exceeded capacity! %u > %zu\n", __func__, n_token_count, n_token_capacity);
2479
0
            return 0;
2480
0
        }
2481
2482
0
        file.read_raw(tokens_out, sizeof(llama_token) * n_token_count);
2483
0
        *n_token_count_out = n_token_count;
2484
0
    }
2485
2486
    // restore the context state
2487
0
    {
2488
0
        const size_t state_size = file.size() - file.tell();
2489
0
        llama_io_read_file io(&file);
2490
0
        const size_t nread = state_seq_read_data(io, seq_id, 0);
2491
0
        if (!nread) {
2492
0
            LLAMA_LOG_ERROR("%s: failed to restore sequence state\n", __func__);
2493
0
            return 0;
2494
0
        }
2495
0
        GGML_ASSERT(nread <= state_size);
2496
0
        GGML_ASSERT(nread + sizeof(uint32_t) * 3 + sizeof(llama_token) * *n_token_count_out == file.tell());
2497
0
    }
2498
2499
0
    return file.tell();
2500
0
}
2501
2502
0
size_t llama_context::state_seq_save_file(llama_seq_id seq_id, const char * filepath, const llama_token * tokens, size_t n_token_count) {
2503
0
    llama_file file(filepath, "wb");
2504
2505
0
    file.write_u32(LLAMA_STATE_SEQ_MAGIC);
2506
0
    file.write_u32(LLAMA_STATE_SEQ_VERSION);
2507
2508
    // save the prompt
2509
0
    file.write_u32((uint32_t) n_token_count);
2510
0
    file.write_raw(tokens, sizeof(llama_token) * n_token_count);
2511
2512
    // save the context state using stream saving
2513
0
    llama_io_write_file io(&file);
2514
0
    state_seq_write_data(io, seq_id, 0);
2515
2516
0
    const size_t res = file.tell();
2517
0
    GGML_ASSERT(res == sizeof(uint32_t) * 3 + sizeof(llama_token) * n_token_count + io.n_bytes());
2518
2519
0
    return res;
2520
0
}
2521
2522
0
size_t llama_context::state_write_data(llama_io_write_i & io) {
2523
0
    LLAMA_LOG_DEBUG("%s: writing state\n", __func__);
2524
2525
    // write model info
2526
0
    {
2527
0
        LLAMA_LOG_DEBUG("%s: - writing model info\n", __func__);
2528
2529
0
        const std::string arch_str = llm_arch_name(model.arch);
2530
0
        io.write_string(arch_str);
2531
        // TODO: add more model-specific info which should prevent loading the session file if not identical
2532
0
    }
2533
2534
    // write output ids
2535
0
    {
2536
0
        LLAMA_LOG_DEBUG("%s: - writing output ids\n", __func__);
2537
2538
0
        const auto n_outputs    = this->n_outputs;
2539
0
        const auto & output_ids = this->output_ids;
2540
2541
0
        std::vector<int32_t> w_output_pos;
2542
2543
0
        w_output_pos.resize(n_outputs);
2544
2545
        // build a more compact representation of the output ids
2546
0
        for (size_t i = 0; i < n_batch(); ++i) {
2547
            // map an output id to a position in the batch
2548
0
            int64_t pos = output_ids[i];
2549
0
            if (pos >= 0) {
2550
0
                GGML_ASSERT(pos < n_outputs);
2551
0
                w_output_pos[pos] = i;
2552
0
            }
2553
0
        }
2554
2555
0
        io.write(&n_outputs, sizeof(n_outputs));
2556
2557
0
        if (n_outputs) {
2558
0
            io.write(w_output_pos.data(), n_outputs * sizeof(int32_t));
2559
0
        }
2560
0
    }
2561
2562
    // write logits
2563
0
    {
2564
0
        LLAMA_LOG_DEBUG("%s: - writing logits\n", __func__);
2565
2566
0
        const uint64_t logits_size = std::min((uint64_t) this->logits_size, (uint64_t) n_outputs * model.vocab.n_tokens());
2567
2568
0
        io.write(&logits_size, sizeof(logits_size));
2569
2570
0
        if (logits_size) {
2571
0
            io.write(logits, logits_size * sizeof(float));
2572
0
        }
2573
0
    }
2574
2575
    // write embeddings
2576
0
    {
2577
0
        LLAMA_LOG_DEBUG("%s: - writing embeddings\n", __func__);
2578
2579
0
        const uint64_t embd_size = std::min((uint64_t) this->embd_size, (uint64_t) n_outputs * model.hparams.n_embd);
2580
2581
0
        io.write(&embd_size, sizeof(embd_size));
2582
2583
0
        if (embd_size) {
2584
0
            io.write(embd, embd_size * sizeof(float));
2585
0
        }
2586
0
    }
2587
2588
    // TODO: handle sampling buffers and samplers state ?
2589
    //       https://github.com/ggml-org/llama.cpp/pull/17004
2590
2591
0
    if (memory != nullptr) {
2592
0
        LLAMA_LOG_DEBUG("%s: - writing memory module\n", __func__);
2593
0
        memory->state_write(io);
2594
0
    }
2595
2596
0
    return io.n_bytes();
2597
0
}
2598
2599
0
size_t llama_context::state_read_data(llama_io_read_i & io) {
2600
0
    LLAMA_LOG_DEBUG("%s: reading state\n", __func__);
2601
2602
    // read model info
2603
0
    {
2604
0
        LLAMA_LOG_DEBUG("%s: - reading model info\n", __func__);
2605
2606
0
        const std::string cur_arch_str = llm_arch_name(model.arch);
2607
2608
0
        std::string arch_str;
2609
0
        io.read_string(arch_str);
2610
0
        if (cur_arch_str != arch_str) {
2611
0
            throw std::runtime_error(format("wrong model arch: '%s' instead of '%s'", arch_str.c_str(), cur_arch_str.c_str()));
2612
0
        }
2613
        // TODO: add more info which needs to be identical but which is not verified otherwise
2614
0
    }
2615
2616
    // read output ids
2617
0
    {
2618
0
        LLAMA_LOG_DEBUG("%s: - reading output ids\n", __func__);
2619
2620
0
        auto n_outputs = this->n_outputs;
2621
0
        io.read_to(&n_outputs, sizeof(n_outputs));
2622
2623
        // Create a dummy batch for state loading.
2624
0
        llama_batch dummy_batch = {};
2625
0
        dummy_batch.n_tokens = 0;
2626
0
        if (n_outputs > output_reserve(n_outputs, dummy_batch)) {
2627
0
            throw std::runtime_error("could not reserve outputs");
2628
0
        }
2629
2630
0
        std::vector<int32_t> output_pos;
2631
2632
0
        if (n_outputs) {
2633
0
            output_pos.resize(n_outputs);
2634
0
            io.read_to(output_pos.data(), n_outputs * sizeof(int32_t));
2635
2636
0
            for (int32_t i = 0; i < (int32_t) output_pos.size(); ++i) {
2637
0
                int32_t id = output_pos[i];
2638
0
                if ((uint32_t) id >= n_batch()) {
2639
0
                    throw std::runtime_error(format("invalid output id, %d does not fit in batch size of %u", id, n_batch()));
2640
0
                }
2641
0
                this->output_ids[id] = i;
2642
0
            }
2643
2644
0
            this->n_outputs = n_outputs;
2645
0
        }
2646
0
    }
2647
2648
    // read logits
2649
0
    {
2650
0
        LLAMA_LOG_DEBUG("%s: - reading logits\n", __func__);
2651
2652
0
        uint64_t logits_size;
2653
0
        io.read_to(&logits_size, sizeof(logits_size));
2654
2655
0
        if (this->logits_size < logits_size) {
2656
0
            throw std::runtime_error("logits buffer too small");
2657
0
        }
2658
2659
0
        if (logits_size) {
2660
0
            io.read_to(this->logits, logits_size * sizeof(float));
2661
0
        }
2662
0
    }
2663
2664
    // read embeddings
2665
0
    {
2666
0
        LLAMA_LOG_DEBUG("%s: - reading embeddings\n", __func__);
2667
2668
0
        uint64_t embd_size;
2669
0
        io.read_to(&embd_size, sizeof(embd_size));
2670
2671
0
        if (this->embd_size < embd_size) {
2672
0
            throw std::runtime_error("embeddings buffer too small");
2673
0
        }
2674
2675
0
        if (embd_size) {
2676
0
            io.read_to(this->embd, embd_size * sizeof(float));
2677
0
        }
2678
0
    }
2679
2680
    // TODO: handle sampling buffers and samplers state ?
2681
    //       https://github.com/ggml-org/llama.cpp/pull/17004
2682
2683
0
    if (memory) {
2684
0
        LLAMA_LOG_DEBUG("%s: - reading memory module\n", __func__);
2685
2686
0
        memory->state_read(io);
2687
0
    }
2688
2689
0
    return io.n_bytes();
2690
0
}
2691
2692
0
size_t llama_context::state_seq_write_data(llama_io_write_i & io, llama_seq_id seq_id, llama_state_seq_flags flags) {
2693
0
    GGML_UNUSED(seq_id);
2694
2695
0
    if (memory) {
2696
0
        memory->state_write(io, seq_id, flags);
2697
0
    }
2698
2699
0
    return io.n_bytes();
2700
0
}
2701
2702
0
size_t llama_context::state_seq_read_data(llama_io_read_i & io, llama_seq_id seq_id, llama_state_seq_flags flags) {
2703
0
    GGML_UNUSED(seq_id);
2704
2705
0
    if (memory) {
2706
0
        memory->state_read(io, seq_id, flags);
2707
0
    }
2708
2709
0
    return io.n_bytes();
2710
0
}
2711
2712
//
2713
// perf
2714
//
2715
2716
0
llama_perf_context_data llama_context::perf_get_data() const {
2717
0
    llama_perf_context_data data = {};
2718
2719
0
    data.t_start_ms  = 1e-3 * t_start_us;
2720
0
    data.t_load_ms   = 1e-3 * t_load_us;
2721
0
    data.t_p_eval_ms = 1e-3 * t_p_eval_us;
2722
0
    data.t_eval_ms   = 1e-3 * t_eval_us;
2723
0
    data.n_p_eval    = std::max(1, n_p_eval);
2724
0
    data.n_eval      = std::max(1, n_eval);
2725
0
    data.n_reused    = std::max(0, n_reused);
2726
2727
0
    return data;
2728
0
}
2729
2730
0
void llama_context::perf_reset() {
2731
0
    t_start_us  = ggml_time_us();
2732
0
    t_eval_us   = n_eval = 0;
2733
0
    t_p_eval_us = n_p_eval = 0;
2734
0
    n_reused    = 0;
2735
0
}
2736
2737
0
std::map<ggml_backend_buffer_type_t, llama_memory_breakdown_data> llama_context::memory_breakdown() const {
2738
0
    std::map<ggml_backend_buffer_type_t, llama_memory_breakdown_data> ret;
2739
0
    for (const auto & [buft, size] : model.memory_breakdown()) {
2740
0
        ret[buft].model += size;
2741
0
    }
2742
0
    if (memory) {
2743
0
        for (const auto & [buft, size] : memory->memory_breakdown()) {
2744
0
            ret[buft].context += size;
2745
0
        }
2746
0
    }
2747
0
    if (model.hparams.no_alloc) {
2748
0
        for (size_t i = 0; i < backends.size(); ++i) {
2749
0
            ggml_backend_t             backend = backends[i].get();
2750
0
            ggml_backend_buffer_type_t buft    = ggml_backend_sched_get_buffer_type(sched.get(), backend);
2751
0
            ret[buft].compute += backend_buf_exp_size[i];
2752
0
        }
2753
0
    } else {
2754
0
        for (const auto & backend_ptr : backends) {
2755
0
            ggml_backend_t             backend = backend_ptr.get();
2756
0
            ggml_backend_buffer_type_t buft    = ggml_backend_sched_get_buffer_type(sched.get(), backend);
2757
0
            ret[buft].compute += ggml_backend_sched_get_buffer_size(sched.get(), backend);
2758
0
        }
2759
0
    }
2760
0
    return ret;
2761
0
}
2762
2763
//
2764
// training
2765
//
2766
2767
0
static void llama_set_param(struct ggml_tensor * tensor, llama_opt_param_filter param_filter, void * userdata) {
2768
0
    if (!tensor || tensor->type != GGML_TYPE_F32) {
2769
0
        return;
2770
0
    }
2771
0
    if (!param_filter(tensor, userdata)) {
2772
0
        return;
2773
0
    }
2774
0
    if (strcmp(tensor->name, "token_embd.weight") == 0) {
2775
0
        return; // FIXME
2776
0
    }
2777
0
    if (strcmp(tensor->name, "rope_freqs.weight") == 0) {
2778
0
        return; // FIXME
2779
0
    }
2780
0
    ggml_set_param(tensor);
2781
0
}
2782
2783
0
void llama_context::opt_init(struct llama_model * model, struct llama_opt_params lopt_params) {
2784
0
    GGML_ASSERT(!opt_ctx);
2785
0
    model->hparams.n_ctx_train = lopt_params.n_ctx_train > 0 ? lopt_params.n_ctx_train : n_ctx();
2786
0
    const uint32_t n_batch     = std::min(this->n_batch(),  model->hparams.n_ctx_train);
2787
0
    const uint32_t n_ubatch    = std::min(this->n_ubatch(), n_batch);
2788
0
    GGML_ASSERT(model->hparams.n_ctx_train % n_batch  == 0);
2789
0
    GGML_ASSERT(n_batch                    % n_ubatch == 0);
2790
2791
0
    ggml_opt_params opt_params = ggml_opt_default_params(sched.get(), GGML_OPT_LOSS_TYPE_CROSS_ENTROPY);
2792
0
    opt_params.opt_period      = n_batch / n_ubatch;
2793
0
    opt_params.get_opt_pars    = lopt_params.get_opt_pars;
2794
0
    opt_params.get_opt_pars_ud = lopt_params.get_opt_pars_ud;
2795
0
    opt_params.optimizer       = lopt_params.optimizer_type;
2796
0
    opt_ctx = ggml_opt_init(opt_params);
2797
2798
0
    llama_opt_param_filter param_filter = lopt_params.param_filter;
2799
0
    void * param_filter_ud              = lopt_params.param_filter_ud;
2800
2801
  //llama_set_param(model->tok_embd,        param_filter, param_filter_ud); // FIXME
2802
0
    llama_set_param(model->type_embd,       param_filter, param_filter_ud);
2803
0
    llama_set_param(model->pos_embd,        param_filter, param_filter_ud);
2804
0
    llama_set_param(model->tok_norm,        param_filter, param_filter_ud);
2805
0
    llama_set_param(model->tok_norm_b,      param_filter, param_filter_ud);
2806
0
    llama_set_param(model->output_norm,     param_filter, param_filter_ud);
2807
0
    llama_set_param(model->output_norm_b,   param_filter, param_filter_ud);
2808
0
    llama_set_param(model->output,          param_filter, param_filter_ud);
2809
0
    llama_set_param(model->output_b,        param_filter, param_filter_ud);
2810
0
    llama_set_param(model->output_norm_enc, param_filter, param_filter_ud);
2811
0
    llama_set_param(model->cls,             param_filter, param_filter_ud);
2812
0
    llama_set_param(model->cls_b,           param_filter, param_filter_ud);
2813
0
    llama_set_param(model->cls_out,         param_filter, param_filter_ud);
2814
0
    llama_set_param(model->cls_out_b,       param_filter, param_filter_ud);
2815
2816
0
    for (struct llama_layer & layer : model->layers) {
2817
0
        for (size_t i = 0; i < sizeof(layer)/sizeof(struct ggml_tensor *); ++i) {
2818
0
            llama_set_param(reinterpret_cast<struct ggml_tensor **>(&layer)[i], param_filter, param_filter_ud);
2819
0
        }
2820
0
    }
2821
0
}
2822
2823
void llama_context::opt_epoch_iter(
2824
        ggml_opt_dataset_t               dataset,
2825
        ggml_opt_result_t                result,
2826
        const std::vector<llama_token> & tokens,
2827
        const std::vector<llama_token> & labels_sparse,
2828
        llama_batch                    & batch,
2829
        ggml_opt_epoch_callback          callback,
2830
        bool                             train,
2831
        int64_t                          idata_in_loop,
2832
        int64_t                          ndata_in_loop,
2833
0
        int64_t                          t_loop_start) {
2834
0
    GGML_ASSERT(opt_ctx);
2835
0
    const uint32_t n_ctx    = llama_model_n_ctx_train(&model);
2836
0
    const uint32_t n_batch  = std::min(this->n_batch(),  n_ctx);
2837
0
    const uint32_t n_ubatch = std::min(this->n_ubatch(), n_batch);
2838
2839
0
    memory->clear(true);
2840
2841
0
    for (uint32_t pos_ctx = 0; pos_ctx < n_ctx; pos_ctx += n_batch) {
2842
0
        batch.n_tokens = n_batch;
2843
0
        for (uint32_t pos_batch = 0; pos_batch < n_batch; ++pos_batch) {
2844
0
            batch.token   [pos_batch]    = tokens[pos_ctx + pos_batch];
2845
0
            batch.pos     [pos_batch]    = pos_ctx + pos_batch;
2846
0
            batch.n_seq_id[pos_batch]    = 1;
2847
0
            batch.seq_id  [pos_batch][0] = 0;
2848
0
            batch.logits  [pos_batch]    = true;
2849
0
        }
2850
2851
0
        if (!balloc->init(batch, model.vocab, nullptr, model.hparams.n_embd_inp(), cparams.kv_unified ? LLAMA_MAX_SEQ : cparams.n_seq_max, true)) {
2852
0
            LLAMA_LOG_ERROR("%s: failed to initialize batch\n", __func__);
2853
0
            return;
2854
0
        }
2855
2856
0
        const uint32_t n_tokens_all = balloc->get_n_tokens();
2857
2858
0
        n_queued_tokens += n_tokens_all;
2859
2860
0
        embd_seq.clear();
2861
2862
0
        uint32_t n_outputs_all = n_tokens_all;
2863
2864
0
        auto mctx = memory->init_batch(*balloc, cparams.n_ubatch, true);
2865
0
        if (!mctx || mctx->get_status() != LLAMA_MEMORY_STATUS_SUCCESS) {
2866
0
            LLAMA_LOG_ERROR("%s: could not initialize batch\n", __func__);
2867
0
            break;
2868
0
        }
2869
2870
        // reserve output buffer
2871
0
        if (output_reserve(n_outputs_all, balloc->get_batch()) < n_outputs_all) {
2872
0
            LLAMA_LOG_ERROR("%s: could not reserve space for batch with %d outputs\n", __func__, n_outputs_all);
2873
0
            GGML_ABORT("TODO: handle this error");
2874
0
        };
2875
2876
0
        uint32_t pos_batch = 0;
2877
0
        do {
2878
0
            const auto & ubatch = mctx->get_ubatch();
2879
2880
0
            n_outputs = ubatch.n_tokens;
2881
2882
0
            if (!mctx->apply()) {
2883
0
                LLAMA_LOG_ERROR("%s: failed to update the memory context\n", __func__);
2884
0
                break;
2885
0
            }
2886
2887
0
            auto * res = gf_res_prev.get();
2888
2889
0
            const auto gparams = graph_params(res, ubatch, mctx.get(), LLM_GRAPH_TYPE_DEFAULT);
2890
2891
0
            res->reset();
2892
2893
0
            auto * gf = model.build_graph(gparams);
2894
2895
0
            struct ggml_context * ctx_compute_opt;
2896
0
            {
2897
0
                const size_t size_gf = ggml_graph_size(gf);
2898
0
                const size_t size_meta = 4*size_gf*ggml_tensor_overhead() + 2*ggml_graph_overhead_custom(size_gf, /*grads = */ true);
2899
0
                struct ggml_init_params params = {
2900
0
                    /*.mem_size   =*/ size_meta,
2901
0
                    /*.mem_buffer =*/ nullptr,
2902
0
                    /*.no_alloc   =*/ true,
2903
0
                };
2904
0
                ctx_compute_opt = ggml_init(params);
2905
0
            }
2906
0
            ggml_opt_prepare_alloc(opt_ctx, ctx_compute_opt, gf, res->get_tokens(), res->get_logits());
2907
0
            ggml_opt_alloc(opt_ctx, train);
2908
2909
0
            res->set_inputs(&ubatch);
2910
0
            {
2911
0
                struct ggml_tensor * labels = ggml_opt_labels(opt_ctx);
2912
0
                GGML_ASSERT(labels->ne[1] == n_ubatch);
2913
0
                ggml_set_zero(labels);
2914
0
                const float onef = 1.0f;
2915
0
                for (uint32_t pos_ubatch = 0; pos_ubatch < n_ubatch; ++pos_ubatch) {
2916
0
                    const uint32_t ilabel = pos_ctx + pos_batch + pos_ubatch;
2917
0
                    GGML_ASSERT(labels_sparse[ilabel] < labels->ne[0]);
2918
0
                    ggml_backend_tensor_set(labels, &onef, (pos_ubatch*labels->ne[0] + labels_sparse[ilabel])*sizeof(float), sizeof(float));
2919
0
                }
2920
0
            }
2921
0
            ggml_opt_eval(opt_ctx, result);
2922
0
            if (callback) {
2923
0
                callback(train, opt_ctx, dataset, result, idata_in_loop + (pos_ctx + pos_batch)/n_ubatch + 1, ndata_in_loop, t_loop_start);
2924
0
            }
2925
0
            ggml_free(ctx_compute_opt);
2926
2927
0
            pos_batch += ubatch.n_tokens;
2928
0
        } while (mctx->next());
2929
0
    }
2930
0
}
2931
2932
void llama_context::opt_epoch(
2933
        ggml_opt_dataset_t        dataset,
2934
        ggml_opt_result_t         result_train,
2935
        ggml_opt_result_t         result_eval,
2936
        int64_t                   idata_split,
2937
        ggml_opt_epoch_callback   callback_train,
2938
0
        ggml_opt_epoch_callback   callback_eval) {
2939
0
    const uint32_t n_ctx    = this->n_ctx();
2940
0
    const uint32_t n_batch  = std::min(cparams.n_batch,  n_ctx);
2941
0
    const uint32_t n_ubatch = std::min(cparams.n_ubatch, n_batch);
2942
0
    const  int64_t ndata    = ggml_opt_dataset_ndata(dataset);
2943
2944
0
    GGML_ASSERT(idata_split >= 0);
2945
0
    GGML_ASSERT(idata_split <= ndata);
2946
2947
0
    const uint32_t ubatch_per_ctx = n_ctx / n_ubatch;
2948
2949
0
    struct llama_batch batch = llama_batch_init(n_batch, 0, 1);
2950
0
    std::vector<llama_token>        tokens(n_ctx);
2951
0
    std::vector<llama_token> labels_sparse(n_ctx);
2952
2953
0
    int64_t idata = 0;
2954
2955
0
    int64_t t_loop_start = ggml_time_us();
2956
0
    int64_t ndata_in_loop = idata_split*ubatch_per_ctx;
2957
0
    for (; idata < idata_split; ++idata) {
2958
0
        constexpr bool train = true;
2959
0
        const int64_t idata_in_loop = idata*ubatch_per_ctx;
2960
2961
0
        ggml_opt_dataset_get_batch_host(dataset, tokens.data(), n_ctx*sizeof(llama_token), labels_sparse.data(), idata);
2962
0
        opt_epoch_iter(dataset, result_train, tokens, labels_sparse, batch,
2963
0
            callback_train, train, idata_in_loop, ndata_in_loop, t_loop_start);
2964
0
    }
2965
2966
0
    t_loop_start = ggml_time_us();
2967
0
    ndata_in_loop = (ndata - idata_split)*ubatch_per_ctx;
2968
0
    for (; idata < ndata; ++idata) {
2969
0
        constexpr bool train = false;
2970
0
        const int64_t idata_in_loop = (idata - idata_split)*ubatch_per_ctx;
2971
2972
0
        ggml_opt_dataset_get_batch_host(dataset, tokens.data(), n_ctx*sizeof(llama_token), labels_sparse.data(), idata);
2973
0
        opt_epoch_iter(dataset, result_eval, tokens, labels_sparse, batch,
2974
0
            callback_eval, train, idata_in_loop, ndata_in_loop, t_loop_start);
2975
0
    }
2976
2977
0
    llama_batch_free(batch);
2978
0
}
2979
2980
//
2981
// interface implementation
2982
//
2983
2984
0
llama_context_params llama_context_default_params() {
2985
0
    llama_context_params result = {
2986
0
        /*.n_ctx                       =*/ 512,
2987
0
        /*.n_batch                     =*/ 2048,
2988
0
        /*.n_ubatch                    =*/ 512,
2989
0
        /*.n_seq_max                   =*/ 1,
2990
0
        /*.n_threads                   =*/ GGML_DEFAULT_N_THREADS, // TODO: better default
2991
0
        /*.n_threads_batch             =*/ GGML_DEFAULT_N_THREADS,
2992
0
        /*.rope_scaling_type           =*/ LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED,
2993
0
        /*.pooling_type                =*/ LLAMA_POOLING_TYPE_UNSPECIFIED,
2994
0
        /*.attention_type              =*/ LLAMA_ATTENTION_TYPE_UNSPECIFIED,
2995
0
        /*.flash_attn_type             =*/ LLAMA_FLASH_ATTN_TYPE_AUTO,
2996
0
        /*.rope_freq_base              =*/ 0.0f,
2997
0
        /*.rope_freq_scale             =*/ 0.0f,
2998
0
        /*.yarn_ext_factor             =*/ -1.0f,
2999
0
        /*.yarn_attn_factor            =*/ -1.0f,
3000
0
        /*.yarn_beta_fast              =*/ -1.0f,
3001
0
        /*.yarn_beta_slow              =*/ -1.0f,
3002
0
        /*.yarn_orig_ctx               =*/ 0,
3003
0
        /*.defrag_thold                =*/ -1.0f,
3004
0
        /*.cb_eval                     =*/ nullptr,
3005
0
        /*.cb_eval_user_data           =*/ nullptr,
3006
0
        /*.type_k                      =*/ GGML_TYPE_F16,
3007
0
        /*.type_v                      =*/ GGML_TYPE_F16,
3008
0
        /*.abort_callback              =*/ nullptr,
3009
0
        /*.abort_callback_data         =*/ nullptr,
3010
0
        /*.embeddings                  =*/ false,
3011
0
        /*.offload_kqv                 =*/ true,
3012
0
        /*.no_perf                     =*/ true,
3013
0
        /*.op_offload                  =*/ true,
3014
0
        /*.swa_full                    =*/ true,
3015
0
        /*.kv_unified                  =*/ false,
3016
0
        /*.sampler                     =*/ nullptr,
3017
0
        /*.n_sampler                   =*/ 0,
3018
0
    };
3019
3020
0
    return result;
3021
0
}
3022
3023
llama_context * llama_init_from_model(
3024
                 llama_model * model,
3025
0
        llama_context_params   params) {
3026
0
    if (!model) {
3027
0
        LLAMA_LOG_ERROR("%s: model cannot be NULL\n", __func__);
3028
0
        return nullptr;
3029
0
    }
3030
3031
0
    if (params.n_batch == 0 && params.n_ubatch == 0) {
3032
0
        LLAMA_LOG_ERROR("%s: n_batch and n_ubatch cannot both be zero\n", __func__);
3033
0
        return nullptr;
3034
0
    }
3035
3036
0
    if (params.n_ctx == 0 && model->hparams.n_ctx_train == 0) {
3037
0
        LLAMA_LOG_ERROR("%s: n_ctx and model->hparams.n_ctx_train cannot both be zero\n", __func__);
3038
0
        return nullptr;
3039
0
    }
3040
3041
0
    if (params.flash_attn_type != LLAMA_FLASH_ATTN_TYPE_DISABLED && model->arch == LLM_ARCH_GROK) {
3042
0
        LLAMA_LOG_WARN("%s: flash_attn is not compatible with Grok - forcing off\n", __func__);
3043
0
        params.flash_attn_type = LLAMA_FLASH_ATTN_TYPE_DISABLED;
3044
0
    }
3045
3046
0
    if (params.flash_attn_type == LLAMA_FLASH_ATTN_TYPE_AUTO && ggml_is_quantized(params.type_k)) {
3047
0
        const uint32_t blck_size = ggml_blck_size(params.type_k);
3048
0
        if (model->hparams.n_embd_head_k % blck_size != 0) {
3049
0
            LLAMA_LOG_ERROR("%s: K cache type %s with block size %u does not divide n_embd_head_k=%u\n",
3050
0
                __func__, ggml_type_name(params.type_k), blck_size, model->hparams.n_embd_head_k);
3051
0
            return nullptr;
3052
0
        }
3053
0
    }
3054
3055
0
    if (params.flash_attn_type == LLAMA_FLASH_ATTN_TYPE_AUTO && ggml_is_quantized(params.type_v)) {
3056
0
        const uint32_t blck_size = ggml_blck_size(params.type_v);
3057
0
        if (model->hparams.n_embd_head_v % blck_size != 0) {
3058
0
            LLAMA_LOG_ERROR("%s: V cache type %s with block size %u does not divide n_embd_head_k=%u\n",
3059
0
                __func__, ggml_type_name(params.type_v), blck_size, model->hparams.n_embd_head_v);
3060
0
            return nullptr;
3061
0
        }
3062
0
    }
3063
3064
0
    if (ggml_is_quantized(params.type_v) && params.flash_attn_type == LLAMA_FLASH_ATTN_TYPE_DISABLED) {
3065
0
        LLAMA_LOG_ERROR("%s: V cache quantization requires flash_attn\n", __func__);
3066
0
        return nullptr;
3067
0
    }
3068
3069
0
    if (params.pooling_type != LLAMA_POOLING_TYPE_UNSPECIFIED &&
3070
0
        params.pooling_type != model->hparams.pooling_type) {
3071
        //user-specified pooling-type is different from the model default
3072
0
        LLAMA_LOG_WARN("%s: model default pooling_type is [%d], but [%d] was specified\n", __func__,
3073
0
                       model->hparams.pooling_type, params.pooling_type);
3074
0
    }
3075
3076
0
    try {
3077
0
        auto * ctx = new llama_context(*model, params);
3078
0
        return ctx;
3079
0
    } catch (const std::exception & err) {
3080
0
        LLAMA_LOG_ERROR("%s: failed to initialize the context: %s\n", __func__, err.what());
3081
0
    }
3082
3083
0
    return nullptr;
3084
0
}
3085
3086
// deprecated
3087
llama_context * llama_new_context_with_model(
3088
                 llama_model * model,
3089
0
        llama_context_params   params) {
3090
0
    return llama_init_from_model(model, params);
3091
0
}
3092
3093
0
void llama_free(llama_context * ctx) {
3094
0
    delete ctx;
3095
0
}
3096
3097
0
uint32_t llama_n_ctx(const llama_context * ctx) {
3098
0
    return ctx->n_ctx();
3099
0
}
3100
3101
0
uint32_t llama_n_ctx_seq(const llama_context * ctx) {
3102
0
    return ctx->n_ctx_seq();
3103
0
}
3104
3105
0
uint32_t llama_n_batch(const llama_context * ctx) {
3106
0
    return ctx->n_batch();
3107
0
}
3108
3109
0
uint32_t llama_n_ubatch(const llama_context * ctx) {
3110
0
    return ctx->n_ubatch();
3111
0
}
3112
3113
0
uint32_t llama_n_seq_max(const llama_context * ctx) {
3114
0
    return ctx->n_seq_max();
3115
0
}
3116
3117
0
const llama_model * llama_get_model(const llama_context * ctx) {
3118
0
    return &ctx->get_model();
3119
0
}
3120
3121
0
enum llama_pooling_type llama_pooling_type(const llama_context * ctx) {
3122
0
    return ctx->pooling_type();
3123
0
}
3124
3125
void llama_attach_threadpool(
3126
            llama_context * ctx,
3127
        ggml_threadpool_t   threadpool,
3128
0
        ggml_threadpool_t   threadpool_batch) {
3129
0
    ctx->attach_threadpool(threadpool, threadpool_batch);
3130
0
}
3131
3132
0
void llama_detach_threadpool(llama_context * ctx) {
3133
0
    ctx->detach_threadpool();
3134
0
}
3135
3136
0
void llama_set_n_threads(llama_context * ctx, int32_t n_threads, int32_t n_threads_batch) {
3137
0
    ctx->set_n_threads(n_threads, n_threads_batch);
3138
0
}
3139
3140
0
int32_t llama_n_threads(llama_context * ctx) {
3141
0
    return ctx->n_threads();
3142
0
}
3143
3144
0
int32_t llama_n_threads_batch(llama_context * ctx) {
3145
0
    return ctx->n_threads_batch();
3146
0
}
3147
3148
0
void llama_set_abort_callback(llama_context * ctx, bool (*abort_callback)(void * data), void * abort_callback_data) {
3149
0
    ctx->set_abort_callback(abort_callback, abort_callback_data);
3150
0
}
3151
3152
0
void llama_set_embeddings(llama_context * ctx, bool embeddings) {
3153
0
    ctx->set_embeddings(embeddings);
3154
0
}
3155
3156
0
void llama_set_causal_attn(llama_context * ctx, bool causal_attn) {
3157
0
    ctx->set_causal_attn(causal_attn);
3158
0
}
3159
3160
0
void llama_set_warmup(llama_context * ctx, bool warmup) {
3161
0
    ctx->set_warmup(warmup);
3162
0
}
3163
3164
0
void llama_synchronize(llama_context * ctx) {
3165
0
    ctx->synchronize();
3166
0
}
3167
3168
0
float * llama_get_logits(llama_context * ctx) {
3169
0
    ctx->synchronize();
3170
3171
0
    return ctx->get_logits();
3172
0
}
3173
3174
0
float * llama_get_logits_ith(llama_context * ctx, int32_t i) {
3175
0
    ctx->synchronize();
3176
3177
0
    float * res = nullptr;
3178
3179
0
    res = ctx->get_sampled_logits_ith(i);
3180
3181
0
    if (!res) {
3182
0
        res = ctx->get_logits_ith(i);
3183
0
    }
3184
3185
0
    return res;
3186
0
}
3187
3188
0
float * llama_get_embeddings(llama_context * ctx) {
3189
0
    ctx->synchronize();
3190
3191
0
    return ctx->get_embeddings();
3192
0
}
3193
3194
0
float * llama_get_embeddings_ith(llama_context * ctx, int32_t i) {
3195
0
    ctx->synchronize();
3196
3197
0
    return ctx->get_embeddings_ith(i);
3198
0
}
3199
3200
0
float * llama_get_embeddings_seq(llama_context * ctx, llama_seq_id seq_id) {
3201
0
    ctx->synchronize();
3202
3203
0
    return ctx->get_embeddings_seq(seq_id);
3204
0
}
3205
3206
0
bool llama_set_sampler(llama_context * ctx, llama_seq_id seq_id, llama_sampler * smpl) {
3207
0
    return ctx->set_sampler(seq_id, smpl);
3208
0
}
3209
3210
0
llama_token llama_get_sampled_token_ith(llama_context * ctx, int32_t i) {
3211
0
    ctx->synchronize();
3212
3213
0
    return ctx->get_sampled_token_ith(i);
3214
0
}
3215
3216
0
float * llama_get_sampled_probs_ith(llama_context * ctx, int32_t i) {
3217
0
    ctx->synchronize();
3218
3219
0
    return ctx->get_sampled_probs_ith(i);
3220
0
}
3221
3222
0
float * llama_get_sampled_logits_ith(llama_context * ctx, int32_t i) {
3223
0
    ctx->synchronize();
3224
3225
0
    return ctx->get_sampled_logits_ith(i);
3226
0
}
3227
3228
0
llama_token * llama_get_sampled_candidates_ith(llama_context * ctx, int32_t i) {
3229
0
    ctx->synchronize();
3230
3231
0
    return const_cast<llama_token *>(ctx->get_sampled_candidates_ith(i));
3232
0
}
3233
3234
0
uint32_t llama_get_sampled_candidates_count_ith(llama_context * ctx, int32_t i) {
3235
0
    ctx->synchronize();
3236
3237
0
    return static_cast<uint32_t>(ctx->get_sampled_candidates_count(i));
3238
0
}
3239
3240
0
uint32_t llama_get_sampled_logits_count_ith(llama_context * ctx, int32_t i) {
3241
0
    ctx->synchronize();
3242
3243
0
    return static_cast<uint32_t>(ctx->get_sampled_logits_count(i));
3244
0
}
3245
3246
0
uint32_t llama_get_sampled_probs_count_ith(llama_context * ctx, int32_t i) {
3247
0
    ctx->synchronize();
3248
3249
0
    return static_cast<uint32_t>(ctx->get_sampled_probs_count(i));
3250
0
}
3251
3252
// llama adapter API
3253
3254
int32_t llama_set_adapter_lora(
3255
            llama_context * ctx,
3256
            llama_adapter_lora * adapter,
3257
0
            float scale) {
3258
0
    ctx->set_adapter_lora(adapter, scale);
3259
3260
0
    return 0;
3261
0
}
3262
3263
int32_t llama_rm_adapter_lora(
3264
            llama_context * ctx,
3265
0
            llama_adapter_lora * adapter) {
3266
0
    bool res = ctx->rm_adapter_lora(adapter);
3267
3268
0
    return res ? 0 : -1;
3269
0
}
3270
3271
0
void llama_clear_adapter_lora(llama_context * ctx) {
3272
0
    ctx->clear_adapter_lora();
3273
0
}
3274
3275
int32_t llama_apply_adapter_cvec(
3276
        llama_context * ctx,
3277
                 const float * data,
3278
                      size_t   len,
3279
                     int32_t   n_embd,
3280
                     int32_t   il_start,
3281
0
                     int32_t   il_end) {
3282
0
    bool res = ctx->apply_adapter_cvec(data, len, n_embd, il_start, il_end);
3283
3284
0
    return res ? 0 : -1;
3285
0
}
3286
3287
//
3288
// memory
3289
//
3290
3291
0
llama_memory_t llama_get_memory(const struct llama_context * ctx) {
3292
0
    return ctx->get_memory();
3293
0
}
3294
3295
0
void llama_memory_clear(llama_memory_t mem, bool data) {
3296
0
    if (!mem) {
3297
0
        return;
3298
0
    }
3299
3300
0
    mem->clear(data);
3301
0
}
3302
3303
bool llama_memory_seq_rm(
3304
        llama_memory_t mem,
3305
          llama_seq_id seq_id,
3306
             llama_pos p0,
3307
0
             llama_pos p1) {
3308
0
    if (!mem) {
3309
0
        return true;
3310
0
    }
3311
3312
0
    return mem->seq_rm(seq_id, p0, p1);
3313
0
}
3314
3315
void llama_memory_seq_cp(
3316
        llama_memory_t mem,
3317
          llama_seq_id seq_id_src,
3318
          llama_seq_id seq_id_dst,
3319
             llama_pos p0,
3320
0
             llama_pos p1) {
3321
0
    if (!mem) {
3322
0
        return;
3323
0
    }
3324
3325
0
    mem->seq_cp(seq_id_src, seq_id_dst, p0, p1);
3326
0
}
3327
3328
void llama_memory_seq_keep(
3329
        llama_memory_t mem,
3330
0
          llama_seq_id seq_id) {
3331
0
    if (!mem) {
3332
0
        return;
3333
0
    }
3334
3335
0
    mem->seq_keep(seq_id);
3336
0
}
3337
3338
void llama_memory_seq_add(
3339
        llama_memory_t mem,
3340
          llama_seq_id seq_id,
3341
             llama_pos p0,
3342
             llama_pos p1,
3343
0
             llama_pos delta) {
3344
0
    if (!mem) {
3345
0
        return;
3346
0
    }
3347
3348
0
    mem->seq_add(seq_id, p0, p1, delta);
3349
0
}
3350
3351
void llama_memory_seq_div(
3352
        llama_memory_t mem,
3353
          llama_seq_id seq_id,
3354
             llama_pos p0,
3355
             llama_pos p1,
3356
0
                   int d) {
3357
0
    if (!mem) {
3358
0
        return;
3359
0
    }
3360
3361
0
    mem->seq_div(seq_id, p0, p1, d);
3362
0
}
3363
3364
llama_pos llama_memory_seq_pos_min(
3365
        llama_memory_t mem,
3366
0
          llama_seq_id seq_id) {
3367
0
    if (!mem) {
3368
0
        return -1;
3369
0
    }
3370
3371
0
    return mem->seq_pos_min(seq_id);
3372
0
}
3373
3374
llama_pos llama_memory_seq_pos_max(
3375
        llama_memory_t mem,
3376
0
          llama_seq_id seq_id) {
3377
0
    if (!mem) {
3378
0
        return -1;
3379
0
    }
3380
3381
0
    return mem->seq_pos_max(seq_id);
3382
0
}
3383
3384
0
bool llama_memory_can_shift(llama_memory_t mem) {
3385
0
    if (!mem) {
3386
0
        return false;
3387
0
    }
3388
3389
0
    return mem->get_can_shift();
3390
0
}
3391
3392
// llama state API
3393
3394
// deprecated
3395
0
size_t llama_get_state_size(llama_context * ctx) {
3396
0
    return llama_state_get_size(ctx);
3397
0
}
3398
3399
// deprecated
3400
0
size_t llama_copy_state_data(llama_context * ctx, uint8_t * dst) {
3401
0
    return llama_state_get_data(ctx, dst, -1);
3402
0
}
3403
3404
// deprecated
3405
0
size_t llama_set_state_data(llama_context * ctx, const uint8_t * src) {
3406
0
    return llama_state_set_data(ctx, src, -1);
3407
0
}
3408
3409
// deprecated
3410
0
bool llama_load_session_file(llama_context * ctx, const char * path_session, llama_token * tokens_out, size_t n_token_capacity, size_t * n_token_count_out) {
3411
0
    return llama_state_load_file(ctx, path_session, tokens_out, n_token_capacity, n_token_count_out);
3412
0
}
3413
3414
// deprecated
3415
0
bool llama_save_session_file(llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
3416
0
    return llama_state_save_file(ctx, path_session, tokens, n_token_count);
3417
0
}
3418
3419
// Returns the *actual* size of the state.
3420
// Intended to be used when saving to state to a buffer.
3421
0
size_t llama_state_get_size(llama_context * ctx) {
3422
0
    return ctx->state_get_size();
3423
0
}
3424
3425
0
size_t llama_state_get_data(llama_context * ctx, uint8_t * dst, size_t size) {
3426
0
    ctx->synchronize();
3427
3428
0
    return ctx->state_get_data(dst, size);
3429
0
}
3430
3431
// Sets the state reading from the specified source address
3432
0
size_t llama_state_set_data(llama_context * ctx, const uint8_t * src, size_t size) {
3433
0
    ctx->synchronize();
3434
3435
0
    return ctx->state_set_data(src, size);
3436
0
}
3437
3438
0
bool llama_state_load_file(llama_context * ctx, const char * path_session, llama_token * tokens_out, size_t n_token_capacity, size_t * n_token_count_out) {
3439
0
    ctx->synchronize();
3440
3441
0
    try {
3442
0
        return ctx->state_load_file(path_session, tokens_out, n_token_capacity, n_token_count_out);
3443
0
    } catch (const std::exception & err) {
3444
0
        LLAMA_LOG_ERROR("%s: error loading session file: %s\n", __func__, err.what());
3445
0
        return false;
3446
0
    }
3447
0
}
3448
3449
0
bool llama_state_save_file(llama_context * ctx, const char * path_session, const llama_token * tokens, size_t n_token_count) {
3450
0
    ctx->synchronize();
3451
3452
0
    try {
3453
0
        return ctx->state_save_file(path_session, tokens, n_token_count);
3454
0
    } catch (const std::exception & err) {
3455
0
        LLAMA_LOG_ERROR("%s: error saving session file: %s\n", __func__, err.what());
3456
0
        return false;
3457
0
    }
3458
0
}
3459
3460
0
size_t llama_state_seq_get_size(llama_context * ctx, llama_seq_id seq_id) {
3461
0
    return llama_state_seq_get_size_ext(ctx, seq_id, 0);
3462
0
}
3463
3464
0
size_t llama_state_seq_get_data(llama_context * ctx, uint8_t * dst, size_t size, llama_seq_id seq_id) {
3465
0
    return llama_state_seq_get_data_ext(ctx, dst, size, seq_id, 0);
3466
0
}
3467
3468
0
size_t llama_state_seq_set_data(llama_context * ctx, const uint8_t * src, size_t size, llama_seq_id seq_id) {
3469
0
    return llama_state_seq_set_data_ext(ctx, src, size, seq_id, 0);
3470
0
}
3471
3472
0
size_t llama_state_seq_get_size_ext(llama_context * ctx, llama_seq_id seq_id, llama_state_seq_flags flags) {
3473
0
    return ctx->state_seq_get_size(seq_id, flags);
3474
0
}
3475
3476
0
size_t llama_state_seq_get_data_ext(llama_context * ctx, uint8_t * dst, size_t size, llama_seq_id seq_id, llama_state_seq_flags flags) {
3477
0
    ctx->synchronize();
3478
3479
0
    return ctx->state_seq_get_data(seq_id, dst, size, flags);
3480
0
}
3481
3482
0
size_t llama_state_seq_set_data_ext(llama_context * ctx, const uint8_t * src, size_t size, llama_seq_id seq_id, llama_state_seq_flags flags) {
3483
0
    ctx->synchronize();
3484
3485
0
    return ctx->state_seq_set_data(seq_id, src, size, flags);
3486
0
}
3487
3488
0
size_t llama_state_seq_save_file(llama_context * ctx, const char * filepath, llama_seq_id seq_id, const llama_token * tokens, size_t n_token_count) {
3489
0
    ctx->synchronize();
3490
3491
0
    try {
3492
0
        return ctx->state_seq_save_file(seq_id, filepath, tokens, n_token_count);
3493
0
    } catch (const std::exception & err) {
3494
0
        LLAMA_LOG_ERROR("%s: error saving sequence state file: %s\n", __func__, err.what());
3495
0
        return 0;
3496
0
    }
3497
0
}
3498
3499
0
size_t llama_state_seq_load_file(llama_context * ctx, const char * filepath, llama_seq_id dest_seq_id, llama_token * tokens_out, size_t n_token_capacity, size_t * n_token_count_out) {
3500
0
    ctx->synchronize();
3501
3502
0
    try {
3503
0
        return ctx->state_seq_load_file(dest_seq_id, filepath, tokens_out, n_token_capacity, n_token_count_out);
3504
0
    } catch (const std::exception & err) {
3505
0
        LLAMA_LOG_ERROR("%s: error loading sequence state file: %s\n", __func__, err.what());
3506
0
        return 0;
3507
0
    }
3508
0
}
3509
3510
///
3511
3512
int32_t llama_encode(
3513
        llama_context * ctx,
3514
0
          llama_batch   batch) {
3515
0
    const int ret = ctx->encode(batch);
3516
0
    if (ret != 0) {
3517
0
        LLAMA_LOG_ERROR("%s: failed to encode, ret = %d\n", __func__, ret);
3518
0
    }
3519
3520
0
    return ret;
3521
0
}
3522
3523
int32_t llama_decode(
3524
        llama_context * ctx,
3525
0
          llama_batch   batch) {
3526
0
    const int ret = ctx->decode(batch);
3527
0
    if (ret != 0 && ret != 1) {
3528
0
        LLAMA_LOG_ERROR("%s: failed to decode, ret = %d\n", __func__, ret);
3529
0
    }
3530
3531
0
    return ret;
3532
0
}
3533
3534
//
3535
// perf
3536
//
3537
3538
0
llama_perf_context_data llama_perf_context(const llama_context * ctx) {
3539
0
    llama_perf_context_data data = {};
3540
3541
0
    if (ctx == nullptr) {
3542
0
        return data;
3543
0
    }
3544
3545
0
    data = ctx->perf_get_data();
3546
3547
0
    return data;
3548
0
}
3549
3550
0
void llama_perf_context_print(const llama_context * ctx) {
3551
0
    const auto data = llama_perf_context(ctx);
3552
3553
0
    const double t_end_ms = 1e-3 * ggml_time_us();
3554
3555
0
    LLAMA_LOG_INFO("%s:        load time = %10.2f ms\n", __func__, data.t_load_ms);
3556
0
    LLAMA_LOG_INFO("%s: prompt eval time = %10.2f ms / %5d tokens (%8.2f ms per token, %8.2f tokens per second)\n",
3557
0
            __func__, data.t_p_eval_ms, data.n_p_eval, data.t_p_eval_ms / data.n_p_eval, 1e3 / data.t_p_eval_ms * data.n_p_eval);
3558
0
    LLAMA_LOG_INFO("%s:        eval time = %10.2f ms / %5d runs   (%8.2f ms per token, %8.2f tokens per second)\n",
3559
0
            __func__, data.t_eval_ms, data.n_eval, data.t_eval_ms / data.n_eval, 1e3 / data.t_eval_ms * data.n_eval);
3560
0
    LLAMA_LOG_INFO("%s:       total time = %10.2f ms / %5d tokens\n", __func__, (t_end_ms - data.t_start_ms), (data.n_p_eval + data.n_eval));
3561
0
    LLAMA_LOG_INFO("%s:    graphs reused = %10d\n", __func__, data.n_reused);
3562
0
}
3563
3564
0
void llama_perf_context_reset(llama_context * ctx) {
3565
0
    ctx->perf_reset();
3566
0
}
3567
3568
0
void llama_memory_breakdown_print(const struct llama_context * ctx) {
3569
0
    const std::vector<ggml_backend_dev_t> & devices = ctx->get_model().devices;
3570
3571
0
    std::map<ggml_backend_buffer_type_t, llama_memory_breakdown_data> memory_breakdown = ctx->memory_breakdown();
3572
3573
0
    std::vector<std::array<std::string, 9>> table_data;
3574
0
    table_data.reserve(devices.size());
3575
0
    const std::string template_header = "%s: | %s | %s   %s    %s   %s   %s   %s    %s |\n";
3576
0
    const std::string template_gpu    = "%s: | %s | %s = %s + (%s = %s + %s + %s) + %s |\n";
3577
0
    const std::string template_other  = "%s: | %s | %s   %s    %s = %s + %s + %s    %s |\n";
3578
3579
0
    table_data.push_back({template_header, "memory breakdown [MiB]", "total", "free", "self", "model", "context", "compute", "unaccounted"});
3580
3581
0
    constexpr size_t MiB = 1024 * 1024;
3582
0
    const std::vector<std::string> desc_prefixes_strip = {"NVIDIA ", "GeForce ", "Tesla ", "AMD ", "Radeon ", "Instinct "};
3583
3584
    // track seen buffer types to avoid double counting:
3585
0
    std::set<ggml_backend_buffer_type_t> seen_buffer_types;
3586
3587
    // accumulative memory breakdown for each device and for host:
3588
0
    std::vector<llama_memory_breakdown_data> mb_dev(devices.size());
3589
0
    llama_memory_breakdown_data              mb_host;
3590
3591
0
    for (const auto & buft_mb : memory_breakdown) {
3592
0
        ggml_backend_buffer_type_t          buft = buft_mb.first;
3593
0
        const llama_memory_breakdown_data & mb   = buft_mb.second;
3594
0
        if (ggml_backend_buft_is_host(buft)) {
3595
0
            mb_host.model   += mb.model;
3596
0
            mb_host.context += mb.context;
3597
0
            mb_host.compute += mb.compute;
3598
0
            seen_buffer_types.insert(buft);
3599
0
            continue;
3600
0
        }
3601
0
        ggml_backend_dev_t dev = ggml_backend_buft_get_device(buft);
3602
0
        if (dev) {
3603
0
            int i_dev = -1;
3604
0
            for (size_t i = 0; i < devices.size(); i++) {
3605
0
                if (devices[i] == dev) {
3606
0
                    i_dev = i;
3607
0
                    break;
3608
0
                }
3609
0
            }
3610
0
            if (i_dev != -1) {
3611
0
                mb_dev[i_dev].model   += mb.model;
3612
0
                mb_dev[i_dev].context += mb.context;
3613
0
                mb_dev[i_dev].compute += mb.compute;
3614
0
                seen_buffer_types.insert(buft);
3615
0
                continue;
3616
0
            }
3617
0
        }
3618
0
    }
3619
3620
    // print memory breakdown for each device:
3621
0
    for (size_t i = 0; i < devices.size(); i++) {
3622
0
        ggml_backend_dev_t          dev = devices[i];
3623
0
        llama_memory_breakdown_data mb  = mb_dev[i];
3624
3625
0
        const std::string name = ggml_backend_dev_name(dev);
3626
0
        std::string desc = ggml_backend_dev_description(dev);
3627
0
        for (const std::string & prefix : desc_prefixes_strip) {
3628
0
            if (desc.length() >= prefix.length() && desc.substr(0, prefix.length()) == prefix) {
3629
0
                desc = desc.substr(prefix.length());
3630
0
            }
3631
0
        }
3632
3633
0
        size_t free, total;
3634
0
        ggml_backend_dev_memory(dev, &free, &total);
3635
3636
0
        const size_t self = mb.model + mb.context + mb.compute;
3637
0
        const size_t unaccounted = total - self - free;
3638
3639
0
        table_data.push_back({
3640
0
            template_gpu,
3641
0
            "  - " + name + " (" + desc + ")",
3642
0
            std::to_string(total / MiB),
3643
0
            std::to_string(free / MiB),
3644
0
            std::to_string(self / MiB),
3645
0
            std::to_string(mb.model / MiB),
3646
0
            std::to_string(mb.context / MiB),
3647
0
            std::to_string(mb.compute / MiB),
3648
0
            std::to_string(unaccounted / MiB)});
3649
0
    }
3650
3651
    // print memory breakdown for host:
3652
0
    {
3653
0
        const size_t self = mb_host.model + mb_host.context + mb_host.compute;
3654
0
        table_data.push_back({
3655
0
            template_other,
3656
0
            "  - Host",
3657
0
            "", // total
3658
0
            "", // free
3659
0
            std::to_string(self / MiB),
3660
0
            std::to_string(mb_host.model / MiB),
3661
0
            std::to_string(mb_host.context / MiB),
3662
0
            std::to_string(mb_host.compute / MiB),
3663
0
            ""}); // unaccounted
3664
0
    }
3665
3666
    // print memory breakdown for all remaining buffer types:
3667
0
    for (const auto & buft_mb : memory_breakdown) {
3668
0
        ggml_backend_buffer_type_t          buft = buft_mb.first;
3669
0
        const llama_memory_breakdown_data & mb   = buft_mb.second;
3670
0
        if (seen_buffer_types.count(buft) == 1) {
3671
0
            continue;
3672
0
        }
3673
0
        const std::string name = ggml_backend_buft_name(buft);
3674
0
        const size_t self = mb.model + mb.context + mb.compute;
3675
0
        table_data.push_back({
3676
0
            template_other,
3677
0
            "  - " + name,
3678
0
            "", // total
3679
0
            "", // free
3680
0
            std::to_string(self / MiB),
3681
0
            std::to_string(mb.model / MiB),
3682
0
            std::to_string(mb.context / MiB),
3683
0
            std::to_string(mb.compute / MiB),
3684
0
            ""}); // unaccounted
3685
0
        seen_buffer_types.insert(buft);
3686
0
    }
3687
3688
0
    for (size_t j = 1; j < table_data[0].size(); j++) {
3689
0
        size_t max_len = 0;
3690
0
        for (const auto & td : table_data) {
3691
0
            max_len = std::max(max_len, td[j].length());
3692
0
        }
3693
0
        for (auto & td : table_data) {
3694
0
            td[j].insert(j == 1 ? td[j].length() : 0, max_len - td[j].length(), ' ');
3695
0
        }
3696
0
    }
3697
0
    for (const auto & td : table_data) {
3698
0
        LLAMA_LOG_INFO(td[0].c_str(),
3699
0
            __func__, td[1].c_str(), td[2].c_str(), td[3].c_str(), td[4].c_str(), td[5].c_str(),
3700
0
            td[6].c_str(), td[7].c_str(), td[8].c_str());
3701
0
    }
3702
0
}
3703
3704
//
3705
// training
3706
//
3707
3708
0
bool llama_opt_param_filter_all(const struct ggml_tensor * tensor, void * userdata) {
3709
0
    GGML_UNUSED(tensor);
3710
0
    GGML_UNUSED(userdata);
3711
0
    return true;
3712
0
}
3713
3714
0
void llama_opt_init(struct llama_context * ctx, struct llama_model * model, struct llama_opt_params lopt_params) {
3715
0
    ctx->opt_init(model, lopt_params);
3716
0
}
3717
3718
void llama_opt_epoch(
3719
        struct llama_context    * ctx,
3720
        ggml_opt_dataset_t        dataset,
3721
        ggml_opt_result_t         result_train,
3722
        ggml_opt_result_t         result_eval,
3723
        int64_t                   idata_split,
3724
        ggml_opt_epoch_callback   callback_train,
3725
0
        ggml_opt_epoch_callback   callback_eval) {
3726
0
    ctx->opt_epoch(
3727
0
        dataset,
3728
0
        result_train,
3729
0
        result_eval,
3730
0
        idata_split,
3731
0
        callback_train,
3732
0
        callback_eval);
3733
0
}