"vscode:/vscode.git/clone" did not exist on "f1484b81b0b763aa010fd2083df933305afb1812"
llama-bench.cpp 59.2 KB
Newer Older
xuxzh1's avatar
init  
xuxzh1 committed
1
2
3
4
5
6
7
8
#include <algorithm>
#include <array>
#include <cassert>
#include <chrono>
#include <cinttypes>
#include <clocale>
#include <cmath>
#include <cstdio>
xuxzh1's avatar
update  
xuxzh1 committed
9
#include <cstdlib>
xuxzh1's avatar
init  
xuxzh1 committed
10
11
12
13
14
15
16
17
#include <cstring>
#include <ctime>
#include <iterator>
#include <map>
#include <numeric>
#include <regex>
#include <sstream>
#include <string>
xuxzh1's avatar
update  
xuxzh1 committed
18
#include <thread>
xuxzh1's avatar
init  
xuxzh1 committed
19
20
#include <vector>

xuxzh1's avatar
update  
xuxzh1 committed
21
#include "common.h"
xuxzh1's avatar
init  
xuxzh1 committed
22
23
24
#include "ggml.h"
#include "llama.h"

xuxzh1's avatar
update  
xuxzh1 committed
25
26
27
28
29
30
#ifdef _WIN32
#    define WIN32_LEAN_AND_MEAN
#    ifndef NOMINMAX
#        define NOMINMAX
#    endif
#    include <windows.h>
xuxzh1's avatar
init  
xuxzh1 committed
31
32
33
34
35
36
37
38
#endif

// utils
static uint64_t get_time_ns() {
    using clock = std::chrono::high_resolution_clock;
    return std::chrono::nanoseconds(clock::now().time_since_epoch()).count();
}

xuxzh1's avatar
update  
xuxzh1 committed
39
template <class T> static std::string join(const std::vector<T> & values, const std::string & delim) {
xuxzh1's avatar
init  
xuxzh1 committed
40
41
42
43
44
45
46
47
48
49
    std::ostringstream str;
    for (size_t i = 0; i < values.size(); i++) {
        str << values[i];
        if (i < values.size() - 1) {
            str << delim;
        }
    }
    return str.str();
}

xuxzh1's avatar
update  
xuxzh1 committed
50
template <typename T, typename F> static std::vector<std::string> transform_to_str(const std::vector<T> & values, F f) {
xuxzh1's avatar
init  
xuxzh1 committed
51
52
53
54
55
    std::vector<std::string> str_values;
    std::transform(values.begin(), values.end(), std::back_inserter(str_values), f);
    return str_values;
}

xuxzh1's avatar
update  
xuxzh1 committed
56
template <typename T> static T avg(const std::vector<T> & v) {
xuxzh1's avatar
init  
xuxzh1 committed
57
58
59
60
    if (v.empty()) {
        return 0;
    }
    T sum = std::accumulate(v.begin(), v.end(), T(0));
xuxzh1's avatar
update  
xuxzh1 committed
61
    return sum / (T) v.size();
xuxzh1's avatar
init  
xuxzh1 committed
62
63
}

xuxzh1's avatar
update  
xuxzh1 committed
64
template <typename T> static T stdev(const std::vector<T> & v) {
xuxzh1's avatar
init  
xuxzh1 committed
65
66
67
    if (v.size() <= 1) {
        return 0;
    }
xuxzh1's avatar
update  
xuxzh1 committed
68
    T mean   = avg(v);
xuxzh1's avatar
init  
xuxzh1 committed
69
    T sq_sum = std::inner_product(v.begin(), v.end(), v.begin(), T(0));
xuxzh1's avatar
update  
xuxzh1 committed
70
    T stdev  = std::sqrt(sq_sum / (T) (v.size() - 1) - mean * mean * (T) v.size() / (T) (v.size() - 1));
xuxzh1's avatar
init  
xuxzh1 committed
71
72
73
74
    return stdev;
}

static std::string get_cpu_info() {
xuxzh1's avatar
update  
xuxzh1 committed
75
76
77
78
79
80
    std::vector<std::string> cpu_list;
    for (size_t i = 0; i < ggml_backend_dev_count(); i++) {
        auto * dev      = ggml_backend_dev_get(i);
        auto   dev_type = ggml_backend_dev_type(dev);
        if (dev_type == GGML_BACKEND_DEVICE_TYPE_CPU || dev_type == GGML_BACKEND_DEVICE_TYPE_ACCEL) {
            cpu_list.push_back(ggml_backend_dev_description(dev));
xuxzh1's avatar
init  
xuxzh1 committed
81
82
        }
    }
xuxzh1's avatar
update  
xuxzh1 committed
83
    return join(cpu_list, ", ");
xuxzh1's avatar
init  
xuxzh1 committed
84
85
86
}

static std::string get_gpu_info() {
xuxzh1's avatar
update  
xuxzh1 committed
87
88
89
90
91
92
    std::vector<std::string> gpu_list;
    for (size_t i = 0; i < ggml_backend_dev_count(); i++) {
        auto * dev      = ggml_backend_dev_get(i);
        auto   dev_type = ggml_backend_dev_type(dev);
        if (dev_type == GGML_BACKEND_DEVICE_TYPE_GPU) {
            gpu_list.push_back(ggml_backend_dev_description(dev));
xuxzh1's avatar
init  
xuxzh1 committed
93
94
        }
    }
xuxzh1's avatar
update  
xuxzh1 committed
95
    return join(gpu_list, ", ");
xuxzh1's avatar
init  
xuxzh1 committed
96
97
98
}

// command line params
xuxzh1's avatar
update  
xuxzh1 committed
99
enum output_formats { NONE, CSV, JSON, JSONL, MARKDOWN, SQL };
xuxzh1's avatar
init  
xuxzh1 committed
100
101
102

static const char * output_format_str(output_formats format) {
    switch (format) {
xuxzh1's avatar
update  
xuxzh1 committed
103
104
105
106
107
108
109
110
111
112
113
114
115
116
        case NONE:
            return "none";
        case CSV:
            return "csv";
        case JSON:
            return "json";
        case JSONL:
            return "jsonl";
        case MARKDOWN:
            return "md";
        case SQL:
            return "sql";
        default:
            GGML_ABORT("invalid output format");
xuxzh1's avatar
init  
xuxzh1 committed
117
118
119
120
121
122
123
124
125
126
    }
}

static bool output_format_from_str(const std::string & s, output_formats & format) {
    if (s == "none") {
        format = NONE;
    } else if (s == "csv") {
        format = CSV;
    } else if (s == "json") {
        format = JSON;
xuxzh1's avatar
update  
xuxzh1 committed
127
128
    } else if (s == "jsonl") {
        format = JSONL;
xuxzh1's avatar
init  
xuxzh1 committed
129
130
131
132
133
134
135
136
137
138
139
140
    } else if (s == "md") {
        format = MARKDOWN;
    } else if (s == "sql") {
        format = SQL;
    } else {
        return false;
    }
    return true;
}

static const char * split_mode_str(llama_split_mode mode) {
    switch (mode) {
xuxzh1's avatar
update  
xuxzh1 committed
141
142
143
144
145
146
147
148
        case LLAMA_SPLIT_MODE_NONE:
            return "none";
        case LLAMA_SPLIT_MODE_LAYER:
            return "layer";
        case LLAMA_SPLIT_MODE_ROW:
            return "row";
        default:
            GGML_ABORT("invalid split mode");
xuxzh1's avatar
init  
xuxzh1 committed
149
150
151
152
153
154
155
156
157
158
    }
}

static std::string pair_str(const std::pair<int, int> & p) {
    static char buf[32];
    snprintf(buf, sizeof(buf), "%d,%d", p.first, p.second);
    return buf;
}

struct cmd_params {
xuxzh1's avatar
update  
xuxzh1 committed
159
160
161
    std::vector<std::string>         model;
    std::vector<int>                 n_prompt;
    std::vector<int>                 n_gen;
xuxzh1's avatar
init  
xuxzh1 committed
162
    std::vector<std::pair<int, int>> n_pg;
xuxzh1's avatar
update  
xuxzh1 committed
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
    std::vector<int>                 n_batch;
    std::vector<int>                 n_ubatch;
    std::vector<ggml_type>           type_k;
    std::vector<ggml_type>           type_v;
    std::vector<int>                 n_threads;
    std::vector<std::string>         cpu_mask;
    std::vector<bool>                cpu_strict;
    std::vector<int>                 poll;
    std::vector<int>                 n_gpu_layers;
    std::vector<std::string>         rpc_servers;
    std::vector<llama_split_mode>    split_mode;
    std::vector<int>                 main_gpu;
    std::vector<bool>                no_kv_offload;
    std::vector<bool>                flash_attn;
    std::vector<std::vector<float>>  tensor_split;
    std::vector<bool>                use_mmap;
    std::vector<bool>                embeddings;
    ggml_numa_strategy               numa;
    int                              reps;
    ggml_sched_priority              prio;
    int                              delay;
    bool                             verbose;
    bool                             progress;
    output_formats                   output_format;
    output_formats                   output_format_stderr;
xuxzh1's avatar
init  
xuxzh1 committed
188
189
190
};

