Coverage Report

Created: 2026-07-16 06:35

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
0
std::string string_join(const std::vector<std::string> & values, const std::string & separator) {
529
0
    std::ostringstream result;
530
0
    for (size_t i = 0; i < values.size(); ++i) {
531
0
        if (i > 0) {
532
0
            result << separator;
533
0
        }
534
0
        result << values[i];
535
0
    }
536
0
    return result.str();
537
0
}
538
539
0
std::vector<std::string> string_split(const std::string & str, const std::string & delimiter) {
540
0
    std::vector<std::string> parts;
541
0
    size_t start = 0;
542
0
    size_t end = str.find(delimiter);
543
544
0
    while (end != std::string::npos) {
545
0
        parts.push_back(str.substr(start, end - start));
546
0
        start = end + delimiter.length();
547
0
        end = str.find(delimiter, start);
548
0
    }
549
550
0
    parts.push_back(str.substr(start));
551
552
0
    return parts;
553
0
}
554
555
0
std::string string_repeat(const std::string & str, size_t n) {
556
0
    if (n == 0) {
557
0
        return "";
558
0
    }
559
560
0
    std::string result;
561
0
    result.reserve(str.length() * n);
562
563
0
    for (size_t i = 0; i < n; ++i) {
564
0
        result += str;
565
0
    }
566
567
0
    return result;
568
0
}
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 fs_get_cache_directory() {
1002
0
    std::string cache_directory = "";
1003
0
    auto ensure_trailing_slash = [](std::string p) {
1004
        // Make sure to add trailing slash
1005
0
        if (p.back() != DIRECTORY_SEPARATOR) {
1006
0
            p += DIRECTORY_SEPARATOR;
1007
0
        }
1008
0
        return p;
1009
0
    };
1010
0
    if (getenv("LLAMA_CACHE")) {
1011
0
        cache_directory = std::getenv("LLAMA_CACHE");
1012
0
    } else {
1013
0
#if defined(__linux__) || defined(__FreeBSD__) || defined(_AIX) || \
1014
0
        defined(__OpenBSD__) || defined(__NetBSD__)
1015
0
        if (std::getenv("XDG_CACHE_HOME")) {
1016
0
            cache_directory = std::getenv("XDG_CACHE_HOME");
1017
0
        } else if (std::getenv("HOME")) {
1018
0
            cache_directory = std::getenv("HOME") + std::string("/.cache/");
1019
0
        } else {
1020
0
#if defined(__linux__)
1021
            /* no $HOME is defined, fallback to getpwuid */
1022
0
            struct passwd *pw = getpwuid(getuid());
1023
0
            if ((!pw) || (!pw->pw_dir)) {
1024
0
                throw std::runtime_error("Failed to find $HOME directory");
1025
0
            }
1026
1027
0
            cache_directory = std::string(pw->pw_dir) + std::string("/.cache/");
1028
#else /* defined(__linux__) */
1029
            throw std::runtime_error("Failed to find $HOME directory");
1030
#endif /* defined(__linux__) */
1031
0
        }
1032
#elif defined(__APPLE__)
1033
        cache_directory = std::getenv("HOME") + std::string("/Library/Caches/");
1034
#elif defined(_WIN32)
1035
        cache_directory = std::getenv("LOCALAPPDATA");
1036
#elif defined(__EMSCRIPTEN__)
1037
        GGML_ABORT("not implemented on this platform");
1038
#else
1039
#  error Unknown architecture
1040
#endif
1041
0
        cache_directory = ensure_trailing_slash(cache_directory);
1042
0
        cache_directory += "llama.cpp";
1043
0
    }
1044
0
    return ensure_trailing_slash(cache_directory);
1045
0
}
1046
1047
0
std::string fs_get_cache_file(const std::string & filename) {
1048
0
    GGML_ASSERT(filename.find(DIRECTORY_SEPARATOR) == std::string::npos);
1049
0
    std::string cache_directory = fs_get_cache_directory();
1050
0
    const bool success = fs_create_directory_with_parents(cache_directory);
1051
0
    if (!success) {
1052
0
        throw std::runtime_error("failed to create cache directory: " + cache_directory);
1053
0
    }
1054
0
    return cache_directory + filename;
1055
0
}
1056
1057
0
std::vector<common_file_info> fs_list(const std::string & path, bool include_directories) {
1058
0
    std::vector<common_file_info> files;
1059
0
    if (path.empty()) return files;
1060
1061
0
    std::filesystem::path dir(path);
1062
0
    if (!std::filesystem::exists(dir) || !std::filesystem::is_directory(dir)) {
1063
0
        return files;
1064
0
    }
1065
1066
0
    for (const auto & entry : std::filesystem::directory_iterator(dir)) {
1067
0
        try {
1068
            // Only include regular files (skip directories)
1069
0
            const auto & p = entry.path();
1070
0
            if (std::filesystem::is_regular_file(p)) {
1071
0
                common_file_info info;
1072
0
                info.path   = p.string();
1073
0
                info.name   = p.filename().string();
1074
0
                info.is_dir = false;
1075
0
                try {
1076
0
                    info.size = static_cast<size_t>(std::filesystem::file_size(p));
1077
0
                } catch (const std::filesystem::filesystem_error &) {
1078
0
                    info.size = 0;
1079
0
                }
1080
0
                files.push_back(std::move(info));
1081
0
            } else if (include_directories && std::filesystem::is_directory(p)) {
1082
0
                common_file_info info;
1083
0
                info.path   = p.string();
1084
0
                info.name   = p.filename().string();
1085
0
                info.size   = 0; // Directories have no size
1086
0
                info.is_dir = true;
1087
0
                files.push_back(std::move(info));
1088
0
            }
1089
0
        } catch (const std::filesystem::filesystem_error &) {
1090
            // skip entries we cannot inspect
1091
0
            continue;
1092
0
        }
1093
0
    }
1094
1095
0
    return files;
1096
0
}
1097
1098
0
std::ifstream fs_open_ifstream(const std::string & fname, std::ios_base::openmode mode) {
1099
#ifdef _WIN32
1100
    int wlen = MultiByteToWideChar(CP_UTF8, 0, fname.c_str(), -1, NULL, 0);
1101
    if (!wlen) { return std::ifstream(); }
1102
    std::vector<wchar_t> wfname(wlen);
1103
    (void)MultiByteToWideChar(CP_UTF8, 0, fname.c_str(), -1, wfname.data(), wlen);
1104
    return std::ifstream(wfname.data(), mode);
1105
#else
1106
0
    return std::ifstream(fname, mode);
1107
0
#endif
1108
0
}
1109
1110
//
1111
// TTY utils
1112
//
1113
1114
0
bool tty_can_use_colors() {
1115
    // Check NO_COLOR environment variable (https://no-color.org/)
1116
0
    if (const char * no_color = std::getenv("NO_COLOR")) {
1117
0
        if (no_color[0] != '\0') {
1118
0
            return false;
1119
0
        }
1120
0
    }
1121
1122
    // Check TERM environment variable
1123
0
    if (const char * term = std::getenv("TERM")) {
1124
0
        if (std::strcmp(term, "dumb") == 0) {
1125
0
            return false;
1126
0
        }
1127
0
    }
1128
1129
    // Check if stdout and stderr are connected to a terminal
1130
    // We check both because log messages can go to either
1131
0
    bool stdout_is_tty = isatty(fileno(stdout));
1132
0
    bool stderr_is_tty = isatty(fileno(stderr));
1133
1134
0
    return stdout_is_tty || stderr_is_tty;
1135
0
}
1136
1137
//
1138
// Model utils
1139
//
1140
1141
// TODO: move to common/sampling
1142
static void common_init_sampler_from_model(
1143
    const llama_model * model,
1144
0
    common_params_sampling & sparams) {
1145
1146
0
    const uint64_t config = sparams.user_sampling_config;
1147
1148
0
    auto get_int32 = [&](const char * key, int32_t & dst, uint64_t user_config) {
1149
0
        if (config & user_config) {
1150
0
            return;
1151
0
        }
1152
1153
0
        char buf[64] = {0};
1154
0
        if (llama_model_meta_val_str(model, key, buf, sizeof(buf)) > 0) {
1155
0
            char * end = nullptr;
1156
0
            int32_t v = strtol(buf, &end, 10);
1157
0
            if (end && end != buf) {
1158
0
                dst = v;
1159
0
            }
1160
0
        }
1161
0
    };
1162
1163
0
    auto get_float = [&](const char * key, float & dst, uint64_t user_config) {
1164
0
        if (config & user_config) {
1165
0
            return;
1166
0
        }
1167
1168
0
        char buf[128] = {0};
1169
0
        if (llama_model_meta_val_str(model, key, buf, sizeof(buf)) > 0) {
1170
0
            char * end = nullptr;
1171
0
            float v = strtof(buf, &end);
1172
0
            if (end && end != buf) {
1173
0
                dst = v;
1174
0
            }
1175
0
        }
1176
0
    };
1177
1178
    // Sampling sequence
1179
0
    if (!(config & common_params_sampling_config::COMMON_PARAMS_SAMPLING_CONFIG_SAMPLERS)) {
1180
0
        char buf[512] = {0};
1181
0
        if (llama_model_meta_val_str(model, llama_model_meta_key_str(LLAMA_MODEL_META_KEY_SAMPLING_SEQUENCE), buf, sizeof(buf)) > 0) {
1182
0
            const std::vector<std::string> sampler_names = string_split<std::string>(std::string(buf), ';');
1183
0
            if (!sampler_names.empty()) {
1184
0
                sparams.samplers = common_sampler_types_from_names(sampler_names);
1185
0
            }
1186
0
        }
1187
0
    }
1188
1189
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);
1190
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);
1191
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);
1192
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);
1193
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);
1194
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);
1195
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);
1196
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);
1197
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);
1198
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);
1199
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);
1200
0
}
1201
1202
struct common_init_result::impl {
1203
    impl() = default;
1204
0
    ~impl() = default;
1205
1206
    // note: the order in which model, context, etc. are declared matters because their destructors will be called bottom-to-top
1207
1208
    llama_model_ptr   model;
1209
    llama_context_ptr context;
1210
1211
    std::vector<llama_adapter_lora_ptr> lora;
1212
1213
    std::vector<common_sampler_ptr> samplers;
1214
    std::vector<llama_sampler_seq_config> samplers_seq_config;
1215
};
1216
1217
common_init_result::common_init_result(common_params & params, bool model_only) :
1218
0
    pimpl(new impl{}) {
1219
0
    auto mparams = common_model_params_to_llama(params);
1220
0
    auto cparams = common_context_params_to_llama(params);
1221
1222
0
    if (params.fit_params) {
1223
0
        COM_TRC("%s", "fitting params to device memory ...\n");
1224
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");
1225
0
        common_fit_params(params.model.path.c_str(), &mparams, &cparams,
1226
0
            params.tensor_split,
1227
0
            params.tensor_buft_overrides.data(),
1228
0
            params.fit_params_target.data(),
1229
0
            params.fit_params_min_ctx,
1230
0
            params.verbosity >= LOG_LEVEL_DEBUG ? GGML_LOG_LEVEL_DEBUG : GGML_LOG_LEVEL_ERROR);
1231
0
    }
1232
1233
0
    llama_model * model = llama_model_load_from_file(params.model.path.c_str(), mparams);
1234
0
    if (model == NULL) {
1235
0
        return;
1236
0
    }
1237
1238
0
    pimpl->model.reset(model);
1239
1240
0
    if (model_only) {
1241
0
        return;
1242
0
    }
1243
1244
0
    const llama_vocab * vocab = llama_model_get_vocab(model);
1245
1246
    // load and optionally apply lora adapters
1247
0
    for (auto & la : params.lora_adapters) {
1248
0
        llama_adapter_lora_ptr lora;
1249
0
        lora.reset(llama_adapter_lora_init(model, la.path.c_str()));
1250
0
        if (lora == nullptr) {
1251
0
            COM_ERR("failed to load lora adapter '%s'\n", la.path.c_str());
1252
0
            pimpl->model.reset(model);
1253
0
            return;
1254
0
        }
1255
1256
0
        char buf[1024];
1257
0
        la.ptr = lora.get();
1258
0
        llama_adapter_meta_val_str(la.ptr, "adapter.lora.task_name", buf, sizeof(buf));
1259
0
        la.task_name = buf;
1260
0
        llama_adapter_meta_val_str(la.ptr, "adapter.lora.prompt_prefix", buf, sizeof(buf));
1261
0
        la.prompt_prefix = buf;
1262
0
        pimpl->lora.emplace_back(std::move(lora)); // copy to list of loaded adapters
1263
0
    }
1264
1265
    // updates params.sampling
1266
    // TODO: fix naming
1267
0
    common_init_sampler_from_model(model, params.sampling);
1268
1269
0
    if (params.sampling.ignore_eos && llama_vocab_eos(vocab) == LLAMA_TOKEN_NULL) {
1270
0
        COM_WRN("%s", "vocab does not have an EOS token, ignoring --ignore-eos\n");
1271
0
        params.sampling.ignore_eos = false;
1272
0
    }
1273
1274
    // initialize once
1275
0
    for (llama_token i = 0; i < llama_vocab_n_tokens(vocab); i++) {
1276
0
        if (llama_vocab_is_eog(vocab, i)) {
1277
0
            COM_TRC("added %s logit bias = %f\n", common_token_to_piece(vocab, i).c_str(), -INFINITY);
1278
0
            params.sampling.logit_bias_eog.push_back({i, -INFINITY});
1279
0
        }
1280
0
    }
1281
1282
0
    if (params.sampling.ignore_eos) {
1283
        // add EOG biases to the active set of logit biases
1284
0
        params.sampling.logit_bias.insert(
1285
0
                params.sampling.logit_bias.end(),
1286
0
                params.sampling.logit_bias_eog.begin(), params.sampling.logit_bias_eog.end());
1287
0
    }
1288
1289
    //if (params.sampling.penalty_last_n == -1) {
1290
    //    LOG_TRC("%s: setting penalty_last_n to ctx_size = %d\n", __func__, llama_n_ctx(lctx));
1291
    //    params.sampling.penalty_last_n = llama_n_ctx(lctx);
1292
    //}
1293
1294
    //if (params.sampling.dry_penalty_last_n == -1) {
1295
    //    LOG_TRC("%s: setting dry_penalty_last_n to ctx_size = %d\n", __func__, llama_n_ctx(lctx));
1296
    //    params.sampling.dry_penalty_last_n = llama_n_ctx(lctx);
1297
    //}
1298
1299
    // init the backend samplers as part of the context creation
1300
0
    pimpl->samplers.resize(cparams.n_seq_max);
1301
0
    pimpl->samplers_seq_config.resize(cparams.n_seq_max);
1302
1303
0
    for (int i = 0; i < (int) cparams.n_seq_max; ++i) {
1304
0
        pimpl->samplers[i].reset(common_sampler_init(model, params.sampling));
1305
0
        pimpl->samplers_seq_config[i] = { i, common_sampler_get(pimpl->samplers[i].get()) };
1306
0
    }
1307
1308
0
    if (params.sampling.backend_sampling) {
1309
0
        cparams.samplers   = pimpl->samplers_seq_config.data();
1310
0
        cparams.n_samplers = pimpl->samplers_seq_config.size();
1311
0
    }
1312
1313
0
    llama_context * lctx = llama_init_from_model(model, cparams);
1314
0
    if (lctx == NULL) {
1315
0
        COM_ERR("failed to create context with model '%s'\n", params.model.path.c_str());
1316
0
        return;
1317
0
    }
1318
1319
0
    pimpl->context.reset(lctx);
1320
0
}
1321
1322
0
llama_model * common_init_result::model() {
1323
0
    return pimpl->model.get();
1324
0
}
1325
1326
0
llama_context * common_init_result::context() {
1327
0
    return pimpl->context.get();
1328
0
}
1329
1330
0
common_sampler * common_init_result::sampler(llama_seq_id seq_id) {
1331
0
    if (seq_id < 0 || seq_id >= (int) pimpl->samplers.size()) {
1332
0
        return nullptr;
1333
0
    }
1334
0
    return pimpl->samplers[seq_id].get();
1335
0
}
1336
1337
0
void common_init_result::reset_samplers() {
1338
0
    for (int i = 0; i < (int) pimpl->samplers.size(); ++i) {
1339
0
        llama_sampler_reset(common_sampler_get(pimpl->samplers[i].get()));
1340
0
    }
1341
0
}
1342
1343
0
std::vector<llama_adapter_lora_ptr> & common_init_result::lora() {
1344
0
    return pimpl->lora;
1345
0
}
1346
1347
0
common_init_result_ptr common_init_from_params(common_params & params, bool model_only) {
1348
0
    common_init_result_ptr res(new common_init_result(params, model_only));
1349
1350
0
    llama_model * model = res->model();
1351
0
    if (model == NULL) {
1352
0
        COM_ERR("failed to load model '%s'\n", params.model.path.c_str());
1353
0
        return res;
1354
0
    }
1355
1356
0
    if (model_only) {
1357
0
        return res;
1358
0
    }
1359
1360
0
    llama_context * lctx = res->context();
1361
0
    if (lctx == NULL) {
1362
0
        COM_ERR("failed to create context with model '%s'\n", params.model.path.c_str());
1363
0
        return res;
1364
0
    }
1365
1366
0
    const llama_vocab * vocab = llama_model_get_vocab(model);
1367
1368
0
    if (params.ctx_shift && !llama_memory_can_shift(llama_get_memory(lctx))) {
1369
0
        COM_WRN("%s", "KV cache shifting is not supported for this context, disabling KV cache shifting\n");
1370
0
        params.ctx_shift = false;
1371
0
    }
1372
1373
0
    if (!params.control_vectors.empty()) {
1374
0
        if (params.control_vector_layer_start <= 0) params.control_vector_layer_start = 1;
1375
0
        if (params.control_vector_layer_end   <= 0) params.control_vector_layer_end   = llama_model_n_layer(model);
1376
1377
0
        const auto cvec = common_control_vector_load(params.control_vectors);
1378
0
        if (cvec.n_embd == -1) {
1379
0
            return res;
1380
0
        }
1381
1382
0
        int err = llama_set_adapter_cvec(
1383
0
                lctx,
1384
0
                cvec.data.data(),
1385
0
                cvec.data.size(),
1386
0
                cvec.n_embd,
1387
0
                params.control_vector_layer_start,
1388
0
                params.control_vector_layer_end);
1389
0
        if (err) {
1390
0
            return res;
1391
0
        }
1392
0
    }
1393
1394
0
    if (llama_pooling_type(lctx) == LLAMA_POOLING_TYPE_RANK) {
1395
0
        bool ok = true;
1396
1397
0
        if (llama_vocab_bos(vocab) == LLAMA_TOKEN_NULL) {
1398
0
            COM_WRN("%s", "vocab does not have a  BOS token, reranking will not work\n");
1399
0
            ok = false;
1400
0
        }
1401
1402
0
        bool has_eos = llama_vocab_eos(vocab) != LLAMA_TOKEN_NULL;
1403
0
        bool has_sep = llama_vocab_sep(vocab) != LLAMA_TOKEN_NULL;
1404
0
        bool has_rerank_prompt = llama_model_chat_template(model, "rerank") != NULL;
1405
1406
0
        if (!has_eos && !has_sep && !has_rerank_prompt) {
1407
0
            COM_WRN("%s", "vocab does not have an EOS token, SEP token, or rerank prompt. Reranking will not work\n");
1408
0
            ok = false;
1409
0
        } else if (!has_eos) {
1410
0
            COM_WRN("%s", "vocab does not have an EOS token, using SEP token as fallback\n");
1411
0
        }
1412
1413
0
        if (!ok) {
1414
0
            return res;
1415
0
        }
1416
0
    }
1417
1418
0
    if (!params.lora_init_without_apply) {
1419
0
        common_set_adapter_lora(lctx, params.lora_adapters);
1420
0
    }
1421
1422
0
    if (params.warmup) {
1423
0
        COM_TRC("%s", "warming up the model with an empty run - please wait ... (--no-warmup to disable)\n");
1424
1425
0
        std::vector<llama_token> tmp;
1426
0
        llama_token bos = llama_vocab_bos(vocab);
1427
0
        llama_token eos = llama_vocab_eos(vocab);
1428
1429
        // some models (e.g. T5) don't have a BOS token
1430
0
        if (bos != LLAMA_TOKEN_NULL) {
1431
0
            tmp.push_back(bos);
1432
0
        }
1433
0
        if (eos != LLAMA_TOKEN_NULL) {
1434
0
            tmp.push_back(eos);
1435
0
        }
1436
0
        if (tmp.empty()) {
1437
0
            tmp.push_back(0);
1438
0
        }
1439
1440
0
        if (llama_model_has_encoder(model)) {
1441
0
            llama_encode(lctx, llama_batch_get_one(tmp.data(), tmp.size()));
1442
0
            llama_token decoder_start_token_id = llama_model_decoder_start_token(model);
1443
0
            if (decoder_start_token_id == LLAMA_TOKEN_NULL) {
1444
0
                decoder_start_token_id = bos;
1445
0
            }
1446
0
            tmp.clear();
1447
0
            tmp.push_back(decoder_start_token_id);
1448
0
        }
1449
0
        if (llama_model_has_decoder(model)) {
1450
0
            llama_decode(lctx, llama_batch_get_one(tmp.data(), std::min(tmp.size(), (size_t) params.n_batch)));
1451
0
        }
1452
0
        llama_memory_clear(llama_get_memory(lctx), true);
1453
0
        llama_synchronize(lctx);
1454
0
        llama_perf_context_reset(lctx);
1455
1456
        // reset samplers to reset RNG state after warmup to the seeded state
1457
0
        res->reset_samplers();
1458
0
    }
1459
1460
0
    return res;
1461
0
}
1462
1463
0
common_init_result::~common_init_result() = default;
1464
1465
0
std::string common_get_model_endpoint() {
1466
0
    const char * model_endpoint_env = getenv("MODEL_ENDPOINT");
1467
    // We still respect the use of environment-variable "HF_ENDPOINT" for backward-compatibility.
1468
0
    const char * hf_endpoint_env = getenv("HF_ENDPOINT");
1469
0
    const char * endpoint_env = model_endpoint_env ? model_endpoint_env : hf_endpoint_env;
1470
0
    std::string model_endpoint = "https://huggingface.co/";
1471
0
    if (endpoint_env) {
1472
0
        model_endpoint = endpoint_env;
1473
0
        if (model_endpoint.back() != '/') {
1474
0
            model_endpoint += '/';
1475
0
        }
1476
0
    }
1477
0
    return model_endpoint;
1478
0
}
1479
1480
0
common_context_seq_rm_type common_context_can_seq_rm(llama_context * ctx) {
1481
0
    auto * mem = llama_get_memory(ctx);
1482
0
    if (mem == nullptr) {
1483
0
        return COMMON_CONTEXT_SEQ_RM_TYPE_NO;
1484
0
    }
1485
1486
0
    common_context_seq_rm_type res = COMMON_CONTEXT_SEQ_RM_TYPE_PART;
1487
1488
0
    llama_memory_clear(mem, true);
1489
1490
    // eval 2 tokens to check if the context is compatible
1491
0
    std::vector<llama_token> tmp;
1492
0
    tmp.push_back(0);
1493
0
    tmp.push_back(0);
1494
1495
0
    int ret = llama_decode(ctx, llama_batch_get_one(tmp.data(), tmp.size()));
1496
0
    if (ret != 0) {
1497
0
        COM_ERR("llama_decode() failed: %d\n", ret);
1498
0
        res = COMMON_CONTEXT_SEQ_RM_TYPE_NO;
1499
0
        goto done;
1500
0
    }
1501
1502
0
    if (llama_n_rs_seq(ctx) > 0) {
1503
0
        COM_TRC("%s", "the context supports bounded partial sequence removal\n");
1504
0
        res = COMMON_CONTEXT_SEQ_RM_TYPE_RS;
1505
0
        goto done;
1506
0
    }
1507
1508
    // try to remove the last tokens
1509
0
    if (!llama_memory_seq_rm(mem, 0, 1, -1)) {
1510
0
        COM_TRC("%s", "the context does not support partial sequence removal\n");
1511
0
        res = COMMON_CONTEXT_SEQ_RM_TYPE_FULL;
1512
0
        goto done;
1513
0
    }
1514
1515
0
done:
1516
0
    llama_memory_clear(mem, true);
1517
0
    llama_synchronize(ctx);
1518
1519
0
    return res;
1520
0
}
1521
1522
0
void common_context_seq_rm(llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1) {
1523
0
    auto * mem = llama_get_memory(ctx);
1524
0
    if (!llama_memory_seq_rm(mem, seq_id, p0, p1)) {
1525
0
        GGML_ABORT("%s", string_format("failed to remove sequence %d with p0=%d, p1=%d\n", seq_id, p0, p1).c_str());
1526
0
    }
1527
0
}
1528
1529
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) {
1530
0
    auto * mem = llama_get_memory(ctx);
1531
0
    llama_memory_seq_cp(mem, seq_id_src, seq_id_dst, p0, p1);
1532
0
}
1533
1534
0
void common_context_seq_add(llama_context * ctx, llama_seq_id seq_id, llama_pos p0, llama_pos p1, llama_pos delta) {
1535
0
    auto * mem = llama_get_memory(ctx);
1536
0
    llama_memory_seq_add(mem, seq_id, p0, p1, delta);
1537
0
}
1538
1539
0
void common_set_adapter_lora(struct llama_context * ctx, std::vector<common_adapter_lora_info> & lora) {
1540
0
    std::vector<llama_adapter_lora *> loras;
1541
0
    std::vector<float> scales;
1542
1543
0
    for (auto & la: lora) {
1544
0
        loras.push_back(la.ptr);
1545
0
        scales.push_back(la.scale);
1546
0
    }
1547
1548
0
    llama_set_adapters_lora(ctx, loras.data(), loras.size(), scales.data());
1549
0
}
1550
1551
4.34k
struct llama_model_params common_model_params_to_llama(common_params & params) {
1552
4.34k
    auto mparams = llama_model_default_params();
1553
1554
4.34k
    if (!params.devices.empty()) {
1555
0
        mparams.devices = params.devices.data();
1556
0
    }
1557
1558
4.34k
    mparams.n_gpu_layers    = params.n_gpu_layers;
1559
4.34k
    mparams.main_gpu        = params.main_gpu;
1560
4.34k
    mparams.split_mode      = params.split_mode;
1561
4.34k
    mparams.tensor_split    = params.tensor_split;
1562
4.34k
    mparams.use_mmap        = params.use_mmap;
1563
4.34k
    mparams.use_direct_io   = params.use_direct_io;
1564
4.34k
    mparams.use_mlock       = params.use_mlock;
1565
4.34k
    mparams.check_tensors   = params.check_tensors;
1566
4.34k
    mparams.use_extra_bufts = !params.no_extra_bufts;
1567
4.34k
    mparams.no_host         = params.no_host;
1568
1569
4.34k
    if (params.kv_overrides.empty()) {
1570
4.34k
        mparams.kv_overrides = NULL;
1571
4.34k
    } else {
1572
0
        GGML_ASSERT(params.kv_overrides.back().key[0] == 0 && "KV overrides not terminated with empty key");
1573
0
        mparams.kv_overrides = params.kv_overrides.data();
1574
0
    }
1575
1576
4.34k
    if (params.tensor_buft_overrides.empty()) {
1577
4.34k
        mparams.tensor_buft_overrides = NULL;
1578
4.34k
    } else {
1579
0
        GGML_ASSERT(params.tensor_buft_overrides.back().pattern == nullptr && "Tensor buffer overrides not terminated with empty pattern");
1580
0
        mparams.tensor_buft_overrides = params.tensor_buft_overrides.data();
1581
0
    }
1582
1583
4.34k
    mparams.progress_callback           = params.load_progress_callback;
1584
4.34k
    mparams.progress_callback_user_data = params.load_progress_callback_user_data;
1585
4.34k
    mparams.no_alloc                    = params.no_alloc;
1586
1587
4.34k
    return mparams;
1588
4.34k
}
1589
1590
0
struct llama_context_params common_context_params_to_llama(const common_params & params) {
1591
0
    auto cparams = llama_context_default_params();
1592
1593
0
    cparams.n_ctx             = params.n_ctx;
1594
0
    cparams.n_seq_max         = params.n_parallel;
1595
0
    cparams.n_rs_seq          = params.speculative.need_n_rs_seq();
1596
0
    cparams.n_outputs_max     = std::max(params.n_outputs_max, 0);
1597
0
    cparams.n_batch           = params.n_batch;
1598
0
    cparams.n_ubatch          = params.n_ubatch;
1599
0
    cparams.n_threads         = params.cpuparams.n_threads;
1600
0
    cparams.n_threads_batch   = params.cpuparams_batch.n_threads == -1 ?
1601
0
                                params.cpuparams.n_threads : params.cpuparams_batch.n_threads;
1602
0
    cparams.embeddings        = params.embedding;
1603
0
    cparams.rope_scaling_type = params.rope_scaling_type;
1604
0
    cparams.rope_freq_base    = params.rope_freq_base;
1605
0
    cparams.rope_freq_scale   = params.rope_freq_scale;
1606
0
    cparams.yarn_ext_factor   = params.yarn_ext_factor;
1607
0
    cparams.yarn_attn_factor  = params.yarn_attn_factor;
1608
0
    cparams.yarn_beta_fast    = params.yarn_beta_fast;
1609
0
    cparams.yarn_beta_slow    = params.yarn_beta_slow;
1610
0
    cparams.yarn_orig_ctx     = params.yarn_orig_ctx;
1611
0
    cparams.pooling_type      = params.pooling_type;
1612
0
    cparams.attention_type    = params.attention_type;
1613
0
    cparams.flash_attn_type   = params.flash_attn_type;
1614
0
    cparams.cb_eval           = params.cb_eval;
1615
0
    cparams.cb_eval_user_data = params.cb_eval_user_data;
1616
0
    cparams.offload_kqv       = !params.no_kv_offload;
1617
0
    cparams.no_perf           = params.no_perf;
1618
0
    cparams.op_offload        = !params.no_op_offload;
1619
0
    cparams.swa_full          = params.swa_full;
1620
0
    cparams.kv_unified        = params.kv_unified;
1621
1622
0
    cparams.type_k = params.cache_type_k;
1623
0
    cparams.type_v = params.cache_type_v;
1624
1625
0
    return cparams;
1626
0
}
1627
1628
0
struct ggml_threadpool_params ggml_threadpool_params_from_cpu_params(const common_cpu_params & params) {
1629
0
    struct ggml_threadpool_params tpp;
1630
1631
0
    ggml_threadpool_params_init(&tpp, params.n_threads); // setup the defaults
1632
1633
0
    if (params.mask_valid) {
1634
0
        std::memcpy(&tpp.cpumask, &params.cpumask, GGML_MAX_N_THREADS);
1635
0
    }
1636
1637
0
    tpp.prio       = params.priority;
1638
0
    tpp.poll       = params.poll;
1639
0
    tpp.strict_cpu = params.strict_cpu;
1640
1641
0
    return tpp;
1642
0
}
1643
1644
//
1645
// Batch utils
1646
//
1647
1648
0
void common_batch_clear(struct llama_batch & batch) {
1649
0
    batch.n_tokens = 0;
1650
0
}
1651
1652
void common_batch_add(
1653
                 struct llama_batch & batch,
1654
                        llama_token   id,
1655
                          llama_pos   pos,
1656
    const std::vector<llama_seq_id> & seq_ids,
1657
0
                               bool   logits) {
1658
0
    GGML_ASSERT(batch.seq_id[batch.n_tokens] && "llama_batch size exceeded");
1659
1660
0
    batch.token   [batch.n_tokens] = id;
1661
0
    batch.pos     [batch.n_tokens] = pos;
1662
0
    batch.n_seq_id[batch.n_tokens] = seq_ids.size();
1663
0
    for (size_t i = 0; i < seq_ids.size(); ++i) {
1664
0
        batch.seq_id[batch.n_tokens][i] = seq_ids[i];
1665
0
    }
1666
0
    batch.logits  [batch.n_tokens] = logits;
1667
1668
0
    batch.n_tokens++;
1669
0
}
1670
1671
//
1672
// Vocab utils
1673
//
1674
1675
std::vector<llama_token> common_tokenize(
1676
  const struct llama_context * ctx,
1677
           const std::string & text,
1678
                        bool   add_special,
1679
0
                        bool   parse_special) {
1680
0
    const llama_model * model = llama_get_model(ctx);
1681
0
    const llama_vocab * vocab = llama_model_get_vocab(model);
1682
0
    return common_tokenize(vocab, text, add_special, parse_special);
1683
0
}
1684
1685
std::vector<llama_token> common_tokenize(
1686
    const struct llama_vocab * vocab,
1687
           const std::string & text,
1688
                        bool   add_special,
1689
0
                        bool   parse_special) {
1690
    // upper limit for the number of tokens
1691
0
    int n_tokens = text.length() + 2 * add_special;
1692
0
    std::vector<llama_token> result(n_tokens);
1693
0
    n_tokens = llama_tokenize(vocab, text.data(), text.length(), result.data(), result.size(), add_special, parse_special);
1694
0
    if (n_tokens == std::numeric_limits<int32_t>::min()) {
1695
0
        throw std::runtime_error("Tokenization failed: input text too large, tokenization result exceeds int32_t limit");
1696
0
    }
1697
0
    if (n_tokens < 0) {
1698
0
        result.resize(-n_tokens);
1699
0
        int check = llama_tokenize(vocab, text.data(), text.length(), result.data(), result.size(), add_special, parse_special);
1700
0
        GGML_ASSERT(check == -n_tokens);
1701
0
    } else {
1702
0
        result.resize(n_tokens);
1703
0
    }
1704
0
    return result;
1705
0
}
1706
1707
0
std::string common_token_to_piece(const struct llama_context * ctx, llama_token token, bool special) {
1708
0
    const llama_model * model = llama_get_model(ctx);
1709
0
    const llama_vocab * vocab = llama_model_get_vocab(model);
1710
0
    return common_token_to_piece(vocab, token, special);
1711
0
}
1712
1713
0
std::string common_token_to_piece(const struct llama_vocab * vocab, llama_token token, bool special) {
1714
0
    std::string piece;
1715
0
    piece.resize(piece.capacity());  // using string internal cache, 15 bytes + '\n'
1716
0
    const int n_chars = llama_token_to_piece(vocab, token, &piece[0], piece.size(), 0, special);
1717
0
    if (n_chars < 0) {
1718
0
        piece.resize(-n_chars);
1719
0
        int check = llama_token_to_piece(vocab, token, &piece[0], piece.size(), 0, special);
1720
0
        GGML_ASSERT(check == -n_chars);
1721
0
    }
1722
0
    else {
1723
0
        piece.resize(n_chars);
1724
0
    }
1725
1726
0
    return piece;
1727
0
}
1728
1729
0
std::string common_detokenize(const struct llama_context * ctx, const std::vector<llama_token> & tokens, bool special) {
1730
0
    const llama_model * model = llama_get_model(ctx);
1731
0
    const llama_vocab * vocab = llama_model_get_vocab(model);
1732
0
    return common_detokenize(vocab, tokens, special);
1733
0
}
1734
1735
0
std::string common_detokenize(const struct llama_vocab * vocab, const std::vector<llama_token> & tokens, bool special) {
1736
0
    std::string text;
1737
0
    text.resize(std::max(text.capacity(), tokens.size()));
1738
0
    int32_t n_chars = llama_detokenize(vocab, tokens.data(), (int32_t)tokens.size(), &text[0], (int32_t)text.size(), false, special);
1739
0
    if (n_chars < 0) {
1740
0
        text.resize(-n_chars);
1741
0
        n_chars = llama_detokenize(vocab, tokens.data(), (int32_t)tokens.size(), &text[0], (int32_t)text.size(), false, special);
1742
0
        GGML_ASSERT(n_chars <= (int32_t)text.size());  // whitespace trimming is performed after per-token detokenization
1743
0
    }
1744
1745
0
    text.resize(n_chars);
1746
1747
    // NOTE: the original tokenizer decodes bytes after collecting the pieces.
1748
0
    return text;
1749
0
}
1750
1751
//
1752
// Embedding utils
1753
//
1754
1755
0
void common_embd_normalize(const float * inp, float * out, int n, int embd_norm) {
1756
0
    double sum = 0.0;
1757
1758
0
    switch (embd_norm) {
1759
0
        case -1: // no normalisation
1760
0
            sum = 1.0;
1761
0
            break;
1762
0
        case 0: // max absolute
1763
0
            for (int i = 0; i < n; i++) {
1764
0
                if (sum < std::abs(inp[i])) {
1765
0
                    sum = std::abs(inp[i]);
1766
0
                }
1767
0
            }
1768
0
            sum /= 32760.0; // make an int16 range
1769
0
            break;
1770
0
        case 2: // euclidean
1771
0
            for (int i = 0; i < n; i++) {
1772
0
                sum += inp[i] * inp[i];
1773
0
            }
1774
0
            sum = std::sqrt(sum);
1775
0
            break;
1776
0
        default: // p-norm (euclidean is p-norm p=2)
1777
0
            for (int i = 0; i < n; i++) {
1778
0
                sum += std::pow(std::abs(inp[i]), embd_norm);
1779
0
            }
1780
0
            sum = std::pow(sum, 1.0 / embd_norm);
1781
0
            break;
1782
0
    }
1783
1784
0
    const float norm = sum > 0.0 ? 1.0 / sum : 0.0f;
1785
1786
0
    for (int i = 0; i < n; i++) {
1787
0
        out[i] = inp[i] * norm;
1788
0
    }
1789
0
}
1790
1791
0
float common_embd_similarity_cos(const float * embd1, const float * embd2, int n){
1792
0
    double sum  = 0.0;
1793
0
    double sum1 = 0.0;
1794
0
    double sum2 = 0.0;
1795
1796
0
    for (int i = 0; i < n; i++) {
1797
0
        sum  += embd1[i] * embd2[i];
1798
0
        sum1 += embd1[i] * embd1[i];
1799
0
        sum2 += embd2[i] * embd2[i];
1800
0
    }
1801
1802
    // Handle the case where one or both vectors are zero vectors
1803
0
    if (sum1 == 0.0 || sum2 == 0.0) {
1804
0
        if (sum1 == 0.0 && sum2 == 0.0) {
1805
0
            return 1.0f; // two zero vectors are similar
1806
0
        }
1807
0
        return 0.0f;
1808
0
    }
1809
1810
0
    return sum / (sqrt(sum1) * sqrt(sum2));
1811
0
}
1812
1813
//
1814
// Control vector utils
1815
//
1816
1817
0
static common_control_vector_data common_control_vector_load_one(const common_control_vector_load_info & load_info) {
1818
0
    common_control_vector_data result = { -1, {} };
1819
1820
0
    ggml_context * ctx = nullptr;
1821
0
    struct gguf_init_params meta_gguf_params = {
1822
0
        /* .no_alloc = */ false,
1823
0
        /* .ctx      = */ &ctx,
1824
0
    };
1825
0
    struct gguf_context * ctx_gguf = gguf_init_from_file(load_info.fname.c_str(), meta_gguf_params);
1826
0
    if (!ctx_gguf) {
1827
0
        COM_ERR("failed to load control vector file from %s\n", load_info.fname.c_str());
1828
0
        return result;
1829
0
    }
1830
1831
0
    int32_t n_tensors = gguf_get_n_tensors(ctx_gguf);
1832
0
    if (n_tensors == 0) {
1833
0
        COM_WRN("no direction tensors found in %s\n", load_info.fname.c_str());
1834
0
    }
1835
1836
0
    for (int i = 0; i < n_tensors; i++) {
1837
0
        std::string name = gguf_get_tensor_name(ctx_gguf, i);
1838
1839
0
        int layer_idx = -1;
1840
1841
        // split on '.'
1842
0
        size_t dotpos = name.find('.');
1843
0
        if (dotpos != std::string::npos && name.substr(0, dotpos) == "direction") {
1844
0
            try {
1845
0
                layer_idx = std::stoi(name.substr(dotpos + 1));
1846
0
            } catch (...) {
1847
0
                layer_idx = -1;
1848
0
            }
1849
0
        }
1850
0
        if (layer_idx < 0) {
1851
0
            COM_ERR("invalid/unparsable direction tensor layer index in %s\n", load_info.fname.c_str());
1852
0
            result.n_embd = -1;
1853
0
            break;
1854
0
        } else if (layer_idx == 0) {
1855
0
            COM_ERR("invalid (zero) direction tensor layer index in %s\n", load_info.fname.c_str());
1856
0
            result.n_embd = -1;
1857
0
            break;
1858
0
        }
1859
1860
0
        struct ggml_tensor * tensor = ggml_get_tensor(ctx, name.c_str());
1861
0
        if (tensor->type != GGML_TYPE_F32) {
1862
0
            COM_ERR("invalid (non-F32) direction tensor type in %s\n", load_info.fname.c_str());
1863
0
            result.n_embd = -1;
1864
0
            break;
1865
0
        }
1866
0
        if (ggml_n_dims(tensor) != 1) {
1867
0
            COM_ERR("invalid (non-1D) direction tensor shape in %s\n", load_info.fname.c_str());
1868
0
            result.n_embd = -1;
1869
0
            break;
1870
0
        }
1871
1872
0
        if (result.n_embd == -1) {
1873
0
            result.n_embd = ggml_nelements(tensor);
1874
0
        } else if (ggml_nelements(tensor) != result.n_embd) {
1875
0
            COM_ERR("direction tensor in %s does not match previous dimensions\n", load_info.fname.c_str());
1876
0
            result.n_embd = -1;
1877
0
            break;
1878
0
        }
1879
1880
        // extend if necessary - do not store data for layer 0 (it's not used)
1881
0
        result.data.resize(std::max(result.data.size(), static_cast<size_t>(result.n_embd * layer_idx)), 0.0f);
1882
1883
0
        const float * src = (const float *) tensor->data;
1884
0
        float * dst = result.data.data() + result.n_embd * (layer_idx - 1);  // layer 1 at [0]
1885
0
        for (int j = 0; j < result.n_embd; j++) {
1886
0
            dst[j] += src[j] * load_info.strength;  // allows multiple directions for same layer in same file
1887
0
        }
1888
1889
0
    }
1890
1891
0
    if (result.n_embd == -1) {
1892
0
        COM_WRN("skipping %s due to invalid direction tensors\n", load_info.fname.c_str());
1893
0
        result.data.clear();
1894
0
    }
1895
1896
0
    gguf_free(ctx_gguf);
1897
0
    ggml_free(ctx);
1898
1899
0
    return result;
1900
0
}
1901
1902
0
common_control_vector_data common_control_vector_load(const std::vector<common_control_vector_load_info> & load_infos) {
1903
0
    common_control_vector_data result = { -1, {} };
1904
1905
0
    for (const auto & info : load_infos) {
1906
0
        auto cur = common_control_vector_load_one(info);
1907
1908
0
        if (cur.n_embd == -1) {
1909
0
            result.n_embd = -1;
1910
0
            break;
1911
0
        }
1912
0
        if (result.n_embd != -1 && result.n_embd != cur.n_embd) {
1913
0
            COM_ERR("control vectors in %s does not match previous dimensions\n", info.fname.c_str());
1914
0
            result.n_embd = -1;
1915
0
            break;
1916
0
        }
1917
1918
0
        if (result.n_embd == -1) {
1919
0
            result = std::move(cur);
1920
0
        } else {
1921
0
            result.data.resize(std::max(result.data.size(), cur.data.size()), 0.0f);  // extend if necessary
1922
0
            for (size_t i = 0; i < cur.data.size(); i++) {
1923
0
                result.data[i] += cur.data[i];
1924
0
            }
1925
0
        }
1926
0
    }
1927
1928
0
    if (result.n_embd == -1) {
1929
0
        COM_ERR("%s", "no valid control vector files passed\n");
1930
0
        result.data.clear();
1931
0
    }
1932
1933
0
    return result;
1934
0
}
1935
1936
0
ggml_opt_dataset_t common_opt_dataset_init(struct llama_context * ctx, const std::vector<llama_token> & tokens, int64_t stride) {
1937
0
    const int64_t ne_datapoint = llama_n_ctx(ctx);
1938
0
    const int64_t ndata        = (tokens.size() - ne_datapoint - 1) / stride;
1939
0
    ggml_opt_dataset_t result = ggml_opt_dataset_init(
1940
0
        GGML_TYPE_I32, GGML_TYPE_I32, ne_datapoint, ne_datapoint, ndata, /*ndata_shard =*/ 1);
1941
1942
0
    llama_token * data   = (llama_token *) ggml_opt_dataset_data(result)->data;
1943
0
    llama_token * labels = (llama_token *) ggml_opt_dataset_labels(result)->data;
1944
1945
0
    for (int64_t idata = 0; idata < ndata; ++idata) {
1946
0
        memcpy(data   + idata*ne_datapoint, tokens.data() + idata*stride + 0, ne_datapoint*sizeof(llama_token));
1947
0
        memcpy(labels + idata*ne_datapoint, tokens.data() + idata*stride + 1, ne_datapoint*sizeof(llama_token));
1948
0
    }
1949
1950
0
    return result;
1951
0
}
1952
1953
0
ggml_opt_optimizer_params common_opt_lr_pars(void * userdata) {
1954
0
    ggml_opt_optimizer_params result = ggml_opt_get_default_optimizer_params(nullptr);
1955
0
    const lr_opt &            d      = *(lr_opt *) userdata;
1956
0
    result.adamw.alpha = result.sgd.alpha = d.get_lr(d.epoch);
1957
0
    result.sgd.wd = result.adamw.wd = d.wd;
1958
0
    return result;
1959
0
}
1960
1961
// TODO make all command line args case-insensitive
1962
0
static inline bool eq_case_insensitive(char const* a, char const* b) {
1963
0
    return !
1964
#if defined(_MSC_VER)
1965
        _stricmp
1966
#else
1967
0
        strcasecmp
1968
0
#endif // defined(_MSC_VER)
1969
0
        (a, b);
1970
0
}
1971
1972
0
enum ggml_opt_optimizer_type common_opt_get_optimizer(const char * n) {
1973
0
    if (eq_case_insensitive("adamw", n)) {
1974
0
        return GGML_OPT_OPTIMIZER_TYPE_ADAMW;
1975
0
    }
1976
0
    if (eq_case_insensitive("sgd", n)) {
1977
0
        return GGML_OPT_OPTIMIZER_TYPE_SGD;
1978
0
    }
1979
0
    return GGML_OPT_OPTIMIZER_TYPE_COUNT;
1980
0
}
1981
1982
// TODO simplify to use just log and exp
1983
static float const k_log_2 = std::log(2.f);
1984
1985
0
void lr_opt::init() {
1986
0
    if (lr_min > 0 && lr_min < lr0) {
1987
0
        float nhalf = std::log(lr0 / lr_min) / k_log_2;
1988
0
        float e     = epochs;
1989
0
        if (decay_epochs > 0 && decay_epochs < e) {
1990
0
            e = decay_epochs;
1991
0
        } else {
1992
0
            decay_epochs = e;
1993
0
        }
1994
0
        scale_epoch = nhalf / e;
1995
0
    }
1996
0
}
1997
1998
0
float lr_opt::get_lr(float epoch) const {
1999
0
    float r = lr_min <= 0 ? lr0 :
2000
0
        epoch >= decay_epochs ? lr_min :
2001
0
        lr0 * std::pow(0.5f, epoch * scale_epoch);
2002
0
    LOG_INF("epoch %.2g lr=%.2g\n", epoch, r);
2003
0
    return r;
2004
0
}
2005
2006
0
bool common_replay_last_token(struct llama_context * ctx, llama_token last_token, int32_t pos) {
2007
0
    llama_batch batch = llama_batch_get_one(&last_token, 1);
2008
0
    batch.pos = &pos;
2009
0
    if (llama_decode(ctx, batch)) {
2010
0
        LOG_ERR("%s: failed to replay last token\n", __func__);
2011
0
        return false;
2012
0
    }
2013
0
    return true;
2014
0
}
2015
2016
bool common_prompt_batch_decode(
2017
              struct llama_context * ctx,
2018
    const std::vector<llama_token> & all_tokens,
2019
                               int   n_new,
2020
                               int & n_past,
2021
                               int   n_batch,
2022
                  std::string_view   state_path,
2023
0
                              bool   save_state) {
2024
0
    if (n_new == 0) {
2025
0
        return true;
2026
0
    }
2027
0
    const int offset = all_tokens.size() - n_new;
2028
2029
0
    if (save_state && n_new > 1) {
2030
0
        const int n_tokens_before_last = n_new - 1;
2031
2032
0
        GGML_ASSERT(n_new <= n_batch);
2033
2034
        // Decode all but the last token so we can save the memory state before decoding the last token.
2035
        // This is done so we can restore the session state later and replay the last token.
2036
        // Memory implementations in recurrent/hybrid models don't support removing tokens from their
2037
        // memory, so we can't just remove the last token from the memory and replay the last token which
2038
        // is the reason for this logic.
2039
0
        if (llama_decode(ctx, llama_batch_get_one(const_cast<llama_token*>(all_tokens.data() + offset), n_tokens_before_last))) {
2040
0
            COM_ERR("%s", "failed to eval\n");
2041
0
            return false;
2042
0
        }
2043
0
        n_past += n_tokens_before_last;
2044
2045
0
        llama_state_save_file(ctx, state_path.data(), all_tokens.data(), all_tokens.size());
2046
0
        COM_INF("saved session before last token to %s, n_new = %zu\n", state_path.data(), all_tokens.size());
2047
2048
0
        llama_token last_token = all_tokens.back();
2049
0
        llama_batch batch = llama_batch_get_one(&last_token, 1);
2050
0
        int32_t pos = n_past;
2051
0
        batch.pos = &pos;
2052
2053
0
        if (llama_decode(ctx, batch)) {
2054
0
            COM_ERR("%s", "failed to eval last token\n");
2055
0
            return false;
2056
0
        }
2057
0
        n_past++;
2058
0
    } else {
2059
0
        if (llama_decode(ctx, llama_batch_get_one(const_cast<llama_token*>(all_tokens.data() + offset), n_new))) {
2060
0
            COM_ERR("%s", "failed to eval\n");
2061
0
            return false;
2062
0
        }
2063
0
        n_past += n_new;
2064
0
    }
2065
2066
0
    return true;
2067
0
}
2068
2069
0
size_t common_prompt_checkpoint::size() const {
2070
0
    return data_tgt.size() + data_dft.size() + data_spec.size();
2071
0
}
2072
2073
0
bool common_prompt_checkpoint::empty() const {
2074
0
    return data_tgt.empty();
2075
0
}
2076
2077
0
void common_prompt_checkpoint::clear() {
2078
0
    n_tokens = 0;
2079
2080
0
    pos_min = 0;
2081
0
    pos_max = 0;
2082
2083
0
    data_tgt.clear();
2084
0
    data_dft.clear();
2085
0
    data_spec.clear();
2086
0
}
2087
2088
void common_prompt_checkpoint::update_pos(
2089
        int64_t n_tokens,
2090
        llama_pos pos_min,
2091
0
        llama_pos pos_max) {
2092
0
    this->n_tokens = n_tokens;
2093
0
    this->pos_min  = pos_min;
2094
0
    this->pos_max  = pos_max;
2095
0
}
2096
2097
void common_prompt_checkpoint::update_tgt(
2098
        llama_context * ctx,
2099
        llama_seq_id seq_id,
2100
0
        llama_state_seq_flags flags) {
2101
0
    if (ctx == nullptr) {
2102
0
        return;
2103
0
    }
2104
2105
0
    const size_t ckpt_size = llama_state_seq_get_size_ext(ctx, seq_id, flags);
2106
2107
0
    data_tgt.resize(ckpt_size);
2108
2109
0
    const size_t n = llama_state_seq_get_data_ext(ctx, data_tgt.data(), ckpt_size, seq_id, flags);
2110
0
    if (n != ckpt_size) {
2111
0
        GGML_ABORT("checkpoint size mismatch: expected %zu, got %zu\n", ckpt_size, n);
2112
0
    }
2113
0
}
2114
2115
void common_prompt_checkpoint::update_dft(
2116
        llama_context * ctx,
2117
        llama_seq_id seq_id,
2118
0
        llama_state_seq_flags flags) {
2119
0
    if (ctx == nullptr) {
2120
0
        return;
2121
0
    }
2122
2123
0
    const size_t ckpt_size = llama_state_seq_get_size_ext(ctx, seq_id, flags);
2124
2125
0
    data_dft.resize(ckpt_size);
2126
2127
0
    const size_t n = llama_state_seq_get_data_ext(ctx, data_dft.data(), ckpt_size, seq_id, flags);
2128
0
    if (n != ckpt_size) {
2129
0
        GGML_ABORT("checkpoint size mismatch: expected %zu, got %zu\n", ckpt_size, n);
2130
0
    }
2131
0
}
2132
2133
void common_prompt_checkpoint::load_tgt(
2134
        llama_context * ctx,
2135
        llama_seq_id seq_id,
2136
0
        llama_state_seq_flags flags) const {
2137
0
    if (ctx == nullptr) {
2138
0
        return;
2139
0
    }
2140
2141
0
    if (data_tgt.empty()) {
2142
0
        return;
2143
0
    }
2144
2145
0
    const size_t n = llama_state_seq_set_data_ext(ctx, data_tgt.data(), data_tgt.size(), seq_id, flags);
2146
0
    if (n != data_tgt.size()) {
2147
0
        GGML_ABORT("checkpoint size mismatch: expected %zu, got %zu\n", data_tgt.size(), n);
2148
0
    }
2149
0
}
2150
2151
void common_prompt_checkpoint::load_dft(
2152
        llama_context * ctx,
2153
        llama_seq_id seq_id,
2154
0
        llama_state_seq_flags flags) const {
2155
0
    if (ctx == nullptr) {
2156
0
        return;
2157
0
    }
2158
2159
0
    if (data_dft.empty()) {
2160
0
        return;
2161
0
    }
2162
2163
0
    const size_t n = llama_state_seq_set_data_ext(ctx, data_dft.data(), data_dft.size(), seq_id, flags);
2164
0
    if (n != data_dft.size()) {
2165
0
        GGML_ABORT("checkpoint size mismatch: expected %zu, got %zu\n", data_dft.size(), n);
2166
0
    }
2167
0
}
2168
2169
0
void common_prompt_checkpoint::clear_tgt() {
2170
0
    data_tgt.clear();
2171
0
}
2172
2173
0
void common_prompt_checkpoint::clear_dft() {
2174
0
    data_dft.clear();
2175
0
    data_spec.clear();
2176
0
}