Coverage Report

Created: 2025-12-28 06:25

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/llama.cpp/src/llama.cpp
Line
Count
Source
1
#include "llama.h"
2
3
#include "llama-impl.h"
4
5
#include "llama-chat.h"
6
#include "llama-context.h"
7
#include "llama-mmap.h"
8
#include "llama-vocab.h"
9
#include "llama-model-loader.h"
10
#include "llama-model-saver.h"
11
#include "llama-model.h"
12
13
#include "ggml.h"
14
#include "ggml-backend.h"
15
16
#include <algorithm>
17
#include <cassert>
18
#include <cinttypes>
19
#include <cstddef>
20
#include <cstdint>
21
#include <cstdio>
22
#include <cstring>
23
#include <ctime>
24
#include <stdexcept>
25
26
#if defined(_MSC_VER)
27
#pragma warning(disable: 4244 4267) // possible loss of data
28
#endif
29
30
//
31
// interface implementation
32
//
33
34
0
const char * llama_flash_attn_type_name(enum llama_flash_attn_type flash_attn_type) {
35
0
    switch (flash_attn_type) {
36
0
        case LLAMA_FLASH_ATTN_TYPE_AUTO:
37
0
            return "auto";
38
0
        case LLAMA_FLASH_ATTN_TYPE_DISABLED:
39
0
            return "disabled";
40
0
        case LLAMA_FLASH_ATTN_TYPE_ENABLED:
41
0
            return "enabled";
42
0
    }
43
0
    GGML_ABORT("fatal error");
44
0
}
45
46
struct llama_device_memory_data {
47
    int64_t total;
48
    int64_t free;
49
    llama_memory_breakdown_data mb;
50
};
51
52
static std::vector<llama_device_memory_data> llama_get_device_memory_data(
53
        const char * path_model, const llama_model_params * mparams, const llama_context_params * cparams,
54
        std::vector<ggml_backend_dev_t> & devs, uint32_t & hp_ngl, uint32_t & hp_n_ctx_train, uint32_t & hp_n_expert,
55
0
        const ggml_log_level log_level) {
56
0
    struct user_data_t {
57
0
        struct {
58
0
            ggml_log_callback callback;
59
0
            void * user_data;
60
0
        } original_logger;
61
0
        ggml_log_level min_level; // prints below this log level go to debug log
62
0
    };
63
0
    user_data_t ud;
64
0
    llama_log_get(&ud.original_logger.callback, &ud.original_logger.user_data);
65
0
    ud.min_level = log_level;
66
67
0
    llama_log_set([](ggml_log_level level, const char * text, void * user_data) {
68
0
        const user_data_t * ud = (const user_data_t *) user_data;
69
0
        const ggml_log_level level_eff = level >= ud->min_level ? level : GGML_LOG_LEVEL_DEBUG;
70
0
        ud->original_logger.callback(level_eff, text, ud->original_logger.user_data);
71
0
    }, &ud);
72
73
0
    llama_model_params mparams_copy = *mparams;
74
0
    mparams_copy.no_alloc  = true;
75
0
    mparams_copy.use_mmap  = false;
76
0
    mparams_copy.use_mlock = false;
77
78
0
    llama_model * model = llama_model_load_from_file(path_model, mparams_copy);
79
0
    if (model == nullptr) {
80
0
        llama_log_set(ud.original_logger.callback, ud.original_logger.user_data);
81
0
        throw std::runtime_error("failed to load model");
82
0
    }
83
84
0
    llama_context * ctx = llama_init_from_model(model, *cparams);
85
0
    if (ctx == nullptr) {
86
0
        llama_model_free(model);
87
0
        llama_log_set(ud.original_logger.callback, ud.original_logger.user_data);
88
0
        throw std::runtime_error("failed to create llama_context from model");
89
0
    }
90
91
0
    std::vector<llama_device_memory_data> ret(model->devices.size());
92
93
0
    std::map<ggml_backend_buffer_type_t, llama_memory_breakdown_data> memory_breakdown = ctx->memory_breakdown();
94
95
0
    for (const auto & [buft, mb] : memory_breakdown) {
96
0
        if (ggml_backend_buft_is_host(buft)) {
97
0
            continue;
98
0
        }
99
100
0
        ggml_backend_dev_t dev = ggml_backend_buft_get_device(buft);
101
0
        if (!dev) {
102
0
            continue;
103
0
        }
104
0
        for (size_t i = 0; i < ret.size(); i++) {
105
0
            if (model->devices[i] == dev) {
106
0
                ret[i].mb.model   += mb.model;
107
0
                ret[i].mb.context += mb.context;
108
0
                ret[i].mb.compute += mb.compute;
109
0
                break;
110
0
            }
111
0
        }
112
0
    }
113
0
    for (size_t i = 0; i < ret.size(); i++) {
114
0
        size_t free, total;
115
0
        ggml_backend_dev_memory(model->devices[i], &free, &total);
116
0
        ret[i].free  = free;
117
0
        ret[i].total = total;
118
0
    }
119
120
0
    devs           = model->devices;
121
0
    hp_ngl         = model->hparams.n_layer;
122
0
    hp_n_ctx_train = model->hparams.n_ctx_train;
123
0
    hp_n_expert    = model->hparams.n_expert;
124
125
0
    llama_memory_breakdown_print(ctx); // goes to debug log
126
127
0
    llama_free(ctx);
128
0
    llama_model_free(model);
129
0
    llama_log_set(ud.original_logger.callback, ud.original_logger.user_data);
130
0
    return ret;
131
0
}
132
133
// enum to identify part of a layer for distributing its tensors:
134
enum layer_fraction_t {
135
    LAYER_FRACTION_NONE = 0, // nothing
136
    LAYER_FRACTION_ATTN = 1, // attention
137
    LAYER_FRACTION_UP   = 2, // attention + up
138
    LAYER_FRACTION_GATE = 3, // attention + up + gate
139
    LAYER_FRACTION_MOE  = 4, // everything but sparse MoE weights
140
};
141
// this enum is only used in llama_params_fit_impl but needs to be defined outside of it to fix a Windows compilation issue
142
143
class llama_params_fit_exception : public std::runtime_error {
144
    using std::runtime_error::runtime_error;
145
};
146
147
static void llama_params_fit_impl(
148
        const char * path_model, struct llama_model_params * mparams, struct llama_context_params * cparams,
149
        float * tensor_split, struct llama_model_tensor_buft_override * tensor_buft_overrides,
150
0
        size_t margin_s, uint32_t n_ctx_min, enum ggml_log_level log_level) {
151
0
    constexpr int64_t MiB = 1024*1024;
152
0
    const int64_t margin = margin_s; // this function uses int64_t rather than size_t for memory sizes to more conveniently handle deficits
153
0
    typedef std::vector<llama_device_memory_data> dmds_t;
154
0
    const llama_model_params default_mparams = llama_model_default_params();
155
156
0
    std::vector<ggml_backend_dev_t> devs;
157
0
    uint32_t hp_ngl = 0; // hparams.n_gpu_layers
158
0
    uint32_t hp_nct = 0; // hparams.n_ctx_train
159
0
    uint32_t hp_nex = 0; // hparams.n_expert
160
161
    // step 1: get data for default parameters and check whether any changes are necessary in the first place
162
163
0
    LLAMA_LOG_DEBUG("%s: getting device memory data for initial parameters:\n", __func__);
164
0
    const dmds_t dmds_full = llama_get_device_memory_data(path_model, mparams, cparams, devs, hp_ngl, hp_nct, hp_nex, log_level);
165
0
    const size_t nd = devs.size(); // number of devices
166
0
    if (nd == 0) {
167
0
        LLAMA_LOG_INFO("%s: no devices with dedicated memory found\n", __func__);
168
0
        return;
169
0
    }
170
171
0
    std::vector<std::string> dev_names;
172
0
    {
173
0
        dev_names.reserve(nd);
174
0
        size_t max_length = 0;
175
0
        for (ggml_backend_dev_t dev : devs) {
176
0
            std::string name = ggml_backend_dev_name(dev);
177
0
            name += " (";
178
0
            name += ggml_backend_dev_description(dev);
179
0
            name += ")";
180
0
            dev_names.push_back(name);
181
0
            max_length = std::max(max_length, name.length());
182
0
        }
183
0
        for (std::string & dn : dev_names) {
184
0
            dn.insert(dn.end(), max_length - dn.length(), ' ');
185
0
        }
186
0
    }
187
188
0
    int64_t sum_free            = 0;
189
0
    int64_t sum_projected_free  = 0;
190
0
    int64_t min_projected_free  = INT64_MAX;
191
0
    int64_t sum_projected_used  = 0;
192
0
    int64_t sum_projected_model = 0;
193
194
0
    if (nd > 1) {
195
0
        LLAMA_LOG_INFO("%s: projected memory use with initial parameters [MiB]:\n", __func__);
196
0
    }
197
0
    for (size_t id = 0; id < nd; id++) {
198
0
        const llama_device_memory_data & dmd = dmds_full[id];
199
200
0
        const int64_t projected_used = dmd.mb.total();
201
0
        const int64_t projected_free = dmd.free - projected_used;
202
203
0
        sum_free            += dmd.free;
204
0
        sum_projected_used  += projected_used;
205
0
        sum_projected_free  += projected_free;
206
0
        min_projected_free   = std::min(min_projected_free, projected_free);
207
0
        sum_projected_model += dmd.mb.model;
208
209
0
        if (nd > 1) {
210
0
            LLAMA_LOG_INFO("%s:   - %s: %6" PRId64 " total, %6" PRId64 " used, %6" PRId64 " %s\n",
211
0
                __func__, dev_names[id].c_str(), dmd.total/MiB, projected_used/MiB, std::abs(projected_free)/MiB,
212
0
                projected_free >= 0 ? "surplus" : "deficit");
213
0
        }
214
0
    }
215
0
    assert(sum_free >= 0 && sum_projected_used >= 0);
216
0
    LLAMA_LOG_INFO("%s: projected to use %" PRId64 " MiB of device memory vs. %" PRId64 " MiB of free device memory\n",
217
0
        __func__, sum_projected_used/MiB, sum_free/MiB);
218
0
    if (min_projected_free >= margin) {
219
0
        if (nd == 1) {
220
0
            LLAMA_LOG_INFO("%s: will leave %" PRId64 " >= %" PRId64 " MiB of free device memory, no changes needed\n",
221
0
                __func__, min_projected_free/MiB, margin/MiB);
222
0
            return;
223
0
        }
224
0
        LLAMA_LOG_INFO("%s: will leave at least %" PRId64 " >= %" PRId64 " MiB of free memory on all devices, no changes needed\n",
225
0
            __func__, min_projected_free/MiB, margin/MiB);
226
0
        return;
227
0
    }
228
229
    // step 2: try reducing memory use by reducing the context size
230
231
0
    {
232
0
        int64_t global_surplus = sum_projected_free - int64_t(nd)*margin;
233
0
        if (global_surplus < 0) {
234
0
            LLAMA_LOG_INFO(nd == 1 ?
235
0
                "%s: cannot fulfill margin of %" PRId64 " MiB, need to reduce device memory by %" PRId64 " MiB\n" :
236
0
                "%s: cannot fulfill margin of %" PRId64 " MiB on all devices, need to use %" PRId64 " MiB less in total\n",
237
0
                __func__, margin/MiB, -global_surplus/MiB);
238
0
            if (cparams->n_ctx == 0) {
239
0
                if (hp_nct > n_ctx_min) {
240
0
                    int64_t sum_used_target = sum_free - nd*margin_s;
241
0
                    if (nd > 1) {
242
                        // for multiple devices we need to be more conservative in terms of how much context we think can fit:
243
                        //   - for dense models only whole layers can be assigned to devices
244
                        //   - for MoE models only whole tensors can be assigned to devices, which we estimate to be <= 1/3 of a layer
245
                        //   - on average we expect a waste of 0.5 layers/tensors per device
246
                        //   - use slightly more than the expected average for nd devices to be safe
247
0
                        const int64_t model_per_layer = sum_projected_model / std::min(uint32_t(mparams->n_gpu_layers), hp_ngl);
248
0
                        sum_used_target -= (nd + 1) * model_per_layer / (hp_nex == 0 ? 2 : 6);
249
0
                    }
250
251
0
                    int64_t sum_projected_used_min_ctx = 0;
252
0
                    cparams->n_ctx = n_ctx_min;
253
0
                    const dmds_t dmds_min_ctx = llama_get_device_memory_data(path_model, mparams, cparams, devs, hp_ngl, hp_nct, hp_nex, log_level);
254
0
                    for (const auto & dmd : dmds_min_ctx) {
255
0
                        sum_projected_used_min_ctx += dmd.mb.total();
256
0
                    }
257
0
                    if (sum_used_target > sum_projected_used_min_ctx) {
258
                        // linear interpolation between minimum and maximum context size:
259
0
                        cparams->n_ctx += (hp_nct - n_ctx_min) * (sum_used_target - sum_projected_used_min_ctx)
260
0
                            / (sum_projected_used - sum_projected_used_min_ctx);
261
0
                        cparams->n_ctx = std::max(cparams->n_ctx - cparams->n_ctx % 256, n_ctx_min); // round down context for CUDA backend
262
263
0
                        const int64_t bytes_per_ctx = (sum_projected_used - sum_projected_used_min_ctx) / (hp_nct - n_ctx_min);
264
0
                        const int64_t memory_reduction = (hp_nct - cparams->n_ctx) * bytes_per_ctx;
265
0
                        LLAMA_LOG_INFO("%s: context size reduced from %" PRIu32 " to %" PRIu32 " -> need %" PRId64 " MiB less memory in total\n",
266
0
                            __func__, hp_nct, cparams->n_ctx, memory_reduction/MiB);
267
0
                        if (nd == 1) {
268
0
                            LLAMA_LOG_INFO("%s: entire model can be fit by reducing context\n", __func__);
269
0
                            return;
270
0
                        }
271
0
                        LLAMA_LOG_INFO("%s: entire model should be fit across devices by reducing context\n", __func__);
272
0
                    } else {
273
0
                        const int64_t memory_reduction = sum_projected_used - sum_projected_used_min_ctx;
274
0
                        LLAMA_LOG_INFO("%s: context size reduced from %" PRIu32 " to %" PRIu32 " -> need %" PRId64 " MiB less memory in total\n",
275
0
                            __func__, hp_nct, cparams->n_ctx, memory_reduction/MiB);
276
0
                    }
277
0
                } else {
278
0
                    LLAMA_LOG_INFO("%s: default model context size is %" PRIu32 " which is <= the min. context size of %" PRIu32 " -> no change\n",
279
0
                        __func__, hp_nct, n_ctx_min);
280
0
                }
281
0
            } else {
282
0
                LLAMA_LOG_INFO("%s: context size set by user to %" PRIu32 " -> no change\n", __func__, cparams->n_ctx);
283
0
            }
284
0
        }
285
0
    }
286
287
0
    if (mparams->n_gpu_layers != default_mparams.n_gpu_layers) {
288
0
        throw llama_params_fit_exception("n_gpu_layers already set by user to " + std::to_string(mparams->n_gpu_layers) + ", abort");
289
0
    }
290
0
    if (nd > 1) {
291
0
        if (!tensor_split) {
292
0
            throw llama_params_fit_exception("did not provide a buffer to write the tensor_split to, abort");
293
0
        }
294
0
        if (mparams->tensor_split) {
295
0
            for (size_t id = 0; id < nd; id++) {
296
0
                if (mparams->tensor_split[id] != 0.0f) {
297
0
                    throw llama_params_fit_exception("model_params::tensor_split already set by user, abort");
298
0
                }
299
0
            }
300
0
        }
301
0
        if (mparams->split_mode == LLAMA_SPLIT_MODE_ROW) {
302
0
            throw llama_params_fit_exception("changing weight allocation for LLAMA_SPLIT_MODE_ROW not implemented, abort");
303
0
        }
304
0
    }
305
0
    if (!tensor_buft_overrides) {
306
0
        throw llama_params_fit_exception("did not provide buffer to set tensor_buft_overrides, abort");
307
0
    }
308
0
    if (mparams->tensor_buft_overrides && (mparams->tensor_buft_overrides->pattern || mparams->tensor_buft_overrides->buft)) {
309
0
        throw llama_params_fit_exception("model_params::tensor_buft_overrides already set by user, abort");
310
0
    }
311
312
    // step 3: iteratively fill the back to front with "dense" layers
313
    //   - for a dense model simply fill full layers, giving each device a contiguous slice of the model
314
    //   - for a MoE model, same as dense model but with all MoE tensors in system memory
315
316
    // utility function that returns a static C string matching the tensors for a specific layer index and layer fraction:
317
0
    auto get_overflow_pattern = [&](const size_t il, const layer_fraction_t lf) -> const char * {
318
0
        constexpr size_t n_strings = 1000;
319
0
        if (il >= n_strings) {
320
0
            throw std::runtime_error("at most " + std::to_string(n_strings) + " model layers are supported");
321
0
        }
322
0
        switch (lf) {
323
0
            case LAYER_FRACTION_ATTN: {
324
0
                static std::array<std::string, n_strings> patterns;
325
0
                if (patterns[il].empty()) {
326
0
                    patterns[il] = "blk\\." + std::to_string(il) + "\\.ffn_(up|gate|down).*";
327
0
                }
328
0
                return patterns[il].c_str();
329
0
            }
330
0
            case LAYER_FRACTION_UP: {
331
0
                static std::array<std::string, n_strings> patterns;
332
0
                if (patterns[il].empty()) {
333
0
                    patterns[il] = "blk\\." + std::to_string(il) + "\\.ffn_(gate|down).*";
334
0
                }
335
0
                return patterns[il].c_str();
336
0
            }
337
0
            case LAYER_FRACTION_GATE: {
338
0
                static std::array<std::string, n_strings> patterns;
339
0
                if (patterns[il].empty()) {
340
0
                    patterns[il] = "blk\\." + std::to_string(il) + "\\.ffn_down.*";
341
0
                }
342
0
                return patterns[il].c_str();
343
0
            }
344
0
            case LAYER_FRACTION_MOE: {
345
0
                static std::array<std::string, n_strings> patterns;
346
0
                if (patterns[il].empty()) {
347
0
                    patterns[il] = "blk\\." + std::to_string(il) + "\\.ffn_(up|down|gate)_(ch|)exps";
348
0
                }
349
0
                return patterns[il].c_str();
350
0
            }
351
0
            default:
352
0
                GGML_ABORT("fatal error");
353
0
        }
354
0
    };
355
356
0
    struct ngl_t {
357
0
        uint32_t n_layer = 0; // number of total layers
358
0
        uint32_t n_part  = 0; // number of partial layers, <= n_layer
359
360
        // for the first partial layer varying parts can overflow, all further layers use LAYER_FRACTION_MOE:
361
0
        layer_fraction_t overflow_type = LAYER_FRACTION_MOE;
362
0
    };
363
364
0
    const size_t ntbo = llama_max_tensor_buft_overrides();
365
366
    // utility function to set n_gpu_layers and tensor_split
367
0
    auto set_ngl_tensor_split_tbo = [&](
368
0
            const std::vector<ngl_t> & ngl_per_device,
369
0
            const std::vector<ggml_backend_buffer_type_t> & overflow_bufts,
370
0
            llama_model_params & mparams) {
371
0
        mparams.n_gpu_layers = 0;
372
0
        for (size_t id = 0; id < nd; id++) {
373
0
            mparams.n_gpu_layers += ngl_per_device[id].n_layer;
374
0
            if (nd > 1) {
375
0
                tensor_split[id] = ngl_per_device[id].n_layer;
376
0
            }
377
0
        }
378
0
        assert(uint32_t(mparams.n_gpu_layers) <= hp_ngl + 1);
379
0
        uint32_t il0 = hp_ngl + 1 - mparams.n_gpu_layers; // start index for tensor buft overrides
380
381
0
        mparams.tensor_split = tensor_split;
382
383
0
        size_t itbo = 0;
384
0
        for (size_t id = 0; id < nd; id++) {
385
0
            il0 += ngl_per_device[id].n_layer - ngl_per_device[id].n_part;
386
0
            for (uint32_t il = il0; il < il0 + ngl_per_device[id].n_part; il++) {
387
0
                if (itbo + 1 >= ntbo) {
388
0
                    tensor_buft_overrides[itbo].pattern = nullptr;
389
0
                    tensor_buft_overrides[itbo].buft    = nullptr;
390
0
                    itbo++;
391
0
                    mparams.tensor_buft_overrides = tensor_buft_overrides;
392
0
                    throw llama_params_fit_exception("llama_max_tensor_buft_overrides() == "
393
0
                        + std::to_string(ntbo) + " is insufficient for model");
394
0
                }
395
0
                tensor_buft_overrides[itbo].pattern = get_overflow_pattern(il, il == il0 ? ngl_per_device[id].overflow_type : LAYER_FRACTION_MOE);
396
0
                tensor_buft_overrides[itbo].buft = overflow_bufts[id];
397
0
                itbo++;
398
0
            }
399
0
            il0 += ngl_per_device[id].n_part;
400
0
        }
401
0
        tensor_buft_overrides[itbo].pattern = nullptr;
402
0
        tensor_buft_overrides[itbo].buft    = nullptr;
403
0
        itbo++;
404
0
        mparams.tensor_buft_overrides = tensor_buft_overrides;
405
0
    };
406
407
    // utility function that returns the memory use per device for given numbers of layers per device
408
0
    auto get_memory_for_layers = [&](
409
0
            const char * func_name,
410
0
            const std::vector<ngl_t> & ngl_per_device,
411
0
            const std::vector<ggml_backend_buffer_type_t> & overflow_bufts) -> std::vector<int64_t> {
412
0
        llama_model_params mparams_copy = *mparams;
413
0
        set_ngl_tensor_split_tbo(ngl_per_device, overflow_bufts, mparams_copy);
414
415
0
        const dmds_t dmd_nl = llama_get_device_memory_data(
416
0
            path_model, &mparams_copy, cparams, devs, hp_ngl, hp_nct, hp_nex, log_level);
417
418
0
        LLAMA_LOG_DEBUG("%s: memory for test allocation by device:\n", func_name);
419
0
        for (size_t id = 0; id < nd; id++) {
420
0
            const ngl_t & n = ngl_per_device[id];
421
0
            LLAMA_LOG_DEBUG(
422
0
                "%s: id=%zu, n_layer=%2" PRIu32 ", n_part=%2" PRIu32 ", overflow_type=%d, mem=%6" PRId64 " MiB\n",
423
0
                func_name, id, n.n_layer, n.n_part, int(n.overflow_type), dmd_nl[id].mb.total()/MiB);
424
0
        }
425
426
0
        std::vector<int64_t> ret;
427
0
        ret.reserve(nd);
428
0
        for (const llama_device_memory_data & dmd : dmd_nl) {
429
0
            ret.push_back(dmd.mb.total());
430
0
        }
431
0
        return ret;
432
0
    };
433
434
0
    int64_t global_surplus_cpu_moe = 0;
435
0
    if (hp_nex > 0) {
436
0
        const static std::string pattern_moe_all = "blk\\.\\d+\\.ffn_(up|down|gate)_(ch|)exps"; // matches all MoE tensors
437
0
        ggml_backend_buffer_type_t cpu_buft = ggml_backend_cpu_buffer_type();
438
0
        tensor_buft_overrides[0] = {pattern_moe_all.c_str(), cpu_buft};
439
0
        tensor_buft_overrides[1] = {nullptr, nullptr};
440
0
        mparams->tensor_buft_overrides = tensor_buft_overrides;
441
442
0
        LLAMA_LOG_DEBUG("%s: getting device memory data with all MoE tensors moved to system memory:\n", __func__);
443
0
        const dmds_t dmds_cpu_moe = llama_get_device_memory_data(
444
0
            path_model, mparams, cparams, devs, hp_ngl, hp_nct, hp_nex, log_level);
445
446
0
        for (const llama_device_memory_data & dmd : dmds_cpu_moe) {
447
0
            global_surplus_cpu_moe += dmd.free;
448
0
            global_surplus_cpu_moe -= int64_t(dmd.mb.total()) + margin;
449
0
        }
450
451
0
        if (global_surplus_cpu_moe > 0) {
452
0
            LLAMA_LOG_INFO("%s: with only dense weights in device memory there is a total surplus of %" PRId64 " MiB\n",
453
0
                __func__, global_surplus_cpu_moe/MiB);
454
0
        } else {
455
0
            LLAMA_LOG_INFO("%s: with only dense weights in device memory there is still a total deficit of %" PRId64 " MiB\n",
456
0
                __func__, -global_surplus_cpu_moe/MiB);
457
0
        }
458
459
        // reset
460
0
        tensor_buft_overrides[0] = {nullptr, nullptr};
461
0
        mparams->tensor_buft_overrides = tensor_buft_overrides;
462
0
    }
463
464
0
    std::vector<int64_t> targets; // maximum acceptable memory use per device
465
0
    targets.reserve(nd);
466
0
    for (size_t id = 0; id < nd; id++) {
467
0
        targets.push_back(dmds_full[id].free - margin);
468
0
        LLAMA_LOG_DEBUG("%s: id=%zu, target=%" PRId64 " MiB\n", __func__, id, targets[id]/MiB);
469
0
    }
470
471
0
    std::vector<ggml_backend_buffer_type_t> overflow_bufts; // which bufts the partial layers of a device overflow to:
472
0
    overflow_bufts.reserve(nd);
473
0
    for (size_t id = 0; id < nd - 1; ++id) {
474
0
        overflow_bufts.push_back(ggml_backend_dev_buffer_type(devs[id + 1]));
475
0
    }
476
0
    overflow_bufts.push_back(ggml_backend_cpu_buffer_type());
477
478
0
    std::vector<ngl_t> ngl_per_device(nd);
479
0
    std::vector<int64_t> mem = get_memory_for_layers(__func__, ngl_per_device, overflow_bufts);
480
0
    if (hp_nex > 0) {
481
0
        for (size_t id = 0; id < nd; id++) {
482
0
            ngl_per_device[id].overflow_type = LAYER_FRACTION_MOE;
483
0
        }
484
0
    }
485
486
    // optimize the number of layers per device using the method of false position:
487
    //   - ngl_per_device has 0 layers for each device, lower bound
488
    //   - try a "high" configuration where a device is given all unassigned layers
489
    //   - interpolate the memory use / layer between low and high linearly to get a guess where it meets our target
490
    //   - check memory use of our guess, replace either the low or high bound
491
    //   - once we only have a difference of a single layer, stop and return the lower bound that just barely still fits
492
    //   - the last device has the output layer, which cannot be a partial layer
493
0
    if (hp_nex == 0) {
494
0
        LLAMA_LOG_INFO("%s: filling dense layers back-to-front:\n", __func__);
495
0
    } else {
496
0
        LLAMA_LOG_INFO("%s: filling dense-only layers back-to-front:\n", __func__);
497
0
    }
498
0
    for (int id = nd - 1; id >= 0; id--) {
499
0
        uint32_t n_unassigned = hp_ngl + 1;
500
0
        for (size_t jd = id + 1; jd < nd; ++jd) {
501
0
            assert(n_unassigned >= ngl_per_device[jd].n_layer);
502
0
            n_unassigned -= ngl_per_device[jd].n_layer;
503
0
        }
504
505
0
        std::vector<ngl_t> ngl_per_device_high = ngl_per_device;
506
0
        ngl_per_device_high[id].n_layer = n_unassigned;
507
0
        if (hp_nex > 0) {
508
0
            ngl_per_device_high[id].n_part = size_t(id) < nd - 1 ? ngl_per_device_high[id].n_layer : ngl_per_device_high[id].n_layer - 1;
509
0
        }
510
0
        if (ngl_per_device_high[id].n_layer > 0) {
511
0
            std::vector<int64_t> mem_high = get_memory_for_layers(__func__, ngl_per_device_high, overflow_bufts);
512
0
            if (mem_high[id] > targets[id]) {
513
0
                assert(ngl_per_device_high[id].n_layer > ngl_per_device[id].n_layer);
514
0
                uint32_t delta = ngl_per_device_high[id].n_layer - ngl_per_device[id].n_layer;
515
0
                LLAMA_LOG_DEBUG("%s: start filling device %" PRIu32 ", delta=%" PRIu32 "\n", __func__, id, delta);
516
0
                while (delta > 1) {
517
0
                    uint32_t step_size = int64_t(delta) * (targets[id] - mem[id]) / (mem_high[id] - mem[id]);
518
0
                    step_size = std::max(step_size, uint32_t(1));
519
0
                    step_size = std::min(step_size, delta - 1);
520
521
0
                    std::vector<ngl_t> ngl_per_device_test = ngl_per_device;
522
0
                    ngl_per_device_test[id].n_layer += step_size;
523
0
                    if (hp_nex) {
524
0
                        ngl_per_device_test[id].n_part += step_size;
525
0
                    }
526
0
                    const std::vector<int64_t> mem_test = get_memory_for_layers(__func__, ngl_per_device_test, overflow_bufts);
527
528
0
                    if (mem_test[id] <= targets[id]) {
529
0
                        ngl_per_device = ngl_per_device_test;
530
0
                        mem            = mem_test;
531
0
                        LLAMA_LOG_DEBUG("%s: set ngl_per_device[%d].n_layer=%" PRIu32 "\n", __func__, id, ngl_per_device[id].n_layer);
532
0
                    } else {
533
0
                        ngl_per_device_high = ngl_per_device_test;
534
0
                        mem_high            = mem_test;
535
0
                        LLAMA_LOG_DEBUG("%s: set ngl_per_device_high[%d].n_layer=%" PRIu32 "\n", __func__, id, ngl_per_device_high[id].n_layer);
536
0
                    }
537
0
                    delta = ngl_per_device_high[id].n_layer - ngl_per_device[id].n_layer;
538
0
                }
539
0
            } else {
540
0
                assert(ngl_per_device_high[id].n_layer == n_unassigned);
541
0
                ngl_per_device = ngl_per_device_high;
542
0
                mem            = mem_high;
543
0
                LLAMA_LOG_DEBUG("%s: set ngl_per_device[%d].n_layer=%" PRIu32 "\n", __func__, id, ngl_per_device[id].n_layer);
544
0
            }
545
0
        }
546
547
0
        const int64_t projected_margin = dmds_full[id].free - mem[id];
548
0
        LLAMA_LOG_INFO(
549
0
            "%s:   - %s: %2" PRIu32 " layers, %6" PRId64 " MiB used, %6" PRId64 " MiB free\n",
550
0
            __func__, dev_names[id].c_str(), ngl_per_device[id].n_layer, mem[id]/MiB, projected_margin/MiB);
551
0
    }
552
0
    if (hp_nex == 0 || global_surplus_cpu_moe <= 0) {
553
0
        set_ngl_tensor_split_tbo(ngl_per_device, overflow_bufts, *mparams);
554
0
        return;
555
0
    }
556
557
    // step 4: for a MoE model where all dense tensors fit,
558
    //     convert the dense-only layers in the back to full layers in the front until all devices are full
559
    // essentially the same procedure as for the dense-only layers except front-to-back
560
    // also, try fitting at least part of one more layer to reduce waste for "small" GPUs with e.g. 24 GiB VRAM
561
562
0
    size_t id_dense_start = nd;
563
0
    for (int id = nd - 1; id >= 0; id--) {
564
0
        if (ngl_per_device[id].n_layer > 0) {
565
0
            id_dense_start = id;
566
0
            continue;
567
0
        }
568
0
        break;
569
0
    }
570
0
    assert(id_dense_start < nd);
571
572
0
    LLAMA_LOG_INFO("%s: converting dense-only layers to full layers and filling them front-to-back with overflow to next device/system memory:\n", __func__);
573
0
    for (size_t id = 0; id <= id_dense_start; id++) {
574
0
        std::vector<ngl_t> ngl_per_device_high = ngl_per_device;
575
0
        for (size_t jd = id_dense_start; jd < nd; jd++) {
576
0
            const uint32_t n_layer_move = jd < nd - 1 ? ngl_per_device_high[jd].n_layer : ngl_per_device_high[jd].n_layer - 1;
577
0
            ngl_per_device_high[id].n_layer += n_layer_move;
578
0
            ngl_per_device_high[jd].n_layer -= n_layer_move;
579
0
            ngl_per_device_high[jd].n_part = 0;
580
0
        }
581
0
        size_t id_dense_start_high = nd - 1;
582
0
        std::vector<int64_t> mem_high = get_memory_for_layers(__func__, ngl_per_device_high, overflow_bufts);
583
584
0
        if (mem_high[id] > targets[id]) {
585
0
            assert(ngl_per_device_high[id].n_layer >= ngl_per_device_high[id].n_part);
586
0
            assert(ngl_per_device[id].n_layer >= ngl_per_device[id].n_part);
587
0
            assert((ngl_per_device_high[id].n_layer - ngl_per_device_high[id].n_part)
588
0
                   >= ngl_per_device[id].n_layer - ngl_per_device[id].n_part);
589
0
            uint32_t delta = (ngl_per_device_high[id].n_layer - ngl_per_device_high[id].n_part)
590
0
                - (ngl_per_device[id].n_layer - ngl_per_device[id].n_part);
591
0
            while (delta > 1) {
592
0
                uint32_t step_size = int64_t(delta) * (targets[id] - mem[id]) / (mem_high[id] - mem[id]);
593
0
                step_size = std::max(step_size, uint32_t(1));
594
0
                step_size = std::min(step_size, delta - 1);
595
596
0
                std::vector<ngl_t> ngl_per_device_test = ngl_per_device;
597
0
                size_t id_dense_start_test = id_dense_start;
598
0
                uint32_t n_converted_test = 0;
599
0
                for (;id_dense_start_test < nd; id_dense_start_test++) {
600
0
                    const uint32_t n_convert_jd = std::min(step_size - n_converted_test, ngl_per_device_test[id_dense_start_test].n_part);
601
0
                    ngl_per_device_test[id_dense_start_test].n_layer -= n_convert_jd;
602
0
                    ngl_per_device_test[id_dense_start_test].n_part -= n_convert_jd;
603
0
                    ngl_per_device_test[id].n_layer += n_convert_jd;
604
0
                    n_converted_test += n_convert_jd;
605
606
0
                    if (ngl_per_device_test[id_dense_start_test].n_layer > 0) {
607
0
                        break;
608
0
                    }
609
0
                }
610
0
                const std::vector<int64_t> mem_test = get_memory_for_layers(__func__, ngl_per_device_test, overflow_bufts);
611
612
0
                if (mem_test[id] <= targets[id]) {
613
0
                    ngl_per_device = ngl_per_device_test;
614
0
                    mem            = mem_test;
615
0
                    id_dense_start = id_dense_start_test;
616
0
                    LLAMA_LOG_DEBUG("%s: set ngl_per_device[%zu].(n_layer, n_part)=(%" PRIu32 ", %" PRIu32 "), id_dense_start=%zu\n",
617
0
                        __func__, id, ngl_per_device[id].n_layer, ngl_per_device[id].n_part, id_dense_start);
618
0
                } else {
619
0
                    ngl_per_device_high = ngl_per_device_test;
620
0
                    mem_high            = mem_test;
621
0
                    id_dense_start_high = id_dense_start_test;
622
0
                    LLAMA_LOG_DEBUG("%s: set ngl_per_device_high[%zu].(n_layer, n_part)=(%" PRIu32 ", %" PRIu32 "), id_dense_start_high=%zu\n",
623
0
                        __func__, id, ngl_per_device_high[id].n_layer, ngl_per_device_high[id].n_part, id_dense_start_high);
624
0
                }
625
0
                delta = (ngl_per_device_high[id].n_layer - ngl_per_device_high[id].n_part)
626
0
                    - (ngl_per_device[id].n_layer - ngl_per_device[id].n_part);
627
0
            }
628
0
        } else {
629
0
            ngl_per_device = ngl_per_device_high;
630
0
            mem            = mem_high;
631
0
            id_dense_start = id_dense_start_high;
632
0
            LLAMA_LOG_DEBUG("%s: set ngl_per_device[%zu].(n_layer, n_part)=(%" PRIu32 ", %" PRIu32 "), id_dense_start=%zu\n",
633
0
                __func__, id, ngl_per_device[id].n_layer, ngl_per_device[id].n_part, id_dense_start);
634
0
        }
635
636
        // try to fit at least part of one more layer
637
0
        if (ngl_per_device[id_dense_start].n_layer > (id < nd - 1 ? 0 : 1)) {
638
0
            std::vector<ngl_t> ngl_per_device_test = ngl_per_device;
639
0
            size_t id_dense_start_test = id_dense_start;
640
0
            ngl_per_device_test[id_dense_start_test].n_layer--;
641
0
            ngl_per_device_test[id_dense_start_test].n_part--;
642
0
            ngl_per_device_test[id].n_layer++;
643
0
            ngl_per_device_test[id].n_part++;
644
0
            if (ngl_per_device_test[id_dense_start_test].n_layer == 0) {
645
0
                id_dense_start_test++;
646
0
            }
647
0
            ngl_per_device_test[id].overflow_type = LAYER_FRACTION_UP;
648
0
            LLAMA_LOG_DEBUG("%s: trying to fit one extra layer with overflow_type=LAYER_FRACTION_UP\n", __func__);
649
0
            std::vector<int64_t> mem_test = get_memory_for_layers(__func__, ngl_per_device_test, overflow_bufts);
650
0
            if (mem_test[id] < targets[id] && (id + 1 == nd || mem_test[id + 1] < targets[id + 1])) {
651
0
                ngl_per_device = ngl_per_device_test;
652
0
                mem            = mem_test;
653
0
                id_dense_start = id_dense_start_test;
654
0
                LLAMA_LOG_DEBUG("%s: set ngl_per_device[%zu].(n_layer, n_part, overflow_type)=(%" PRIu32 ", %" PRIu32 ", UP), id_dense_start=%zu\n",
655
0
                    __func__, id, ngl_per_device[id].n_layer, ngl_per_device[id].n_part, id_dense_start);
656
657
0
                ngl_per_device_test[id].overflow_type = LAYER_FRACTION_GATE;
658
0
                LLAMA_LOG_DEBUG("%s: trying to fit one extra layer with overflow_type=LAYER_FRACTION_GATE\n", __func__);
659
0
                mem_test = get_memory_for_layers(__func__, ngl_per_device_test, overflow_bufts);
660
0
                if (mem_test[id] < targets[id] && (id + 1 == nd || mem_test[id + 1] < targets[id + 1])) {
661
0
                    ngl_per_device = ngl_per_device_test;
662
0
                    mem            = mem_test;
663
0
                    id_dense_start = id_dense_start_test;
664
0
                    LLAMA_LOG_DEBUG("%s: set ngl_per_device[%zu].(n_layer, n_part, overflow_type)=(%" PRIu32 ", %" PRIu32 ", GATE), id_dense_start=%zu\n",
665
0
                        __func__, id, ngl_per_device[id].n_layer, ngl_per_device[id].n_part, id_dense_start);
666
0
                }
667
0
            } else {
668
0
                ngl_per_device_test[id].overflow_type = LAYER_FRACTION_ATTN;
669
0
                LLAMA_LOG_DEBUG("%s: trying to fit one extra layer with overflow_type=LAYER_FRACTION_ATTN\n", __func__);
670
0
                mem_test = get_memory_for_layers(__func__, ngl_per_device_test, overflow_bufts);
671
0
                if (mem_test[id] < targets[id] && (id + 1 == nd || mem_test[id + 1] < targets[id + 1])) {
672
0
                    ngl_per_device = ngl_per_device_test;
673
0
                    mem            = mem_test;
674
0
                    id_dense_start = id_dense_start_test;
675
0
                    LLAMA_LOG_DEBUG("%s: set ngl_per_device[%zu].(n_layer, n_part, overflow_type)=(%" PRIu32 ", %" PRIu32 ", ATTN), id_dense_start=%zu\n",
676
0
                        __func__, id, ngl_per_device[id].n_layer, ngl_per_device[id].n_part, id_dense_start);
677
0
                }
678
0
            }
679
0
        }
680
681
0
        const int64_t projected_margin = dmds_full[id].free - mem[id];
682
0
        LLAMA_LOG_INFO(
683
0
            "%s:   - %s: %2" PRIu32 " layers (%2" PRIu32 " overflowing), %6" PRId64 " MiB used, %6" PRId64 " MiB free\n",
684
0
            __func__, dev_names[id].c_str(), ngl_per_device[id].n_layer, ngl_per_device[id].n_part, mem[id]/MiB, projected_margin/MiB);
685
0
    }
686
687
0
    set_ngl_tensor_split_tbo(ngl_per_device, overflow_bufts, *mparams);
688
0
}
689
690
enum llama_params_fit_status llama_params_fit(
691
        const char * path_model, struct llama_model_params * mparams, struct llama_context_params * cparams,
692
        float * tensor_split, struct llama_model_tensor_buft_override * tensor_buft_overrides,
693
0
        size_t margin_s, uint32_t n_ctx_min, enum ggml_log_level log_level) {
694
0
    const int64_t t0_us = llama_time_us();
695
0
    llama_params_fit_status status = LLAMA_PARAMS_FIT_STATUS_SUCCESS;
696
0
    try {
697
0
        llama_params_fit_impl(path_model, mparams, cparams, tensor_split, tensor_buft_overrides, margin_s, n_ctx_min, log_level);
698
0
        LLAMA_LOG_INFO("%s: successfully fit params to free device memory\n", __func__);
699
0
    } catch (const llama_params_fit_exception & e) {
700
0
        LLAMA_LOG_WARN("%s: failed to fit params to free device memory: %s\n", __func__, e.what());
701
0
        status = LLAMA_PARAMS_FIT_STATUS_FAILURE;
702
0
    } catch (const std::runtime_error & e) {
703
0
        LLAMA_LOG_ERROR("%s: encountered an error while trying to fit params to free device memory: %s\n", __func__, e.what());
704
0
        status = LLAMA_PARAMS_FIT_STATUS_ERROR;
705
0
    }
706
0
    const int64_t t1_us = llama_time_us();
707
0
    LLAMA_LOG_INFO("%s: fitting params to free memory took %.2f seconds\n", __func__, (t1_us - t0_us) * 1e-6);
708
0
    return status;
709
0
}
710
711
0
struct llama_sampler_chain_params llama_sampler_chain_default_params() {
712
0
    struct llama_sampler_chain_params result = {
713
0
        /*.no_perf                     =*/ true,
714
0
    };
715
716
0
    return result;
717
0
}
718
719
0
size_t llama_max_devices(void) {
720
0
    return 16;
721
0
}
722
723
0
size_t llama_max_tensor_buft_overrides() {
724
0
    return 4096;
725
0
}
726
727
0
bool llama_supports_mmap(void) {
728
0
    return llama_mmap::SUPPORTED;
729
0
}
730
731
0
bool llama_supports_mlock(void) {
732
0
    return llama_mlock::SUPPORTED;
733
0
}
734
735
0
bool llama_supports_gpu_offload(void) {
736
0
    return ggml_backend_dev_by_type(GGML_BACKEND_DEVICE_TYPE_GPU) != nullptr ||
737
0
           ggml_backend_dev_by_type(GGML_BACKEND_DEVICE_TYPE_IGPU) != nullptr ||
738
0
           llama_supports_rpc();
739
0
}
740
741
0
bool llama_supports_rpc(void) {
742
0
    return ggml_backend_reg_by_name("RPC") != nullptr;
743
0
}
744
745
30
void llama_backend_init(void) {
746
30
    ggml_time_init();
747
748
    // needed to initialize f16 tables
749
30
    {
750
30
        struct ggml_init_params params = { 0, NULL, false };
751
30
        struct ggml_context * ctx = ggml_init(params);
752
30
        ggml_free(ctx);
753
30
    }
754
30
}
755
756
0
void llama_numa_init(enum ggml_numa_strategy numa) {
757
0
    if (numa != GGML_NUMA_STRATEGY_DISABLED) {
758
0
        auto * dev = ggml_backend_dev_by_type(GGML_BACKEND_DEVICE_TYPE_CPU);
759
0
        GGML_ASSERT(dev && "CPU backend is not loaded");
760
0
        auto * reg = ggml_backend_dev_backend_reg(dev);
761
0
        auto * numa_init_fn = (decltype(ggml_numa_init) *) ggml_backend_reg_get_proc_address(reg, "ggml_backend_cpu_numa_init");
762
0
        if (numa_init_fn) {
763
0
            numa_init_fn(numa);
764
0
        }
765
0
    }
766
0
}
767
768
2
void llama_backend_free(void) {
769
2
    ggml_quantize_free();
770
2
}
771
772
0
int64_t llama_time_us(void) {
773
0
    return ggml_time_us();
774
0
}
775
776
// Returns 0 on success, -1 on error, and -2 on cancellation via llama_progress_callback
777
0
static int llama_model_load(const std::string & fname, std::vector<std::string> & splits, llama_model & model, llama_model_params & params) {
778
    // loading time will be recalculated after the first eval, so
779
    // we take page faults deferred by mmap() into consideration
780
0
    model.t_load_us = 0;
781
0
    time_meas tm(model.t_load_us);
782
783
0
    model.t_start_us = tm.t_start_us;
784
785
0
    try {
786
0
        llama_model_loader ml(fname, splits, params.use_mmap, params.check_tensors, params.no_alloc, params.kv_overrides, params.tensor_buft_overrides);
787
788
0
        ml.print_info();
789
790
0
        model.hparams.vocab_only = params.vocab_only;
791
0
        model.hparams.no_alloc   = params.no_alloc;
792
793
0
        try {
794
0
            model.load_arch(ml);
795
0
        } catch(const std::exception & e) {
796
0
            throw std::runtime_error("error loading model architecture: " + std::string(e.what()));
797
0
        }
798
0
        try {
799
0
            model.load_hparams(ml);
800
0
        } catch(const std::exception & e) {
801
0
            throw std::runtime_error("error loading model hyperparameters: " + std::string(e.what()));
802
0
        }
803
0
        if (model.arch == LLM_ARCH_CLIP) {
804
0
            throw std::runtime_error("CLIP cannot be used as main model, use it with --mmproj instead");
805
0
        }
806
0
        try {
807
0
            model.load_vocab(ml);
808
0
        } catch(const std::exception & e) {
809
0
            throw std::runtime_error("error loading model vocabulary: " + std::string(e.what()));
810
0
        }
811
812
0
        model.load_stats(ml);
813
0
        model.print_info();
814
815
0
        if (params.vocab_only) {
816
0
            LLAMA_LOG_INFO("%s: vocab only - skipping tensors\n", __func__);
817
0
            return 0;
818
0
        }
819
820
0
        if (!model.load_tensors(ml)) {
821
0
            return -2;
822
0
        }
823
0
    } catch (const std::exception & err) {
824
0
        LLAMA_LOG_ERROR("%s: error loading model: %s\n", __func__, err.what());
825
0
        return -1;
826
0
    }
827
828
0
    return 0;
829
0
}
830
831
static struct llama_model * llama_model_load_from_file_impl(
832
        const std::string & path_model,
833
        std::vector<std::string> & splits,
834
2
        struct llama_model_params params) {
835
2
    ggml_time_init();
836
837
2
    if (!params.vocab_only && ggml_backend_reg_count() == 0) {
838
0
        LLAMA_LOG_ERROR("%s: no backends are loaded. hint: use ggml_backend_load() or ggml_backend_load_all() to load a backend before calling this function\n", __func__);
839
0
        return nullptr;
840
0
    }
841
842
2
    unsigned cur_percentage = 0;
843
2
    if (params.progress_callback == NULL) {
844
0
        params.progress_callback_user_data = &cur_percentage;
845
0
        params.progress_callback = [](float progress, void * ctx) {
846
0
            unsigned * cur_percentage_p = (unsigned *) ctx;
847
0
            unsigned percentage = (unsigned) (100 * progress);
848
0
            while (percentage > *cur_percentage_p) {
849
0
                *cur_percentage_p = percentage;
850
0
                LLAMA_LOG_CONT(".");
851
0
                if (percentage >= 100) {
852
0
                    LLAMA_LOG_CONT("\n");
853
0
                }
854
0
            }
855
0
            return true;
856
0
        };
857
0
    }
858
859
2
    llama_model * model = new llama_model(params);
860
861
    // create list of devices to use with this model
862
2
    if (params.devices) {
863
0
        for (ggml_backend_dev_t * dev = params.devices; *dev; ++dev) {
864
0
            model->devices.push_back(*dev);
865
0
        }
866
2
    } else {
867
        // default device selection
868
869
        // build list of available devices
870
2
        std::vector<ggml_backend_dev_t> gpus;
871
2
        std::vector<ggml_backend_dev_t> igpus;
872
2
        std::vector<ggml_backend_dev_t> rpc_servers;
873
874
4
        for (size_t i = 0; i < ggml_backend_dev_count(); ++i) {
875
2
            ggml_backend_dev_t dev = ggml_backend_dev_get(i);
876
2
            switch (ggml_backend_dev_type(dev)) {
877
2
                case GGML_BACKEND_DEVICE_TYPE_CPU:
878
2
                case GGML_BACKEND_DEVICE_TYPE_ACCEL:
879
                    // skip CPU backends since they are handled separately
880
2
                    break;
881
882
0
                case GGML_BACKEND_DEVICE_TYPE_GPU: {
883
0
                    ggml_backend_reg_t reg = ggml_backend_dev_backend_reg(dev);
884
0
                    if (ggml_backend_reg_name(reg) == std::string("RPC")) {
885
0
                        rpc_servers.push_back(dev);
886
0
                    } else {
887
                        // check if there is already a GPU with the same device id
888
0
                        ggml_backend_dev_props props;
889
0
                        ggml_backend_dev_get_props(dev, &props);
890
0
                        auto it = std::find_if(gpus.begin(), gpus.end(), [&props](ggml_backend_dev_t d) {
891
0
                            ggml_backend_dev_props d_props;
892
0
                            ggml_backend_dev_get_props(d, &d_props);
893
0
                            if (props.device_id && d_props.device_id) {
894
0
                                return strcmp(props.device_id, d_props.device_id) == 0;
895
0
                            }
896
0
                            return false;
897
0
                        });
898
899
0
                        if (it != gpus.end()) {
900
0
                            LLAMA_LOG_INFO("%s: skipping device %s (%s) with id %s - already using device %s (%s) with the same id\n",
901
0
                                    __func__,
902
0
                                    ggml_backend_dev_name(dev), ggml_backend_dev_description(dev),
903
0
                                    props.device_id ? props.device_id : "unknown id",
904
0
                                    ggml_backend_dev_name(*it), ggml_backend_dev_description(*it));
905
0
                        } else {
906
0
                            gpus.push_back(dev);
907
0
                        }
908
0
                    }
909
0
                    break;
910
2
                }
911
912
0
                case GGML_BACKEND_DEVICE_TYPE_IGPU:
913
0
                    igpus.push_back(dev);
914
0
                    break;
915
2
            }
916
2
        }
917
918
        // add RPC servers at the front of the list to minimize network transfers
919
2
        model->devices.insert(model->devices.begin(), rpc_servers.begin(), rpc_servers.end());
920
921
        // add GPUs
922
2
        model->devices.insert(model->devices.end(), gpus.begin(), gpus.end());
923
924
        // add integrated GPUs only if no other devices were found
925
2
        if (model->devices.empty()) {
926
2
            model->devices.insert(model->devices.end(), igpus.begin(), igpus.end());
927
2
        }
928
2
    }
929
930
    // if using single GPU mode, remove all except the main GPU
931
2
    if (params.split_mode == LLAMA_SPLIT_MODE_NONE) {
932
2
        if (params.main_gpu < 0) {
933
0
            model->devices.clear();
934
2
        } else {
935
2
            if (params.main_gpu >= (int)model->devices.size()) {
936
2
                LLAMA_LOG_ERROR("%s: invalid value for main_gpu: %d (available devices: %zu)\n", __func__, params.main_gpu, model->devices.size());
937
2
                llama_model_free(model);
938
2
                return nullptr;
939
2
            }
940
0
            ggml_backend_dev_t main_gpu = model->devices[params.main_gpu];
941
0
            model->devices.clear();
942
0
            model->devices.push_back(main_gpu);
943
0
        }
944
2
    }
945
946
0
    for (auto * dev : model->devices) {
947
0
        ggml_backend_dev_props props;
948
0
        ggml_backend_dev_get_props(dev, &props);
949
0
        LLAMA_LOG_INFO("%s: using device %s (%s) (%s) - %zu MiB free\n", __func__,
950
0
                ggml_backend_dev_name(dev), ggml_backend_dev_description(dev),
951
0
                props.device_id ? props.device_id : "unknown id",
952
0
                props.memory_free/1024/1024);
953
0
    }
954
955
0
    const int status = llama_model_load(path_model, splits, *model, params);
956
0
    GGML_ASSERT(status <= 0);
957
0
    if (status < 0) {
958
0
        if (status == -1) {
959
0
            LLAMA_LOG_ERROR("%s: failed to load model\n", __func__);
960
0
        } else if (status == -2) {
961
0
            LLAMA_LOG_INFO("%s: cancelled model load\n", __func__);
962
0
        }
963
964
0
        llama_model_free(model);
965
0
        return nullptr;
966
0
    }
967
968
0
    return model;
969
0
}
970
971
// deprecated
972
struct llama_model * llama_load_model_from_file(
973
        const char * path_model,
974
2
        struct llama_model_params params) {
975
2
    return llama_model_load_from_file(path_model, params);
976
2
}
977
978
struct llama_model * llama_model_load_from_file(
979
        const char * path_model,
980
2
        struct llama_model_params params) {
981
2
    std::vector<std::string> splits = {};
982
2
    return llama_model_load_from_file_impl(path_model, splits, params);
983
2
}
984
985
struct llama_model * llama_model_load_from_splits(
986
        const char ** paths,
987
        size_t n_paths,
988
0
        struct llama_model_params params) {
989
0
    std::vector<std::string> splits;
990
0
    if (n_paths == 0) {
991
0
        LLAMA_LOG_ERROR("%s: list of splits is empty\n", __func__);
992
0
        return nullptr;
993
0
    }
994
0
    splits.reserve(n_paths);
995
0
    for (size_t i = 0; i < n_paths; ++i) {
996
0
        splits.push_back(paths[i]);
997
0
    }
998
0
    return llama_model_load_from_file_impl(splits.front(), splits, params);
999
0
}
1000
1001
0
void llama_model_save_to_file(const struct llama_model * model, const char * path_model) {
1002
0
    llama_model_saver ms(*model);
1003
0
    ms.add_kv_from_model();
1004
0
    ms.add_tensors_from_model();
1005
0
    ms.save(path_model);
1006
0
}
1007
1008
//
1009
// chat templates
1010
//
1011
1012
int32_t llama_chat_apply_template(
1013
                              const char * tmpl,
1014
         const struct llama_chat_message * chat,
1015
                                  size_t   n_msg,
1016
                                    bool   add_ass,
1017
                                    char * buf,
1018
0
                                 int32_t   length) {
1019
0
    const std::string curr_tmpl(tmpl == nullptr ? "chatml" : tmpl);
1020
1021
    // format the chat to string
1022
0
    std::vector<const llama_chat_message *> chat_vec;
1023
0
    chat_vec.resize(n_msg);
1024
0
    for (size_t i = 0; i < n_msg; i++) {
1025
0
        chat_vec[i] = &chat[i];
1026
0
    }
1027
1028
0
    std::string formatted_chat;
1029
0
    llm_chat_template detected_tmpl = llm_chat_detect_template(curr_tmpl);
1030
0
    if (detected_tmpl == LLM_CHAT_TEMPLATE_UNKNOWN) {
1031
0
        return -1;
1032
0
    }
1033
0
    int32_t res = llm_chat_apply_template(detected_tmpl, chat_vec, formatted_chat, add_ass);
1034
0
    if (res < 0) {
1035
0
        return res;
1036
0
    }
1037
0
    if (buf && length > 0) {
1038
0
        strncpy(buf, formatted_chat.c_str(), length);
1039
0
    }
1040
0
    return res;
1041
0
}
1042
1043
//
1044
// model split
1045
//
1046
1047
0
int llama_split_path(char * split_path, size_t maxlen, const char * path_prefix, int split_no, int split_count) {
1048
0
    static const char * const SPLIT_PATH_FORMAT = "%s-%05d-of-%05d.gguf";
1049
0
    if (snprintf(split_path, maxlen, SPLIT_PATH_FORMAT, path_prefix, split_no + 1, split_count)) {
1050
0
        return strlen(split_path);
1051
0
    }
1052
0
    return 0;
1053
0
}
1054
1055
0
int llama_split_prefix(char * split_prefix, size_t maxlen, const char * split_path, int split_no, int split_count) {
1056
0
    std::string str_split_path(split_path);
1057
0
    char postfix[32];
1058
0
    snprintf(postfix, 32, "-%05d-of-%05d.gguf", split_no + 1, split_count);
1059
0
    std::string str_postfix(postfix);
1060
1061
    // check if split_prefix ends with postfix
1062
0
    int size_prefix = str_split_path.size() - str_postfix.size();
1063
0
    if (size_prefix > 0 && str_split_path.find(str_postfix, size_prefix) != std::string::npos) {
1064
0
        snprintf(split_prefix, std::min((size_t) size_prefix + 1, maxlen), "%s", split_path);
1065
0
        return size_prefix;
1066
0
    }
1067
1068
0
    return 0;
1069
0
}
1070
1071
0
const char * llama_print_system_info(void) {
1072
0
    static std::string s;
1073
0
    s.clear(); // Clear the string, since it's static, otherwise it will accumulate data from previous calls.
1074
1075
0
    for (size_t i = 0; i < ggml_backend_reg_count(); i++) {
1076
0
        auto * reg = ggml_backend_reg_get(i);
1077
0
        auto * get_features_fn = (ggml_backend_get_features_t) ggml_backend_reg_get_proc_address(reg, "ggml_backend_get_features");
1078
0
        if (get_features_fn) {
1079
0
            ggml_backend_feature * features = get_features_fn(reg);
1080
0
            s += ggml_backend_reg_name(reg);
1081
0
            s += " : ";
1082
0
            for (; features->name; features++) {
1083
0
                s += features->name;
1084
0
                s += " = ";
1085
0
                s += features->value;
1086
0
                s += " | ";
1087
0
            }
1088
0
        }
1089
0
    }
1090
1091
0
    return s.c_str();
1092
0
}
1093