Coverage Report

Created: 2026-04-12 06:40

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