Coverage Report

Created: 2026-06-22 06:47

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