Coverage Report

Created: 2026-01-13 06:15

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/llama.cpp/src/llama-context.h
Line
Count
Source
1
#pragma once
2
3
#include "llama.h"
4
#include "llama-cparams.h"
5
#include "llama-graph.h"
6
#include "llama-adapter.h"
7
8
#include "ggml-cpp.h"
9
#include "ggml-opt.h"
10
11
#include <map>
12
#include <vector>
13
14
struct llama_model;
15
class llama_batch_allocr;
16
17
class llama_io_read_i;
18
class llama_io_write_i;
19
20
// "memory" as in abstract memory for the context
21
struct llama_memory_i;
22
struct llama_memory_context_i;
23
24
// "memory" as in physical memory for a buffer type, in bytes
25
struct llama_memory_breakdown_data {
26
    size_t model   = 0; // memory allocated for the model
27
    size_t context = 0; // memory allocated for the context
28
    size_t compute = 0; // memory allocated for temporary compute buffers
29
30
0
    size_t total() const {
31
0
        return model + context + compute;
32
0
    }
33
};
34
35
struct llama_context {
36
    // init scheduler and compute buffers, reserve worst-case graphs
37
    llama_context(
38
            const llama_model & model,
39
                  llama_context_params params);
40
41
    ~llama_context();
42
43
    void synchronize();
44
45
    const llama_model   & get_model()   const;
46
    const llama_cparams & get_cparams() const;
47
48
    ggml_backend_sched_t get_sched() const;
49
50
    uint32_t n_ctx()     const;
51
    uint32_t n_ctx_seq() const;
52
    uint32_t n_batch()   const;
53
    uint32_t n_ubatch()  const;
54
    uint32_t n_seq_max() const;
55
56
    uint32_t n_threads()       const;
57
    uint32_t n_threads_batch() const;
58
59
    llama_memory_t get_memory() const;
60
61
    // return true if the memory was updated
62
    bool memory_update(bool optimize);
63
64
    enum llama_pooling_type pooling_type() const;
65
66
    float * get_logits();
67
    float * get_logits_ith(int32_t i);
68
69
    float * get_embeddings();
70
    float * get_embeddings_ith(int32_t i);
71
    float * get_embeddings_seq(llama_seq_id seq_id);
72
73
    llama_token * get_sampled_tokens() const;
74
    llama_token   get_sampled_token_ith(int32_t idx);
75
76
    float * get_sampled_logits_ith(int32_t idx);
77
    size_t  get_sampled_logits_count(int32_t idx);
78
79
    float * get_sampled_probs_ith(int32_t idx);
80
    size_t  get_sampled_probs_count(int32_t idx);
81
82
    const llama_token * get_sampled_candidates_ith(int32_t idx);
83
    size_t get_sampled_candidates_count(int32_t idx);
84
85
    void attach_threadpool(
86
            ggml_threadpool_t threadpool,
87
            ggml_threadpool_t threadpool_batch);
88
89
    void detach_threadpool();
90
91
    void set_n_threads(int32_t n_threads, int32_t n_threads_batch);
92
93
    void set_abort_callback(bool (*abort_callback)(void * data), void * abort_callback_data);
94
95
    void set_embeddings (bool value);
96
    void set_causal_attn(bool value);
97
    void set_warmup(bool value);
98
99
    void set_adapter_lora(
100
            llama_adapter_lora * adapter,
101
            float scale);
102
103
    bool rm_adapter_lora(
104
            llama_adapter_lora * adapter);
105
106
    void clear_adapter_lora();
107
108
    bool apply_adapter_cvec(
109
            const float * data,
110
                 size_t   len,
111
                int32_t   n_embd,
112
                int32_t   il_start,
113
                int32_t   il_end);
114
115
    // process a single ubatch with a specific graph type
116
    // if memory_context is provided, it will be applied first to the context's memory
117
    // ret contains the status of the graph computation
118
    // returns nullptr only if ret != GGML_STATUS_SUCCESS
119
    llm_graph_result * process_ubatch(
120
                const llama_ubatch & ubatch,
121
                    llm_graph_type   gtype,
122
            llama_memory_context_i * mctx,
123
                       ggml_status & ret);
124
125
    int encode(const llama_batch & batch_inp);
126
    int decode(const llama_batch & batch_inp);
127
128
    //
129
    // state save/load
130
    //
131
132
    size_t state_get_size();
133
    size_t state_get_data(      uint8_t * dst, size_t size);
134
    size_t state_set_data(const uint8_t * src, size_t size);
135
136
    size_t state_seq_get_size(llama_seq_id seq_id, llama_state_seq_flags flags);
137
    size_t state_seq_get_data(llama_seq_id seq_id,       uint8_t * dst, size_t size, llama_state_seq_flags flags);
138
    size_t state_seq_set_data(llama_seq_id seq_id, const uint8_t * src, size_t size, llama_state_seq_flags flags);
139
140
    bool state_load_file(
141
            const char * filepath,
142
           llama_token * tokens_out,
143
                size_t   n_token_capacity,
144
                size_t * n_token_count_out);
145
146
    bool state_save_file(
147
            const char * filepath,
148
     const llama_token * tokens,
149
                size_t   n_token_count);
150
151
    size_t state_seq_load_file(
152
          llama_seq_id   seq_id,
153
            const char * filepath,
154
           llama_token * tokens_out,
155
                size_t   n_token_capacity,
156
                size_t * n_token_count_out);
157
158
    size_t state_seq_save_file(
159
          llama_seq_id   seq_id,
160
            const char * filepath,
161
     const llama_token * tokens,
162
                size_t   n_token_count);
163
164
    //
165
    // perf
166
    //
167
168
    llama_perf_context_data perf_get_data() const;
169
    void perf_reset();
170
171
    std::map<ggml_backend_buffer_type_t, llama_memory_breakdown_data> memory_breakdown() const;
172
173
    //
174
    // training
175
    //
176
177
    void opt_init(struct llama_model * model, struct llama_opt_params lopt_params);
178
179
    // TODO: more flexible combinations of logical/physical batch size and context size
180
    void opt_epoch(
181
            ggml_opt_dataset_t      dataset,
182
            ggml_opt_result_t       result_train,
183
            ggml_opt_result_t       result_eval,
184
            int64_t                 idata_split,
185
            ggml_opt_epoch_callback callback_train,
186
            ggml_opt_epoch_callback callback_eval);
187
188
    void opt_epoch_iter(
189
            ggml_opt_dataset_t               dataset,
190
            ggml_opt_result_t                result,
191
            const std::vector<llama_token> & tokens,
192
            const std::vector<llama_token> & labels_sparse,
193
            llama_batch                    & batch,
194
            ggml_opt_epoch_callback          callback,
195
            bool                             train,
196
            int64_t                          idata_in_loop,
197
            int64_t                          ndata_in_loop,
198
            int64_t                          t_loop_start);
199
200
private:
201
    //
202
    // output
203
    //
204
205
    // Make sure enough space is available for outputs.
206
    // Returns max number of outputs for which space was reserved.
207
    uint32_t output_reserve(int32_t n_outputs, const llama_batch & batch);
208
209
    void output_reorder();
210
211
    // map the output row index `i` to batch index
212
    int64_t output_resolve_row(int32_t i) const;
213
214
    //
215
    // graph
216
    //
217
218
public:
219
    uint32_t graph_max_nodes(uint32_t n_tokens) const;
220
221
    // can reuse the llm_graph_result instance of the context (for example to update a memory module)
222
    llm_graph_result * get_gf_res_reserve() const;
223
224
    // returns the result of ggml_backend_sched_graph_compute_async execution
225
    ggml_status graph_compute(ggml_cgraph * gf, bool batched);
226
227
    // reserve a graph with a dummy ubatch of the specified size
228
    ggml_cgraph * graph_reserve(
229
        uint32_t n_tokens, uint32_t n_seqs, uint32_t n_outputs, const llama_memory_context_i * mctx, bool split_only = false, size_t * sizes = nullptr);
230
231
    bool set_sampler(llama_seq_id seq_id, llama_sampler * sampler);
232
233
private:
234
    llm_graph_params graph_params(
235
                        llm_graph_result * res,
236
                      const llama_ubatch & ubatch,
237
            const llama_memory_context_i * mctx,
238
                          llm_graph_type   gtype) const;
239
240
    llm_graph_cb graph_get_cb() const;
241
242
    // TODO: read/write lora adapters and cvec
243
    size_t state_write_data(llama_io_write_i & io);
244
    size_t state_read_data (llama_io_read_i  & io);
245
246
    size_t state_seq_write_data(llama_io_write_i & io, llama_seq_id seq_id, llama_state_seq_flags flags);
247
    size_t state_seq_read_data (llama_io_read_i  & io, llama_seq_id seq_id, llama_state_seq_flags flags);
248
249
    //
250
    // members
251
    //
252
253
    const llama_model & model;
254
255
    llama_cparams       cparams;
256
    llama_adapter_cvec  cvec;
257
    llama_adapter_loras loras;
258
259
    llama_cross cross; // TODO: tmp for handling cross-attention - need something better probably
260
261
    std::unique_ptr<llama_memory_i> memory;
262
263
    // decode output (2-dimensional array: [n_outputs][n_vocab])
264
    size_t  logits_size = 0; // capacity (of floats) for logits
265
    float * logits      = nullptr;
266
267
    // embeddings output (2-dimensional array: [n_outputs][n_embd])
268
    // populated only when pooling_type == LLAMA_POOLING_TYPE_NONE
269
    size_t  embd_size = 0; // capacity (of floats) for embeddings
270
    float * embd      = nullptr;
271
272
    // TODO: simplify
273
    struct sampling_info {
274
        std::map<llama_seq_id, llama_sampler *> samplers;
275
276
        float       * logits      = nullptr;
277
        size_t        logits_size = 0;
278
279
        llama_token * sampled      = nullptr;
280
        size_t        sampled_size = 0;
281
282
        float       * probs        = nullptr;
283
        size_t        probs_size   = 0;
284
285
        llama_token * candidates   = nullptr;
286
        size_t        candidates_size = 0;
287
288
        std::vector<uint32_t> logits_count;
289
        std::vector<uint32_t> probs_count;
290
        std::vector<uint32_t> candidates_count;
291
292
        std::vector<llama_token> token_ids_full_vocab;
293
    };
294
295
    sampling_info sampling;
296
297
    // sequence embeddings output (map of [n_embd] vectors)
298
    // populated only when pooling_type != LLAMA_POOLING_TYPE_NONE
299
    std::map<llama_seq_id, std::vector<float>> embd_seq;
300
301
    // reuse the batch_allocr to avoid unnecessary memory allocations
302
    std::unique_ptr<llama_batch_allocr> balloc;
303
304
    uint32_t n_outputs = 0; // number of actually-used outputs in the current ubatch or last logical batch
305
306
    std::vector<int32_t> output_ids; // map batch token positions to ids of the logits and embd buffers
307
308
    struct swap_info {
309
        uint32_t i0;
310
        uint32_t i1;
311
    };
312
313
    std::vector<swap_info> output_swaps;
314
315
    ggml_backend_sched_ptr sched;
316
317
    ggml_backend_t backend_cpu = nullptr;
318
    std::vector<ggml_backend_ptr> backends;
319
320
    // training
321
    ggml_opt_context_t opt_ctx = nullptr;
322
323
    ggml_threadpool_t threadpool       = nullptr;
324
    ggml_threadpool_t threadpool_batch = nullptr;
325
326
    ggml_abort_callback abort_callback      = nullptr;
327
    void *              abort_callback_data = nullptr;
328
329
    std::vector<std::pair<ggml_backend_t, ggml_backend_set_n_threads_t>> set_n_threads_fns;
330
331
    // pointers and buffer types used for the compute buffer of each backend
332
    std::vector<ggml_backend_t>             backend_ptrs;
333
    std::vector<ggml_backend_buffer_type_t> backend_buft;
334
    std::vector<size_t>                     backend_buf_exp_size; // expected buffer sizes
335
336
    llm_graph_result_ptr gf_res_prev;
337
    llm_graph_result_ptr gf_res_reserve;
338
339
    // host buffer for the model output (logits and embeddings)
340
    ggml_backend_buffer_ptr buf_output;
341
342
    bool has_evaluated_once = false;
343
344
    // env: LLAMA_GRAPH_REUSE_DISABLE
345
    bool graph_reuse_disable = false;
346
347
    // perf
348
    mutable int64_t t_start_us  = 0;
349
    mutable int64_t t_load_us   = 0;
350
    mutable int64_t t_p_eval_us = 0;
351
    mutable int64_t t_eval_us   = 0;
352
353
    mutable int64_t t_compute_start_us = 0;
354
    mutable int64_t n_queued_tokens    = 0;
355
356
    mutable int32_t n_p_eval = 0; // number of tokens in eval calls for the prompt (with batch size > 1)
357
    mutable int32_t n_eval   = 0; // number of eval calls
358
359
    mutable int32_t n_reused = 0; // number of times the previous graph was reused
360
};