static const cmd_params cmd_params_defaults = {
xuxzh1's avatar
update  
xuxzh1 committed
191
192
193
    /* model                */ { "models/7B/ggml-model-q4_0.gguf" },
    /* n_prompt             */ { 512 },
    /* n_gen                */ { 128 },
xuxzh1's avatar
init  
xuxzh1 committed
194
    /* n_pg                 */ {},
xuxzh1's avatar
update  
xuxzh1 committed
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
    /* n_batch              */ { 2048 },
    /* n_ubatch             */ { 512 },
    /* type_k               */ { GGML_TYPE_F16 },
    /* type_v               */ { GGML_TYPE_F16 },
    /* n_threads            */ { cpu_get_num_math() },
    /* cpu_mask             */ { "0x0" },
    /* cpu_strict           */ { false },
    /* poll                 */ { 50 },
    /* n_gpu_layers         */ { 99 },
    /* rpc_servers          */ { "" },
    /* split_mode           */ { LLAMA_SPLIT_MODE_LAYER },
    /* main_gpu             */ { 0 },
    /* no_kv_offload        */ { false },
    /* flash_attn           */ { false },
    /* tensor_split         */ { std::vector<float>(llama_max_devices(), 0.0f) },
    /* use_mmap             */ { true },
    /* embeddings           */ { false },
xuxzh1's avatar
init  
xuxzh1 committed
212
213
    /* numa                 */ GGML_NUMA_STRATEGY_DISABLED,
    /* reps                 */ 5,
xuxzh1's avatar
update  
xuxzh1 committed
214
215
    /* prio                 */ GGML_SCHED_PRIO_NORMAL,
    /* delay                */ 0,
xuxzh1's avatar
init  
xuxzh1 committed
216
    /* verbose              */ false,
xuxzh1's avatar
update  
xuxzh1 committed
217
    /* progress             */ false,
xuxzh1's avatar
init  
xuxzh1 committed
218
219
220
221
222
223
224
225
226
    /* output_format        */ MARKDOWN,
    /* output_format_stderr */ NONE,
};

static void print_usage(int /* argc */, char ** argv) {
    printf("usage: %s [options]\n", argv[0]);
    printf("\n");
    printf("options:\n");
    printf("  -h, --help\n");
xuxzh1's avatar
update  
xuxzh1 committed
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
    printf("  -m, --model <filename>                    (default: %s)\n", join(cmd_params_defaults.model, ",").c_str());
    printf("  -p, --n-prompt <n>                        (default: %s)\n",
           join(cmd_params_defaults.n_prompt, ",").c_str());
    printf("  -n, --n-gen <n>                           (default: %s)\n", join(cmd_params_defaults.n_gen, ",").c_str());
    printf("  -pg <pp,tg>                               (default: %s)\n",
           join(transform_to_str(cmd_params_defaults.n_pg, pair_str), ",").c_str());
    printf("  -b, --batch-size <n>                      (default: %s)\n",
           join(cmd_params_defaults.n_batch, ",").c_str());
    printf("  -ub, --ubatch-size <n>                    (default: %s)\n",
           join(cmd_params_defaults.n_ubatch, ",").c_str());
    printf("  -ctk, --cache-type-k <t>                  (default: %s)\n",
           join(transform_to_str(cmd_params_defaults.type_k, ggml_type_name), ",").c_str());
    printf("  -ctv, --cache-type-v <t>                  (default: %s)\n",
           join(transform_to_str(cmd_params_defaults.type_v, ggml_type_name), ",").c_str());
    printf("  -t, --threads <n>                         (default: %s)\n",
           join(cmd_params_defaults.n_threads, ",").c_str());
    printf("  -C, --cpu-mask <hex,hex>                  (default: %s)\n",
           join(cmd_params_defaults.cpu_mask, ",").c_str());
    printf("  --cpu-strict <0|1>                        (default: %s)\n",
           join(cmd_params_defaults.cpu_strict, ",").c_str());
    printf("  --poll <0...100>                          (default: %s)\n", join(cmd_params_defaults.poll, ",").c_str());
    printf("  -ngl, --n-gpu-layers <n>                  (default: %s)\n",
           join(cmd_params_defaults.n_gpu_layers, ",").c_str());
    if (llama_supports_rpc()) {
        printf("  -rpc, --rpc <rpc_servers>                 (default: %s)\n",
               join(cmd_params_defaults.rpc_servers, ",").c_str());
    }
    printf("  -sm, --split-mode <none|layer|row>        (default: %s)\n",
           join(transform_to_str(cmd_params_defaults.split_mode, split_mode_str), ",").c_str());
    printf("  -mg, --main-gpu <i>                       (default: %s)\n",
           join(cmd_params_defaults.main_gpu, ",").c_str());
    printf("  -nkvo, --no-kv-offload <0|1>              (default: %s)\n",
           join(cmd_params_defaults.no_kv_offload, ",").c_str());
    printf("  -fa, --flash-attn <0|1>                   (default: %s)\n",
           join(cmd_params_defaults.flash_attn, ",").c_str());
    printf("  -mmp, --mmap <0|1>                        (default: %s)\n",
           join(cmd_params_defaults.use_mmap, ",").c_str());
    printf("  --numa <distribute|isolate|numactl>       (default: disabled)\n");
    printf("  -embd, --embeddings <0|1>                 (default: %s)\n",
           join(cmd_params_defaults.embeddings, ",").c_str());
    printf("  -ts, --tensor-split <ts0/ts1/..>          (default: 0)\n");
    printf("  -r, --repetitions <n>                     (default: %d)\n", cmd_params_defaults.reps);
    printf("  --prio <0|1|2|3>                          (default: %d)\n", cmd_params_defaults.prio);
    printf("  --delay <0...N> (seconds)                 (default: %d)\n", cmd_params_defaults.delay);
    printf("  -o, --output <csv|json|jsonl|md|sql>      (default: %s)\n",
           output_format_str(cmd_params_defaults.output_format));
    printf("  -oe, --output-err <csv|json|jsonl|md|sql> (default: %s)\n",
           output_format_str(cmd_params_defaults.output_format_stderr));
    printf("  -v, --verbose                             (default: %s)\n", cmd_params_defaults.verbose ? "1" : "0");
    printf("  --progress                                (default: %s)\n", cmd_params_defaults.progress ? "1" : "0");
xuxzh1's avatar
init  
xuxzh1 committed
277
    printf("\n");
xuxzh1's avatar
update  
xuxzh1 committed
278
279
280
    printf(
        "Multiple values can be given for each parameter by separating them with ',' or by specifying the parameter "
        "multiple times.\n");
xuxzh1's avatar
init  
xuxzh1 committed
281
282
283
284
285
286
}

static ggml_type ggml_type_from_name(const std::string & s) {
    if (s == "f16") {
        return GGML_TYPE_F16;
    }
xuxzh1's avatar
update  
xuxzh1 committed
287
288
289
    if (s == "bf16") {
        return GGML_TYPE_BF16;
    }
xuxzh1's avatar
init  
xuxzh1 committed
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
    if (s == "q8_0") {
        return GGML_TYPE_Q8_0;
    }
    if (s == "q4_0") {
        return GGML_TYPE_Q4_0;
    }
    if (s == "q4_1") {
        return GGML_TYPE_Q4_1;
    }
    if (s == "q5_0") {
        return GGML_TYPE_Q5_0;
    }
    if (s == "q5_1") {
        return GGML_TYPE_Q5_1;
    }
    if (s == "iq4_nl") {
        return GGML_TYPE_IQ4_NL;
    }

    return GGML_TYPE_COUNT;
}

