Coverage Report

Created: 2026-08-22 07:18

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/llama.cpp/common/fit.cpp
Line
Count
Source
1
#include "fit.h"
2
3
#include "log.h"
4
5
#include "../src/llama-ext.h"
6
7
#include <array>
8
#include <cassert>
9
#include <stdexcept>
10
#include <cinttypes>
11
#include <set>
12
#include <string>
13
#include <vector>
14
15
// this enum is only used in llama_params_fit_impl but needs to be defined outside of it to fix a Windows compilation issue
16
// enum to identify part of a layer for distributing its tensors:
17
enum common_layer_fraction_t {
18
    LAYER_FRACTION_NONE = 0, // nothing
19
    LAYER_FRACTION_ATTN = 1, // attention
20
    LAYER_FRACTION_UP   = 2, // attention + up
21
    LAYER_FRACTION_GATE = 3, // attention + up + gate
22
    LAYER_FRACTION_MOE  = 4, // everything but sparse MoE weights
23
};
24
25
class common_params_fit_exception : public std::runtime_error {
26
    using std::runtime_error::runtime_error;
27
};
28
29
static std::vector<llama_device_memory_data> common_get_device_memory_data_impl(
30
        const char * path_model,
31
        const llama_model_params * mparams,
32
        const llama_context_params * cparams,
33
        std::vector<ggml_backend_dev_t> & devs,
34
        uint32_t & hp_ngl,
35
        uint32_t & hp_n_ctx_train,
36
        uint32_t & hp_n_expert,
37
0
        ggml_log_level log_level) {
38
0
    struct user_data_t {
39
0
        struct {
40
0
            ggml_log_callback callback;
41
0
            void * user_data;
42
0
        } original_logger;
43
0
        ggml_log_level min_level; // prints below this log level go to debug log
44
0
    };
45
0
    user_data_t ud;
46
0
    llama_log_get(&ud.original_logger.callback, &ud.original_logger.user_data);
47
0
    ud.min_level = log_level;
48
49
0
    llama_log_set([](ggml_log_level level, const char * text, void * user_data) {
50
0
        const user_data_t * ud = (const user_data_t *) user_data;
51
0
        const ggml_log_level level_eff = level >= ud->min_level ? level : GGML_LOG_LEVEL_DEBUG;
52
0
        ud->original_logger.callback(level_eff, text, ud->original_logger.user_data);
53
0
    }, &ud);
54
55
0
    llama_model_params mparams_copy = *mparams;
56
0
    mparams_copy.no_alloc  = true;
57
0
    mparams_copy.load_mode = LLAMA_LOAD_MODE_NONE;
58
59
0
    llama_model * model = llama_model_load_from_file(path_model, mparams_copy);
60
0
    if (model == nullptr) {
61
0
        llama_log_set(ud.original_logger.callback, ud.original_logger.user_data);
62
0
        throw std::runtime_error("failed to load model");
63
0
    }
64
65
0
    llama_context * ctx = llama_init_from_model(model, *cparams);
66
0
    if (ctx == nullptr) {
67
0
        llama_model_free(model);
68
0
        llama_log_set(ud.original_logger.callback, ud.original_logger.user_data);
69
0
        throw std::runtime_error("failed to create llama_context from model");
70
0
    }
71
72
0
    const size_t nd = llama_model_n_devices(model);
73
0
    std::vector<llama_device_memory_data> ret(nd + 1);
74
75
0
    llama_memory_breakdown memory_breakdown = llama_get_memory_breakdown(ctx);
76
77
0
    for (const auto & [buft, mb] : memory_breakdown) {
78
0
        if (ggml_backend_buft_is_host(buft)) {
79
0
            ret.back().mb.model   += mb.model;
80
0
            ret.back().mb.context += mb.context;
81
0
            ret.back().mb.compute += mb.compute;
82
0
            continue;
83
0
        }
84
85
0
        ggml_backend_dev_t dev = ggml_backend_buft_get_device(buft);
86
0
        if (!dev) {
87
0
            continue;
88
0
        }
89
0
        for (size_t i = 0; i < nd; i++) {
90
0
            if (dev == llama_model_get_device(model, i)) {
91
0
                ret[i].mb.model   += mb.model;
92
0
                ret[i].mb.context += mb.context;
93
0
                ret[i].mb.compute += mb.compute;
94
0
                break;
95
0
            }
96
0
        }
97
0
    }
98
99
0
    {
100
0
        ggml_backend_dev_t cpu_dev = ggml_backend_dev_by_type(GGML_BACKEND_DEVICE_TYPE_CPU);
101
0
        if (cpu_dev == nullptr) {
102
0
            throw std::runtime_error("no CPU backend found");
103
0
        }
104
0
        size_t free;
105
0
        size_t total;
106
0
        ggml_backend_dev_memory(cpu_dev, &free, &total);
107
0
        ret.back().free  = free;
108
0
        ret.back().total = total;
109
0
    }
110
0
    for (size_t i = 0; i < nd; i++) {
111
0
        ggml_backend_dev_t dev = llama_model_get_device(model, i);
112
113
0
        size_t free;
114
0
        size_t total;
115
0
        ggml_backend_dev_memory(dev, &free, &total);
116
117
        // Some non-GPU accelerator backends, such as BLAS, report 0/0 and rely on
118
        // the host-memory fallback. For GPU-like backends, keep 0/0 so --fit does
119
        // not assign anything to a device with an unknown memory budget.
120
0
        if (free == 0 && total == 0) {
121
0
            const enum ggml_backend_dev_type type = ggml_backend_dev_type(dev);
122
0
            if (type == GGML_BACKEND_DEVICE_TYPE_GPU || type == GGML_BACKEND_DEVICE_TYPE_IGPU) {
123
0
                LOG_WRN("%s: device %s did not report memory; --fit will not use it\n",
124
0
                        __func__, ggml_backend_dev_name(dev));
125
0
            } else {
126
0
                free  = ret.back().free;
127
0
                total = ret.back().total;
128
0
            }
129
0
        }
130
0
        ret[i].free  = free;
131
0
        ret[i].total = total;
132
0
    }
133
134
0
    devs.clear();
135
0
    for (int i = 0; i < llama_model_n_devices(model); i++) {
136
0
        devs.push_back(llama_model_get_device(model, i));
137
0
    }
138
139
0
    hp_ngl         = llama_model_n_layer(model);
140
0
    if (mparams->load_mtp) {
141
0
        hp_ngl    += llama_model_n_layer_nextn(model);
142
0
    }
143
0
    hp_n_ctx_train = llama_model_n_ctx_train(model);
144
0
    hp_n_expert    = llama_model_n_expert(model);
145
146
0
    common_memory_breakdown_print(ctx);
147
148
0
    llama_free(ctx);
149
0
    llama_model_free(model);
150
0
    llama_log_set(ud.original_logger.callback, ud.original_logger.user_data);
151
152
0
    return ret;
153
0
}
154
155
common_device_memory_data_vec common_get_device_memory_data(
156
        const char * path_model,
157
        const llama_model_params * mparams,
158
        const llama_context_params * cparams,
159
        std::vector<ggml_backend_dev_t> & devs,
160
        uint32_t & hp_ngl,
161
        uint32_t & hp_n_ctx_train,
162
        uint32_t & hp_n_expert,
163
0
        ggml_log_level log_level) {
164
0
    std::vector<llama_device_memory_data> impl = common_get_device_memory_data_impl(
165
0
            path_model, mparams, cparams, devs, hp_ngl, hp_n_ctx_train, hp_n_expert, log_level);
166
167
0
    common_device_memory_data_vec ret(impl.size());
168
0
    for (size_t i = 0; i < impl.size(); i++) {
169
0
        ret[i].total   = impl[i].total;
170
0
        ret[i].free    = impl[i].free;
171
0
        ret[i].model   = impl[i].mb.model;
172
0
        ret[i].context = impl[i].mb.context;
173
0
        ret[i].compute = impl[i].mb.compute;
174
0
    }
175
0
    return ret;
176
0
}
177
178
static void common_params_fit_impl(
179
        const char * path_model, struct llama_model_params * mparams, struct llama_context_params * cparams,
180
        float * tensor_split, struct llama_model_tensor_buft_override * tensor_buft_overrides,
181
0
        size_t * margins_s, uint32_t n_ctx_min, enum ggml_log_level log_level) {
182
0
    if (mparams->split_mode == LLAMA_SPLIT_MODE_TENSOR) {
183
0
        throw common_params_fit_exception("llama_params_fit is not implemented for SPLIT_MODE_TENSOR, abort");
184
0
    }
185
0
    constexpr int64_t MiB = 1024*1024;
186
0
    typedef std::vector<llama_device_memory_data> dmds_t;
187
0
    const llama_model_params default_mparams = llama_model_default_params();
188
189
0
    std::vector<ggml_backend_dev_t> devs;
190
0
    uint32_t hp_ngl = 0; // hparams.n_gpu_layers
191
0
    uint32_t hp_nct = 0; // hparams.n_ctx_train
192
0
    uint32_t hp_nex = 0; // hparams.n_expert
193
194
    // step 1: get data for default parameters and check whether any changes are necessary in the first place
195
196
0
    LOG_TRC("%s: getting device memory data for initial parameters:\n", __func__);
197
0
    const dmds_t dmds_full = common_get_device_memory_data_impl(path_model, mparams, cparams, devs, hp_ngl, hp_nct, hp_nex, log_level);
198
0
    const size_t nd = devs.size(); // number of devices
199
200
0
    std::vector<int64_t> margins; // this function uses int64_t rather than size_t for memory sizes to more conveniently handle deficits
201
0
    margins.reserve(nd);
202
0
    if (nd == 0) {
203
0
        margins.push_back(margins_s[0]);
204
0
    } else {
205
0
        for (size_t id = 0; id < nd; id++) {
206
0
            margins.push_back(margins_s[id]);
207
0
        }
208
0
    }
209
210
0
    std::vector<std::string> dev_names;
211
0
    {
212
0
        dev_names.reserve(nd);
213
0
        size_t max_length = 0;
214
0
        for (const auto & dev : devs) {
215
0
            std::string name = ggml_backend_dev_name(dev);
216
0
            name += " (";
217
0
            name += ggml_backend_dev_description(dev);
218
0
            name += ")";
219
0
            dev_names.push_back(name);
220
0
            max_length = std::max(max_length, name.length());
221
0
        }
222
0
        for (std::string & dn : dev_names) {
223
0
            dn.insert(dn.end(), max_length - dn.length(), ' ');
224
0
        }
225
0
    }
226
227
0
    int64_t sum_free            = 0;
228
0
    int64_t sum_projected_free  = 0;
229
0
    int64_t sum_projected_used  = 0;
230
0
    int64_t sum_projected_model = 0;
231
0
    std::vector<int64_t> projected_free_per_device;
232
0
    projected_free_per_device.reserve(nd);
233
234
0
    if (nd == 0) {
235
0
        sum_projected_used = dmds_full.back().mb.total();
236
0
        sum_free           = dmds_full.back().total;
237
0
        sum_projected_free = sum_free - sum_projected_used;
238
0
        LOG_TRC("%s: projected to use %" PRId64 " MiB of host memory vs. %" PRId64 " MiB of total host memory\n",
239
0
            __func__, sum_projected_used/MiB, sum_free/MiB);
240
0
        if (sum_projected_free >= margins[0]) {
241
0
            LOG_TRC("%s: will leave %" PRId64 " >= %" PRId64 " MiB of system memory, no changes needed\n",
242
0
                __func__, sum_projected_free/MiB, margins[0]/MiB);
243
0
            return;
244
0
        }
245
0
    } else {
246
0
        if (nd > 1) {
247
0
            LOG_TRC("%s: projected memory use with initial parameters [MiB]:\n", __func__);
248
0
        }
249
0
        for (size_t id = 0; id < nd; id++) {
250
0
            const llama_device_memory_data & dmd = dmds_full[id];
251
252
0
            const int64_t projected_used = dmd.mb.total();
253
0
            const int64_t projected_free = dmd.free - projected_used;
254
0
            projected_free_per_device.push_back(projected_free);
255
256
0
            sum_free            += dmd.free;
257
0
            sum_projected_used  += projected_used;
258
0
            sum_projected_free  += projected_free;
259
0
            sum_projected_model += dmd.mb.model;
260
261
0
            if (nd > 1) {
262
0
                LOG_TRC("%s:   - %s: %6" PRId64 " total, %6" PRId64 " used, %6" PRId64 " free vs. target of %6" PRId64 "\n",
263
0
                    __func__, dev_names[id].c_str(), dmd.total/MiB, projected_used/MiB, projected_free/MiB, margins[id]/MiB);
264
0
            }
265
0
        }
266
0
        assert(sum_free >= 0 && sum_projected_used >= 0);
267
0
        LOG_TRC("%s: projected to use %" PRId64 " MiB of device memory vs. %" PRId64 " MiB of free device memory\n",
268
0
            __func__, sum_projected_used/MiB, sum_free/MiB);
269
0
        if (nd == 1) {
270
0
            if (projected_free_per_device[0] >= margins[0]) {
271
0
                LOG_TRC("%s: will leave %" PRId64 " >= %" PRId64 " MiB of free device memory, no changes needed\n",
272
0
                    __func__, projected_free_per_device[0]/MiB, margins[0]/MiB);
273
0
                return;
274
0
            }
275
0
        } else {
276
0
            bool changes_needed = false;
277
0
            for (size_t id = 0; id < nd; id++) {
278
0
                if (projected_free_per_device[id] < margins[id]) {
279
0
                    changes_needed = true;
280
0
                    break;
281
0
                }
282
0
            }
283
0
            if (!changes_needed) {
284
0
                LOG_TRC("%s: targets for free memory can be met on all devices, no changes needed\n", __func__);
285
0
                return;
286
0
            }
287
0
        }
288
0
    }
289
290
    // step 2: try reducing memory use by reducing the context size
291
292
0
    {
293
0
        int64_t global_surplus = sum_projected_free;
294
0
        if (nd == 0) {
295
0
            global_surplus -= margins[0];
296
0
        } else {
297
0
            for (size_t id = 0; id < nd; id++) {
298
0
                global_surplus -= margins[id];
299
0
            }
300
0
        }
301
0
        if (global_surplus < 0) {
302
0
            if (nd <= 1) {
303
0
                LOG_TRC("%s: cannot meet free memory target of %" PRId64 " MiB, need to reduce device memory by %" PRId64 " MiB\n",
304
0
                    __func__, margins[0]/MiB, -global_surplus/MiB);
305
0
            } else {
306
0
                LOG_TRC(
307
0
                    "%s: cannot meet free memory targets on all devices, need to use %" PRId64 " MiB less in total\n",
308
0
                    __func__, -global_surplus/MiB);
309
0
            }
310
0
            if (cparams->n_ctx == 0) {
311
0
                if (hp_nct > n_ctx_min) {
312
0
                    int64_t sum_used_target = sum_free;
313
0
                    if (nd == 0) {
314
0
                        sum_used_target -= margins[0];
315
0
                    } else {
316
0
                        for (size_t id = 0; id < nd; id++) {
317
0
                            sum_used_target -= margins[id];
318
0
                        }
319
0
                    }
320
0
                    if (nd > 1) {
321
                        // for multiple devices we need to be more conservative in terms of how much context we think can fit:
322
                        //   - for dense models only whole layers can be assigned to devices
323
                        //   - for MoE models only whole tensors can be assigned to devices, which we estimate to be <= 1/3 of a layer
324
                        //   - on average we expect a waste of 0.5 layers/tensors per device
325
                        //   - use slightly more than the expected average for nd devices to be safe
326
0
                        const int64_t model_per_layer = sum_projected_model / std::min(uint32_t(mparams->n_gpu_layers), hp_ngl);
327
0
                        sum_used_target -= (nd + 1) * model_per_layer / (hp_nex == 0 ? 2 : 6);
328
0
                    }
329
330
0
                    int64_t sum_projected_used_min_ctx = 0;
331
0
                    cparams->n_ctx = n_ctx_min;
332
0
                    const dmds_t dmds_min_ctx = common_get_device_memory_data_impl(path_model, mparams, cparams, devs, hp_ngl, hp_nct, hp_nex, log_level);
333
0
                    if (nd == 0) {
334
0
                        sum_projected_used_min_ctx = dmds_min_ctx.back().mb.total();
335
0
                    } else {
336
0
                        for (size_t id = 0; id < nd; id++) {
337
0
                            sum_projected_used_min_ctx += dmds_min_ctx[id].mb.total();
338
0
                        }
339
0
                    }
340
0
                    if (sum_used_target > sum_projected_used_min_ctx) {
341
                        // linear interpolation between minimum and maximum context size:
342
0
                        cparams->n_ctx += (hp_nct - n_ctx_min) * (sum_used_target - sum_projected_used_min_ctx)
343
0
                            / (sum_projected_used - sum_projected_used_min_ctx);
344
0
                        cparams->n_ctx = std::max(cparams->n_ctx - cparams->n_ctx % 256, n_ctx_min); // round down context for CUDA backend
345
346
0
                        const int64_t bytes_per_ctx = (sum_projected_used - sum_projected_used_min_ctx) / (hp_nct - n_ctx_min);
347
0
                        const int64_t memory_reduction = (hp_nct - cparams->n_ctx) * bytes_per_ctx;
348
0
                        LOG_TRC("%s: context size reduced from %" PRIu32 " to %" PRIu32 " -> need %" PRId64 " MiB less memory in total\n",
349
0
                            __func__, hp_nct, cparams->n_ctx, memory_reduction/MiB);
350
0
                        if (nd <= 1) {
351
0
                            LOG_TRC("%s: entire model can be fit by reducing context\n", __func__);
352
0
                            return;
353
0
                        }
354
0
                        LOG_TRC("%s: entire model should be fit across devices by reducing context\n", __func__);
355
0
                    } else {
356
0
                        const int64_t memory_reduction = sum_projected_used - sum_projected_used_min_ctx;
357
0
                        LOG_TRC("%s: context size reduced from %" PRIu32 " to %" PRIu32 " -> need %" PRId64 " MiB less memory in total\n",
358
0
                            __func__, hp_nct, cparams->n_ctx, memory_reduction/MiB);
359
0
                    }
360
0
                } else {
361
0
                    if (n_ctx_min == UINT32_MAX) {
362
0
                        LOG_TRC("%s: user has requested full context size of %" PRIu32 " -> no change\n", __func__, hp_nct);
363
0
                    } else {
364
0
                        LOG_TRC("%s: default model context size is %" PRIu32 " which is <= the min. context size of %" PRIu32 " -> no change\n",
365
0
                            __func__, hp_nct, n_ctx_min);
366
0
                    }
367
0
                }
368
0
            } else {
369
0
                LOG_TRC("%s: context size set by user to %" PRIu32 " -> no change\n", __func__, cparams->n_ctx);
370
0
            }
371
0
        }
372
0
    }
373
0
    if (nd == 0) {
374
0
        throw common_params_fit_exception("was unable to fit model into system memory by reducing context, abort");
375
0
    }
376
377
0
    if (mparams->n_gpu_layers != default_mparams.n_gpu_layers) {
378
0
        throw common_params_fit_exception("n_gpu_layers already set by user to " + std::to_string(mparams->n_gpu_layers) + ", abort");
379
0
    }
380
0
    if (nd > 1) {
381
0
        if (!tensor_split) {
382
0
            throw common_params_fit_exception("did not provide a buffer to write the tensor_split to, abort");
383
0
        }
384
0
        if (mparams->tensor_split) {
385
0
            for (size_t id = 0; id < nd; id++) {
386
0
                if (mparams->tensor_split[id] != 0.0f) {
387
0
                    throw common_params_fit_exception("model_params::tensor_split already set by user, abort");
388
0
                }
389
0
            }
390
0
        }
391
0
        if (mparams->split_mode == LLAMA_SPLIT_MODE_ROW) {
392
0
            throw common_params_fit_exception("changing weight allocation for LLAMA_SPLIT_MODE_ROW not implemented, abort");
393
0
        }
394
0
    }
395
0
    if (!tensor_buft_overrides) {
396
0
        throw common_params_fit_exception("did not provide buffer to set tensor_buft_overrides, abort");
397
0
    }
398
0
    if (mparams->tensor_buft_overrides && (mparams->tensor_buft_overrides->pattern || mparams->tensor_buft_overrides->buft)) {
399
0
        throw common_params_fit_exception("model_params::tensor_buft_overrides already set by user, abort");
400
0
    }
401
402
    // step 3: iteratively fill the back to front with "dense" layers
403
    //   - for a dense model simply fill full layers, giving each device a contiguous slice of the model
404
    //   - for a MoE model, same as dense model but with all MoE tensors in system memory
405
406
    // utility function that returns a static C string matching the tensors for a specific layer index and layer fraction:
407
0
    auto get_overflow_pattern = [&](const size_t il, const common_layer_fraction_t lf) -> const char * {
408
0
        constexpr size_t n_strings = 1000;
409
0
        if (il >= n_strings) {
410
0
            throw std::runtime_error("at most " + std::to_string(n_strings) + " model layers are supported");
411
0
        }
412
0
        switch (lf) {
413
0
            case LAYER_FRACTION_ATTN: {
414
0
                static std::array<std::string, n_strings> patterns;
415
0
                if (patterns[il].empty()) {
416
0
                    patterns[il] = "blk\\." + std::to_string(il) + "\\.ffn_(gate|up|gate_up|down).*";
417
0
                }
418
0
                return patterns[il].c_str();
419
0
            }
420
0
            case LAYER_FRACTION_UP: {
421
0
                static std::array<std::string, n_strings> patterns;
422
0
                if (patterns[il].empty()) {
423
0
                    patterns[il] = "blk\\." + std::to_string(il) + "\\.ffn_(gate|gate_up|down).*";
424
0
                }
425
0
                return patterns[il].c_str();
426
0
            }
427
0
            case LAYER_FRACTION_GATE: {
428
0
                static std::array<std::string, n_strings> patterns;
429
0
                if (patterns[il].empty()) {
430
0
                    patterns[il] = "blk\\." + std::to_string(il) + "\\.ffn_down.*";
431
0
                }
432
0
                return patterns[il].c_str();
433
0
            }
434
0
            case LAYER_FRACTION_MOE: {
435
0
                static std::array<std::string, n_strings> patterns;
436
0
                if (patterns[il].empty()) {
437
0
                    patterns[il] = "blk\\." + std::to_string(il) + "\\.ffn_(up|down|gate_up|gate)_(ch|)exps";
438
0
                }
439
0
                return patterns[il].c_str();
440
0
            }
441
0
            default:
442
0
                GGML_ABORT("fatal error");
443
0
        }
444
0
    };
445
446
0
    struct ngl_t {
447
0
        uint32_t n_layer = 0; // number of total layers
448
0
        uint32_t n_part  = 0; // number of partial layers, <= n_layer
449
450
        // for the first partial layer varying parts can overflow, all further layers use LAYER_FRACTION_MOE:
451
0
        common_layer_fraction_t overflow_type = LAYER_FRACTION_MOE;
452
453
0
        uint32_t n_full() const {
454
0
            assert(n_layer >= n_part);
455
0
            return n_layer - n_part;
456
0
        }
457
0
    };
458
459
0
    const size_t ntbo = llama_max_tensor_buft_overrides();
460
461
    // utility function to set n_gpu_layers and tensor_split
462
0
    auto set_ngl_tensor_split_tbo = [&](
463
0
            const std::vector<ngl_t> & ngl_per_device,
464
0
            const std::vector<ggml_backend_buffer_type_t> & overflow_bufts,
465
0
            llama_model_params & mparams) {
466
0
        mparams.n_gpu_layers = 0;
467
0
        for (size_t id = 0; id < nd; id++) {
468
0
            mparams.n_gpu_layers += ngl_per_device[id].n_layer;
469
0
            if (nd > 1) {
470
0
                tensor_split[id] = ngl_per_device[id].n_layer;
471
0
            }
472
0
        }
473
0
        assert(uint32_t(mparams.n_gpu_layers) <= hp_ngl + 1);
474
0
        uint32_t il0 = hp_ngl + 1 - mparams.n_gpu_layers; // start index for tensor buft overrides
475
476
0
        mparams.tensor_split = tensor_split;
477
478
0
        size_t itbo = 0;
479
0
        for (size_t id = 0; id < nd; id++) {
480
0
            il0 += ngl_per_device[id].n_full();
481
0
            for (uint32_t il = il0; il < il0 + ngl_per_device[id].n_part; il++) {
482
0
                if (itbo + 1 >= ntbo) {
483
0
                    tensor_buft_overrides[itbo].pattern = nullptr;
484
0
                    tensor_buft_overrides[itbo].buft    = nullptr;
485
0
                    itbo++;
486
0
                    mparams.tensor_buft_overrides = tensor_buft_overrides;
487
0
                    throw common_params_fit_exception("llama_max_tensor_buft_overrides() == "
488
0
                        + std::to_string(ntbo) + " is insufficient for model");
489
0
                }
490
0
                tensor_buft_overrides[itbo].pattern = get_overflow_pattern(il, il == il0 ? ngl_per_device[id].overflow_type : LAYER_FRACTION_MOE);
491
0
                tensor_buft_overrides[itbo].buft = il == il0 ? overflow_bufts[id] : ggml_backend_cpu_buffer_type();
492
0
                itbo++;
493
0
            }
494
0
            il0 += ngl_per_device[id].n_part;
495
0
        }
496
0
        tensor_buft_overrides[itbo].pattern = nullptr;
497
0
        tensor_buft_overrides[itbo].buft    = nullptr;
498
0
        itbo++;
499
0
        mparams.tensor_buft_overrides = tensor_buft_overrides;
500
0
    };
501
502
    // utility function that returns the memory use per device for given numbers of layers per device
503
0
    auto get_memory_for_layers = [&](
504
0
            const char * func_name,
505
0
            const std::vector<ngl_t> & ngl_per_device,
506
0
            const std::vector<ggml_backend_buffer_type_t> & overflow_bufts) -> std::vector<int64_t> {
507
0
        llama_model_params mparams_copy = *mparams;
508
0
        set_ngl_tensor_split_tbo(ngl_per_device, overflow_bufts, mparams_copy);
509
510
0
        const dmds_t dmd_nl = common_get_device_memory_data_impl(
511
0
            path_model, &mparams_copy, cparams, devs, hp_ngl, hp_nct, hp_nex, log_level);
512
513
0
        LOG_TRC("%s: memory for test allocation by device:\n", func_name);
514
0
        for (size_t id = 0; id < nd; id++) {
515
0
            const ngl_t & n = ngl_per_device[id];
516
0
            LOG_TRC(
517
0
                "%s: id=%zu, n_layer=%2" PRIu32 ", n_part=%2" PRIu32 ", overflow_type=%d, mem=%6" PRId64 " MiB\n",
518
0
                func_name, id, n.n_layer, n.n_part, int(n.overflow_type), dmd_nl[id].mb.total()/MiB);
519
0
        }
520
521
0
        std::vector<int64_t> ret;
522
0
        ret.reserve(nd);
523
0
        for (size_t id = 0; id < nd; id++) {
524
0
            ret.push_back(dmd_nl[id].mb.total());
525
0
        }
526
0
        return ret;
527
0
    };
528
529
0
    int64_t global_surplus_cpu_moe = 0;
530
0
    if (hp_nex > 0) {
531
0
        const static std::string pattern_moe_all = "blk\\.\\d+\\.ffn_(up|down|gate_up|gate)_(ch|)exps"; // matches all MoE tensors
532
0
        ggml_backend_buffer_type_t cpu_buft = ggml_backend_cpu_buffer_type();
533
0
        tensor_buft_overrides[0] = {pattern_moe_all.c_str(), cpu_buft};
534
0
        tensor_buft_overrides[1] = {nullptr, nullptr};
535
0
        mparams->tensor_buft_overrides = tensor_buft_overrides;
536
537
0
        LOG_TRC("%s: getting device memory data with all MoE tensors moved to system memory:\n", __func__);
538
0
        const dmds_t dmds_cpu_moe = common_get_device_memory_data_impl(
539
0
            path_model, mparams, cparams, devs, hp_ngl, hp_nct, hp_nex, log_level);
540
541
0
        for (size_t id = 0; id < nd; id++) {
542
0
            global_surplus_cpu_moe += dmds_cpu_moe[id].free;
543
0
            global_surplus_cpu_moe -= int64_t(dmds_cpu_moe[id].mb.total()) + margins[id];
544
0
        }
545
546
0
        if (global_surplus_cpu_moe > 0) {
547
0
            LOG_TRC("%s: with only dense weights in device memory there is a total surplus of %" PRId64 " MiB\n",
548
0
                __func__, global_surplus_cpu_moe/MiB);
549
0
        } else {
550
0
            LOG_TRC("%s: with only dense weights in device memory there is still a total deficit of %" PRId64 " MiB\n",
551
0
                __func__, -global_surplus_cpu_moe/MiB);
552
0
        }
553
554
        // reset
555
0
        tensor_buft_overrides[0] = {nullptr, nullptr};
556
0
        mparams->tensor_buft_overrides = tensor_buft_overrides;
557
0
    }
558
559
0
    std::vector<int64_t> targets; // maximum acceptable memory use per device
560
0
    targets.reserve(nd);
561
0
    for (size_t id = 0; id < nd; id++) {
562
0
        targets.push_back(dmds_full[id].free - margins[id]);
563
0
        LOG_TRC("%s: id=%zu, target=%" PRId64 " MiB\n", __func__, id, targets[id]/MiB);
564
0
    }
565
566
0
    std::vector<ggml_backend_buffer_type_t> overflow_bufts; // which bufts the first partial layer of a device overflows to:
567
0
    overflow_bufts.reserve(nd);
568
0
    for (size_t id = 0; id < nd; id++) {
569
0
        overflow_bufts.push_back(ggml_backend_cpu_buffer_type());
570
0
    }
571
572
0
    std::vector<ngl_t> ngl_per_device(nd);
573
0
    std::vector<int64_t> mem = get_memory_for_layers(__func__, ngl_per_device, overflow_bufts);
574
575
    // optimize the number of layers per device using the method of false position:
576
    //   - ngl_per_device has 0 layers for each device, lower bound
577
    //   - try a "high" configuration where a device is given all unassigned layers
578
    //   - interpolate the memory use / layer between low and high linearly to get a guess where it meets our target
579
    //   - check memory use of our guess, replace either the low or high bound
580
    //   - once we only have a difference of a single layer, stop and return the lower bound that just barely still fits
581
    //   - the last device has the output layer, which cannot be a partial layer
582
0
    if (hp_nex == 0) {
583
0
        LOG_TRC("%s: filling dense layers back-to-front:\n", __func__);
584
0
    } else {
585
0
        LOG_TRC("%s: filling dense-only layers back-to-front:\n", __func__);
586
0
    }
587
0
    for (int id = nd - 1; id >= 0; id--) {
588
0
        uint32_t n_unassigned = hp_ngl + 1;
589
0
        for (size_t jd = id + 1; jd < nd; ++jd) {
590
0
            assert(n_unassigned >= ngl_per_device[jd].n_layer);
591
0
            n_unassigned -= ngl_per_device[jd].n_layer;
592
0
        }
593
594
0
        std::vector<ngl_t> ngl_per_device_high = ngl_per_device;
595
0
        ngl_per_device_high[id].n_layer = n_unassigned;
596
0
        if (hp_nex > 0) {
597
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;
598
0
        }
599
0
        if (ngl_per_device_high[id].n_layer > 0) {
600
0
            std::vector<int64_t> mem_high = get_memory_for_layers(__func__, ngl_per_device_high, overflow_bufts);
601
0
            if (mem_high[id] > targets[id]) {
602
0
                assert(ngl_per_device_high[id].n_layer > ngl_per_device[id].n_layer);
603
0
                uint32_t delta = ngl_per_device_high[id].n_layer - ngl_per_device[id].n_layer;
604
0
                LOG_TRC("%s: start filling device %" PRIu32 ", delta=%" PRIu32 "\n", __func__, id, delta);
605
0
                while (delta > 1) {
606
0
                    uint32_t step_size = int64_t(delta) * (targets[id] - mem[id]) / (mem_high[id] - mem[id]);
607
0
                    step_size = std::max(step_size, uint32_t(1));
608
0
                    step_size = std::min(step_size, delta - 1);
609
610
0
                    std::vector<ngl_t> ngl_per_device_test = ngl_per_device;
611
0
                    ngl_per_device_test[id].n_layer += step_size;
612
0
                    if (hp_nex) {
613
0
                        ngl_per_device_test[id].n_part += size_t(id) == nd - 1 && ngl_per_device_test[id].n_part == 0 ?
614
0
                            step_size - 1 : step_size; // the first layer is the output layer which must always be full
615
0
                    }
616
0
                    const std::vector<int64_t> mem_test = get_memory_for_layers(__func__, ngl_per_device_test, overflow_bufts);
617
618
0
                    if (mem_test[id] <= targets[id]) {
619
0
                        ngl_per_device = ngl_per_device_test;
620
0
                        mem            = mem_test;
621
0
                        LOG_TRC("%s: set ngl_per_device[%d].n_layer=%" PRIu32 "\n", __func__, id, ngl_per_device[id].n_layer);
622
0
                    } else {
623
0
                        ngl_per_device_high = ngl_per_device_test;
624
0
                        mem_high            = mem_test;
625
0
                        LOG_TRC("%s: set ngl_per_device_high[%d].n_layer=%" PRIu32 "\n", __func__, id, ngl_per_device_high[id].n_layer);
626
0
                    }
627
0
                    delta = ngl_per_device_high[id].n_layer - ngl_per_device[id].n_layer;
628
0
                }
629
0
            } else {
630
0
                assert(ngl_per_device_high[id].n_layer == n_unassigned);
631
0
                ngl_per_device = ngl_per_device_high;
632
0
                mem            = mem_high;
633
0
                LOG_TRC("%s: set ngl_per_device[%d].n_layer=%" PRIu32 "\n", __func__, id, ngl_per_device[id].n_layer);
634
0
            }
635
0
        }
636
637
0
        const int64_t projected_margin = dmds_full[id].free - mem[id];
638
0
        LOG_TRC(
639
0
            "%s:   - %s: %2" PRIu32 " layers, %6" PRId64 " MiB used, %6" PRId64 " MiB free\n",
640
0
            __func__, dev_names[id].c_str(), ngl_per_device[id].n_layer, mem[id]/MiB, projected_margin/MiB);
641
0
    }
642
0
    if (hp_nex == 0 || global_surplus_cpu_moe <= 0) {
643
0
        set_ngl_tensor_split_tbo(ngl_per_device, overflow_bufts, *mparams);
644
0
        return;
645
0
    }
646
647
    // step 4: for a MoE model where all dense tensors fit,
648
    //     convert the dense-only layers in the back to full layers in the front until all devices are full
649
    // essentially the same procedure as for the dense-only layers except front-to-back
650
    // also, try fitting at least part of one more layer to reduce waste for "small" GPUs with e.g. 24 GiB VRAM
651
652
0
    size_t id_dense_start = nd;
653
0
    for (int id = nd - 1; id >= 0; id--) {
654
0
        if (ngl_per_device[id].n_layer > 0) {
655
0
            id_dense_start = id;
656
0
            continue;
657
0
        }
658
0
        break;
659
0
    }
660
0
    assert(id_dense_start < nd);
661
662
0
    LOG_TRC("%s: converting dense-only layers to full layers and filling them front-to-back with overflow to next device/system memory:\n", __func__);
663
0
    for (size_t id = 0; id <= id_dense_start && id_dense_start < nd; id++) {
664
0
        std::vector<ngl_t> ngl_per_device_high = ngl_per_device;
665
0
        for (size_t jd = id_dense_start; jd < nd; jd++) {
666
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;
667
0
            ngl_per_device_high[id].n_layer += n_layer_move;
668
0
            ngl_per_device_high[jd].n_layer -= n_layer_move;
669
0
            ngl_per_device_high[jd].n_part = 0;
670
0
        }
671
0
        size_t id_dense_start_high = nd - 1;
672
0
        std::vector<int64_t> mem_high = get_memory_for_layers(__func__, ngl_per_device_high, overflow_bufts);
673
674
0
        if (mem_high[id] > targets[id]) {
675
0
            assert(ngl_per_device_high[id].n_full() >= ngl_per_device[id].n_full());
676
0
            uint32_t delta = ngl_per_device_high[id].n_full() - ngl_per_device[id].n_full();
677
0
            while (delta > 1) {
678
0
                uint32_t step_size = int64_t(delta) * (targets[id] - mem[id]) / (mem_high[id] - mem[id]);
679
0
                step_size = std::max(step_size, uint32_t(1));
680
0
                step_size = std::min(step_size, delta - 1);
681
682
0
                std::vector<ngl_t> ngl_per_device_test = ngl_per_device;
683
0
                size_t id_dense_start_test = id_dense_start;
684
0
                uint32_t n_converted_test = 0;
685
0
                for (;id_dense_start_test < nd; id_dense_start_test++) {
686
0
                    const uint32_t n_convert_jd = std::min(step_size - n_converted_test, ngl_per_device_test[id_dense_start_test].n_part);
687
0
                    ngl_per_device_test[id_dense_start_test].n_layer -= n_convert_jd;
688
0
                    ngl_per_device_test[id_dense_start_test].n_part -= n_convert_jd;
689
0
                    ngl_per_device_test[id].n_layer += n_convert_jd;
690
0
                    n_converted_test += n_convert_jd;
691
692
0
                    if (ngl_per_device_test[id_dense_start_test].n_part > 0) {
693
0
                        break;
694
0
                    }
695
0
                }
696
0
                const std::vector<int64_t> mem_test = get_memory_for_layers(__func__, ngl_per_device_test, overflow_bufts);
697
698
0
                if (mem_test[id] <= targets[id]) {
699
0
                    ngl_per_device = ngl_per_device_test;
700
0
                    mem            = mem_test;
701
0
                    id_dense_start = id_dense_start_test;
702
0
                    LOG_TRC("%s: set ngl_per_device[%zu].(n_layer, n_part)=(%" PRIu32 ", %" PRIu32 "), id_dense_start=%zu\n",
703
0
                        __func__, id, ngl_per_device[id].n_layer, ngl_per_device[id].n_part, id_dense_start);
704
0
                } else {
705
0
                    ngl_per_device_high = ngl_per_device_test;
706
0
                    mem_high            = mem_test;
707
0
                    id_dense_start_high = id_dense_start_test;
708
0
                    LOG_TRC("%s: set ngl_per_device_high[%zu].(n_layer, n_part)=(%" PRIu32 ", %" PRIu32 "), id_dense_start_high=%zu\n",
709
0
                        __func__, id, ngl_per_device_high[id].n_layer, ngl_per_device_high[id].n_part, id_dense_start_high);
710
0
                }
711
0
                assert(ngl_per_device_high[id].n_full() >= ngl_per_device[id].n_full());
712
0
                delta = ngl_per_device_high[id].n_full() - ngl_per_device[id].n_full();
713
0
            }
714
0
        } else {
715
0
            ngl_per_device = ngl_per_device_high;
716
0
            mem            = mem_high;
717
0
            id_dense_start = id_dense_start_high;
718
0
            LOG_TRC("%s: set ngl_per_device[%zu].(n_layer, n_part)=(%" PRIu32 ", %" PRIu32 "), id_dense_start=%zu\n",
719
0
                __func__, id, ngl_per_device[id].n_layer, ngl_per_device[id].n_part, id_dense_start);
720
0
        }
721
722
        // try to fit at least part of one more layer
723
0
        if (ngl_per_device[id_dense_start].n_layer > (id < nd - 1 ? 0 : 1)) {
724
0
            std::vector<ngl_t> ngl_per_device_test = ngl_per_device;
725
0
            size_t id_dense_start_test = id_dense_start;
726
0
            ngl_per_device_test[id_dense_start_test].n_layer--;
727
0
            ngl_per_device_test[id_dense_start_test].n_part--;
728
0
            ngl_per_device_test[id].n_layer++;
729
0
            ngl_per_device_test[id].n_part++;
730
0
            if (ngl_per_device_test[id_dense_start_test].n_part == 0) {
731
0
                id_dense_start_test++;
732
0
            }
733
0
            ngl_per_device_test[id].overflow_type = LAYER_FRACTION_UP;
734
0
            std::vector<ggml_backend_buffer_type_t> overflow_bufts_test = overflow_bufts;
735
0
            if (id < nd - 1) {
736
0
                overflow_bufts_test[id] = ggml_backend_dev_buffer_type(devs[id + 1]);
737
0
            }
738
0
            LOG_TRC("%s: trying to fit one extra layer with overflow_type=LAYER_FRACTION_UP\n", __func__);
739
0
            std::vector<int64_t> mem_test = get_memory_for_layers(__func__, ngl_per_device_test, overflow_bufts_test);
740
0
            if (mem_test[id] < targets[id] && (id + 1 == nd || mem_test[id + 1] < targets[id + 1])) {
741
0
                ngl_per_device = ngl_per_device_test;
742
0
                overflow_bufts = overflow_bufts_test;
743
0
                mem            = mem_test;
744
0
                id_dense_start = id_dense_start_test;
745
0
                LOG_TRC("%s: set ngl_per_device[%zu].(n_layer, n_part, overflow_type)=(%" PRIu32 ", %" PRIu32 ", UP), id_dense_start=%zu\n",
746
0
                    __func__, id, ngl_per_device[id].n_layer, ngl_per_device[id].n_part, id_dense_start);
747
748
0
                ngl_per_device_test[id].overflow_type = LAYER_FRACTION_GATE;
749
0
                LOG_TRC("%s: trying to fit one extra layer with overflow_type=LAYER_FRACTION_GATE\n", __func__);
750
0
                mem_test = get_memory_for_layers(__func__, ngl_per_device_test, overflow_bufts_test);
751
0
                if (mem_test[id] < targets[id] && (id + 1 == nd || mem_test[id + 1] < targets[id + 1])) {
752
0
                    ngl_per_device = ngl_per_device_test;
753
0
                    overflow_bufts = overflow_bufts_test;
754
0
                    mem            = mem_test;
755
0
                    id_dense_start = id_dense_start_test;
756
0
                    LOG_TRC("%s: set ngl_per_device[%zu].(n_layer, n_part, overflow_type)=(%" PRIu32 ", %" PRIu32 ", GATE), id_dense_start=%zu\n",
757
0
                        __func__, id, ngl_per_device[id].n_layer, ngl_per_device[id].n_part, id_dense_start);
758
0
                }
759
0
            } else {
760
0
                ngl_per_device_test[id].overflow_type = LAYER_FRACTION_ATTN;
761
0
                LOG_TRC("%s: trying to fit one extra layer with overflow_type=LAYER_FRACTION_ATTN\n", __func__);
762
0
                mem_test = get_memory_for_layers(__func__, ngl_per_device_test, overflow_bufts_test);
763
0
                if (mem_test[id] < targets[id] && (id + 1 == nd || mem_test[id + 1] < targets[id + 1])) {
764
0
                    ngl_per_device = ngl_per_device_test;
765
0
                    overflow_bufts = overflow_bufts_test;
766
0
                    mem            = mem_test;
767
0
                    id_dense_start = id_dense_start_test;
768
0
                    LOG_TRC("%s: set ngl_per_device[%zu].(n_layer, n_part, overflow_type)=(%" PRIu32 ", %" PRIu32 ", ATTN), id_dense_start=%zu\n",
769
0
                        __func__, id, ngl_per_device[id].n_layer, ngl_per_device[id].n_part, id_dense_start);
770
0
                }
771
0
            }
772
0
        }
773
774
0
        const int64_t projected_margin = dmds_full[id].free - mem[id];
775
0
        LOG_TRC(
776
0
            "%s:   - %s: %2" PRIu32 " layers (%2" PRIu32 " overflowing), %6" PRId64 " MiB used, %6" PRId64 " MiB free\n",
777
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);
778
0
    }
779
780
    // print info for devices that were not changed during the conversion from dense only to full layers:
781
0
    for (size_t id = id_dense_start + 1; id < nd; id++) {
782
0
        const int64_t projected_margin = dmds_full[id].free - mem[id];
783
0
        LOG_TRC(
784
0
            "%s:   - %s: %2" PRIu32 " layers (%2" PRIu32 " overflowing), %6" PRId64 " MiB used, %6" PRId64 " MiB free\n",
785
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);
786
0
    }
787
788
0
    set_ngl_tensor_split_tbo(ngl_per_device, overflow_bufts, *mparams);
789
0
}
790
791
enum common_params_fit_status common_fit_params(
792
        const char * path_model,
793
        llama_model_params * mparams,
794
        llama_context_params * cparams,
795
        float * tensor_split,
796
        llama_model_tensor_buft_override * tensor_buft_overrides,
797
        size_t * margins,
798
        uint32_t n_ctx_min,
799
0
        ggml_log_level log_level) {
800
0
    const int64_t t0_us = llama_time_us();
801
0
    common_params_fit_status status = COMMON_PARAMS_FIT_STATUS_SUCCESS;
802
0
    try {
803
0
        common_params_fit_impl(path_model, mparams, cparams, tensor_split, tensor_buft_overrides, margins, n_ctx_min, log_level);
804
0
        LOG_TRC("%s: successfully fit params to free device memory\n", __func__);
805
0
    } catch (const common_params_fit_exception & e) {
806
0
        LOG_WRN("%s: failed to fit params to free device memory: %s\n", __func__, e.what());
807
0
        status = COMMON_PARAMS_FIT_STATUS_FAILURE;
808
0
    } catch (const std::runtime_error & e) {
809
0
        LOG_ERR("%s: encountered an error while trying to fit params to free device memory: %s\n", __func__, e.what());
810
0
        status = COMMON_PARAMS_FIT_STATUS_ERROR;
811
0
    }
812
0
    const int64_t t1_us = llama_time_us();
813
0
    LOG_TRC("%s: fitting params to free memory took %.2f seconds\n", __func__, (t1_us - t0_us) * 1e-6);
814
0
    return status;
815
0
}
816
817
0
void common_memory_breakdown_print(const struct llama_context * ctx) {
818
    //const auto & devices = ctx->get_model().devices;
819
0
    const auto * model = llama_get_model(ctx);
820
821
0
    std::vector<ggml_backend_dev_t> devices;
822
0
    for (int i = 0; i < llama_model_n_devices(model); i++) {
823
0
        devices.push_back(llama_model_get_device(model, i));
824
0
    }
825
826
0
    llama_memory_breakdown memory_breakdown = llama_get_memory_breakdown(ctx);
827
828
0
    std::vector<std::array<std::string, 9>> table_data;
829
0
    table_data.reserve(devices.size());
830
0
    const std::string template_header = "%s: | %s | %s   %s    %s   %s   %s   %s    %s |\n";
831
0
    const std::string template_gpu    = "%s: | %s | %s = %s + (%s = %s + %s + %s) + %s |\n";
832
0
    const std::string template_other  = "%s: | %s | %s   %s    %s = %s + %s + %s    %s |\n";
833
834
0
    table_data.push_back({template_header, "memory breakdown [MiB]", "total", "free", "self", "model", "context", "compute", "unaccounted"});
835
836
0
    constexpr size_t MiB = 1024 * 1024;
837
0
    const std::vector<std::string> desc_prefixes_strip = {"NVIDIA ", "GeForce ", "Tesla ", "AMD ", "Radeon ", "Instinct "};
838
839
    // track seen buffer types to avoid double counting:
840
0
    std::set<ggml_backend_buffer_type_t> seen_buffer_types;
841
842
    // accumulative memory breakdown for each device and for host:
843
0
    std::vector<llama_memory_breakdown_data> mb_dev(devices.size());
844
0
    llama_memory_breakdown_data              mb_host;
845
846
0
    for (const auto & buft_mb : memory_breakdown) {
847
0
        ggml_backend_buffer_type_t          buft = buft_mb.first;
848
0
        const llama_memory_breakdown_data & mb   = buft_mb.second;
849
0
        if (ggml_backend_buft_is_host(buft)) {
850
0
            mb_host.model   += mb.model;
851
0
            mb_host.context += mb.context;
852
0
            mb_host.compute += mb.compute;
853
0
            seen_buffer_types.insert(buft);
854
0
            continue;
855
0
        }
856
0
        ggml_backend_dev_t dev = ggml_backend_buft_get_device(buft);
857
0
        if (dev) {
858
0
            int i_dev = -1;
859
0
            for (size_t i = 0; i < devices.size(); i++) {
860
0
                if (devices[i] == dev) {
861
0
                    i_dev = i;
862
0
                    break;
863
0
                }
864
0
            }
865
0
            if (i_dev != -1) {
866
0
                mb_dev[i_dev].model   += mb.model;
867
0
                mb_dev[i_dev].context += mb.context;
868
0
                mb_dev[i_dev].compute += mb.compute;
869
0
                seen_buffer_types.insert(buft);
870
0
                continue;
871
0
            }
872
0
        }
873
0
    }
874
875
    // print memory breakdown for each device:
876
0
    for (size_t i = 0; i < devices.size(); i++) {
877
0
        ggml_backend_dev_t dev = devices[i];
878
0
        llama_memory_breakdown_data mb = mb_dev[i];
879
880
0
        const std::string name = ggml_backend_dev_name(dev);
881
0
        std::string desc = ggml_backend_dev_description(dev);
882
0
        for (const std::string & prefix : desc_prefixes_strip) {
883
0
            if (desc.length() >= prefix.length() && desc.substr(0, prefix.length()) == prefix) {
884
0
                desc = desc.substr(prefix.length());
885
0
            }
886
0
        }
887
888
0
        size_t free, total;
889
0
        ggml_backend_dev_memory(dev, &free, &total);
890
891
0
        const size_t self = mb.model + mb.context + mb.compute;
892
0
        const int64_t unaccounted = static_cast<int64_t>(total) - static_cast<int64_t>(free) - static_cast<int64_t>(self);
893
894
0
        table_data.push_back({
895
0
            template_gpu,
896
0
            "  - " + name + " (" + desc + ")",
897
0
            std::to_string(total / MiB),
898
0
            std::to_string(free / MiB),
899
0
            std::to_string(self / MiB),
900
0
            std::to_string(mb.model / MiB),
901
0
            std::to_string(mb.context / MiB),
902
0
            std::to_string(mb.compute / MiB),
903
0
            std::to_string(unaccounted / static_cast<int64_t>(MiB))});
904
0
    }
905
906
    // print memory breakdown for host:
907
0
    {
908
0
        const size_t self = mb_host.model + mb_host.context + mb_host.compute;
909
0
        table_data.push_back({
910
0
            template_other,
911
0
            "  - Host",
912
0
            "", // total
913
0
            "", // free
914
0
            std::to_string(self / MiB),
915
0
            std::to_string(mb_host.model / MiB),
916
0
            std::to_string(mb_host.context / MiB),
917
0
            std::to_string(mb_host.compute / MiB),
918
0
            ""}); // unaccounted
919
0
    }
920
921
    // print memory breakdown for all remaining buffer types:
922
0
    for (const auto & buft_mb : memory_breakdown) {
923
0
        ggml_backend_buffer_type_t          buft = buft_mb.first;
924
0
        const llama_memory_breakdown_data & mb   = buft_mb.second;
925
0
        if (seen_buffer_types.count(buft) == 1) {
926
0
            continue;
927
0
        }
928
0
        const std::string name = ggml_backend_buft_name(buft);
929
0
        const size_t self = mb.model + mb.context + mb.compute;
930
0
        table_data.push_back({
931
0
            template_other,
932
0
            "  - " + name,
933
0
            "", // total
934
0
            "", // free
935
0
            std::to_string(self / MiB),
936
0
            std::to_string(mb.model / MiB),
937
0
            std::to_string(mb.context / MiB),
938
0
            std::to_string(mb.compute / MiB),
939
0
            ""}); // unaccounted
940
0
        seen_buffer_types.insert(buft);
941
0
    }
942
943
0
    for (size_t j = 1; j < table_data[0].size(); j++) {
944
0
        size_t max_len = 0;
945
0
        for (const auto & td : table_data) {
946
0
            max_len = std::max(max_len, td[j].length());
947
0
        }
948
0
        for (auto & td : table_data) {
949
0
            td[j].insert(j == 1 ? td[j].length() : 0, max_len - td[j].length(), ' ');
950
0
        }
951
0
    }
952
0
    for (const auto & td : table_data) {
953
0
        LOG_TRC(td[0].c_str(),
954
0
            __func__, td[1].c_str(), td[2].c_str(), td[3].c_str(), td[4].c_str(), td[5].c_str(),
955
0
            td[6].c_str(), td[7].c_str(), td[8].c_str());
956
0
    }
957
0
}
958
959
void common_fit_print(
960
        const char * path_model,
961
        llama_model_params * mparams,
962
0
        llama_context_params * cparams) {
963
0
    std::vector<ggml_backend_dev_t> devs;
964
0
    uint32_t hp_ngl = 0; // hparams.n_gpu_layers
965
0
    uint32_t hp_nct = 0; // hparams.n_ctx_train
966
0
    uint32_t hp_nex = 0; // hparams.n_expert
967
968
0
    auto dmd = common_get_device_memory_data_impl(path_model, mparams, cparams, devs, hp_ngl, hp_nct, hp_nex, GGML_LOG_LEVEL_ERROR);
969
0
    GGML_ASSERT(dmd.size() == devs.size() + 1);
970
971
0
    for (size_t id = 0; id < devs.size(); id++) {
972
0
        printf("%s ",  ggml_backend_dev_name(devs[id]));
973
0
        printf("%zu ", dmd[id].mb.model/1024/1024);
974
0
        printf("%zu ", dmd[id].mb.context/1024/1024);
975
0
        printf("%zu ", dmd[id].mb.compute/1024/1024);
976
0
        printf("\n");
977
0
    }
978
979
0
    printf("Host ");
980
0
    printf("%zu ", dmd.back().mb.model/1024/1024);
981
0
    printf("%zu ", dmd.back().mb.context/1024/1024);
982
0
    printf("%zu ", dmd.back().mb.compute/1024/1024);
983
0
    printf("\n");
984
0
}