Coverage Report

Created: 2026-08-22 07:18

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/llama.cpp/common/common.cpp
Line
Count
Source
1
#include "ggml.h"
2
#include "gguf.h"
3
4
#include "build-info.h"
5
#include "common.h"
6
#include "fit.h"
7
#include "log.h"
8
#include "llama.h"
9
#include "sampling.h"
10
#include "speculative.h"
11
#include "unicode.h"
12
13
#include <algorithm>
14
#include <cinttypes>
15
#include <climits>
16
#include <cmath>
17
#include <chrono>
18
#include <cstdarg>
19
#include <cstring>
20
#include <ctime>
21
#include <filesystem>
22
#include <fstream>
23
#include <iostream>
24
#include <iterator>
25
#include <regex>
26
#include <sstream>
27
#include <string>
28
#include <thread>
29
#include <unordered_set>
30
#include <vector>
31
32
#if defined(__APPLE__) && defined(__MACH__)
33
#include <sys/types.h>
34
#include <sys/sysctl.h>
35
#endif
36
37
#if defined(_WIN32)
38
#define WIN32_LEAN_AND_MEAN
39
#ifndef NOMINMAX
40
#   define NOMINMAX
41
#endif
42
#include <locale>
43
#include <windows.h>
44
#include <string.h>
45
#include <fcntl.h>
46
#include <io.h>
47
#else
48
#include <sys/ioctl.h>
49
#include <sys/stat.h>
50
#include <unistd.h>
51
#endif
52
53
#if defined(__linux__)
54
#include <sys/types.h>
55
#include <pwd.h>
56
#endif
57
58
#if defined(_AIX)
59
#include <sys/systemcfg.h>
60
#endif
61
62
#if defined(_MSC_VER)
63
#pragma warning(disable: 4244 4267) // possible loss of data
64
#endif
65
66
0
common_time_meas::common_time_meas(int64_t & t_acc, bool disable) : t_start_us(disable ? -1 : ggml_time_us()), t_acc(t_acc) {}
67
68
0
common_time_meas::~common_time_meas() {
69
0
    if (t_start_us >= 0) {
70
0
        t_acc += ggml_time_us() - t_start_us;
71
0
    }
72
0
}
73
74
//
75
// CPU utils
76
//
77
78
0
int32_t common_cpu_get_num_physical_cores() {
79
#if defined(_AIX)
80
    int32_t logical_cpus = _system_configuration.ncpus;
81
    int32_t smt_threads = _system_configuration.smt_threads;
82
    if (smt_threads > 0) {
83
        return static_cast<int32_t>(logical_cpus / smt_threads);
84
    }
85
    if (logical_cpus > 0) {
86
        return static_cast<int32_t>(logical_cpus);
87
    }
88
#elif defined(__linux__)
89
    // enumerate the set of thread siblings, num entries is num cores
90
0
    std::unordered_set<std::string> siblings;
91
0
    for (uint32_t cpu=0; cpu < UINT32_MAX; ++cpu) {
92
0
        std::ifstream thread_siblings("/sys/devices/system/cpu/cpu"
93
0
            + std::to_string(cpu) + "/topology/thread_siblings");
94
0
        if (!thread_siblings.is_open()) {
95
0
            break; // no more cpus
96
0
        }
97
0
        std::string line;
98
0
        if (std::getline(thread_siblings, line)) {
99
0
            siblings.insert(line);
100
0
        }
101
0
    }
102
0
    if (!siblings.empty()) {
103
0
        return static_cast<int32_t>(siblings.size());
104
0
    }
105
#elif defined(__APPLE__) && defined(__MACH__)
106
    int32_t num_physical_cores;
107
    size_t len = sizeof(num_physical_cores);
108
    int result = sysctlbyname("hw.perflevel0.physicalcpu", &num_physical_cores, &len, NULL, 0);
109
    if (result == 0) {
110
        return num_physical_cores;
111
    }
112
    result = sysctlbyname("hw.physicalcpu", &num_physical_cores, &len, NULL, 0);
113
    if (result == 0) {
114
        return num_physical_cores;
115
    }
116
#elif defined(_WIN32) && (_WIN32_WINNT >= 0x0601) && !defined(__MINGW64__) // windows 7 and later
117
    // TODO: windows + arm64 + mingw64
118
    unsigned int n_threads_win = std::thread::hardware_concurrency();
119
    unsigned int default_threads = n_threads_win > 0 ? (n_threads_win <= 4 ? n_threads_win : n_threads_win / 2) : 4;
120
121
    DWORD buffer_size = 0;
122
    if (!GetLogicalProcessorInformationEx(RelationProcessorCore, nullptr, &buffer_size)) {
123
        if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
124
            return default_threads;
125
        }
126
    }
127
128
    std::vector<char> buffer(buffer_size);
129
    if (!GetLogicalProcessorInformationEx(RelationProcessorCore, reinterpret_cast<PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX>(buffer.data()), &buffer_size)) {
130
        return default_threads;
131
    }
132
133
    int32_t num_physical_cores = 0;
134
    PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX info = reinterpret_cast<PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX>(buffer.data());
135
    while (buffer_size > 0) {
136
        if (info->Relationship == RelationProcessorCore) {
137
            num_physical_cores += info->Processor.GroupCount;
138
        }
139
        buffer_size -= info->Size;
140
        info = reinterpret_cast<PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX>(reinterpret_cast<char*>(info) + info->Size);
141
    }
142
143
    return num_physical_cores > 0 ? num_physical_cores : default_threads;
144
#endif
145
0
    unsigned int n_threads = std::thread::hardware_concurrency();
146
0
    return n_threads > 0 ? (n_threads <= 4 ? n_threads : n_threads / 2) : 4;
147
0
}
148
149
#if defined(__x86_64__) && defined(__linux__) && !defined(__ANDROID__)
150
#include <pthread.h>
151
152
static void cpuid(unsigned leaf, unsigned subleaf,
153
0
                  unsigned *eax, unsigned *ebx, unsigned *ecx, unsigned *edx) {
154
0
    __asm__("movq\t%%rbx,%%rsi\n\t"
155
0
            "cpuid\n\t"
156
0
            "xchgq\t%%rbx,%%rsi"
157
0
            : "=a"(*eax), "=S"(*ebx), "=c"(*ecx), "=d"(*edx)
158
0
            : "0"(leaf), "2"(subleaf));
159
0
}
160
161
0
static int pin_cpu(int cpu) {
162
0
    cpu_set_t mask;
163
0
    CPU_ZERO(&mask);
164
0
    CPU_SET(cpu, &mask);
165
0
    return pthread_setaffinity_np(pthread_self(), sizeof(mask), &mask);
166
0
}
167
168
0
static bool is_hybrid_cpu(void) {
169
0
    unsigned eax, ebx, ecx, edx;
170
0
    cpuid(7, 0, &eax, &ebx, &ecx, &edx);
171
0
    return !!(edx & (1u << 15));
172
0
}
173
174
0
static bool is_running_on_efficiency_core(void) {
175
0
    unsigned eax, ebx, ecx, edx;
176
0
    cpuid(0x1a, 0, &eax, &ebx, &ecx, &edx);
177
0
    int intel_atom = 0x20;
178
0
    int core_type = (eax & 0xff000000u) >> 24;
179
0
    return core_type == intel_atom;
180
0
}
181
182
0
static int cpu_count_math_cpus(int n_cpu) {
183
0
    int result = 0;
184
0
    for (int cpu = 0; cpu < n_cpu; ++cpu) {
185
0
        if (pin_cpu(cpu)) {
186
0
            return -1;
187
0
        }
188
0
        if (is_running_on_efficiency_core()) {
189
0
            continue; // efficiency cores harm lockstep threading
190
0
        }
191
0
        ++cpu; // hyperthreading isn't useful for linear algebra
192
0
        ++result;
193
0
    }
194
0
    return result;
195
0
}
196
197
#endif // __x86_64__ && __linux__
198
199
/**
200
 * Returns number of CPUs on system that are useful for math.
201
 */