static cmd_params parse_cmd_params(int argc, char ** argv) {
xuxzh1's avatar
update  
xuxzh1 committed
313
314
315
316
317
318
319
320
    cmd_params        params;
    std::string       arg;
    bool              invalid_param = false;
    const std::string arg_prefix    = "--";
    const char        split_delim   = ',';

    params.verbose              = cmd_params_defaults.verbose;
    params.output_format        = cmd_params_defaults.output_format;
xuxzh1's avatar
init  
xuxzh1 committed
321
    params.output_format_stderr = cmd_params_defaults.output_format_stderr;
xuxzh1's avatar
update  
xuxzh1 committed
322
323
324
325
326
    params.reps                 = cmd_params_defaults.reps;
    params.numa                 = cmd_params_defaults.numa;
    params.prio                 = cmd_params_defaults.prio;
    params.delay                = cmd_params_defaults.delay;
    params.progress             = cmd_params_defaults.progress;
xuxzh1's avatar
init  
xuxzh1 committed
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367

    for (int i = 1; i < argc; i++) {
        arg = argv[i];
        if (arg.compare(0, arg_prefix.size(), arg_prefix) == 0) {
            std::replace(arg.begin(), arg.end(), '_', '-');
        }

        if (arg == "-h" || arg == "--help") {
            print_usage(argc, argv);
            exit(0);
        } else if (arg == "-m" || arg == "--model") {
            if (++i >= argc) {
                invalid_param = true;
                break;
            }
            auto p = string_split<std::string>(argv[i], split_delim);
            params.model.insert(params.model.end(), p.begin(), p.end());
        } else if (arg == "-p" || arg == "--n-prompt") {
            if (++i >= argc) {
                invalid_param = true;
                break;
            }
            auto p = string_split<int>(argv[i], split_delim);
            params.n_prompt.insert(params.n_prompt.end(), p.begin(), p.end());
        } else if (arg == "-n" || arg == "--n-gen") {
            if (++i >= argc) {
                invalid_param = true;
                break;
            }
            auto p = string_split<int>(argv[i], split_delim);
            params.n_gen.insert(params.n_gen.end(), p.begin(), p.end());
        } else if (arg == "-pg") {
            if (++i >= argc) {
                invalid_param = true;
                break;
            }
            auto p = string_split<std::string>(argv[i], ',');
            if (p.size() != 2) {
                invalid_param = true;
                break;
            }
xuxzh1's avatar
update  
xuxzh1 committed
368
            params.n_pg.push_back({ std::stoi(p[0]), std::stoi(p[1]) });
xuxzh1's avatar
init  
xuxzh1 committed
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
        } else if (arg == "-b" || arg == "--batch-size") {
            if (++i >= argc) {
                invalid_param = true;
                break;
            }
            auto p = string_split<int>(argv[i], split_delim);
            params.n_batch.insert(params.n_batch.end(), p.begin(), p.end());
        } else if (arg == "-ub" || arg == "--ubatch-size") {
            if (++i >= argc) {
                invalid_param = true;
                break;
            }
            auto p = string_split<int>(argv[i], split_delim);
            params.n_ubatch.insert(params.n_ubatch.end(), p.begin(), p.end());
        } else if (arg == "-ctk" || arg == "--cache-type-k") {
            if (++i >= argc) {
                invalid_param = true;
                break;
            }
xuxzh1's avatar
update  
xuxzh1 committed
388
            auto                   p = string_split<std::string>(argv[i], split_delim);
xuxzh1's avatar
init  
xuxzh1 committed
389
390
391
392
393
394
395
396
397
            std::vector<ggml_type> types;
            for (const auto & t : p) {
                ggml_type gt = ggml_type_from_name(t);
                if (gt == GGML_TYPE_COUNT) {
                    invalid_param = true;
                    break;
                }
                types.push_back(gt);
            }
xuxzh1's avatar
update  
xuxzh1 committed
398
399
400
            if (invalid_param) {
                break;
            }
xuxzh1's avatar
init  
xuxzh1 committed
401
402
403
404
405
406
            params.type_k.insert(params.type_k.end(), types.begin(), types.end());
        } else if (arg == "-ctv" || arg == "--cache-type-v") {
            if (++i >= argc) {
                invalid_param = true;
                break;
            }
xuxzh1's avatar
update  
xuxzh1 committed
407
            auto                   p = string_split<std::string>(argv[i], split_delim);
xuxzh1's avatar
init  
xuxzh1 committed
408
409
410
411
412
413
414
415
416
            std::vector<ggml_type> types;
            for (const auto & t : p) {
                ggml_type gt = ggml_type_from_name(t);
                if (gt == GGML_TYPE_COUNT) {
                    invalid_param = true;
                    break;
                }
                types.push_back(gt);
            }
xuxzh1's avatar
update  
xuxzh1 committed
417
418
419
            if (invalid_param) {
                break;
            }
xuxzh1's avatar
init  
xuxzh1 committed
420
421
422
423
424
425
426
427
            params.type_v.insert(params.type_v.end(), types.begin(), types.end());
        } else if (arg == "-t" || arg == "--threads") {
            if (++i >= argc) {
                invalid_param = true;
                break;
            }
            auto p = string_split<int>(argv[i], split_delim);
            params.n_threads.insert(params.n_threads.end(), p.begin(), p.end());
xuxzh1's avatar
update  
xuxzh1 committed
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
        } else if (arg == "-C" || arg == "--cpu-mask") {
            if (++i >= argc) {
                invalid_param = true;
                break;
            }
            auto p = string_split<std::string>(argv[i], split_delim);
            params.cpu_mask.insert(params.cpu_mask.end(), p.begin(), p.end());
        } else if (arg == "--cpu-strict") {
            if (++i >= argc) {
                invalid_param = true;
                break;
            }
            auto p = string_split<bool>(argv[i], split_delim);
            params.cpu_strict.insert(params.cpu_strict.end(), p.begin(), p.end());
        } else if (arg == "--poll") {
            if (++i >= argc) {
                invalid_param = true;
                break;
            }
            auto p = string_split<int>(argv[i], split_delim);
            params.poll.insert(params.poll.end(), p.begin(), p.end());
xuxzh1's avatar
init  
xuxzh1 committed
449
450
451
452
453
454
455
        } else if (arg == "-ngl" || arg == "--n-gpu-layers") {
            if (++i >= argc) {
                invalid_param = true;
                break;
            }
            auto p = string_split<int>(argv[i], split_delim);
            params.n_gpu_layers.insert(params.n_gpu_layers.end(), p.begin(), p.end());
xuxzh1's avatar
update  
xuxzh1 committed
456
        } else if (llama_supports_rpc() && (arg == "-rpc" || arg == "--rpc")) {
xuxzh1's avatar
init  
xuxzh1 committed
457
458
459
460
461
462
463
464
465
466
            if (++i >= argc) {
                invalid_param = true;
                break;
            }
            params.rpc_servers.push_back(argv[i]);
        } else if (arg == "-sm" || arg == "--split-mode") {
            if (++i >= argc) {
                invalid_param = true;
                break;
            }
xuxzh1's avatar
update  
xuxzh1 committed
467
            auto                          p = string_split<std::string>(argv[i], split_delim);
xuxzh1's avatar
init  
xuxzh1 committed
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
            std::vector<llama_split_mode> modes;
            for (const auto & m : p) {
                llama_split_mode mode;
                if (m == "none") {
                    mode = LLAMA_SPLIT_MODE_NONE;
                } else if (m == "layer") {
                    mode = LLAMA_SPLIT_MODE_LAYER;
                } else if (m == "row") {
                    mode = LLAMA_SPLIT_MODE_ROW;
                } else {
                    invalid_param = true;
                    break;
                }
                modes.push_back(mode);
            }
xuxzh1's avatar
update  
xuxzh1 committed
483
484
485
            if (invalid_param) {
                break;
            }
xuxzh1's avatar
init  
xuxzh1 committed
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
            params.split_mode.insert(params.split_mode.end(), modes.begin(), modes.end());
        } else if (arg == "-mg" || arg == "--main-gpu") {
            if (++i >= argc) {
                invalid_param = true;
                break;
            }
            params.main_gpu = string_split<int>(argv[i], split_delim);
        } else if (arg == "-nkvo" || arg == "--no-kv-offload") {
            if (++i >= argc) {
                invalid_param = true;
                break;
            }
            auto p = string_split<bool>(argv[i], split_delim);
            params.no_kv_offload.insert(params.no_kv_offload.end(), p.begin(), p.end());
        } else if (arg == "--numa") {
            if (++i >= argc) {
                invalid_param = true;
                break;
            } else {
                std::string value(argv[i]);
xuxzh1's avatar
update  
xuxzh1 committed
506
507
508
509
510
511
512
513
514
515
                /**/ if (value == "distribute" || value == "") {
                    params.numa = GGML_NUMA_STRATEGY_DISTRIBUTE;
                } else if (value == "isolate") {
                    params.numa = GGML_NUMA_STRATEGY_ISOLATE;
                } else if (value == "numactl") {
                    params.numa = GGML_NUMA_STRATEGY_NUMACTL;
                } else {
                    invalid_param = true;
                    break;
                }
xuxzh1's avatar
init  
xuxzh1 committed
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
            }
        } else if (arg == "-fa" || arg == "--flash-attn") {
            if (++i >= argc) {
                invalid_param = true;
                break;
            }
            auto p = string_split<bool>(argv[i], split_delim);
            params.flash_attn.insert(params.flash_attn.end(), p.begin(), p.end());
        } else if (arg == "-mmp" || arg == "--mmap") {
            if (++i >= argc) {
                invalid_param = true;
                break;
            }
            auto p = string_split<bool>(argv[i], split_delim);
            params.use_mmap.insert(params.use_mmap.end(), p.begin(), p.end());
        } else if (arg == "-embd" || arg == "--embeddings") {
            if (++i >= argc) {
                invalid_param = true;
                break;
            }
            auto p = string_split<bool>(argv[i], split_delim);
            params.embeddings.insert(params.embeddings.end(), p.begin(), p.end());
        } else if (arg == "-ts" || arg == "--tensor-split") {
            if (++i >= argc) {
                invalid_param = true;
                break;
            }
            for (auto ts : string_split<std::string>(argv[i], split_delim)) {
                // split string by ; and /
xuxzh1's avatar
update  
xuxzh1 committed
545
546
547
                const std::regex           regex{ R"([;/]+)" };
                std::sregex_token_iterator it{ ts.begin(), ts.end(), regex, -1 };
                std::vector<std::string>   split_arg{ it, {} };
xuxzh1's avatar
init  
xuxzh1 committed
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
                GGML_ASSERT(split_arg.size() <= llama_max_devices());

                std::vector<float> tensor_split(llama_max_devices());
                for (size_t i = 0; i < llama_max_devices(); ++i) {
                    if (i < split_arg.size()) {
                        tensor_split[i] = std::stof(split_arg[i]);
                    } else {
                        tensor_split[i] = 0.0f;
                    }
                }
                params.tensor_split.push_back(tensor_split);
            }
        } else if (arg == "-r" || arg == "--repetitions") {
            if (++i >= argc) {
                invalid_param = true;
                break;
            }
            params.reps = std::stoi(argv[i]);
xuxzh1's avatar
update  
xuxzh1 committed
566
567
568
569
570
571
572
573
574
575
576
577
        } else if (arg == "--prio") {
            if (++i >= argc) {
                invalid_param = true;
                break;
            }
            params.prio = (enum ggml_sched_priority) std::stoi(argv[i]);
        } else if (arg == "--delay") {
            if (++i >= argc) {
                invalid_param = true;
                break;
            }
            params.delay = std::stoi(argv[i]);
xuxzh1's avatar
init  
xuxzh1 committed
578
579
580
581
582
583
584
585
586
587
588
589
590
591
        } else if (arg == "-o" || arg == "--output") {
            if (++i >= argc) {
                invalid_param = true;
                break;
            }
            invalid_param = !output_format_from_str(argv[i], params.output_format);
        } else if (arg == "-oe" || arg == "--output-err") {
            if (++i >= argc) {
                invalid_param = true;
                break;
            }
            invalid_param = !output_format_from_str(argv[i], params.output_format_stderr);
        } else if (arg == "-v" || arg == "--verbose") {
            params.verbose = true;
xuxzh1's avatar
update  
xuxzh1 committed
592
593
        } else if (arg == "--progress") {
            params.progress = true;
xuxzh1's avatar
init  
xuxzh1 committed
594
595
596
597
598
599
600
601
602
603
604
605
        } else {
            invalid_param = true;
            break;
        }
    }
    if (invalid_param) {
        fprintf(stderr, "error: invalid parameter for argument: %s\n", arg.c_str());
        print_usage(argc, argv);
        exit(1);
    }

    // set defaults
xuxzh1's avatar
update  
xuxzh1 committed
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
    if (params.model.empty()) {
        params.model = cmd_params_defaults.model;
    }
    if (params.n_prompt.empty()) {
        params.n_prompt = cmd_params_defaults.n_prompt;
    }
    if (params.n_gen.empty()) {
        params.n_gen = cmd_params_defaults.n_gen;
    }
    if (params.n_pg.empty()) {
        params.n_pg = cmd_params_defaults.n_pg;
    }
    if (params.n_batch.empty()) {
        params.n_batch = cmd_params_defaults.n_batch;
    }
    if (params.n_ubatch.empty()) {
        params.n_ubatch = cmd_params_defaults.n_ubatch;
    }
    if (params.type_k.empty()) {
        params.type_k = cmd_params_defaults.type_k;
    }
    if (params.type_v.empty()) {
        params.type_v = cmd_params_defaults.type_v;
    }
    if (params.n_gpu_layers.empty()) {
        params.n_gpu_layers = cmd_params_defaults.n_gpu_layers;
    }
    if (params.rpc_servers.empty()) {
        params.rpc_servers = cmd_params_defaults.rpc_servers;
    }
    if (params.split_mode.empty()) {
        params.split_mode = cmd_params_defaults.split_mode;
    }
    if (params.main_gpu.empty()) {
        params.main_gpu = cmd_params_defaults.main_gpu;
    }
    if (params.no_kv_offload.empty()) {
        params.no_kv_offload = cmd_params_defaults.no_kv_offload;
    }
    if (params.flash_attn.empty()) {
        params.flash_attn = cmd_params_defaults.flash_attn;
    }
    if (params.tensor_split.empty()) {
        params.tensor_split = cmd_params_defaults.tensor_split;
    }
    if (params.use_mmap.empty()) {
        params.use_mmap = cmd_params_defaults.use_mmap;
    }
    if (params.embeddings.empty()) {
        params.embeddings = cmd_params_defaults.embeddings;
    }
    if (params.n_threads.empty()) {
        params.n_threads = cmd_params_defaults.n_threads;
    }
    if (params.cpu_mask.empty()) {
        params.cpu_mask = cmd_params_defaults.cpu_mask;
    }
    if (params.cpu_strict.empty()) {
        params.cpu_strict = cmd_params_defaults.cpu_strict;
    }
    if (params.poll.empty()) {
        params.poll = cmd_params_defaults.poll;
    }
xuxzh1's avatar
init  
xuxzh1 committed
669
670
671
672
673

    return params;
}

