okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-own-1b (033cfdd8c) into f-own-int: nothing downloads llama.cppb2de2641f

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