202
0
int32_t common_cpu_get_num_math() {
203
0
#if defined(__x86_64__) && defined(__linux__) && !defined(__ANDROID__)
204
0
    int n_cpu = sysconf(_SC_NPROCESSORS_ONLN);
205
0
    if (n_cpu < 1) {
206
0
        return common_cpu_get_num_physical_cores();
207
0
    }
208
0
    if (is_hybrid_cpu()) {
209
0
        cpu_set_t affinity;
210
0
        if (!pthread_getaffinity_np(pthread_self(), sizeof(affinity), &affinity)) {
211
0
            int result = cpu_count_math_cpus(n_cpu);
212
0
            pthread_setaffinity_np(pthread_self(), sizeof(affinity), &affinity);
213
0
            if (result > 0) {
214
0
                return result;
215
0
            }
216
0
        }
217
0
    }
218
#elif defined(__powerpc64__) || defined(__powerpc__)
219
    int32_t smt_factor = 1;
220
    int phy_cpus = common_cpu_get_num_physical_cores();
221
    int logical_cpus = sysconf(_SC_NPROCESSORS_ONLN);
222
    if (phy_cpus > 0 && logical_cpus > phy_cpus) {
223
        smt_factor = logical_cpus / phy_cpus;
224
    }
225
    return phy_cpus * std::min(smt_factor, 2);
226
#endif
227
0
    return common_cpu_get_num_physical_cores();
228
0
}
229
230
// Helper for setting process priority
231
232
#if defined(_WIN32)
233
234
bool set_process_priority(enum ggml_sched_priority prio) {
235
    if (prio == GGML_SCHED_PRIO_NORMAL) {
236
        return true;
237
    }
238
239
    DWORD p = NORMAL_PRIORITY_CLASS;
240
    switch (prio) {
241
        case GGML_SCHED_PRIO_LOW:      p = BELOW_NORMAL_PRIORITY_CLASS; break;
242
        case GGML_SCHED_PRIO_NORMAL:   p = NORMAL_PRIORITY_CLASS;       break;
243
        case GGML_SCHED_PRIO_MEDIUM:   p = ABOVE_NORMAL_PRIORITY_CLASS; break;
244
        case GGML_SCHED_PRIO_HIGH:     p = HIGH_PRIORITY_CLASS;         break;
245
        case GGML_SCHED_PRIO_REALTIME: p = REALTIME_PRIORITY_CLASS;     break;
246
    }
247
248
    if (!SetPriorityClass(GetCurrentProcess(), p)) {
249
        COM_WRN("failed to set process priority class %d : (%d)\n", prio, (int) GetLastError());
250
        return false;
251
    }
252
253
    return true;
254
}
255
256
#else // MacOS and POSIX
257
#include <sys/types.h>
258
#include <sys/resource.h>
259
260
0
bool set_process_priority(enum ggml_sched_priority prio) {
261
0
    if (prio == GGML_SCHED_PRIO_NORMAL) {
262
0
        return true;
263
0
    }
264
265
0
    int p = 0;
266
0
    switch (prio) {
267
0
        case GGML_SCHED_PRIO_LOW:      p =  5;  break;
268
0
        case GGML_SCHED_PRIO_NORMAL:   p =  0;  break;
269
0
        case GGML_SCHED_PRIO_MEDIUM:   p = -5;  break;
270
0
        case GGML_SCHED_PRIO_HIGH:     p = -10; break;
271
0
        case GGML_SCHED_PRIO_REALTIME: p = -20; break;
272
0
    }
273
274
0
    if (setpriority(PRIO_PROCESS, 0, p) != 0) {
275
0
        COM_WRN("failed to set process priority %d : %s (%d)\n", prio, strerror(errno), errno);
276
0
        return false;
277
0
    }
278
0
    return true;
279
0
}
280
281
#endif
282
283
//
284
// CLI argument parsing
285
//
286
287
288
0
void postprocess_cpu_params(common_cpu_params & cpuparams, const common_cpu_params * role_model) {
289
0
    int32_t n_set = 0;
290
291
0
    if (cpuparams.n_threads < 0) {
292
        // Assuming everything about cpuparams is invalid
293
0
        if (role_model != nullptr) {
294
0
            cpuparams = *role_model;
295
0
        } else {
296
0
            cpuparams.n_threads = common_cpu_get_num_math();
297
0
        }
298
0
    }
299
300
0
    for (int32_t i = 0; i < GGML_MAX_N_THREADS; i++) {
301
0
        if (cpuparams.cpumask[i]) {
302
0
            n_set++;
303
0
        }
304
0
    }
305
306
0
    if (n_set && n_set < cpuparams.n_threads) {
307
        // Not enough set bits, may experience performance issues.
308
0
        COM_WRN("Not enough set bits in CPU mask (%d) to satisfy requested thread count: %d\n", n_set, cpuparams.n_threads);
309
0
    }
310
0
}
311
312
0
bool parse_cpu_range(const std::string & range, bool (&boolmask)[GGML_MAX_N_THREADS]) {
313
0
    size_t dash_loc = range.find('-');
314
0
    if (dash_loc == std::string::npos) {
315
0
        COM_ERR("%s", "Format of CPU range is invalid! Expected [<start>]-[<end>].\n");
316
0
        return false;
317
0
    }
318
319
0
    size_t start_i;
320
0
    size_t end_i;
321
322
0
    if (dash_loc == 0) {
323
0
        start_i = 0;
324
0
    } else {
325
0
        start_i = std::stoull(range.substr(0, dash_loc));
326
0
        if (start_i >= GGML_MAX_N_THREADS) {
327
0
            COM_ERR("%s", "Start index out of bounds!\n");
328
0
            return false;
329
0
        }
330
0
    }
331
332
0
    if (dash_loc == range.length() - 1) {
333
0
        end_i = GGML_MAX_N_THREADS - 1;
334
0
    } else {
335
0
        end_i = std::stoull(range.substr(dash_loc + 1));
336
0
        if (end_i >= GGML_MAX_N_THREADS) {
337
0
            COM_ERR("%s", "End index out of bounds!\n");
338
0
            return false;
339
0
        }
340
0
    }
341
342
0
    for (size_t i = start_i; i <= end_i; i++) {
343
0
        boolmask[i] = true;
344
0
    }
345
346
0
    return true;
347
0
}
348
349
0
bool parse_cpu_mask(const std::string & mask, bool (&boolmask)[GGML_MAX_N_THREADS]) {
350
    // Discard potential 0x prefix
351
0
    size_t start_i = 0;
352
0
    if (mask.length() >= 2 && mask.substr(0, 2) == "0x") {
353
0
        start_i = 2;
354
0
    }
355
356
0
    size_t num_digits = mask.length() - start_i;
357
0
    num_digits = std::min<size_t>(num_digits, 128);
358
359
0
    size_t end_i = num_digits + start_i;
360
361
0
    for (size_t i = start_i, n = (num_digits*4 - 1); i < end_i; i++, n-=4) {
362
0
        char c = mask.at(i);
363
0
        int8_t id = c;
364
365
0
        if ((c >= '0' && c <= '9')) {
366
0
            id -= '0';
367
0
        } else if (c >= 'a' && c <= 'f') {
368
0
            id -= 'a' - 10;
369
0
        } else if (c >= 'A' && c <= 'F') {
370
0
            id -= 'A' - 10;
371
0
        } else {
372
0
            COM_ERR("Invalid hex character '%c' at position %d\n", c, int32_t(i));
373
0
            return false;
374
0
        }
375
376
0
        boolmask[  n  ] = boolmask[  n  ] || ((id & 8) != 0);
377
0
        boolmask[n - 1] = boolmask[n - 1] || ((id & 4) != 0);
378
0
        boolmask[n - 2] = boolmask[n - 2] || ((id & 2) != 0);
379
0
        boolmask[n - 3] = boolmask[n - 3] || ((id & 1) != 0);
380
0
    }
381
382
0
    return true;
383
0
}
384
385
0
void common_init() {
386
#if defined(_WIN32)
387
    SetConsoleOutputCP(CP_UTF8);
388
    SetConsoleCP(CP_UTF8);
389
#endif
390
391
0
    common_log_set_prefix(common_log_main(), true);
392
0
    common_log_set_timestamps(common_log_main(), true);
393
394
0
    llama_log_set(common_log_default_callback, NULL);
395
0
}
396
397
0
void common_params_print_info(const common_params & params, bool print_devices) {
398
0
#ifdef NDEBUG
399
0
    const char * build_type = "";
400
#else
401
    const char * build_type = " (debug)";
402
#endif
403
0
    COM_TRC("%s: build %d (%s) with %s for %s%s\n", __func__, llama_build_number(), llama_commit(), llama_compiler(), llama_build_target(), build_type);
404
405
0
    COM_INF("%s: verbosity = %d (adjust with the `-lv N` CLI arg)\n", __func__, common_log_get_verbosity_thold());
406
407
    // device enumeration creates a primary context on CUDA backends, skip it when the caller does not own any device
408
0
    if (print_devices) {
409
0
        COM_TRC("%s", "device_info:\n");
410
0
        for (size_t i = 0; i < ggml_backend_dev_count(); ++i) {
411
0
            auto * dev = ggml_backend_dev_get(i);
412
0
            size_t free, total;
413
0
            ggml_backend_dev_memory(dev, &free, &total);
414
0
            COM_TRC("  - %-8s: %s (%zu MiB, %zu MiB free)\n", ggml_backend_dev_name(dev), ggml_backend_dev_description(dev), total / 1024 / 1024, free / 1024 / 1024);
415
0
        }
416
0
    }
417
0
    COM_TRC("%s\n", common_params_get_system_info(params).c_str());
418
0
}
419
420
0
std::string common_params_get_system_info(const common_params & params) {
421
0
    std::ostringstream os;
422
423
0
    os << "system_info: n_threads = " << params.cpuparams.n_threads;
424
0
    if (params.cpuparams_batch.n_threads != -1) {
425
0
        os << " (n_threads_batch = " << params.cpuparams_batch.n_threads << ")";
426
0
    }
427
#if defined(_WIN32) && (_WIN32_WINNT >= 0x0601) && !defined(__MINGW64__) // windows 7 and later
428
    // TODO: windows + arm64 + mingw64
429
    DWORD logicalProcessorCount = GetActiveProcessorCount(ALL_PROCESSOR_GROUPS);
430
    os << " / " << logicalProcessorCount << " | " << llama_print_system_info();
431
#else
432
0
    os << " / " << std::thread::hardware_concurrency() << " | " << llama_print_system_info();
433
0
#endif
434
435
0
    return os.str();
436
0
}
437
438
//
439
// String utils
440
//
441
442
0
std::string string_format(const char * fmt, ...) {
443
0
    va_list ap;
444
0
    va_list ap2;
445
0
    va_start(ap, fmt);
446
0
    va_copy(ap2, ap);
447
0
    int size = vsnprintf(NULL, 0, fmt, ap);
448
0
    GGML_ASSERT(size >= 0 && size < INT_MAX); // NOLINT
449
0
    std::vector<char> buf(size + 1);
450
0
    int size2 = vsnprintf(buf.data(), size + 1, fmt, ap2);
451
0
    GGML_ASSERT(size2 == size);
452
0
    va_end(ap2);
453
0
    va_end(ap);
454
0
    return std::string(buf.data(), size);
455
0
}
456
457
0
std::string string_strip(const std::string & str) {
458
0
    size_t start = 0;
459
0
    size_t end = str.size();
460
0
    while (start < end && std::isspace(str[start])) {
461
0
        start++;
462
0
    }
463
0
    while (end > start && std::isspace(str[end - 1])) {
464
0
        end--;
465
0
    }
466
0
    return str.substr(start, end - start);
467
0
}
468
469
0
std::string string_lcs(std::string_view a, std::string_view b) {
470
0
    if (a.empty() || b.empty()) return {};
471
472
0
    std::vector<std::vector<size_t>> dp(a.size() + 1, std::vector<size_t>(b.size() + 1, 0));
473
0
    size_t best_len = 0;
474
0
    size_t best_end_a = 0;
475
476
0
    for (size_t i = 1; i <= a.size(); ++i) {
477
0
        for (size_t j = 1; j <= b.size(); ++j) {
478
0
            if (a[i - 1] == b[j - 1]) {
479
0
                dp[i][j] = dp[i - 1][j - 1] + 1;
480
0
                if (dp[i][j] > best_len) {
481
0
                    best_len = dp[i][j];
482
0
                    best_end_a = i;
483
0
                }
484
0
            }
485
0
        }
486
0
    }
487
0
    return std::string(a.substr(best_end_a - best_len, best_len));
488
0
}
489
490
0
std::string string_get_sortable_timestamp() {
491
0
    using clock = std::chrono::system_clock;
492
493
0
    const clock::time_point current_time = clock::now();
494
0
    const time_t as_time_t = clock::to_time_t(current_time);
495
0
    char timestamp_no_ns[100];
496
0
    std::strftime(timestamp_no_ns, 100, "%Y_%m_%d-%H_%M_%S", std::localtime(&as_time_t));
497
498
0
    const int64_t ns = std::chrono::duration_cast<std::chrono::nanoseconds>(
499
0
        current_time.time_since_epoch() % 1000000000).count();
500
0
    char timestamp_ns[11];
501
0
    snprintf(timestamp_ns, 11, "%09" PRId64, ns);
502
503
0
    return std::string(timestamp_no_ns) + "." + std::string(timestamp_ns);
504
0
}
505
506
0
void string_replace_all(std::string & s, const std::string & search, const std::string & replace) {
507
0
    if (search.empty()) {
508
0
        return;
509
0
    }
510
0
    std::string builder;
511
0
    builder.reserve(s.length());
512
0
    size_t pos = 0;
513
0
    size_t last_pos = 0;
514
0
    while ((pos = s.find(search, last_pos)) != std::string::npos) {
515
0
        builder.append(s, last_pos, pos - last_pos);
516
0
        builder.append(replace);
517
0
        last_pos = pos + search.length();
518
0
    }
519
0
    builder.append(s, last_pos, std::string::npos);
520
0
    s = std::move(builder);
521
0
}
522
523
0
std::string regex_escape(const std::string & s) {
524
0
    static const std::regex special_chars("[.^$|()*+?\\[\\]{}\\\\]");
525
0
    return std::regex_replace(s, special_chars, "\\$&");
526
0
}
527
528
20.0k
std::string string_join(const std::vector<std::string> & values, const std::string & separator) {
529
20.0k
    std::ostringstream result;
530
732k
    for (size_t i = 0; i < values.size(); ++i) {
531
712k
        if (i > 0) {
532
693k
            result << separator;
533
693k
        }
534
712k
        result << values[i];
535
712k
    }
536
20.0k
    return result.str();
537
20.0k
}
538
539
13.2k
std::vector<std::string> string_split(const std::string & str, const std::string & delimiter) {
540
13.2k
    std::vector<std::string> parts;
541
13.2k
    size_t start = 0;
542
13.2k
    size_t end = str.find(delimiter);
543
544
70.5k
    while (end != std::string::npos) {
545
57.2k
        parts.push_back(str.substr(start, end - start));
546
57.2k
        start = end + delimiter.length();
547
57.2k
        end = str.find(delimiter, start);
548
57.2k
    }
549
550
13.2k
    parts.push_back(str.substr(start));
551
552
13.2k
    return parts;
553
13.2k
}
554
555
73.2k
std::string string_repeat(const std::string & str, size_t n) {
556
73.2k
    if (n == 0) {
557
0
        return "";
558
0
    }
559
560
73.2k
    std::string result;
561
73.2k
    result.reserve(str.length() * n);
562
563
445k
    for (size_t i = 0; i < n; ++i) {
564
371k
        result += str;
565
371k
    }
566
567
73.2k
    return result;
568
73.2k
}
569
570
0
std::string string_from(bool value) {
571
0
    return value ? "true" : "false";
572
0
}
573
574
0
std::string string_from(const std::vector<int> & values) {
575
0
    std::stringstream buf;
576
577
0
    buf << "[ ";
578
0
    bool first = true;
579
0
    for (auto e : values) {
580
0
        if (first) {
581
0
            first = false;
582
0
        } else {
583
0
            buf << ", ";
584
0
        }
585
0
        buf << std::to_string(e);
586
0
    }
587
0
    buf << " ]";
588
589
0
    return buf.str();
590
0
}
591
592
0
std::string string_from(const struct llama_context * ctx, const std::vector<llama_token> & tokens) {
593
0
    std::stringstream buf;
594
595
0
    buf << "[ ";
596
597
0
    bool first = true;
598
0
    for (const auto & token : tokens) {
599
0
        if (!first) {
600
0
            buf << ", ";
601
0
        } else {
602
0
            first = false;
603
0
        }
604
605
0
        auto detokenized = common_token_to_piece(ctx, token);
606
607
0
        buf << "'" << detokenized << "'"
608
0
            << ":" << std::to_string(token);
609
0
    }
610
611
0
    buf << " ]";
612
613
0
    return buf.str();
614
0
}
615
616
0
std::string string_from(const struct llama_context * ctx, const struct llama_batch & batch) {
617
0
    std::stringstream buf;
618
619
0
    buf << "[ ";
620
621
0
    bool first = true;
622
0
    for (int i = 0; i < batch.n_tokens; ++i) {
623
0
        if (!first) {
624
0
            buf << ", ";
625
0
        } else {
626
0
            first = false;
627
0
        }
628
629
0
        auto detokenized = common_token_to_piece(ctx, batch.token[i]);
630
631
0
        buf << "\n"          << std::to_string(i)
632
0
            << ", token '"   << detokenized << "'"
633
0
            << ", pos "      << std::to_string(batch.pos[i])
634
0
            << ", n_seq_id " << std::to_string(batch.n_seq_id[i])
635
0
            << ", seq_id "   << std::to_string(batch.seq_id[i][0])
636
0
            << ", logits "   << std::to_string(batch.logits[i]);
637
0
    }
638
639
0
    buf << " ]";
640
641
0
    return buf.str();
642
0
}
643
644
0
void string_process_escapes(std::string & input) {
645
0
    std::size_t input_len = input.length();
646
0
    std::size_t output_idx = 0;
647
648
0
    for (std::size_t input_idx = 0; input_idx < input_len; ++input_idx) {
649
0
        if (input[input_idx] == '\\' && input_idx + 1 < input_len) {
650
0
            switch (input[++input_idx]) {
651
0
                case 'n':  input[output_idx++] = '\n'; break;
652
0
                case 'r':  input[output_idx++] = '\r'; break;
653
0
                case 't':  input[output_idx++] = '\t'; break;
654
0
                case '\'': input[output_idx++] = '\''; break;
655
0
                case '\"': input[output_idx++] = '\"'; break;
656
0
                case '\\': input[output_idx++] = '\\'; break;
657
0
                case 'x':
658
                    // Handle \x12, etc
659
0
                    if (input_idx + 2 < input_len) {
660
0
                        const char x[3] = { input[input_idx + 1], input[input_idx + 2], 0 };
661
0
                        char *err_p = nullptr;
662
0
                        const long val = std::strtol(x, &err_p, 16);
663
0
                        if (err_p == x + 2) {
664
0
                            input_idx += 2;
665
0
                            input[output_idx++] = char(val);
666
0
                            break;
667
0
                        }
668
0
                    }
669
                    // fall through
670
0
                default:   input[output_idx++] = '\\';
671
0
                           input[output_idx++] = input[input_idx]; break;
672
0
            }
673
0
        } else {
674
0
            input[output_idx++] = input[input_idx];
675
0
        }
676
0
    }
677
678
0
    input.resize(output_idx);
679
0
}
680
681
0
bool string_parse_kv_override(const char * data, std::vector<llama_model_kv_override> & overrides) {
682
0
    const char * sep = strchr(data, '=');
683
0
    if (sep == nullptr || sep - data >= 128) {
684
0
        COM_ERR("%s: malformed KV override '%s'\n", __func__, data);
685
0
        return false;
686
0
    }
687
0
    llama_model_kv_override kvo;
688
0
    std::strncpy(kvo.key, data, sep - data);
689
0
    kvo.key[sep - data] = 0;
690
0
    sep++;
691
0
    if (strncmp(sep, "int:", 4) == 0) {
692
0
        sep += 4;
693
0
        kvo.tag = LLAMA_KV_OVERRIDE_TYPE_INT;
694
0
        kvo.val_i64 = std::atol(sep);
695
0
    } else if (strncmp(sep, "float:", 6) == 0) {
696
0
        sep += 6;
697
0
        kvo.tag = LLAMA_KV_OVERRIDE_TYPE_FLOAT;
698
0
        kvo.val_f64 = std::atof(sep);
699
0
    } else if (strncmp(sep, "bool:", 5) == 0) {
700
0
        sep += 5;
701
0
        kvo.tag = LLAMA_KV_OVERRIDE_TYPE_BOOL;
702
0
        if (std::strcmp(sep, "true") == 0) {
703
0
            kvo.val_bool = true;
704
0
        } else if (std::strcmp(sep, "false") == 0) {
705
0
            kvo.val_bool = false;
706
0
        } else {
707
0
            COM_ERR("%s: invalid boolean value for KV override '%s'\n", __func__, data);
708
0
            return false;
709
0
        }
710
0
    } else if (strncmp(sep, "str:", 4) == 0) {
711
0
        sep += 4;
712
0
        kvo.tag = LLAMA_KV_OVERRIDE_TYPE_STR;
713
0
        if (strlen(sep) > 127) {
714
0
            COM_ERR("%s: malformed KV override '%s', value cannot exceed 127 chars\n", __func__, data);
715
0
            return false;
716
0
        }
717
0
        strncpy(kvo.val_str, sep, 127);
718
0
        kvo.val_str[127] = '\0';
719
0
    } else {
720
0
        COM_ERR("%s: invalid type for KV override '%s'\n", __func__, data);
721
0
        return false;
722
0
    }
723
0
    overrides.emplace_back(std::move(kvo));
724
0
    return true;
725
0
}
726
727
0
static inline bool glob_class_match(const char c, const char * pattern, const char * class_end) {
728
0
    const char * class_start = pattern;
729
0
    bool negated = false;
730
731
0
    if (*class_start == '!') {
732
0
        negated = true;
733
0
        class_start++;
734
0
    }
735
736
    // If first character after negation is ']' or '-', treat it as literal
737
0
    if (*class_start == ']' || *class_start == '-') {
738
0
        if (class_start < class_end && *class_start == c) {
739
0
            return !negated;
740
0
        }
741
0
        class_start++;
742
0
    }
743
744
0
    bool matched = false;
745
746
0
    while (class_start < class_end) {
747
0
        if (class_start + 2 < class_end && class_start[1] == '-' && class_start[2] != ']') {
748
0
            char start_char = *class_start;
749
0
            char end_char = class_start[2];
750
0
            if (c >= start_char && c <= end_char) {
751
0
                matched = true;
752
0
                break;
753
0
            }
754
0
            class_start += 3;
755
0
        } else {
756
0
            if (*class_start == c) {
757
0
                matched = true;
758
0
                break;
759
0
            }
760
0
            class_start++;
761
0
        }
762
0
    }
763
764
0
    return negated ? !matched : matched;
765
0
}
766
767
// simple glob: * matches non-/ chars, ** matches anything including /, [] matches character class
768
0
static inline bool glob_match(const char * pattern, const char * str) {
769
0
    if (*pattern == '\0') {
770
0
        return *str == '\0';
771
0
    }
772
0
    if (pattern[0] == '*' && pattern[1] == '*') {
773
0
        const char * p = pattern + 2;
774
0
        if (glob_match(p, str)) return true;
775
0
        if (*str != '\0') return glob_match(pattern, str + 1);
776
0
        return false;
777
0
    }
778
0
    if (*pattern == '*') {
779
0
        const char * p = pattern + 1;
780
0
        for (; *str != '\0' && *str != '/'; str++) {
781
0
            if (glob_match(p, str)) return true;
782
0
        }
783
0
        return glob_match(p, str);
784
0
    }
785
0
    if (*pattern == '?' && *str != '\0' && *str != '/') {
786
0
        return glob_match(pattern + 1, str + 1);
787
0
    }
788
0
    if (*pattern == '[') {
789
0
        const char * class_end = pattern + 1;
790
        // If first character after '[' is ']' or '-', treat it as literal
791
0
        if (*class_end == ']' || *class_end == '-') {
792
0
            class_end++;
793
0
        }
794
0
        while (*class_end != '\0' && *class_end != ']') {
795
0
            class_end++;
796
0
        }
797
0
        if (*class_end == ']') {
798
0
            if (*str == '\0') return false;
799
0
            bool matched = glob_class_match(*str, pattern + 1, class_end);
800
0
            return matched && glob_match(class_end + 1, str + 1);
801
0
        } else {
802
0
            if (*str == '[') {
803
0
                return glob_match(pattern + 1, str + 1);
804
0
            }
805
0
            return false;
806
0
        }
807
0
    }
808
0
    if (*pattern == *str) {
809
0
        return glob_match(pattern + 1, str + 1);
810
0
    }
811
0
    return false;
812
0
}
813
814
0
bool glob_match(const std::string & pattern, const std::string & str) {
815
0
    return glob_match(pattern.c_str(), str.c_str());
816
0
}
817
818
//
819
// Filesystem utils
820
//
821
822
// Validate if a filename is safe to use
823
// To validate a full path, split the path by the OS-specific path separator, and validate each part with this function
824
0
bool fs_validate_filename(const std::string & filename, bool allow_subdirs) {
825
0
    if (!filename.length()) {
826
        // Empty filename invalid
827
0
        return false;
828
0
    }
829
0
    if (filename.length() > 255) {
830
        // Limit at common largest possible filename on Linux filesystems
831
        // to avoid unnecessary further validation
832
        // (On systems with smaller limits it will be caught by the OS)
833
0
        return false;
834
0
    }
835
836
0
    size_t offset = 0;
837
0
    while (offset < filename.size()) {
838
0
        utf8_parse_result result = common_parse_utf8_codepoint(filename, offset);
839
840
0
        if (result.status != utf8_parse_result::SUCCESS) {
841
0
            return false;
842
0
        }
843
0
        uint32_t c = result.codepoint;
844
845
0
        if ((result.bytes_consumed == 2 && c < 0x80) ||
846
0
            (result.bytes_consumed == 3 && c < 0x800) ||
847
0
            (result.bytes_consumed == 4 && c < 0x10000)) {
848
0
            return false;
849
0
        }
850
851
        // Check for forbidden codepoints:
852
        // - Control characters
853
        // - Unicode equivalents of illegal characters
854
        // - UTF-16 surrogate pairs
855
        // - UTF-8 replacement character
856
        // - Byte order mark (BOM)
857
        // - Illegal characters: / \ : * ? " < > |
858
0
        if (c <= 0x1F // Control characters (C0)
859
0
            || c == 0x7F // Control characters (DEL)
860
0
            || (c >= 0x80 && c <= 0x9F) // Control characters (C1)
861
0
            || c == 0xFF0E // Fullwidth Full Stop (period equivalent)
862
0
            || c == 0x2215 // Division Slash (forward slash equivalent)
863
0
            || c == 0x2216 // Set Minus (backslash equivalent)
864
0
            || (c >= 0xD800 && c <= 0xDFFF) // UTF-16 surrogate pairs
865
0
            || c > 0x10FFFF // Max Unicode limit
866
0
            || c == 0xFFFD // Replacement Character (UTF-8)
867
0
            || c == 0xFEFF // Byte Order Mark (BOM)
868
0
            || c == ':' || c == '*' // Illegal characters
869
0
            || c == '?' || c == '"' || c == '<' || c == '>' || c == '|') {
870
0
            return false;
871
0
        }
872
0
        if (!allow_subdirs && (c == '/' || c == '\\')) {
873
            // Subdirectories not allowed, reject path separators
874
0
            return false;
875
0
        }
876
0
        offset += result.bytes_consumed;
877
0
    }
878
879
    // Reject any leading or trailing ' ', or any trailing '.', these are stripped on Windows and will cause a different filename
880
    // Unicode and other whitespace is not affected, only 0x20 space
881
0
    if (filename.front() == ' ' || filename.back() == ' ' || filename.back() == '.') {
882
0
        return false;
883
0
    }
884
885
    // Reject any ".." (currently stricter than necessary, it should be fine to just check for == ".." instead)
886
0
    if (filename.find("..") != std::string::npos) {
887
0
        return false;
888
0
    }
889
890
    // Reject "."
891
0
    if (filename == ".") {
892
0
        return false;
893
0
    }
894
895
0
    return true;
896
0
}
897
898
#include <iostream>
899
900
901
#ifdef _WIN32
902
static std::wstring utf8_to_wstring(const std::string & str) {
903
    if (str.empty()) {
904
        return std::wstring();
905
    }
906
907
    int size = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), (int)str.size(), NULL, 0);