struct cmd_params_instance {
xuxzh1's avatar
update  
xuxzh1 committed
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
    std::string        model;
    int                n_prompt;
    int                n_gen;
    int                n_batch;
    int                n_ubatch;
    ggml_type          type_k;
    ggml_type          type_v;
    int                n_threads;
    std::string        cpu_mask;
    bool               cpu_strict;
    int                poll;
    int                n_gpu_layers;
    std::string        rpc_servers;
    llama_split_mode   split_mode;
    int                main_gpu;
    bool               no_kv_offload;
    bool               flash_attn;
xuxzh1's avatar
init  
xuxzh1 committed
691
    std::vector<float> tensor_split;
xuxzh1's avatar
update  
xuxzh1 committed
692
693
    bool               use_mmap;
    bool               embeddings;
xuxzh1's avatar
init  
xuxzh1 committed
694
695
696
697
698
699
700
701

    llama_model_params to_llama_mparams() const {
        llama_model_params mparams = llama_model_default_params();

        mparams.n_gpu_layers = n_gpu_layers;
        if (!rpc_servers.empty()) {
            mparams.rpc_servers = rpc_servers.c_str();
        }
xuxzh1's avatar
update  
xuxzh1 committed
702
703
        mparams.split_mode   = split_mode;
        mparams.main_gpu     = main_gpu;
xuxzh1's avatar
init  
xuxzh1 committed
704
        mparams.tensor_split = tensor_split.data();
xuxzh1's avatar
update  
xuxzh1 committed
705
        mparams.use_mmap     = use_mmap;
xuxzh1's avatar
init  
xuxzh1 committed
706
707
708
709
710

        return mparams;
    }

    bool equal_mparams(const cmd_params_instance & other) const {
xuxzh1's avatar
update  
xuxzh1 committed
711
712
        return model == other.model && n_gpu_layers == other.n_gpu_layers && rpc_servers == other.rpc_servers &&
               split_mode == other.split_mode && main_gpu == other.main_gpu && use_mmap == other.use_mmap &&
xuxzh1's avatar
init  
xuxzh1 committed
713
714
715
716
717
718
               tensor_split == other.tensor_split;
    }

    llama_context_params to_llama_cparams() const {
        llama_context_params cparams = llama_context_default_params();

xuxzh1's avatar
update  
xuxzh1 committed
719
720
721
722
723
        cparams.n_ctx       = n_prompt + n_gen;
        cparams.n_batch     = n_batch;
        cparams.n_ubatch    = n_ubatch;
        cparams.type_k      = type_k;
        cparams.type_v      = type_v;
xuxzh1's avatar
init  
xuxzh1 committed
724
        cparams.offload_kqv = !no_kv_offload;
xuxzh1's avatar
update  
xuxzh1 committed
725
726
        cparams.flash_attn  = flash_attn;
        cparams.embeddings  = embeddings;
xuxzh1's avatar
init  
xuxzh1 committed
727
728
729
730
731
732
733
734
735

        return cparams;
    }
};

static std::vector<cmd_params_instance> get_cmd_params_instances(const cmd_params & params) {
    std::vector<cmd_params_instance> instances;

    // this ordering minimizes the number of times that each model needs to be reloaded
xuxzh1's avatar
update  
xuxzh1 committed
736
    // clang-format off
xuxzh1's avatar
init  
xuxzh1 committed
737
738
739
740
741
742
743
744
745
746
747
748
749
750
    for (const auto & m : params.model)
    for (const auto & nl : params.n_gpu_layers)
    for (const auto & rpc : params.rpc_servers)
    for (const auto & sm : params.split_mode)
    for (const auto & mg : params.main_gpu)
    for (const auto & ts : params.tensor_split)
    for (const auto & mmp : params.use_mmap)
    for (const auto & embd : params.embeddings)
    for (const auto & nb : params.n_batch)
    for (const auto & nub : params.n_ubatch)
    for (const auto & tk : params.type_k)
    for (const auto & tv : params.type_v)
    for (const auto & nkvo : params.no_kv_offload)
    for (const auto & fa : params.flash_attn)
xuxzh1's avatar
update  
xuxzh1 committed
751
752
753
754
    for (const auto & nt : params.n_threads)
    for (const auto & cm : params.cpu_mask)
    for (const auto & cs : params.cpu_strict)
    for (const auto & pl : params.poll) {
xuxzh1's avatar
init  
xuxzh1 committed
755
756
757
758
759
760
761
762
763
764
765
766
767
        for (const auto & n_prompt : params.n_prompt) {
            if (n_prompt == 0) {
                continue;
            }
            cmd_params_instance instance = {
                /* .model        = */ m,
                /* .n_prompt     = */ n_prompt,
                /* .n_gen        = */ 0,
                /* .n_batch      = */ nb,
                /* .n_ubatch     = */ nub,
                /* .type_k       = */ tk,
                /* .type_v       = */ tv,
                /* .n_threads    = */ nt,
xuxzh1's avatar
update  
xuxzh1 committed
768
769
770
                /* .cpu_mask     = */ cm,
                /* .cpu_strict   = */ cs,
                /* .poll         = */ pl,
xuxzh1's avatar
init  
xuxzh1 committed
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
                /* .n_gpu_layers = */ nl,
                /* .rpc_servers  = */ rpc,
                /* .split_mode   = */ sm,
                /* .main_gpu     = */ mg,
                /* .no_kv_offload= */ nkvo,
                /* .flash_attn   = */ fa,
                /* .tensor_split = */ ts,
                /* .use_mmap     = */ mmp,
                /* .embeddings   = */ embd,
            };
            instances.push_back(instance);
        }

        for (const auto & n_gen : params.n_gen) {
            if (n_gen == 0) {
                continue;
            }
            cmd_params_instance instance = {
                /* .model        = */ m,
                /* .n_prompt     = */ 0,
                /* .n_gen        = */ n_gen,
                /* .n_batch      = */ nb,
                /* .n_ubatch     = */ nub,
                /* .type_k       = */ tk,
                /* .type_v       = */ tv,
                /* .n_threads    = */ nt,
xuxzh1's avatar
update  
xuxzh1 committed
797
798
799
                /* .cpu_mask     = */ cm,
                /* .cpu_strict   = */ cs,
                /* .poll         = */ pl,
xuxzh1's avatar
init  
xuxzh1 committed
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
                /* .n_gpu_layers = */ nl,
                /* .rpc_servers  = */ rpc,
                /* .split_mode   = */ sm,
                /* .main_gpu     = */ mg,
                /* .no_kv_offload= */ nkvo,
                /* .flash_attn   = */ fa,
                /* .tensor_split = */ ts,
                /* .use_mmap     = */ mmp,
                /* .embeddings   = */ embd,
            };
            instances.push_back(instance);
        }

        for (const auto & n_pg : params.n_pg) {
            if (n_pg.first == 0 && n_pg.second == 0) {
                continue;
            }
            cmd_params_instance instance = {
                /* .model        = */ m,
                /* .n_prompt     = */ n_pg.first,
                /* .n_gen        = */ n_pg.second,
                /* .n_batch      = */ nb,
                /* .n_ubatch     = */ nub,
                /* .type_k       = */ tk,
                /* .type_v       = */ tv,
                /* .n_threads    = */ nt,
xuxzh1's avatar
update  
xuxzh1 committed
826
827
828
                /* .cpu_mask     = */ cm,
                /* .cpu_strict   = */ cs,
                /* .poll         = */ pl,
xuxzh1's avatar
init  
xuxzh1 committed
829
830
831
832
833
834
835
836
837
838
839
840
841
                /* .n_gpu_layers = */ nl,
                /* .rpc_servers  = */ rpc,
                /* .split_mode   = */ sm,
                /* .main_gpu     = */ mg,
                /* .no_kv_offload= */ nkvo,
                /* .flash_attn   = */ fa,
                /* .tensor_split = */ ts,
                /* .use_mmap     = */ mmp,
                /* .embeddings   = */ embd,
            };
            instances.push_back(instance);
        }
    }
xuxzh1's avatar
update  
xuxzh1 committed
842
    // clang-format on
xuxzh1's avatar
init  
xuxzh1 committed
843
844
845
846
847
848

    return instances;
}

struct test {
    static const std::string build_commit;
xuxzh1's avatar
update  
xuxzh1 committed
849
    static const int         build_number;
xuxzh1's avatar
init  
xuxzh1 committed
850
851
    static const std::string cpu_info;
    static const std::string gpu_info;
xuxzh1's avatar
update  
xuxzh1 committed
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
    std::string              model_filename;
    std::string              model_type;
    uint64_t                 model_size;
    uint64_t                 model_n_params;
    int                      n_batch;
    int                      n_ubatch;
    int                      n_threads;
    std::string              cpu_mask;
    bool                     cpu_strict;
    int                      poll;
    ggml_type                type_k;
    ggml_type                type_v;
    int                      n_gpu_layers;
    llama_split_mode         split_mode;
    int                      main_gpu;
    bool                     no_kv_offload;
    bool                     flash_attn;
    std::vector<float>       tensor_split;
    bool                     use_mmap;
    bool                     embeddings;
    int                      n_prompt;
    int                      n_gen;
    std::string              test_time;
    std::vector<uint64_t>    samples_ns;
xuxzh1's avatar
init  
xuxzh1 committed
876
877
878
879
880

    test(const cmd_params_instance & inst, const llama_model * lmodel, const llama_context * ctx) {
        model_filename = inst.model;
        char buf[128];
        llama_model_desc(lmodel, buf, sizeof(buf));
xuxzh1's avatar
update  
xuxzh1 committed
881
882
        model_type     = buf;
        model_size     = llama_model_size(lmodel);
xuxzh1's avatar
init  
xuxzh1 committed
883
        model_n_params = llama_model_n_params(lmodel);
xuxzh1's avatar
update  
xuxzh1 committed
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
        n_batch        = inst.n_batch;
        n_ubatch       = inst.n_ubatch;
        n_threads      = inst.n_threads;
        cpu_mask       = inst.cpu_mask;
        cpu_strict     = inst.cpu_strict;
        poll           = inst.poll;
        type_k         = inst.type_k;
        type_v         = inst.type_v;
        n_gpu_layers   = inst.n_gpu_layers;
        split_mode     = inst.split_mode;
        main_gpu       = inst.main_gpu;
        no_kv_offload  = inst.no_kv_offload;
        flash_attn     = inst.flash_attn;
        tensor_split   = inst.tensor_split;
        use_mmap       = inst.use_mmap;
        embeddings     = inst.embeddings;
        n_prompt       = inst.n_prompt;
        n_gen          = inst.n_gen;
xuxzh1's avatar
init  
xuxzh1 committed
902
        // RFC 3339 date-time format
xuxzh1's avatar
update  
xuxzh1 committed
903
        time_t t       = time(NULL);
xuxzh1's avatar
init  
xuxzh1 committed
904
905
906
907
908
909
        std::strftime(buf, sizeof(buf), "%FT%TZ", gmtime(&t));
        test_time = buf;

        (void) ctx;
    }

xuxzh1's avatar
update  
xuxzh1 committed
910
    uint64_t avg_ns() const { return ::avg(samples_ns); }
xuxzh1's avatar
init  
xuxzh1 committed
911

xuxzh1's avatar
update  
xuxzh1 committed
912
    uint64_t stdev_ns() const { return ::stdev(samples_ns); }
xuxzh1's avatar
init  
xuxzh1 committed
913
914

    std::vector<double> get_ts() const {
xuxzh1's avatar
update  
xuxzh1 committed
915
        int                 n_tokens = n_prompt + n_gen;
xuxzh1's avatar
init  
xuxzh1 committed
916
        std::vector<double> ts;
xuxzh1's avatar
update  
xuxzh1 committed
917
918
        std::transform(samples_ns.begin(), samples_ns.end(), std::back_inserter(ts),
                       [n_tokens](uint64_t t) { return 1e9 * n_tokens / t; });
xuxzh1's avatar
init  
xuxzh1 committed
919
920
921
        return ts;
    }

xuxzh1's avatar
update  
xuxzh1 committed
922
    double avg_ts() const { return ::avg(get_ts()); }
xuxzh1's avatar
init  
xuxzh1 committed
923

xuxzh1's avatar
update  
xuxzh1 committed
924
    double stdev_ts() const { return ::stdev(get_ts()); }
xuxzh1's avatar
init  
xuxzh1 committed
925
926

    static std::string get_backend() {
xuxzh1's avatar
update  
xuxzh1 committed
927
928
929
930
931
932
933
        std::vector<std::string> backends;
        for (size_t i = 0; i < ggml_backend_reg_count(); i++) {
            auto *      reg  = ggml_backend_reg_get(i);
            std::string name = ggml_backend_reg_name(reg);
            if (name != "CPU") {
                backends.push_back(ggml_backend_reg_name(reg));
            }
xuxzh1's avatar
init  
xuxzh1 committed
934
        }
xuxzh1's avatar
update  
xuxzh1 committed
935
        return backends.empty() ? "CPU" : join(backends, ",");
xuxzh1's avatar
init  
xuxzh1 committed
936
937
938
939
    }

    static const std::vector<std::string> & get_fields() {
        static const std::vector<std::string> fields = {
xuxzh1's avatar
update  
xuxzh1 committed
940
941
942
943
944
945
            "build_commit", "build_number", "cpu_info",       "gpu_info",   "backends",     "model_filename",
            "model_type",   "model_size",   "model_n_params", "n_batch",    "n_ubatch",     "n_threads",
            "cpu_mask",     "cpu_strict",   "poll",           "type_k",     "type_v",       "n_gpu_layers",
            "split_mode",   "main_gpu",     "no_kv_offload",  "flash_attn", "tensor_split", "use_mmap",
            "embeddings",   "n_prompt",     "n_gen",          "test_time",  "avg_ns",       "stddev_ns",
            "avg_ts",       "stddev_ts",
xuxzh1's avatar
init  
xuxzh1 committed
946
947
948
949
        };
        return fields;
    }

xuxzh1's avatar
update  
xuxzh1 committed
950
    enum field_type { STRING, BOOL, INT, FLOAT };
xuxzh1's avatar
init  
xuxzh1 committed
951
952

    static field_type get_field_type(const std::string & field) {
xuxzh1's avatar
update  
xuxzh1 committed
953
954
955
956
        if (field == "build_number" || field == "n_batch" || field == "n_ubatch" || field == "n_threads" ||
            field == "poll" || field == "model_size" || field == "model_n_params" || field == "n_gpu_layers" ||
            field == "main_gpu" || field == "n_prompt" || field == "n_gen" || field == "avg_ns" ||
            field == "stddev_ns") {
xuxzh1's avatar
init  
xuxzh1 committed
957
958
            return INT;
        }
xuxzh1's avatar
update  
xuxzh1 committed
959
960
        if (field == "f16_kv" || field == "no_kv_offload" || field == "cpu_strict" || field == "flash_attn" ||
            field == "use_mmap" || field == "embeddings") {
xuxzh1's avatar
init  
xuxzh1 committed
961
962
963
964
965
966
967
968
969
970
            return BOOL;
        }
        if (field == "avg_ts" || field == "stddev_ts") {
            return FLOAT;
        }
        return STRING;
    }