908
909
    if (size <= 0) {
910
        return std::wstring();
911
    }
912
913
    std::wstring wstr(size, 0);
914
    MultiByteToWideChar(CP_UTF8, 0, str.c_str(), (int)str.size(), &wstr[0], size);
915
916
    return wstr;
917
}
918
#endif
919
920
// returns true if successful, false otherwise
921
0
bool fs_create_directory_with_parents(const std::string & path) {
922
#ifdef _WIN32
923
    std::wstring wpath = utf8_to_wstring(path);
924
925
    // if the path already exists, check whether it's a directory
926
    const DWORD attributes = GetFileAttributesW(wpath.c_str());
927
    if ((attributes != INVALID_FILE_ATTRIBUTES) && (attributes & FILE_ATTRIBUTE_DIRECTORY)) {
928
        return true;
929
    }
930
931
    size_t pos_slash = 0;
932
933
    // process path from front to back, procedurally creating directories
934
    while ((pos_slash = path.find('\\', pos_slash)) != std::string::npos) {
935
        const std::wstring subpath = wpath.substr(0, pos_slash);
936
937
        pos_slash += 1;
938
939
        // skip the drive letter, in some systems it can return an access denied error
940
        if (subpath.length() == 2 && subpath[1] == ':') {
941
            continue;
942
        }
943
944
        const bool success = CreateDirectoryW(subpath.c_str(), NULL);
945
946
        if (!success) {
947
            const DWORD error = GetLastError();
948
949
            // if the path already exists, ensure that it's a directory
950
            if (error == ERROR_ALREADY_EXISTS) {
951
                const DWORD attributes = GetFileAttributesW(subpath.c_str());
952
                if (attributes == INVALID_FILE_ATTRIBUTES || !(attributes & FILE_ATTRIBUTE_DIRECTORY)) {
953
                    return false;
954
                }
955
            } else {
956
                return false;
957
            }
958
        }
959
    }
960
961
    return true;
962
#else
963
    // if the path already exists, check whether it's a directory
964
0
    struct stat info;
965
0
    if (stat(path.c_str(), &info) == 0) {
966
0
        return S_ISDIR(info.st_mode);
967
0
    }
968
969
0
    size_t pos_slash = 1; // skip leading slashes for directory creation
970
971
    // process path from front to back, procedurally creating directories
972
0
    while ((pos_slash = path.find('/', pos_slash)) != std::string::npos) {
973
0
        const std::string subpath = path.substr(0, pos_slash);
974
0
        struct stat info;
975
976
        // if the path already exists, ensure that it's a directory
977
0
        if (stat(subpath.c_str(), &info) == 0) {
978
0
            if (!S_ISDIR(info.st_mode)) {
979
0
                return false;
980
0
            }
981
0
        } else {
982
            // create parent directories
983
0
            const int ret = mkdir(subpath.c_str(), 0755);
984
0
            if (ret != 0) {
985
0
                return false;
986
0
            }
987
0
        }
988
989
0
        pos_slash += 1;
990
0
    }
991
992
0
    return true;
993
0
#endif // _WIN32
994
0
}
995
996
0
bool fs_is_directory(const std::string & path) {
997
0
    std::filesystem::path dir(path);
998
0
    return std::filesystem::exists(dir) && std::filesystem::is_directory(dir);
999
0
}
1000
1001
0
std::string common_get_env(const std::string & name) {
1002
0
    const char * value = std::getenv(name.c_str());
1003
0
    return value == nullptr ? "" : value;
1004
0
}
1005
1006
0
void common_set_env(const std::string & name, const std::string & value) {
1007
#if defined(_WIN32)
1008
    _putenv_s(name.c_str(), value.c_str());
1009
#else
1010
0
    if (value.empty()) {
1011
0
        unsetenv(name.c_str());
1012
0
    } else {
1013
0
        setenv(name.c_str(), value.c_str(), 1);
1014
0
    }
1015
0
#endif
1016
0
}
1017
1018
0
std::string fs_get_cache_directory() {
1019
0
    std::string cache_directory = "";
1020
0
    auto ensure_trailing_slash = [](std::string p) {
1021
        // Make sure to add trailing slash
1022
0
        if (p.empty() || p.back() != DIRECTORY_SEPARATOR) {
1023
0
            p += DIRECTORY_SEPARATOR;
1024
0
        }
1025
0
        return p;
1026
0
    };
1027
0
    cache_directory = common_get_env("LLAMA_CACHE");
1028
0
    if (cache_directory.empty()) {
1029
0
#if defined(__linux__) || defined(__FreeBSD__) || defined(_AIX) || \
1030
0
        defined(__OpenBSD__) || defined(__NetBSD__)
1031
0
        const std::string xdg_cache_home = common_get_env("XDG_CACHE_HOME");
1032
0
        const std::string home           = common_get_env("HOME");
1033
0
        if (!xdg_cache_home.empty()) {
1034
0
            cache_directory = xdg_cache_home;
1035
0
        } else if (!home.empty()) {
1036
0
            cache_directory = home + "/.cache/";
1037
0
        } else {
1038
0
#if defined(__linux__)
1039
            /* no $HOME is defined, fallback to getpwuid */
1040
0
            struct passwd *pw = getpwuid(getuid());
1041
0
            if ((!pw) || (!pw->pw_dir)) {
1042
0
                throw std::runtime_error("Failed to find $HOME directory");
1043
0
            }
1044
1045
0
            cache_directory = std::string(pw->pw_dir) + std::string("/.cache/");
1046
#else /* defined(__linux__) */
1047
            throw std::runtime_error("Failed to find $HOME directory");
1048
#endif /* defined(__linux__) */
1049
0
        }
1050
#elif defined(__APPLE__)
1051
        cache_directory = common_get_env("HOME");
1052
        if (cache_directory.empty()) {
1053
            throw std::runtime_error("Failed to find $HOME directory");
1054
        }
1055
        cache_directory += "/Library/Caches/";
1056
#elif defined(_WIN32)
1057
        cache_directory = common_get_env("LOCALAPPDATA");
1058
        if (cache_directory.empty()) {
1059
            throw std::runtime_error("Failed to find %LOCALAPPDATA% directory");
1060
        }
1061
#elif defined(__EMSCRIPTEN__)
1062
        GGML_ABORT("not implemented on this platform");
1063
#else
1064
#  error Unknown architecture
1065
#endif
1066
0
        cache_directory = ensure_trailing_slash(cache_directory);
1067
0
        cache_directory += "llama.cpp";
1068
0
    }
1069
0
    return ensure_trailing_slash(cache_directory);
1070
0
}
1071
1072
0
std::string fs_get_config_directory() {
1073
0
    std::string config_directory = "";
1074
0
    auto ensure_trailing_slash = [](std::string p) {
1075
0
        if (p.empty() || p.back() != DIRECTORY_SEPARATOR) {
1076
0
            p += DIRECTORY_SEPARATOR;
1077
0
        }
1078
0
        return p;
1079
0
    };
1080
0
#if defined(__linux__) || defined(__FreeBSD__) || defined(_AIX) || \
1081
0
        defined(__OpenBSD__) || defined(__NetBSD__) || defined(__APPLE__)
1082
0
    const std::string xdg_config_home = common_get_env("XDG_CONFIG_HOME");
1083
0
    const std::string home            = common_get_env("HOME");
1084
0
    if (!xdg_config_home.empty()) {
1085
0
        config_directory = xdg_config_home;
1086
0
    } else if (!home.empty()) {
1087
0
        config_directory = home + "/.config/";
1088
0
    } else {
1089
0
#if defined(__linux__)
1090
        /* no $HOME is defined, fallback to getpwuid */
1091
0
        struct passwd *pw = getpwuid(getuid());
1092
0
        if ((!pw) || (!pw->pw_dir)) {
1093
0
            throw std::runtime_error("Failed to find $HOME directory");
1094
0
        }
1095
1096
0
        config_directory = std::string(pw->pw_dir) + std::string("/.config/");
1097
#else
1098
        throw std::runtime_error("Failed to find $HOME directory");
1099
#endif
1100
0
    }
1101
#elif defined(_WIN32)
1102
    config_directory = common_get_env("APPDATA");
1103
    if (config_directory.empty()) {
1104
        throw std::runtime_error("Failed to find %APPDATA% directory");
1105
    }
1106
#elif defined(__EMSCRIPTEN__)
1107
    // caller decides what to do when there is no config directory
1108
    throw std::runtime_error("not implemented on this platform");
1109
#else
1110
#  error Unknown architecture
1111
#endif
1112
0
    config_directory = ensure_trailing_slash(config_directory);
1113
0
    config_directory += "llama.cpp";
1114
0
    return ensure_trailing_slash(config_directory);
1115
0
}
1116
1117
0
std::string fs_get_cache_file(const std::string & filename) {
1118
0
    GGML_ASSERT(filename.find(DIRECTORY_SEPARATOR) == std::string::npos);
1119
0
    std::string cache_directory = fs_get_cache_directory();
1120
0
    const bool success = fs_create_directory_with_parents(cache_directory);
1121
0
    if (!success) {
1122
0
        throw std::runtime_error("failed to create cache directory: " + cache_directory);
1123
0
    }
1124
0
    return cache_directory + filename;
1125
0
}
1126
1127
0
std::vector<common_file_info> fs_list(const std::string & path, bool include_directories) {
1128
0
    std::vector<common_file_info> files;
1129
0
    if (path.empty()) return files;
1130
1131
0
    std::filesystem::path dir(path);
1132
0
    if (!std::filesystem::exists(dir) || !std::filesystem::is_directory(dir)) {
1133
0
        return files;
1134
0
    }
1135
1136
0
    for (const auto & entry : std::filesystem::directory_iterator(dir)) {
1137
0
        try {
1138
            // Only include regular files (skip directories)
1139
0
            const auto & p = entry.path();
1140
0
            if (std::filesystem::is_regular_file(p)) {
1141
0
                common_file_info info;
1142
0
                info.path   = p.string();
1143
0
                info.name   = p.filename().string();
1144
0
                info.is_dir = false;
1145
0
                try {
1146
0
                    info.size = static_cast<size_t>(std::filesystem::file_size(p));
1147
0
                } catch (const std::filesystem::filesystem_error &) {
1148
0
                    info.size = 0;
1149
0
                }
1150
0
                files.push_back(std::move(info));
1151
0
            } else if (include_directories && std::filesystem::is_directory(p)) {
1152
0
                common_file_info info;
1153
0
                info.path   = p.string();
1154
0
                info.name   = p.filename().string();
1155
0
                info.size   = 0; // Directories have no size
1156
0
                info.is_dir = true;
1157
0
                files.push_back(std::move(info));
1158
0
            }
1159
0
        } catch (const std::filesystem::filesystem_error &) {
1160
            // skip entries we cannot inspect
1161
0
            continue;
1162
0
        }
1163
0
    }
1164
1165
0
    return files;
1166
0
}
1167
1168
0
std::ifstream fs_open_ifstream(const std::string & fname, std::ios_base::openmode mode) {
1169
#ifdef _WIN32
1170
    int wlen = MultiByteToWideChar(CP_UTF8, 0, fname.c_str(), -1, NULL, 0);
1171
    if (!wlen) { return std::ifstream(); }
1172
    std::vector<wchar_t> wfname(wlen);
1173
    (void)MultiByteToWideChar(CP_UTF8, 0, fname.c_str(), -1, wfname.data(), wlen);
1174
    return std::ifstream(wfname.data(), mode);
1175
#else
1176
0
    return std::ifstream(fname, mode);
1177
0
#endif
1178
0
}
1179
1180
//
1181
// TTY utils
1182
//
1183
1184
0
bool tty_can_use_colors() {
1185
    // Check NO_COLOR environment variable (https://no-color.org/)
1186
0
    if (const char * no_color = std::getenv("NO_COLOR")) {
1187
0
        if (no_color[0] != '\0') {
1188
0
            return false;
1189
0
        }
1190
0
    }
1191
1192
    // Check TERM environment variable
1193
0
    if (const char * term = std::getenv("TERM")) {
1194
0
        if (std::strcmp(term, "dumb") == 0) {
1195
0
            return false;
1196
0
        }
1197
0
    }
1198
1199
    // Check if stdout and stderr are connected to a terminal
1200
    // We check both because log messages can go to either
1201
0
    bool stdout_is_tty = isatty(fileno(stdout));
1202
0
    bool stderr_is_tty = isatty(fileno(stderr));
1203
1204
0
    return stdout_is_tty || stderr_is_tty;
1205
0
}
1206
1207
//
1208
// Model utils
1209
//
1210
1211
// TODO: move to common/sampling
1212
static void common_init_sampler_from_model(
1213
    const llama_model * model,
1214
0
    common_params_sampling & sparams) {
1215
1216
0
    const uint64_t config = sparams.user_sampling_config;
1217
1218
0
    auto get_int32 = [&](const char * key, int32_t & dst, uint64_t user_config) {
1219
0
        if (config & user_config) {
1220
0
            return;
1221
0
        }
1222
1223
0
        char buf[64] = {0};
1224
0
        if (llama_model_meta_val_str(model, key, buf, sizeof(buf)) > 0) {
1225
0
            char * end = nullptr;
1226
0
            int32_t v = strtol(buf, &end, 10);
1227
0
            if (end && end != buf) {
1228
0
                dst = v;
1229
0
            }
1230
0
        }
1231
0
    };
1232
1233
0
    auto get_float = [&](const char * key, float & dst, uint64_t user_config) {
1234
0
        if (config & user_config) {
1235
0
            return;
1236
0
        }
1237
1238
0
        char buf[128] = {0};
1239
0
        if (llama_model_meta_val_str(model, key, buf, sizeof(buf)) > 0) {
1240
0
            char * end = nullptr;
1241
0
            float v = strtof(buf, &end);
1242
0
            if (end && end != buf) {
1243
0
                dst = v;
1244
0
            }
1245
0
        }
1246
0
    };
1247
1248
    // Sampling sequence
1249
0
    if (!(config & common_params_sampling_config::COMMON_PARAMS_SAMPLING_CONFIG_SAMPLERS)) {
1250
0
        char buf[512] = {0};
1251
0
        if (llama_model_meta_val_str(model, llama_model_meta_key_str(LLAMA_MODEL_META_KEY_SAMPLING_SEQUENCE), buf, sizeof(buf)) > 0) {
1252
0
            const std::vector<std::string> sampler_names = string_split<std::string>(std::string(buf), ';');
1253
0
            if (!sampler_names.empty()) {
1254
0
                sparams.samplers = common_sampler_types_from_names(sampler_names);
1255
0
            }
1256
0
        }
1257
0
    }
1258
1259
0
    get_int32(llama_model_meta_key_str(LLAMA_MODEL_META_KEY_SAMPLING_TOP_K),           sparams.top_k,           common_params_sampling_config::COMMON_PARAMS_SAMPLING_CONFIG_TOP_K);
1260
0
    get_float(llama_model_meta_key_str(LLAMA_MODEL_META_KEY_SAMPLING_TOP_P),           sparams.top_p,           common_params_sampling_config::COMMON_PARAMS_SAMPLING_CONFIG_TOP_P);
1261
0
    get_float(llama_model_meta_key_str(LLAMA_MODEL_META_KEY_SAMPLING_MIN_P),           sparams.min_p,           common_params_sampling_config::COMMON_PARAMS_SAMPLING_CONFIG_MIN_P);
1262
0
    get_float(llama_model_meta_key_str(LLAMA_MODEL_META_KEY_SAMPLING_XTC_PROBABILITY), sparams.xtc_probability, common_params_sampling_config::COMMON_PARAMS_SAMPLING_CONFIG_XTC_PROBABILITY);
1263
0
    get_float(llama_model_meta_key_str(LLAMA_MODEL_META_KEY_SAMPLING_XTC_THRESHOLD),   sparams.xtc_threshold,   common_params_sampling_config::COMMON_PARAMS_SAMPLING_CONFIG_XTC_THRESHOLD);
1264
0
    get_float(llama_model_meta_key_str(LLAMA_MODEL_META_KEY_SAMPLING_TEMP),            sparams.temp,            common_params_sampling_config::COMMON_PARAMS_SAMPLING_CONFIG_TEMP);
1265
0
    get_int32(llama_model_meta_key_str(LLAMA_MODEL_META_KEY_SAMPLING_PENALTY_LAST_N),  sparams.penalty_last_n,  common_params_sampling_config::COMMON_PARAMS_SAMPLING_CONFIG_PENALTY_LAST_N);
1266
0
    get_float(llama_model_meta_key_str(LLAMA_MODEL_META_KEY_SAMPLING_PENALTY_REPEAT),  sparams.penalty_repeat,  common_params_sampling_config::COMMON_PARAMS_SAMPLING_CONFIG_PENALTY_REPEAT);
1267
0
    get_int32(llama_model_meta_key_str(LLAMA_MODEL_META_KEY_SAMPLING_MIROSTAT),        sparams.mirostat,        common_params_sampling_config::COMMON_PARAMS_SAMPLING_CONFIG_MIROSTAT);
1268
0
    get_float(llama_model_meta_key_str(LLAMA_MODEL_META_KEY_SAMPLING_MIROSTAT_TAU),    sparams.mirostat_tau,    common_params_sampling_config::COMMON_PARAMS_SAMPLING_CONFIG_MIROSTAT_TAU);
1269
0
    get_float(llama_model_meta_key_str(LLAMA_MODEL_META_KEY_SAMPLING_MIROSTAT_ETA),    sparams.mirostat_eta,    common_params_sampling_config::COMMON_PARAMS_SAMPLING_CONFIG_MIROSTAT_ETA);
1270
0
}
1271
1272
struct common_init_result::impl {
1273
    impl() = default;
1274
0
    ~impl() = default;
1275
1276
    // note: the order in which model, context, etc. are declared matters because their destructors will be called bottom-to-top
1277
1278
    common_threadpools threadpools;
1279
1280
    llama_model_ptr   model;
1281
    llama_context_ptr context;
1282
1283
    std::vector<llama_adapter_lora_ptr> lora;
1284
1285
    std::vector<common_sampler_ptr> samplers;
1286
    std::vector<llama_sampler_seq_config> samplers_seq_config;
1287
};
1288
1289
common_init_result::common_init_result(common_params & params, bool model_only) :
1290
0
    pimpl(new impl{}) {
1291
0
    auto mparams = common_model_params_to_llama(params);
1292
0
    auto cparams = common_context_params_to_llama(params);
1293
1294
0
    if (params.fit_params) {
1295
0
        COM_TRC("%s", "fitting params to device memory ...\n");
1296
0
        COM_TRC("%s", "(for bugs during this step try to reproduce them with -fit off, or provide --verbose logs if the bug only occurs with -fit on)\n");
1297
0
        common_fit_params(params.model.path.c_str(), &mparams, &cparams,
1298
0
            params.tensor_split,
1299
0
            params.tensor_buft_overrides.data(),
1300
0
            params.fit_params_target.data(),
1301
0
            params.fit_params_min_ctx,
1302
0
            params.verbosity >= LOG_LEVEL_DEBUG ? GGML_LOG_LEVEL_DEBUG : GGML_LOG_LEVEL_ERROR);
1303
0
    }
1304
1305
0
    llama_model * model = llama_model_load_from_file(params.model.path.c_str(), mparams);
1306
0
    if (model == NULL) {
1307
0
        return;
1308
0
    }
1309
1310
0
    pimpl->model.reset(model);
1311
1312
0
    if (model_only) {
1313
0
        return;
1314
0
    }
1315
1316
0
    const llama_vocab * vocab = llama_model_get_vocab(model);
1317
1318
    // load and optionally apply lora adapters
1319
0
    for (auto & la : params.lora_adapters) {
1320
0
        llama_adapter_lora_ptr lora;
1321
0
        lora.reset(llama_adapter_lora_init(model, la.path.c_str()));
1322
0
        if (lora == nullptr) {
1323
0
            COM_ERR("failed to load lora adapter '%s'\n", la.path.c_str());
1324
0
            return;
1325
0
        }
1326
1327
0
        char buf[1024];
1328
0
        la.ptr = lora.get();
1329
0
        llama_adapter_meta_val_str(la.ptr, "adapter.lora.task_name", buf, sizeof(buf));
1330
0
        la.task_name = buf;
1331
0
        llama_adapter_meta_val_str(la.ptr, "adapter.lora.prompt_prefix", buf, sizeof(buf));
1332
0
        la.prompt_prefix = buf;
1333
0
        pimpl->lora.emplace_back(std::move(lora)); // copy to list of loaded adapters
1334
0
    }
1335
1336
    // updates params.sampling
1337
    // TODO: fix naming
1338
0
    common_init_sampler_from_model(model, params.sampling);
1339
1340
0
    if (params.sampling.ignore_eos && llama_vocab_eos(vocab) == LLAMA_TOKEN_NULL) {
1341
0
        COM_WRN("%s", "vocab does not have an EOS token, ignoring --ignore-eos\n");
1342
0
        params.sampling.ignore_eos = false;
1343
0
    }
1344
1345
    // initialize once
1346
0
    for (llama_token i = 0; i < llama_vocab_n_tokens(vocab); i++) {
1347
0
        if (llama_vocab_is_eog(vocab, i)) {
1348
0
            COM_TRC("added %s logit bias = %f\n", common_token_to_piece(vocab, i).c_str(), -INFINITY);
1349
0
            params.sampling.logit_bias_eog.push_back({i, -INFINITY});
1350
0
        }
1351
0
    }
1352
1353
0
    if (params.sampling.ignore_eos) {
1354
        // add EOG biases to the active set of logit biases
1355
0
        params.sampling.logit_bias.insert(
1356
0
                params.sampling.logit_bias.end(),
1357
0
                params.sampling.logit_bias_eog.begin(), params.sampling.logit_bias_eog.end());
1358
0
    }
1359
1360
    // init the backend samplers as part of the context creation
1361
0
    pimpl->samplers.resize(cparams.n_seq_max);
1362
0
    pimpl->samplers_seq_config.resize(cparams.n_seq_max);
1363
1364
0
    for (int i = 0; i < (int) cparams.n_seq_max; ++i) {
1365
0
        pimpl->samplers[i].reset(common_sampler_init(model, params.sampling));
1366
0
        pimpl->samplers_seq_config[i] = { i, common_sampler_get(pimpl->samplers[i].get()) };
1367
0
    }
1368
1369
0
    if (params.sampling.backend_sampling) {
1370
0
        cparams.samplers   = pimpl->samplers_seq_config.data();
1371
0
        cparams.n_samplers = pimpl->samplers_seq_config.size();
1372
0
    }
1373
1374
0
    llama_context * lctx = llama_init_from_model(model, cparams);
1375
0
    if (lctx == NULL) {
1376
0
        COM_ERR("failed to create context with model '%s'\n", params.model.path.c_str());
1377
0
        return;
1378
0
    }
1379
1380
0
    pimpl->context.reset(lctx);
1381
1382
0
    set_process_priority(params.cpuparams.priority);
1383
1384
0
    pimpl->threadpools.init(lctx, params);
1385
0
}
1386
1387
0
llama_model * common_init_result::model() {
1388
0
    return pimpl->model.get();
1389
0
}
1390
1391
0
llama_context * common_init_result::context() {
1392
0
    return pimpl->context.get();
1393
0
}
1394
1395
0
common_sampler * common_init_result::sampler(llama_seq_id seq_id) {
1396
0
    if (seq_id < 0 || seq_id >= (int) pimpl->samplers.size()) {
1397
0
        return nullptr;
1398
0
    }
1399
0
    return pimpl->samplers[seq_id].get();
1400
0
}
1401
1402
0
void common_init_result::reset_samplers() {
1403
0
    for (int i = 0; i < (int) pimpl->samplers.size(); ++i) {
1404
0
        llama_sampler_reset(common_sampler_get(pimpl->samplers[i].get()));
1405
0
    }
1406
0
}
1407
1408
0
std::vector<llama_adapter_lora_ptr> & common_init_result::lora() {
1409
0
    return pimpl->lora;
1410
0
}
1411
1412
0
common_init_result_ptr common_init_from_params(common_params & params, bool model_only) {
1413
0
    common_init_result_ptr res(new common_init_result(params, model_only));
1414
1415
0
    llama_model * model = res->model();
1416
0
    if (model == NULL) {
1417
0
        COM_ERR("failed to load model '%s'\n", params.model.path.c_str());
1418
0
        return res;
1419
0
    }
1420
1421
0
    if (model_only) {
1422
0
        return res;
1423
0
    }
1424
1425
0
    llama_context * lctx = res->context();
1426
0
    if (lctx == NULL) {
1427
0
        COM_ERR("failed to create context with model '%s'\n", params.model.path.c_str());
1428
0
        return res;
1429
0
    }
1430
1431
0
    const llama_vocab * vocab = llama_model_get_vocab(model);
1432
1433
0
    if (params.ctx_shift && !llama_memory_can_shift(llama_get_memory(lctx))) {
1434
0
        COM_WRN("%s", "KV cache shifting is not supported for this context, disabling KV cache shifting\n");
1435
0
        params.ctx_shift = false;
1436
0
    }
1437
1438
0
    if (!params.control_vectors.empty()) {
1439
0
        if (params.control_vector_layer_start <= 0) params.control_vector_layer_start = 1;
1440
0
        if (params.control_vector_layer_end   <= 0) params.control_vector_layer_end   = llama_model_n_layer(model);
1441
1442
0
        const auto cvec = common_control_vector_load(params.control_vectors);
1443
0
        if (cvec.n_embd == -1) {
1444
0
            return res;
1445
0
        }
1446
1447
0
        int err = llama_set_adapter_cvec(
1448
0
                lctx,
1449
0
                cvec.data.data(),
1450
0
                cvec.data.size(),
1451
0
                cvec.n_embd,
1452
0
                params.control_vector_layer_start,
1453
0
                params.control_vector_layer_end);
1454
0
        if (err) {
1455
0
            return res;
1456
0
        }
1457
0
    }
1458
1459
0
    if (llama_pooling_type(lctx) == LLAMA_POOLING_TYPE_RANK) {
1460
0
        bool ok = true;
1461
1462
0
        if (llama_vocab_bos(vocab) == LLAMA_TOKEN_NULL) {
1463
0
            COM_WRN("%s", "vocab does not have a  BOS token, reranking will not work\n");
1464
0
            ok = false;
1465
0
        }
1466
1467
0
        bool has_eos = llama_vocab_eos(vocab) != LLAMA_TOKEN_NULL;
1468
0
        bool has_sep = llama_vocab_sep(vocab) != LLAMA_TOKEN_NULL;
1469
0
        bool has_rerank_prompt = llama_model_chat_template(model, "rerank") != NULL;
1470
1471
0
        if (!has_eos && !has_sep && !has_rerank_prompt) {
1472
0
            COM_WRN("%s", "vocab does not have an EOS token, SEP token, or rerank prompt. Reranking will not work\n");
1473
0
            ok = false;
1474
0
        } else if (!has_eos) {
1475
0
            COM_WRN("%s", "vocab does not have an EOS token, using SEP token as fallback\n");
1476
0
        }
1477
1478
0
        if (!ok) {
1479
0
            return res;
1480
0
        }
1481
0
    }
1482
1483
0
    if (!params.lora_init_without_apply) {
1484
0
        common_set_adapter_lora(lctx, params.lora_adapters);
1485
0
    }
1486
1487
0
    if (params.warmup) {
1488
0
        COM_TRC("%s", "warming up the model with an empty run - please wait ... (--no-warmup to disable)\n");
1489
1490
0
        std::vector<llama_token> tmp;
1491
0
        llama_token bos = llama_vocab_bos(vocab);
1492
0
        llama_token eos = llama_vocab_eos(vocab);
1493
1494
        // some models (e.g. T5) don't have a BOS token
1495
0
        if (bos != LLAMA_TOKEN_NULL) {
1496
0
            tmp.push_back(bos);
1497
0
        }
1498
0
        if (eos != LLAMA_TOKEN_NULL) {
1499
0
            tmp.push_back(eos);
1500
0
        }
1501
0
        if (tmp.empty()) {
1502
0
            tmp.push_back(0);
1503
0
        }
1504
1505
0
        if (llama_model_has_encoder(model)) {
1506
0
            llama_encode(lctx, llama_batch_get_one(tmp.data(), tmp.size()));
1507
0
            llama_token decoder_start_token_id = llama_model_decoder_start_token(model);
1508
0
            if (decoder_start_token_id == LLAMA_TOKEN_NULL) {
1509
0
                decoder_start_token_id = bos;
1510
0
            }
1511
0
            tmp.clear();
1512
0
            tmp.push_back(decoder_start_token_id);
1513
0
        }
1514
0
        if (llama_model_has_decoder(model)) {
1515
0
            llama_decode(lctx, llama_batch_get_one(tmp.data(), std::min(tmp.size(), (size_t) params.n_batch)));
1516
0
        }
1517
0
        llama_memory_clear(llama_get_memory(lctx), true);
1518
0
        llama_synchronize(lctx);
1519
0
        llama_perf_context_reset(lctx);
1520
1521
        // reset samplers to reset RNG state after warmup to the seeded state
1522
0
        res->reset_samplers();
1523
0
    }
1524
1525
0
    return res;
1526
0
}
1527
1528
0
common_init_result::~common_init_result() = default;
1529
1530
0
std::string common_get_model_endpoint() {
1531
0
    std::string endpoint = common_get_env("MODEL_ENDPOINT");
1532
0
    if (endpoint.empty()) {
1533
        // the HF_ENDPOINT variable is respected for backward compatibility
1534
0
        endpoint = common_get_env("HF_ENDPOINT");
1535
0
    }
1536
0
    if (endpoint.empty()) {
1537
0
        return "https://huggingface.co/";
1538
0
    }
1539
0
    if (endpoint.back() != '/') {
1540
0
        endpoint += '/';
1541
0
    }
1542
0
    return endpoint;
1543
0
}
1544
1545
0
char * common_get_model_or_exit(int argc, char * argv[]) {
1546
0
    if (argc > 1) {
1547
0
        return argv[1];
1548
0
    }
1549
1550
0
    char * path = getenv("LLAMACPP_TEST_MODELFILE");
1551
0
    if (!path || strlen(path) == 0) {
1552
0
        fprintf(stderr, "\033[33mWARNING: No model file provided. Skipping this test. Set LLAMACPP_TEST_MODELFILE=<gguf_model_path> to silence this warning and run this test.\n\033[0m");
1553
0
        exit(EXIT_SUCCESS);
1554
0
    }
1555
1556
0
    return path;
1557
0
}
1558
1559
0
common_context_seq_rm_type common_context_can_seq_rm(llama_context * ctx) {
1560
0
    auto * mem = llama_get_memory(ctx);
1561
0
    if (mem == nullptr) {
1562
0
        return COMMON_CONTEXT_SEQ_RM_TYPE_NO;
1563
0
    }
1564
1565
0
    common_context_seq_rm_type res = COMMON_CONTEXT_SEQ_RM_TYPE_PART;
1566
1567
0
    llama_memory_clear(mem, true);
1568
1569
    // eval 2 tokens to check if the context is compatible
1570
0
    std::vector<llama_token> tmp;
1571
0
    tmp.push_back(0);
1572
0
    tmp.push_back(0);
1573
1574
0
    int ret = llama_decode(ctx, llama_batch_get_one(tmp.data(), tmp.size()));
1575
0
    if (ret != 0) {
1576
0
        COM_ERR("llama_decode() failed: %d\n", ret);
1577
0
        res = COMMON_CONTEXT_SEQ_RM_TYPE_NO;
1578
0
        goto done;
1579
0
    }
1580
1581
0
    if (llama_n_rs_seq(ctx) > 0) {
1582
0
        COM_TRC("%s", "the context supports bounded partial sequence removal\n");
1583
0
        res = COMMON_CONTEXT_SEQ_RM_TYPE_RS;
1584
0
        goto done;
1585
0
    }
1586
1587
    // try to remove the last tokens
1588
0
    if (!llama_memory_seq_rm(mem, 0, 1, -1)) {
1589
0
        COM_TRC("%s", "the context does not support partial sequence removal\n");
1590
0
        res = COMMON_CONTEXT_SEQ_RM_TYPE_FULL;
1591
0
        goto done;
1592
0
    }
1593
1594
0
done:
1595
0
    llama_memory_clear(mem, true);
1596
0
    llama_synchronize(ctx);
1597
1598
0
    return res;
1599
0
}
1600
1601
0
static void common_context_seq_rm(llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1) {
1602
0
    auto * mem = llama_get_memory(ctx);
1603
0
    if (!llama_memory_seq_rm(mem, seq_id, p0, p1)) {
1604
0
        GGML_ABORT("%s", string_format("failed to remove sequence %d with p0=%d, p1=%d\n", seq_id, p0, p1).c_str());
1605
0
    }
1606
0
}
1607
1608
0
static void common_context_seq_cp(llama_context * ctx, llama_seq_id seq_id_src, llama_seq_id seq_id_dst, llama_pos p0, llama_pos p1) {
1609
0
    auto * mem = llama_get_memory(ctx);
1610
0
    llama_memory_seq_cp(mem, seq_id_src, seq_id_dst, p0, p1);
1611
0
}
1612
1613
0
static void common_context_seq_add(llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, llama_pos delta) {
1614
0
    auto * mem = llama_get_memory(ctx);
1615
0
    llama_memory_seq_add(mem, seq_id, p0, p1, delta);
1616
0
}
1617
1618
0
void common_memory::init(llama_context * ctx_tgt, llama_context * ctx_dft) {
1619
0
    this->ctx_tgt = ctx_tgt;
1620
0
    this->ctx_dft = ctx_dft;
1621
0
}
1622
1623
0
void common_memory::seq_rm(llama_seq_id seq_id, llama_pos p0, llama_pos p1) const {
1624
0
    common_context_seq_rm(ctx_tgt, seq_id, p0, p1);
1625
0
    if (ctx_dft) {
1626
0
        common_context_seq_rm(ctx_dft, seq_id, p0, p1);
1627
0
    }
1628
0
}
1629
1630
0
void common_memory::seq_cp(llama_seq_id seq_id_src, llama_seq_id seq_id_dst, llama_pos p0, llama_pos p1) const {
1631
0
    common_context_seq_cp(ctx_tgt, seq_id_src, seq_id_dst, p0, p1);
1632
0
    if (ctx_dft) {
1633
0
        common_context_seq_cp(ctx_dft, seq_id_src, seq_id_dst, p0, p1);
1634
0
    }
1635
0
}
1636
1637
0
void common_memory::seq_add(llama_seq_id seq_id, llama_pos p0, llama_pos p1, llama_pos delta) const {
1638
0
    common_context_seq_add(ctx_tgt, seq_id, p0, p1, delta);
1639
0
    if (ctx_dft) {
1640
0
        common_context_seq_add(ctx_dft, seq_id, p0, p1, delta);
1641
0
    }
1642
0
}
1643
1644
0
void common_set_adapter_lora(struct llama_context * ctx, std::vector<common_adapter_lora_info> & lora) {
1645
0
    std::vector<llama_adapter_lora *> loras;
1646
0
    std::vector<float> scales;
1647
1648
0
    for (auto & la: lora) {
1649
0
        loras.push_back(la.ptr);
1650
0
        scales.push_back(la.scale);
1651
0
    }
1652
1653
0
    llama_set_adapters_lora(ctx, loras.data(), loras.size(), scales.data());
1654
0
}
1655
1656
6.55k
struct llama_model_params common_model_params_to_llama(common_params & params) {
1657
6.55k
    auto mparams = llama_model_default_params();
1658
1659
6.55k
    if (!params.devices.empty()) {
1660
0
        mparams.devices = params.devices.data();
1661
0
    }
1662
1663
6.55k
    mparams.n_gpu_layers    = params.n_gpu_layers;
1664
6.55k
    mparams.main_gpu        = params.main_gpu;
1665
6.55k
    mparams.split_mode      = params.split_mode;
1666
6.55k
    mparams.load_mode       = params.load_mode;
1667
6.55k
    mparams.tensor_split    = params.tensor_split;
1668
6.55k
    mparams.check_tensors   = params.check_tensors;
1669
6.55k
    mparams.use_extra_bufts = !params.no_extra_bufts;
1670
6.55k
    mparams.no_host         = params.no_host;
1671
1672
6.55k
    if (params.kv_overrides.empty()) {
1673
6.55k
        mparams.kv_overrides = NULL;
1674
6.55k
    } else {
1675
0
        GGML_ASSERT(params.kv_overrides.back().key[0] == 0 && "KV overrides not terminated with empty key");
1676
0
        mparams.kv_overrides = params.kv_overrides.data();
1677
0
    }
1678
1679
6.55k
    if (params.tensor_buft_overrides.empty()) {
1680
6.55k
        mparams.tensor_buft_overrides = NULL;
1681
6.55k
    } else {
1682
0
        GGML_ASSERT(params.tensor_buft_overrides.back().pattern == nullptr && "Tensor buffer overrides not terminated with empty pattern");
1683
0
        mparams.tensor_buft_overrides = params.tensor_buft_overrides.data();
1684
0
    }
1685
1686
6.55k
    mparams.progress_callback           = params.load_progress_callback;
1687
6.55k
    mparams.progress_callback_user_data = params.load_progress_callback_user_data;
1688
6.55k
    mparams.no_alloc                    = params.no_alloc;
1689
6.55k
    mparams.load_mtp                    = std::find(params.speculative.types.begin(), params.speculative.types.end(), COMMON_SPECULATIVE_TYPE_DRAFT_MTP) != params.speculative.types.end();
1690
1691
6.55k
    return mparams;
1692
6.55k
}
1693
1694
0
struct llama_context_params common_context_params_to_llama(const common_params & params) {
1695
0
    auto cparams = llama_context_default_params();
1696
1697
0
    cparams.n_ctx             = params.n_ctx;
1698
0
    cparams.n_seq_max         = params.n_parallel;
1699
0
    cparams.n_rs_seq          = params.speculative.need_n_rs_seq();
1700
0
    cparams.n_outputs_max     = std::max(params.n_outputs_max, 0);
1701
0
    cparams.n_outputs_max_per_seq = std::max(params.n_outputs_max_per_seq, 0);
1702
0
    cparams.n_batch           = params.n_batch;
1703
0
    cparams.n_ubatch          = params.n_ubatch;
1704
0
    cparams.n_threads         = params.cpuparams.n_threads;
1705
0
    cparams.n_threads_batch   = params.cpuparams_batch.n_threads == -1 ?
1706
0
                                params.cpuparams.n_threads : params.cpuparams_batch.n_threads;
1707
0
    cparams.embeddings        = params.embedding;
1708
0
    cparams.rope_scaling_type = params.rope_scaling_type;
1709
0
    cparams.rope_freq_base    = params.rope_freq_base;
1710
0
    cparams.rope_freq_scale   = params.rope_freq_scale;
1711
0
    cparams.yarn_ext_factor   = params.yarn_ext_factor;
1712
0
    cparams.yarn_attn_factor  = params.yarn_attn_factor;
1713
0
    cparams.yarn_beta_fast    = params.yarn_beta_fast;
1714
0
    cparams.yarn_beta_slow    = params.yarn_beta_slow;
1715
0
    cparams.yarn_orig_ctx     = params.yarn_orig_ctx;
1716
0
    cparams.pooling_type      = params.pooling_type;
1717
0
    cparams.attention_type    = params.attention_type;
1718
0
    cparams.flash_attn_type   = params.flash_attn_type;
1719
0
    cparams.cb_eval           = params.cb_eval;
1720
0
    cparams.cb_eval_user_data = params.cb_eval_user_data;
1721
0
    cparams.offload_kqv       = !params.no_kv_offload;
1722
0
    cparams.no_perf           = params.no_perf;
1723
0
    cparams.op_offload        = !params.no_op_offload;
1724
0
    cparams.swa_full          = params.swa_full;
1725
0
    cparams.kv_unified        = params.kv_unified;
1726
1727
0
    cparams.type_k = params.cache_type_k;
1728
0
    cparams.type_v = params.cache_type_v;
1729
1730
0
    return cparams;
1731
0
}
1732
1733
//
1734
// Threadpool utils
1735
//
1736
1737
0
struct ggml_threadpool_params ggml_threadpool_params_from_cpu_params(const common_cpu_params & params) {
1738
0
    struct ggml_threadpool_params tpp;
1739
1740
0
    ggml_threadpool_params_init(&tpp, params.n_threads); // setup the defaults
1741
1742
0
    if (params.mask_valid) {
1743
0
        std::memcpy(&tpp.cpumask, &params.cpumask, GGML_MAX_N_THREADS);
1744
0
    }
1745
1746
0
    tpp.prio       = params.priority;
1747
0
    tpp.poll       = params.poll;
1748
0
    tpp.strict_cpu = params.strict_cpu;
1749
1750
0
    return tpp;
1751
0
}
1752
1753
0
common_threadpools::~common_threadpools() {
1754
0
    if (!free_fn) {
1755
0
        return;
1756
0
    }
1757
0
    free_fn(threadpool);
1758
0
    free_fn(threadpool_batch);
1759
0
}
1760
1761
0
void common_threadpools::init(llama_context * ctx, const common_params & params) {
1762
0
    GGML_ASSERT(!threadpool);
1763
0
    GGML_ASSERT(!threadpool_batch);
1764
1765
0
    COM_INF("llama threadpool init, n_threads = %d\n", (int) params.cpuparams.n_threads);
1766
1767
0
    auto * cpu_dev = ggml_backend_dev_by_type(GGML_BACKEND_DEVICE_TYPE_CPU);
1768
0
    if (!cpu_dev) {
1769
0
        COM_WRN("%s", "no CPU backend found\n");
1770
0
        return;
1771
0
    }
1772
0
    auto * reg = ggml_backend_dev_backend_reg(cpu_dev);
1773
0
    auto * ggml_threadpool_new_fn = (decltype(ggml_threadpool_new) *) ggml_backend_reg_get_proc_address(reg, "ggml_threadpool_new");
1774
0
    free_fn = (decltype(ggml_threadpool_free) *) ggml_backend_reg_get_proc_address(reg, "ggml_threadpool_free");
1775
1776
0
    struct ggml_threadpool_params tpp_batch =
1777
0
            ggml_threadpool_params_from_cpu_params(params.cpuparams_batch);
1778
0
    struct ggml_threadpool_params tpp =
1779
0
            ggml_threadpool_params_from_cpu_params(params.cpuparams);
1780
1781
    // each pool needs to match the respective n_threads exactly
1782
    // see: https://github.com/ggml-org/llama.cpp/pull/27138#issuecomment-5332307332
1783
0
    if (!ggml_threadpool_params_match(&tpp, &tpp_batch)) {
1784
0
        threadpool_batch = ggml_threadpool_new_fn(&tpp_batch);
1785
0
        if (!threadpool_batch) {
1786
0
            COM_WRN("batch threadpool create failed : n_threads %d\n", tpp_batch.n_threads);
1787
0
            return;
1788
0
        }
1789
1790
        // start the non-batch threadpool in the paused state
1791
0
        tpp.paused = true;
1792
0
    }
1793
1794
0
    threadpool = ggml_threadpool_new_fn(&tpp);
1795
0
    if (!threadpool) {
1796
0
        COM_WRN("threadpool create failed : n_threads %d\n", tpp.n_threads);
1797
0
        free_fn(threadpool_batch);
1798
0
        threadpool_batch = nullptr;
1799
0
        return;
1800
0
    }
1801
1802
0
    llama_attach_threadpool(ctx, threadpool, threadpool_batch);
1803
0
}
1804
1805
//
1806
// Batch utils
1807
//
1808
1809
0
void common_batch_clear(struct llama_batch & batch) {
1810
0
    batch.n_tokens = 0;
1811
0
}
1812
1813
void common_batch_add(
1814
                 struct llama_batch & batch,
1815
                        llama_token   id,
1816
                          llama_pos   pos,
1817
    const std::vector<llama_seq_id> & seq_ids,
1818
0
                               bool   logits) {
1819
0
    GGML_ASSERT(batch.seq_id[batch.n_tokens] && "llama_batch size exceeded");
1820
1821
0
    batch.token   [batch.n_tokens] = id;
1822
0
    batch.pos     [batch.n_tokens] = pos;
1823
0
    batch.n_seq_id[batch.n_tokens] = seq_ids.size();
1824
0
    for (size_t i = 0; i < seq_ids.size(); ++i) {
1825
0
        batch.seq_id[batch.n_tokens][i] = seq_ids[i];
1826
0
    }
1827
0
    batch.logits  [batch.n_tokens] = logits;
1828
1829
0
    batch.n_tokens++;
1830
0
}
1831
1832
//
1833
// Vocab utils
1834
//
1835
1836
std::vector<llama_token> common_tokenize(
1837
  const struct llama_context * ctx,
1838
           const std::string & text,
1839
                        bool   add_special,
1840
0
                        bool   parse_special) {
1841
0
    const llama_model * model = llama_get_model(ctx);
1842
0
    const llama_vocab * vocab = llama_model_get_vocab(model);
1843
0
    return common_tokenize(vocab, text, add_special, parse_special);
1844
0
}
1845
1846
std::vector<llama_token> common_tokenize(
1847
    const struct llama_vocab * vocab,
1848
           const std::string & text,
1849
                        bool   add_special,
1850
0
                        bool   parse_special) {
1851
    // upper limit for the number of tokens
1852
0
    int n_tokens = text.length() + 2 * add_special;
1853
0
    std::vector<llama_token> result(n_tokens);
1854
0
    n_tokens = llama_tokenize(vocab, text.data(), text.length(), result.data(), result.size(), add_special, parse_special);
1855
0
    if (n_tokens == std::numeric_limits<int32_t>::min()) {
1856
0
        throw std::runtime_error("Tokenization failed: input text too large, tokenization result exceeds int32_t limit");
1857
0
    }
1858
0
    if (n_tokens < 0) {
1859
0
        result.resize(-n_tokens);
1860
0
        int check = llama_tokenize(vocab, text.data(), text.length(), result.data(), result.size(), add_special, parse_special);
1861
0
        GGML_ASSERT(check == -n_tokens);
1862
0
    } else {
1863
0
        result.resize(n_tokens);
1864
0
    }
1865
0
    return result;
1866
0
}
1867
1868
0
std::string common_token_to_piece(const struct llama_context * ctx, llama_token token, bool special) {
1869
0
    const llama_model * model = llama_get_model(ctx);
1870
0
    const llama_vocab * vocab = llama_model_get_vocab(model);
1871
0
    return common_token_to_piece(vocab, token, special);
1872
0
}
1873
1874
0
std::string common_token_to_piece(const struct llama_vocab * vocab, llama_token token, bool special) {
1875
0
    std::string piece;
1876
0
    piece.resize(piece.capacity());  // using string internal cache, 15 bytes + '\n'
1877
0
    const int n_chars = llama_token_to_piece(vocab, token, &piece[0], piece.size(), 0, special);
1878
0
    if (n_chars < 0) {
1879
0
        piece.resize(-n_chars);
1880
0
        int check = llama_token_to_piece(vocab, token, &piece[0], piece.size(), 0, special);
1881
0
        GGML_ASSERT(check == -n_chars);
1882
0
    }
1883
0
    else {
1884
0
        piece.resize(n_chars);
1885
0
    }
1886
1887
0
    return piece;
1888
0
}
1889
1890
0
std::string common_detokenize(const struct llama_context * ctx, const std::vector<llama_token> & tokens, bool special) {
1891
0
    const llama_model * model = llama_get_model(ctx);
1892
0
    const llama_vocab * vocab = llama_model_get_vocab(model);
1893
0
    return common_detokenize(vocab, tokens, special);
1894
0
}
1895
1896
0
std::string common_detokenize(const struct llama_vocab * vocab, const std::vector<llama_token> & tokens, bool special) {
1897
0
    std::string text;
1898
0
    text.resize(std::max(text.capacity(), tokens.size()));
1899
0
    int32_t n_chars = llama_detokenize(vocab, tokens.data(), (int32_t)tokens.size(), &text[0], (int32_t)text.size(), false, special);
1900
0
    if (n_chars < 0) {
1901
0
        text.resize(-n_chars);
1902
0
        n_chars = llama_detokenize(vocab, tokens.data(), (int32_t)tokens.size(), &text[0], (int32_t)text.size(), false, special);
1903
0
        GGML_ASSERT(n_chars <= (int32_t)text.size());  // whitespace trimming is performed after per-token detokenization
1904
0
    }
1905
1906
0
    text.resize(n_chars);
1907
1908
    // NOTE: the original tokenizer decodes bytes after collecting the pieces.
1909
0
    return text;
1910
0
}
1911
1912
//
1913
// Embedding utils
1914
//
1915
1916
0
void common_embd_normalize(const float * inp, float * out, int n, int embd_norm) {
1917
0
    double sum = 0.0;
1918
1919
0
    switch (embd_norm) {
1920
0
        case -1: // no normalisation
1921
0
            sum = 1.0;
1922
0
            break;
1923
0
        case 0: // max absolute
1924
0
            for (int i = 0; i < n; i++) {
1925
0
                if (sum < std::abs(inp[i])) {
1926
0
                    sum = std::abs(inp[i]);
1927
0
                }
1928
0
            }
1929
0
            sum /= 32760.0; // make an int16 range
1930
0
            break;
1931
0
        case 2: // euclidean
1932
0
            for (int i = 0; i < n; i++) {
1933
0
                sum += inp[i] * inp[i];
1934
0
            }
1935
0
            sum = std::sqrt(sum);
1936
0
            break;
1937
0
        default: // p-norm (euclidean is p-norm p=2)
1938
0
            for (int i = 0; i < n; i++) {
1939
0
                sum += std::pow(std::abs(inp[i]), embd_norm);
1940
0
            }
1941
0
            sum = std::pow(sum, 1.0 / embd_norm);
1942
0
            break;
1943
0
    }
1944
1945
0
    const float norm = sum > 0.0 ? 1.0 / sum : 0.0f;
1946
1947
0
    for (int i = 0; i < n; i++) {
1948
0
        out[i] = inp[i] * norm;
1949
0
    }
1950
0
}
1951
1952
0
float common_embd_similarity_cos(const float * embd1, const float * embd2, int n){
1953
0
    double sum  = 0.0;
1954
0
    double sum1 = 0.0;
1955
0
    double sum2 = 0.0;
1956
1957
0
    for (int i = 0; i < n; i++) {
1958
0
        sum  += embd1[i] * embd2[i];
1959
0
        sum1 += embd1[i] * embd1[i];
1960
0
        sum2 += embd2[i] * embd2[i];
1961
0
    }
1962
1963
    // Handle the case where one or both vectors are zero vectors
1964
0
    if (sum1 == 0.0 || sum2 == 0.0) {
1965
0
        if (sum1 == 0.0 && sum2 == 0.0) {
1966
0
            return 1.0f; // two zero vectors are similar
1967
0
        }
1968
0
        return 0.0f;
1969
0
    }
1970
1971
0
    return sum / (sqrt(sum1) * sqrt(sum2));
1972
0
}
1973
1974
//
1975
// Control vector utils
1976
//
1977
1978
0
static common_control_vector_data common_control_vector_load_one(const common_control_vector_load_info & load_info) {
1979
0
    common_control_vector_data result = { -1, {} };
1980
1981
0
    ggml_context * ctx = nullptr;
1982
0
    struct gguf_init_params meta_gguf_params = {
1983
0
        /* .no_alloc = */ false,
1984
0
        /* .ctx      = */ &ctx,
1985
0
    };
1986
0
    struct gguf_context * ctx_gguf = gguf_init_from_file(load_info.fname.c_str(), meta_gguf_params);
1987
0
    if (!ctx_gguf) {
1988
0
        COM_ERR("failed to load control vector file from %s\n", load_info.fname.c_str());
1989
0
        return result;
1990
0
    }
1991
1992
0
    int32_t n_tensors = gguf_get_n_tensors(ctx_gguf);
1993
0
    if (n_tensors == 0) {
1994
0
        COM_WRN("no direction tensors found in %s\n", load_info.fname.c_str());
1995
0
    }
1996
1997
0
    for (int i = 0; i < n_tensors; i++) {
1998
0
        std::string name = gguf_get_tensor_name(ctx_gguf, i);
1999
2000
0
        int layer_idx = -1;
2001
2002
        // split on '.'
2003
0
        size_t dotpos = name.find('.');
2004
0
        if (dotpos != std::string::npos && name.substr(0, dotpos) == "direction") {
2005
0
            try {
2006
0
                layer_idx = std::stoi(name.substr(dotpos + 1));
2007
0
            } catch (...) {
2008
0
                layer_idx = -1;
2009
0
            }
2010
0
        }
2011
0
        if (layer_idx < 0) {
2012
0
            COM_ERR("invalid/unparsable direction tensor layer index in %s\n", load_info.fname.c_str());
2013
0
            result.n_embd = -1;
2014
0
            break;
2015
0
        } else if (layer_idx == 0) {
2016
0
            COM_ERR("invalid (zero) direction tensor layer index in %s\n", load_info.fname.c_str());
2017
0
            result.n_embd = -1;
2018
0
            break;
2019
0
        }
2020
2021
0
        struct ggml_tensor * tensor = ggml_get_tensor(ctx, name.c_str());
2022
0
        if (tensor->type != GGML_TYPE_F32) {
2023
0
            COM_ERR("invalid (non-F32) direction tensor type in %s\n", load_info.fname.c_str());
2024
0
            result.n_embd = -1;
2025
0
            break;
2026
0
        }
2027
0
        if (ggml_n_dims(tensor) != 1) {
2028
0
            COM_ERR("invalid (non-1D) direction tensor shape in %s\n", load_info.fname.c_str());
2029
0
            result.n_embd = -1;
2030
0
            break;
2031
0
        }
2032
2033
0
        if (result.n_embd == -1) {
2034
0
            result.n_embd = ggml_nelements(tensor);
2035
0
        } else if (ggml_nelements(tensor) != result.n_embd) {
2036
0
            COM_ERR("direction tensor in %s does not match previous dimensions\n", load_info.fname.c_str());
2037
0
            result.n_embd = -1;
2038
0
            break;
2039
0
        }
2040
2041
        // extend if necessary - do not store data for layer 0 (it's not used)
2042
0
        result.data.resize(std::max(result.data.size(), static_cast<size_t>(result.n_embd * layer_idx)), 0.0f);
2043
2044
0
        const float * src = (const float *) tensor->data;
2045
0
        float * dst = result.data.data() + result.n_embd * (layer_idx - 1);  // layer 1 at [0]
2046
0
        for (int j = 0; j < result.n_embd; j++) {
2047
0
            dst[j] += src[j] * load_info.strength;  // allows multiple directions for same layer in same file
2048
0
        }
2049
2050
0
    }
2051
2052
0
    if (result.n_embd == -1) {
2053
0
        COM_WRN("skipping %s due to invalid direction tensors\n", load_info.fname.c_str());
2054
0
        result.data.clear();
2055
0
    }
2056
2057
0
    gguf_free(ctx_gguf);
2058
0
    ggml_free(ctx);
2059
2060
0
    return result;
2061
0
}
2062
2063
0
common_control_vector_data common_control_vector_load(const std::vector<common_control_vector_load_info> & load_infos) {
2064
0
    common_control_vector_data result = { -1, {} };
2065
2066
0
    for (const auto & info : load_infos) {
2067
0
        auto cur = common_control_vector_load_one(info);
2068
2069
0
        if (cur.n_embd == -1) {
2070
0
            result.n_embd = -1;
2071
0
            break;
2072
0
        }
2073
0
        if (result.n_embd != -1 && result.n_embd != cur.n_embd) {
2074
0
            COM_ERR("control vectors in %s does not match previous dimensions\n", info.fname.c_str());
2075
0
            result.n_embd = -1;
2076
0
            break;
2077
0
        }
2078
2079
0
        if (result.n_embd == -1) {
2080
0
            result = std::move(cur);
2081
0
        } else {
2082
0
            result.data.resize(std::max(result.data.size(), cur.data.size()), 0.0f);  // extend if necessary
2083
0
            for (size_t i = 0; i < cur.data.size(); i++) {
2084
0
                result.data[i] += cur.data[i];
2085
0
            }
2086
0
        }
2087
0
    }
2088
2089
0
    if (result.n_embd == -1) {
2090
0
        COM_ERR("%s", "no valid control vector files passed\n");
2091
0
        result.data.clear();
2092
0
    }
2093
2094
0
    return result;
2095
0
}
2096
2097
0
ggml_opt_dataset_t common_opt_dataset_init(struct llama_context * ctx, const std::vector<llama_token> & tokens, int64_t stride) {
2098
0
    const int64_t ne_datapoint = llama_n_ctx(ctx);
2099
0
    const int64_t ndata        = (tokens.size() - ne_datapoint - 1) / stride;
2100
0
    ggml_opt_dataset_t result = ggml_opt_dataset_init(
2101
0
        GGML_TYPE_I32, GGML_TYPE_I32, ne_datapoint, ne_datapoint, ndata, /*ndata_shard =*/ 1);
2102
2103
0
    llama_token * data   = (llama_token *) ggml_opt_dataset_data(result)->data;
2104
0
    llama_token * labels = (llama_token *) ggml_opt_dataset_labels(result)->data;
2105
2106
0
    for (int64_t idata = 0; idata < ndata; ++idata) {
2107
0
        memcpy(data   + idata*ne_datapoint, tokens.data() + idata*stride + 0, ne_datapoint*sizeof(llama_token));
2108
0
        memcpy(labels + idata*ne_datapoint, tokens.data() + idata*stride + 1, ne_datapoint*sizeof(llama_token));
2109
0
    }
2110
2111
0
    return result;
2112
0
}
2113
2114
0
ggml_opt_optimizer_params common_opt_lr_pars(void * userdata) {
2115
0
    ggml_opt_optimizer_params result = ggml_opt_get_default_optimizer_params(nullptr);
2116
0
    const lr_opt &            d      = *(lr_opt *) userdata;
2117
0
    result.adamw.alpha = result.sgd.alpha = d.get_lr(d.epoch);
2118
0
    result.sgd.wd = result.adamw.wd = d.wd;
2119
0
    return result;
2120
0
}
2121
2122
// TODO make all command line args case-insensitive
2123
0
static inline bool eq_case_insensitive(char const* a, char const* b) {
2124
0
    return !
2125
#if defined(_MSC_VER)
2126
        _stricmp
2127
#else
2128
0
        strcasecmp
2129
0
#endif // defined(_MSC_VER)
2130
0
        (a, b);
2131
0
}
2132
2133
0
enum ggml_opt_optimizer_type common_opt_get_optimizer(const char * n) {
2134
0
    if (eq_case_insensitive("adamw", n)) {
2135
0
        return GGML_OPT_OPTIMIZER_TYPE_ADAMW;
2136
0
    }
2137
0
    if (eq_case_insensitive("sgd", n)) {
2138
0
        return GGML_OPT_OPTIMIZER_TYPE_SGD;
2139
0
    }
2140
0
    return GGML_OPT_OPTIMIZER_TYPE_COUNT;
2141
0
}
2142
2143
// TODO simplify to use just log and exp
2144
static float const k_log_2 = std::log(2.f);
2145
2146
0
void lr_opt::init() {
2147
0
    if (lr_min > 0 && lr_min < lr0) {
2148
0
        float nhalf = std::log(lr0 / lr_min) / k_log_2;
2149
0
        float e     = epochs;
2150
0
        if (decay_epochs > 0 && decay_epochs < e) {
2151
0
            e = decay_epochs;
2152
0
        } else {
2153
0
            decay_epochs = e;
2154
0
        }
2155
0
        scale_epoch = nhalf / e;
2156
0
    }
2157
0
}
2158
2159
0
float lr_opt::get_lr(float epoch) const {
2160
0
    float r = lr_min <= 0 ? lr0 :
2161
0
        epoch >= decay_epochs ? lr_min :
2162
0
        lr0 * std::pow(0.5f, epoch * scale_epoch);
2163
0
    LOG_INF("epoch %.2g lr=%.2g\n", epoch, r);
2164
0
    return r;
2165
0
}
2166
2167
0
bool common_replay_last_token(struct llama_context * ctx, llama_token last_token, int32_t pos) {
2168
0
    llama_batch batch = llama_batch_get_one(&last_token, 1);
2169
0
    batch.pos = &pos;
2170
0
    if (llama_decode(ctx, batch)) {
2171
0
        LOG_ERR("%s: failed to replay last token\n", __func__);
2172
0
        return false;
2173
0
    }
2174
0
    return true;
2175
0
}
2176
2177
bool common_prompt_batch_decode(
2178
              struct llama_context * ctx,
2179
    const std::vector<llama_token> & all_tokens,
2180
                               int   n_new,
2181
                               int & n_past,
2182
                               int   n_batch,
2183
                  std::string_view   state_path,
2184
0
                              bool   save_state) {
2185
0
    if (n_new == 0) {
2186
0
        return true;
2187
0
    }
2188
0
    const int offset = all_tokens.size() - n_new;
2189
2190
0
    if (save_state && n_new > 1) {
2191
0
        const int n_tokens_before_last = n_new - 1;
2192
2193
0
        GGML_ASSERT(n_new <= n_batch);
2194
2195
        // Decode all but the last token so we can save the memory state before decoding the last token.
2196
        // This is done so we can restore the session state later and replay the last token.
2197
        // Memory implementations in recurrent/hybrid models don't support removing tokens from their
2198
        // memory, so we can't just remove the last token from the memory and replay the last token which
2199
        // is the reason for this logic.
2200
0
        if (llama_decode(ctx, llama_batch_get_one(const_cast<llama_token*>(all_tokens.data() + offset), n_tokens_before_last))) {
2201
0
            COM_ERR("%s", "failed to eval\n");
2202
0
            return false;
2203
0
        }
2204
0
        n_past += n_tokens_before_last;
2205
2206
0
        llama_state_save_file(ctx, state_path.data(), all_tokens.data(), all_tokens.size());
2207
0
        COM_INF("saved session before last token to %s, n_new = %zu\n", state_path.data(), all_tokens.size());
2208
2209
0
        llama_token last_token = all_tokens.back();
2210
0
        llama_batch batch = llama_batch_get_one(&last_token, 1);
2211
0
        int32_t pos = n_past;
2212
0
        batch.pos = &pos;
2213
2214
0
        if (llama_decode(ctx, batch)) {
2215
0
            COM_ERR("%s", "failed to eval last token\n");
2216
0
            return false;
2217
0
        }
2218
0
        n_past++;
2219
0
    } else {
2220
0
        if (llama_decode(ctx, llama_batch_get_one(const_cast<llama_token*>(all_tokens.data() + offset), n_new))) {
2221
0
            COM_ERR("%s", "failed to eval\n");
2222
0
            return false;
2223
0
        }
2224
0
        n_past += n_new;
2225
0
    }
2226
2227
0
    return true;
2228
0
}
2229
2230
0
size_t common_prompt_checkpoint::size() const {
2231
0
    return data_tgt.size() + data_dft.size() + data_spec.size();
2232
0
}
2233
2234
0
bool common_prompt_checkpoint::empty() const {
2235
0
    return data_tgt.empty();
2236
0
}
2237
2238
0
void common_prompt_checkpoint::clear() {
2239
0
    n_tokens = 0;
2240
2241
0
    pos_min = 0;
2242
0
    pos_max = 0;
2243
2244
0
    data_tgt.clear();
2245
0
    data_dft.clear();
2246
0
    data_spec.clear();
2247
0
}
2248
2249
void common_prompt_checkpoint::update_pos(
2250
        int64_t n_tokens,
2251
        llama_pos pos_min,
2252
0
        llama_pos pos_max) {
2253
0
    this->n_tokens = n_tokens;
2254
0
    this->pos_min  = pos_min;
2255
0
    this->pos_max  = pos_max;
2256
0
}
2257
2258
void common_prompt_checkpoint::update_tgt(
2259
        llama_context * ctx,
2260
        llama_seq_id seq_id,
2261
0
        llama_state_seq_flags flags) {
2262
0
    if (ctx == nullptr) {
2263
0
        return;
2264
0
    }
2265
2266
0
    const size_t ckpt_size = llama_state_seq_get_size_ext(ctx, seq_id, flags);
2267
2268
0
    data_tgt.resize(ckpt_size);
2269
2270
0
    const size_t n = llama_state_seq_get_data_ext(ctx, data_tgt.data(), ckpt_size, seq_id, flags);
2271
0
    if (n != ckpt_size) {
2272
0
        GGML_ABORT("checkpoint size mismatch: expected %zu, got %zu\n", ckpt_size, n);
2273
0
    }
2274
0
}
2275
2276
void common_prompt_checkpoint::update_dft(
2277
        llama_context * ctx,
2278
        llama_seq_id seq_id,
2279
0
        llama_state_seq_flags flags) {
2280
0
    if (ctx == nullptr) {
2281
0
        return;
2282
0
    }
2283
2284
0
    const size_t ckpt_size = llama_state_seq_get_size_ext(ctx, seq_id, flags);
2285
2286
0
    data_dft.resize(ckpt_size);
2287
2288
0
    const size_t n = llama_state_seq_get_data_ext(ctx, data_dft.data(), ckpt_size, seq_id, flags);
2289
0
    if (n != ckpt_size) {
2290
0
        GGML_ABORT("checkpoint size mismatch: expected %zu, got %zu\n", ckpt_size, n);
2291
0
    }
2292
0
}
2293
2294
void common_prompt_checkpoint::load_tgt(
2295
        llama_context * ctx,
2296
        llama_seq_id seq_id,
2297
0
        llama_state_seq_flags flags) const {
2298
0
    if (ctx == nullptr) {
2299
0
        return;
2300
0
    }
2301
2302
0
    if (data_tgt.empty()) {
2303
0
        return;
2304
0
    }
2305
2306
0
    const size_t n = llama_state_seq_set_data_ext(ctx, data_tgt.data(), data_tgt.size(), seq_id, flags);
2307
0
    if (n != data_tgt.size()) {
2308
0
        GGML_ABORT("checkpoint size mismatch: expected %zu, got %zu\n", data_tgt.size(), n);
2309
0
    }
2310
0
}
2311
2312
void common_prompt_checkpoint::load_dft(
2313
        llama_context * ctx,
2314
        llama_seq_id seq_id,
2315
0
        llama_state_seq_flags flags) const {
2316
0
    if (ctx == nullptr) {
2317
0
        return;
2318
0
    }
2319
2320
0
    if (data_dft.empty()) {
2321
0
        return;
2322
0
    }
2323
2324
0
    const size_t n = llama_state_seq_set_data_ext(ctx, data_dft.data(), data_dft.size(), seq_id, flags);
2325
0
    if (n != data_dft.size()) {
2326
0
        GGML_ABORT("checkpoint size mismatch: expected %zu, got %zu\n", data_dft.size(), n);
2327
0
    }
2328
0
}
2329
2330
0
void common_prompt_checkpoint::clear_tgt() {
2331
0
    data_tgt.clear();
2332
0
}
2333
2334
0
void common_prompt_checkpoint::clear_dft() {
2335
0
    data_dft.clear();
2336
0
    data_spec.clear();
2337
0
}