    std::vector<std::string> get_values() const {
        std::string tensor_split_str;
xuxzh1's avatar
update  
xuxzh1 committed
971
        int         max_nonzero = 0;
xuxzh1's avatar
init  
xuxzh1 committed
972
973
974
975
976
977
978
979
980
981
982
983
984
        for (size_t i = 0; i < llama_max_devices(); i++) {
            if (tensor_split[i] > 0) {
                max_nonzero = i;
            }
        }
        for (int i = 0; i <= max_nonzero; i++) {
            char buf[32];
            snprintf(buf, sizeof(buf), "%.2f", tensor_split[i]);
            tensor_split_str += buf;
            if (i < max_nonzero) {
                tensor_split_str += "/";
            }
        }
xuxzh1's avatar
update  
xuxzh1 committed
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
        std::vector<std::string> values = { build_commit,
                                            std::to_string(build_number),
                                            cpu_info,
                                            gpu_info,
                                            get_backend(),
                                            model_filename,
                                            model_type,
                                            std::to_string(model_size),
                                            std::to_string(model_n_params),
                                            std::to_string(n_batch),
                                            std::to_string(n_ubatch),
                                            std::to_string(n_threads),
                                            cpu_mask,
                                            std::to_string(cpu_strict),
                                            std::to_string(poll),
                                            ggml_type_name(type_k),
                                            ggml_type_name(type_v),
                                            std::to_string(n_gpu_layers),
                                            split_mode_str(split_mode),
                                            std::to_string(main_gpu),
                                            std::to_string(no_kv_offload),
                                            std::to_string(flash_attn),
                                            tensor_split_str,
                                            std::to_string(use_mmap),
                                            std::to_string(embeddings),
                                            std::to_string(n_prompt),
                                            std::to_string(n_gen),
                                            test_time,
                                            std::to_string(avg_ns()),
                                            std::to_string(stdev_ns()),
                                            std::to_string(avg_ts()),
                                            std::to_string(stdev_ts()) };
xuxzh1's avatar
init  
xuxzh1 committed
1017
1018
1019
1020
1021
        return values;
    }

    std::map<std::string, std::string> get_map() const {
        std::map<std::string, std::string> map;
xuxzh1's avatar
update  
xuxzh1 committed
1022
1023
1024
1025
        auto                               fields = get_fields();
        auto                               values = get_values();
        std::transform(fields.begin(), fields.end(), values.begin(), std::inserter(map, map.end()),
                       std::make_pair<const std::string &, const std::string &>);
xuxzh1's avatar
init  
xuxzh1 committed
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
        return map;
    }
};

const std::string test::build_commit = LLAMA_COMMIT;
const int         test::build_number = LLAMA_BUILD_NUMBER;
const std::string test::cpu_info     = get_cpu_info();
const std::string test::gpu_info     = get_gpu_info();

struct printer {
    virtual ~printer() {}

    FILE * fout;
xuxzh1's avatar
update  
xuxzh1 committed
1039

xuxzh1's avatar
init  
xuxzh1 committed
1040
    virtual void print_header(const cmd_params & params) { (void) params; }
xuxzh1's avatar
update  
xuxzh1 committed
1041

xuxzh1's avatar
init  
xuxzh1 committed
1042
    virtual void print_test(const test & t) = 0;
xuxzh1's avatar
update  
xuxzh1 committed
1043
1044

    virtual void print_footer() {}
xuxzh1's avatar
init  
xuxzh1 committed
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
};

struct csv_printer : public printer {
    static std::string escape_csv(const std::string & field) {
        std::string escaped = "\"";
        for (auto c : field) {
            if (c == '"') {
                escaped += "\"";
            }
            escaped += c;
        }
        escaped += "\"";
        return escaped;
    }

xuxzh1's avatar
update  
xuxzh1 committed
1060
    void print_header(const cmd_params & params) override {
xuxzh1's avatar
init  
xuxzh1 committed
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
        std::vector<std::string> fields = test::get_fields();
        fprintf(fout, "%s\n", join(fields, ",").c_str());
        (void) params;
    }

    void print_test(const test & t) override {
        std::vector<std::string> values = t.get_values();
        std::transform(values.begin(), values.end(), values.begin(), escape_csv);
        fprintf(fout, "%s\n", join(values, ",").c_str());
    }
};

xuxzh1's avatar
update  
xuxzh1 committed
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
static std::string escape_json(const std::string & value) {
    std::string escaped;
    for (auto c : value) {
        if (c == '"') {
            escaped += "\\\"";
        } else if (c == '\\') {
            escaped += "\\\\";
        } else if (c <= 0x1f) {
            char buf[8];
            snprintf(buf, sizeof(buf), "\\u%04x", c);
            escaped += buf;
        } else {
            escaped += c;
xuxzh1's avatar
init  
xuxzh1 committed
1086
1087
        }
    }
xuxzh1's avatar
update  
xuxzh1 committed
1088
1089
    return escaped;
}
xuxzh1's avatar
init  
xuxzh1 committed
1090

xuxzh1's avatar
update  
xuxzh1 committed
1091
1092
1093
1094
1095
1096
1097
1098
static std::string format_json_value(const std::string & field, const std::string & value) {
    switch (test::get_field_type(field)) {
        case test::STRING:
            return "\"" + escape_json(value) + "\"";
        case test::BOOL:
            return value == "0" ? "false" : "true";
        default:
            return value;
xuxzh1's avatar
init  
xuxzh1 committed
1099
    }
xuxzh1's avatar
update  
xuxzh1 committed
1100
1101
1102
1103
}

struct json_printer : public printer {
    bool first = true;
xuxzh1's avatar
init  
xuxzh1 committed
1104
1105
1106
1107
1108
1109
1110
1111
1112

    void print_header(const cmd_params & params) override {
        fprintf(fout, "[\n");
        (void) params;
    }

    void print_fields(const std::vector<std::string> & fields, const std::vector<std::string> & values) {
        assert(fields.size() == values.size());
        for (size_t i = 0; i < fields.size(); i++) {
xuxzh1's avatar
update  
xuxzh1 committed
1113
1114
            fprintf(fout, "    \"%s\": %s,\n", fields.at(i).c_str(),
                    format_json_value(fields.at(i), values.at(i)).c_str());
xuxzh1's avatar
init  
xuxzh1 committed
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
        }
    }

    void print_test(const test & t) override {
        if (first) {
            first = false;
        } else {
            fprintf(fout, ",\n");
        }
        fprintf(fout, "  {\n");
        print_fields(test::get_fields(), t.get_values());
        fprintf(fout, "    \"samples_ns\": [ %s ],\n", join(t.samples_ns, ", ").c_str());
        fprintf(fout, "    \"samples_ts\": [ %s ]\n", join(t.get_ts(), ", ").c_str());
        fprintf(fout, "  }");
        fflush(fout);
    }

xuxzh1's avatar
update  
xuxzh1 committed
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
    void print_footer() override { fprintf(fout, "\n]\n"); }
};

struct jsonl_printer : public printer {
    void print_fields(const std::vector<std::string> & fields, const std::vector<std::string> & values) {
        assert(fields.size() == values.size());
        for (size_t i = 0; i < fields.size(); i++) {
            fprintf(fout, "\"%s\": %s, ", fields.at(i).c_str(), format_json_value(fields.at(i), values.at(i)).c_str());
        }
    }

    void print_test(const test & t) override {
        fprintf(fout, "{");
        print_fields(test::get_fields(), t.get_values());
        fprintf(fout, "\"samples_ns\": [ %s ],", join(t.samples_ns, ", ").c_str());
        fprintf(fout, "\"samples_ts\": [ %s ]", join(t.get_ts(), ", ").c_str());
        fprintf(fout, "}\n");
        fflush(fout);
xuxzh1's avatar
init  
xuxzh1 committed
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
    }
};

struct markdown_printer : public printer {
    std::vector<std::string> fields;

    static int get_field_width(const std::string & field) {
        if (field == "model") {
            return -30;
        }
        if (field == "t/s") {
xuxzh1's avatar
update  
xuxzh1 committed
1161
            return 20;
xuxzh1's avatar
init  
xuxzh1 committed
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
        }
        if (field == "size" || field == "params") {
            return 10;
        }
        if (field == "n_gpu_layers") {
            return 3;
        }
        if (field == "n_threads") {
            return 7;
        }
        if (field == "n_batch") {
            return 7;
        }
        if (field == "n_ubatch") {
            return 8;
        }
        if (field == "type_k" || field == "type_v") {
            return 6;
        }
        if (field == "split_mode") {
            return 5;
        }
        if (field == "flash_attn") {
            return 2;
        }
        if (field == "use_mmap") {
            return 4;
        }
        if (field == "test") {
            return 13;
        }

xuxzh1's avatar
update  
xuxzh1 committed
1194
        int width = std::max((int) field.length(), 10);
xuxzh1's avatar
init  
xuxzh1 committed
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235

        if (test::get_field_type(field) == test::STRING) {
            return -width;
        }
        return width;
    }

    static std::string get_field_display_name(const std::string & field) {
        if (field == "n_gpu_layers") {
            return "ngl";
        }
        if (field == "split_mode") {
            return "sm";
        }
        if (field == "n_threads") {
            return "threads";
        }
        if (field == "no_kv_offload") {
            return "nkvo";
        }
        if (field == "flash_attn") {
            return "fa";
        }
        if (field == "use_mmap") {
            return "mmap";
        }
        if (field == "embeddings") {
            return "embd";
        }
        if (field == "tensor_split") {
            return "ts";
        }
        return field;
    }

    void print_header(const cmd_params & params) override {
        // select fields to print
        fields.emplace_back("model");
        fields.emplace_back("size");
        fields.emplace_back("params");
        fields.emplace_back("backend");
xuxzh1's avatar
update  
xuxzh1 committed
1236
1237
        bool is_cpu_backend = test::get_backend().find("CPU") != std::string::npos ||
                              test::get_backend().find("BLAS") != std::string::npos;
xuxzh1's avatar
init  
xuxzh1 committed
1238
1239
1240
1241
1242
1243
        if (!is_cpu_backend) {
            fields.emplace_back("n_gpu_layers");
        }
        if (params.n_threads.size() > 1 || params.n_threads != cmd_params_defaults.n_threads || is_cpu_backend) {
            fields.emplace_back("n_threads");
        }
xuxzh1's avatar
update  
xuxzh1 committed
1244
1245
1246
1247
1248
1249
1250
1251
1252
        if (params.cpu_mask.size() > 1 || params.cpu_mask != cmd_params_defaults.cpu_mask) {
            fields.emplace_back("cpu_mask");
        }
        if (params.cpu_strict.size() > 1 || params.cpu_strict != cmd_params_defaults.cpu_strict) {
            fields.emplace_back("cpu_strict");
        }
        if (params.poll.size() > 1 || params.poll != cmd_params_defaults.poll) {
            fields.emplace_back("poll");
        }
xuxzh1's avatar
init  
xuxzh1 committed
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
        if (params.n_batch.size() > 1 || params.n_batch != cmd_params_defaults.n_batch) {
            fields.emplace_back("n_batch");
        }
        if (params.n_ubatch.size() > 1 || params.n_ubatch != cmd_params_defaults.n_ubatch) {
            fields.emplace_back("n_ubatch");
        }
        if (params.type_k.size() > 1 || params.type_k != cmd_params_defaults.type_k) {
            fields.emplace_back("type_k");
        }
        if (params.type_v.size() > 1 || params.type_v != cmd_params_defaults.type_v) {
            fields.emplace_back("type_v");
        }
        if (params.main_gpu.size() > 1 || params.main_gpu != cmd_params_defaults.main_gpu) {
            fields.emplace_back("main_gpu");
        }
        if (params.split_mode.size() > 1 || params.split_mode != cmd_params_defaults.split_mode) {
            fields.emplace_back("split_mode");
        }
        if (params.no_kv_offload.size() > 1 || params.no_kv_offload != cmd_params_defaults.no_kv_offload) {
            fields.emplace_back("no_kv_offload");
        }
        if (params.flash_attn.size() > 1 || params.flash_attn != cmd_params_defaults.flash_attn) {
            fields.emplace_back("flash_attn");
        }
        if (params.tensor_split.size() > 1 || params.tensor_split != cmd_params_defaults.tensor_split) {
            fields.emplace_back("tensor_split");
        }
        if (params.use_mmap.size() > 1 || params.use_mmap != cmd_params_defaults.use_mmap) {
            fields.emplace_back("use_mmap");
        }
        if (params.embeddings.size() > 1 || params.embeddings != cmd_params_defaults.embeddings) {
            fields.emplace_back("embeddings");
        }
        fields.emplace_back("test");
        fields.emplace_back("t/s");

        fprintf(fout, "|");
        for (const auto & field : fields) {
            fprintf(fout, " %*s |", get_field_width(field), get_field_display_name(field).c_str());
        }
        fprintf(fout, "\n");
        fprintf(fout, "|");
        for (const auto & field : fields) {
            int width = get_field_width(field);
            fprintf(fout, " %s%s |", std::string(std::abs(width) - 1, '-').c_str(), width > 0 ? ":" : "-");
        }
        fprintf(fout, "\n");
    }

    void print_test(const test & t) override {
        std::map<std::string, std::string> vmap = t.get_map();

        fprintf(fout, "|");
        for (const auto & field : fields) {
            std::string value;
xuxzh1's avatar
update  
xuxzh1 committed
1308
            char        buf[128];
xuxzh1's avatar
init  
xuxzh1 committed
1309
1310
1311
            if (field == "model") {
                value = t.model_type;
            } else if (field == "size") {
xuxzh1's avatar
update  
xuxzh1 committed
1312
                if (t.model_size < 1024 * 1024 * 1024) {
xuxzh1's avatar
init  
xuxzh1 committed
1313
1314
1315
1316
1317
1318
                    snprintf(buf, sizeof(buf), "%.2f MiB", t.model_size / 1024.0 / 1024.0);
                } else {
                    snprintf(buf, sizeof(buf), "%.2f GiB", t.model_size / 1024.0 / 1024.0 / 1024.0);
                }
                value = buf;
            } else if (field == "params") {
xuxzh1's avatar
update  
xuxzh1 committed
1319
                if (t.model_n_params < 1000 * 1000 * 1000) {
xuxzh1's avatar
init  
xuxzh1 committed
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
                    snprintf(buf, sizeof(buf), "%.2f M", t.model_n_params / 1e6);
                } else {
                    snprintf(buf, sizeof(buf), "%.2f B", t.model_n_params / 1e9);
                }
                value = buf;
            } else if (field == "backend") {
                value = test::get_backend();
            } else if (field == "test") {
                if (t.n_prompt > 0 && t.n_gen == 0) {
                    snprintf(buf, sizeof(buf), "pp%d", t.n_prompt);
                } else if (t.n_gen > 0 && t.n_prompt == 0) {
                    snprintf(buf, sizeof(buf), "tg%d", t.n_gen);
                } else {
                    snprintf(buf, sizeof(buf), "pp%d+tg%d", t.n_prompt, t.n_gen);
                }
                value = buf;
            } else if (field == "t/s") {
                snprintf(buf, sizeof(buf), "%.2f ± %.2f", t.avg_ts(), t.stdev_ts());
                value = buf;
            } else if (vmap.find(field) != vmap.end()) {
                value = vmap.at(field);
            } else {
                assert(false);
                exit(1);
            }

            int width = get_field_width(field);
            if (field == "t/s") {
                // HACK: the utf-8 character is 2 bytes
                width += 1;
            }
            fprintf(fout, " %*s |", width, value.c_str());
        }
        fprintf(fout, "\n");
    }

    void print_footer() override {
        fprintf(fout, "\nbuild: %s (%d)\n", test::build_commit.c_str(), test::build_number);
    }
};

struct sql_printer : public printer {
    static std::string get_sql_field_type(const std::string & field) {
        switch (test::get_field_type(field)) {
            case test::STRING:
                return "TEXT";
            case test::BOOL:
            case test::INT:
                return "INTEGER";
            case test::FLOAT:
                return "REAL";
            default:
                assert(false);
                exit(1);
        }
    }

    void print_header(const cmd_params & params) override {
        std::vector<std::string> fields = test::get_fields();
        fprintf(fout, "CREATE TABLE IF NOT EXISTS test (\n");
        for (size_t i = 0; i < fields.size(); i++) {
xuxzh1's avatar
update  
xuxzh1 committed
1381
1382
            fprintf(fout, "  %s %s%s\n", fields.at(i).c_str(), get_sql_field_type(fields.at(i)).c_str(),
                    i < fields.size() - 1 ? "," : "");
xuxzh1's avatar
init  
xuxzh1 committed
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
        }
        fprintf(fout, ");\n");
        fprintf(fout, "\n");
        (void) params;
    }

    void print_test(const test & t) override {
        fprintf(fout, "INSERT INTO test (%s) ", join(test::get_fields(), ", ").c_str());
        fprintf(fout, "VALUES (");
        std::vector<std::string> values = t.get_values();
        for (size_t i = 0; i < values.size(); i++) {
            fprintf(fout, "'%s'%s", values.at(i).c_str(), i < values.size() - 1 ? ", " : "");
        }
        fprintf(fout, ");\n");
    }
};

xuxzh1's avatar
update  
xuxzh1 committed
1400
static void test_prompt(llama_context * ctx, int n_prompt, int n_batch, int n_threads) {
xuxzh1's avatar
init  
xuxzh1 committed
1401
1402
    llama_set_n_threads(ctx, n_threads, n_threads);

xuxzh1's avatar
update  
xuxzh1 committed
1403
1404
    const llama_model * model   = llama_get_model(ctx);
    const int32_t       n_vocab = llama_n_vocab(model);
xuxzh1's avatar
init  
xuxzh1 committed
1405
1406
1407
1408
1409
1410
1411

    std::vector<llama_token> tokens(n_batch);

    int n_processed = 0;

    while (n_processed < n_prompt) {
        int n_tokens = std::min(n_prompt - n_processed, n_batch);
xuxzh1's avatar
update  
xuxzh1 committed
1412
        tokens[0]    = n_processed == 0 && llama_add_bos_token(model) ? llama_token_bos(model) : std::rand() % n_vocab;
xuxzh1's avatar
init  
xuxzh1 committed
1413
1414
1415
        for (int i = 1; i < n_tokens; i++) {
            tokens[i] = std::rand() % n_vocab;
        }
xuxzh1's avatar
update  
xuxzh1 committed
1416
        llama_decode(ctx, llama_batch_get_one(tokens.data(), n_tokens));
xuxzh1's avatar
init  
xuxzh1 committed
1417
1418
1419
1420
1421
1422
        n_processed += n_tokens;
    }

    llama_synchronize(ctx);
}

xuxzh1's avatar
update  
xuxzh1 committed
1423
static void test_gen(llama_context * ctx, int n_gen, int n_threads) {
xuxzh1's avatar
init  
xuxzh1 committed
1424
1425
    llama_set_n_threads(ctx, n_threads, n_threads);

xuxzh1's avatar
update  
xuxzh1 committed
1426
1427
    const llama_model * model   = llama_get_model(ctx);
    const int32_t       n_vocab = llama_n_vocab(model);
xuxzh1's avatar
init  
xuxzh1 committed
1428
1429
1430
1431

    llama_token token = llama_add_bos_token(model) ? llama_token_bos(model) : std::rand() % n_vocab;

    for (int i = 0; i < n_gen; i++) {
xuxzh1's avatar
update  
xuxzh1 committed
1432
        llama_decode(ctx, llama_batch_get_one(&token, 1));
xuxzh1's avatar
init  
xuxzh1 committed
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
        llama_synchronize(ctx);
        token = std::rand() % n_vocab;
    }
}

static void llama_null_log_callback(enum ggml_log_level level, const char * text, void * user_data) {
    (void) level;
    (void) text;
    (void) user_data;
}

static std::unique_ptr<printer> create_printer(output_formats format) {
    switch (format) {
        case NONE:
            return nullptr;
        case CSV:
            return std::unique_ptr<printer>(new csv_printer());
        case JSON:
            return std::unique_ptr<printer>(new json_printer());
xuxzh1's avatar
update  
xuxzh1 committed
1452
1453
        case JSONL:
            return std::unique_ptr<printer>(new jsonl_printer());
xuxzh1's avatar
init  
xuxzh1 committed
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
        case MARKDOWN:
            return std::unique_ptr<printer>(new markdown_printer());
        case SQL:
            return std::unique_ptr<printer>(new sql_printer());
    }
    GGML_ABORT("fatal error");
}

int main(int argc, char ** argv) {
    // try to set locale for unicode characters in markdown
    setlocale(LC_CTYPE, ".UTF-8");

#if !defined(NDEBUG)
    fprintf(stderr, "warning: asserts enabled, performance may be affected\n");
#endif

#if (defined(_MSC_VER) && defined(_DEBUG)) || (!defined(_MSC_VER) && !defined(__OPTIMIZE__))
    fprintf(stderr, "warning: debug build, performance may be affected\n");
#endif

#if defined(__SANITIZE_ADDRESS__) || defined(__SANITIZE_THREAD__)
    fprintf(stderr, "warning: sanitizer enabled, performance may be affected\n");
#endif

    cmd_params params = parse_cmd_params(argc, argv);

    // initialize llama.cpp
    if (!params.verbose) {
        llama_log_set(llama_null_log_callback, NULL);
    }
    llama_backend_init();
    llama_numa_init(params.numa);

xuxzh1's avatar
update  
xuxzh1 committed
1487
1488
    set_process_priority(params.prio);

xuxzh1's avatar
init  
xuxzh1 committed
1489
    // initialize printer
xuxzh1's avatar
update  
xuxzh1 committed
1490
    std::unique_ptr<printer> p     = create_printer(params.output_format);
xuxzh1's avatar
init  
xuxzh1 committed
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
    std::unique_ptr<printer> p_err = create_printer(params.output_format_stderr);

    if (p) {
        p->fout = stdout;
        p->print_header(params);
    }

    if (p_err) {
        p_err->fout = stderr;
        p_err->print_header(params);
    }

    std::vector<cmd_params_instance> params_instances = get_cmd_params_instances(params);

xuxzh1's avatar
update  
xuxzh1 committed
1505
    llama_model *               lmodel    = nullptr;
xuxzh1's avatar
init  
xuxzh1 committed
1506
1507
    const cmd_params_instance * prev_inst = nullptr;

xuxzh1's avatar
update  
xuxzh1 committed
1508
1509
    int  params_idx   = 0;
    auto params_count = params_instances.size();
xuxzh1's avatar
init  
xuxzh1 committed
1510
    for (const auto & inst : params_instances) {
xuxzh1's avatar
update  
xuxzh1 committed
1511
1512
1513
1514
        params_idx++;
        if (params.progress) {
            fprintf(stderr, "llama-bench: benchmark %d/%ld: starting\n", params_idx, params_count);
        }
xuxzh1's avatar
init  
xuxzh1 committed
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
        // keep the same model between tests when possible
        if (!lmodel || !prev_inst || !inst.equal_mparams(*prev_inst)) {
            if (lmodel) {
                llama_free_model(lmodel);
            }

            lmodel = llama_load_model_from_file(inst.model.c_str(), inst.to_llama_mparams());
            if (lmodel == NULL) {
                fprintf(stderr, "%s: error: failed to load model '%s'\n", __func__, inst.model.c_str());
                return 1;
            }
            prev_inst = &inst;
        }

        llama_context * ctx = llama_new_context_with_model(lmodel, inst.to_llama_cparams());
        if (ctx == NULL) {
            fprintf(stderr, "%s: error: failed to create context with model '%s'\n", __func__, inst.model.c_str());
            llama_free_model(lmodel);
            return 1;
        }

        test t(inst, lmodel, ctx);

        llama_kv_cache_clear(ctx);

xuxzh1's avatar
update  
xuxzh1 committed
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
        // cool off before the test
        if (params.delay) {
            std::this_thread::sleep_for(std::chrono::seconds(params.delay));
        }

        struct ggml_threadpool_params tpp = ggml_threadpool_params_default(t.n_threads);
        if (!parse_cpu_mask(t.cpu_mask, tpp.cpumask)) {
            fprintf(stderr, "%s: failed to parse cpu-mask: %s\n", __func__, t.cpu_mask.c_str());
            exit(1);
        }
        tpp.strict_cpu = t.cpu_strict;
        tpp.poll       = t.poll;
        tpp.prio       = params.prio;

        struct ggml_threadpool * threadpool = ggml_threadpool_new(&tpp);
        if (!threadpool) {
            fprintf(stderr, "%s: threadpool create failed : n_threads %d\n", __func__, tpp.n_threads);
            exit(1);
        }

        llama_attach_threadpool(ctx, threadpool, NULL);

xuxzh1's avatar
init  
xuxzh1 committed
1562
1563
        // warmup run
        if (t.n_prompt > 0) {
xuxzh1's avatar
update  
xuxzh1 committed
1564
1565
1566
            if (params.progress) {
                fprintf(stderr, "llama-bench: benchmark %d/%ld: warmup prompt run\n", params_idx, params_count);
            }
xuxzh1's avatar
init  
xuxzh1 committed
1567
            //test_prompt(ctx, std::min(t.n_batch, std::min(t.n_prompt, 32)), 0, t.n_batch, t.n_threads);
xuxzh1's avatar
update  
xuxzh1 committed
1568
            test_prompt(ctx, t.n_prompt, t.n_batch, t.n_threads);
xuxzh1's avatar
init  
xuxzh1 committed
1569
1570
        }
        if (t.n_gen > 0) {
xuxzh1's avatar
update  
xuxzh1 committed
1571
1572
1573
1574
            if (params.progress) {
                fprintf(stderr, "llama-bench: benchmark %d/%ld: warmup generation run\n", params_idx, params_count);
            }
            test_gen(ctx, 1, t.n_threads);
xuxzh1's avatar
init  
xuxzh1 committed
1575
1576
1577
1578
1579
1580
1581
1582
        }

        for (int i = 0; i < params.reps; i++) {
            llama_kv_cache_clear(ctx);

            uint64_t t_start = get_time_ns();

            if (t.n_prompt > 0) {
xuxzh1's avatar
update  
xuxzh1 committed
1583
1584
1585
1586
1587
                if (params.progress) {
                    fprintf(stderr, "llama-bench: benchmark %d/%ld: prompt run %d/%d\n", params_idx, params_count,
                            i + 1, params.reps);
                }
                test_prompt(ctx, t.n_prompt, t.n_batch, t.n_threads);
xuxzh1's avatar
init  
xuxzh1 committed
1588
1589
            }
            if (t.n_gen > 0) {
xuxzh1's avatar
update  
xuxzh1 committed
1590
1591
1592
1593
1594
                if (params.progress) {
                    fprintf(stderr, "llama-bench: benchmark %d/%ld: generation run %d/%d\n", params_idx, params_count,
                            i + 1, params.reps);
                }
                test_gen(ctx, t.n_gen, t.n_threads);
xuxzh1's avatar
init  
xuxzh1 committed
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
            }

            uint64_t t_ns = get_time_ns() - t_start;
            t.samples_ns.push_back(t_ns);
        }

        if (p) {
            p->print_test(t);
            fflush(p->fout);
        }

        if (p_err) {
            p_err->print_test(t);
            fflush(p_err->fout);
        }

xuxzh1's avatar
update  
xuxzh1 committed
1611
        llama_perf_context_print(ctx);
xuxzh1's avatar
init  
xuxzh1 committed
1612
1613

        llama_free(ctx);
xuxzh1's avatar
update  
xuxzh1 committed
1614
1615

        ggml_threadpool_free(threadpool);
xuxzh1's avatar
init  
xuxzh1 committed
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
    }

    llama_free_model(lmodel);

    if (p) {
        p->print_footer();
    }

    if (p_err) {
        p_err->print_footer();
    }

    llama_backend_free();

    return 0;
}