cui-llama.rn 1.3.6 → 1.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. package/README.md +22 -1
  2. package/android/src/main/CMakeLists.txt +25 -26
  3. package/android/src/main/java/com/rnllama/LlamaContext.java +31 -9
  4. package/android/src/main/java/com/rnllama/RNLlama.java +98 -0
  5. package/android/src/main/jni-utils.h +94 -0
  6. package/android/src/main/jni.cpp +133 -63
  7. package/android/src/newarch/java/com/rnllama/RNLlamaModule.java +15 -0
  8. package/android/src/oldarch/java/com/rnllama/RNLlamaModule.java +15 -0
  9. package/cpp/common.cpp +2085 -1982
  10. package/cpp/common.h +696 -664
  11. package/cpp/ggml-alloc.c +1042 -1037
  12. package/cpp/ggml-backend-impl.h +255 -256
  13. package/cpp/ggml-backend-reg.cpp +582 -582
  14. package/cpp/ggml-backend.cpp +2002 -2002
  15. package/cpp/ggml-backend.h +354 -352
  16. package/cpp/ggml-common.h +1853 -1853
  17. package/cpp/ggml-cpp.h +39 -39
  18. package/cpp/ggml-cpu-aarch64.cpp +4247 -4247
  19. package/cpp/ggml-cpu-aarch64.h +8 -8
  20. package/cpp/ggml-cpu-impl.h +386 -386
  21. package/cpp/ggml-cpu-quants.c +10920 -10839
  22. package/cpp/ggml-cpu-traits.cpp +36 -36
  23. package/cpp/ggml-cpu-traits.h +38 -38
  24. package/cpp/ggml-cpu.c +14391 -14122
  25. package/cpp/ggml-cpu.cpp +635 -627
  26. package/cpp/ggml-cpu.h +135 -135
  27. package/cpp/ggml-impl.h +567 -567
  28. package/cpp/ggml-metal-impl.h +288 -0
  29. package/cpp/ggml-metal.m +4884 -4884
  30. package/cpp/ggml-opt.cpp +854 -0
  31. package/cpp/ggml-opt.h +216 -0
  32. package/cpp/ggml-quants.c +5238 -5238
  33. package/cpp/ggml-threading.h +14 -14
  34. package/cpp/ggml.c +6514 -6448
  35. package/cpp/ggml.h +2194 -2163
  36. package/cpp/gguf.cpp +1329 -1325
  37. package/cpp/gguf.h +202 -202
  38. package/cpp/json-schema-to-grammar.cpp +1045 -1045
  39. package/cpp/json-schema-to-grammar.h +8 -8
  40. package/cpp/json.hpp +24766 -24766
  41. package/cpp/llama-adapter.cpp +347 -346
  42. package/cpp/llama-adapter.h +74 -73
  43. package/cpp/llama-arch.cpp +1487 -1434
  44. package/cpp/llama-arch.h +400 -395
  45. package/cpp/llama-batch.cpp +368 -368
  46. package/cpp/llama-batch.h +88 -88
  47. package/cpp/llama-chat.cpp +578 -567
  48. package/cpp/llama-chat.h +52 -51
  49. package/cpp/llama-context.cpp +1775 -1771
  50. package/cpp/llama-context.h +128 -128
  51. package/cpp/llama-cparams.cpp +1 -1
  52. package/cpp/llama-cparams.h +37 -37
  53. package/cpp/llama-cpp.h +30 -30
  54. package/cpp/llama-grammar.cpp +1139 -1139
  55. package/cpp/llama-grammar.h +143 -143
  56. package/cpp/llama-hparams.cpp +71 -71
  57. package/cpp/llama-hparams.h +139 -140
  58. package/cpp/llama-impl.cpp +167 -167
  59. package/cpp/llama-impl.h +61 -61
  60. package/cpp/llama-kv-cache.cpp +718 -718
  61. package/cpp/llama-kv-cache.h +218 -218
  62. package/cpp/llama-mmap.cpp +590 -589
  63. package/cpp/llama-mmap.h +67 -67
  64. package/cpp/llama-model-loader.cpp +1124 -1011
  65. package/cpp/llama-model-loader.h +167 -158
  66. package/cpp/llama-model.cpp +3997 -2202
  67. package/cpp/llama-model.h +370 -391
  68. package/cpp/llama-sampling.cpp +2408 -2406
  69. package/cpp/llama-sampling.h +32 -48
  70. package/cpp/llama-vocab.cpp +3247 -1982
  71. package/cpp/llama-vocab.h +125 -182
  72. package/cpp/llama.cpp +10077 -12544
  73. package/cpp/llama.h +1323 -1285
  74. package/cpp/log.cpp +401 -401
  75. package/cpp/log.h +121 -121
  76. package/cpp/rn-llama.hpp +123 -116
  77. package/cpp/sampling.cpp +505 -500
  78. package/cpp/sgemm.cpp +2597 -2597
  79. package/cpp/sgemm.h +14 -14
  80. package/cpp/speculative.cpp +277 -274
  81. package/cpp/speculative.h +28 -28
  82. package/cpp/unicode.cpp +2 -3
  83. package/ios/RNLlama.mm +47 -0
  84. package/ios/RNLlamaContext.h +3 -1
  85. package/ios/RNLlamaContext.mm +71 -14
  86. package/jest/mock.js +15 -3
  87. package/lib/commonjs/NativeRNLlama.js.map +1 -1
  88. package/lib/commonjs/index.js +33 -37
  89. package/lib/commonjs/index.js.map +1 -1
  90. package/lib/module/NativeRNLlama.js.map +1 -1
  91. package/lib/module/index.js +31 -35
  92. package/lib/module/index.js.map +1 -1
  93. package/lib/typescript/NativeRNLlama.d.ts +26 -6
  94. package/lib/typescript/NativeRNLlama.d.ts.map +1 -1
  95. package/lib/typescript/index.d.ts +21 -36
  96. package/lib/typescript/index.d.ts.map +1 -1
  97. package/llama-rn.podspec +4 -18
  98. package/package.json +2 -3
  99. package/src/NativeRNLlama.ts +32 -13
  100. package/src/index.ts +52 -47
  101. package/cpp/llama.cpp.rej +0 -23
package/cpp/common.cpp CHANGED
@@ -1,1982 +1,2085 @@
1
- #if defined(_MSC_VER)
2
- #define _SILENCE_CXX17_CODECVT_HEADER_DEPRECATION_WARNING
3
- #endif
4
-
5
- #include "ggml.h"
6
- #include "gguf.h"
7
-
8
- #include "common.h"
9
- #include "log.h"
10
- // Change JSON_ASSERT from assert() to LM_GGML_ASSERT:
11
- #define JSON_ASSERT LM_GGML_ASSERT
12
- #include "json.hpp"
13
- #include "json-schema-to-grammar.h"
14
- #include "llama.h"
15
-
16
- #include <algorithm>
17
- #include <cinttypes>
18
- #include <climits>
19
- #include <cmath>
20
- #include <codecvt>
21
- #include <cstdarg>
22
- #include <cstring>
23
- #include <ctime>
24
- #include <filesystem>
25
- #include <fstream>
26
- #include <iostream>
27
- #include <iterator>
28
- #include <regex>
29
- #include <sstream>
30
- #include <string>
31
- #include <thread>
32
- #include <unordered_map>
33
- #include <unordered_set>
34
- #include <vector>
35
-
36
- #if defined(__APPLE__) && defined(__MACH__)
37
- #include <sys/types.h>
38
- #include <sys/sysctl.h>
39
- #endif
40
-
41
- #if defined(_WIN32)
42
- #define WIN32_LEAN_AND_MEAN
43
- #ifndef NOMINMAX
44
- # define NOMINMAX
45
- #endif
46
- #include <locale>
47
- #include <windows.h>
48
- #include <fcntl.h>
49
- #include <io.h>
50
- #else
51
- #include <sys/ioctl.h>
52
- #include <sys/stat.h>
53
- #include <unistd.h>
54
- #endif
55
- #if defined(LLAMA_USE_CURL)
56
- #include <curl/curl.h>
57
- #include <curl/easy.h>
58
- #include <future>
59
- #endif
60
-
61
- // build info
62
- int LLAMA_BUILD_NUMBER = 0;
63
- char const *LLAMA_COMMIT = "unknown";
64
- char const *LLAMA_COMPILER = "unknown";
65
- char const *LLAMA_BUILD_TARGET = "unknown";
66
-
67
- #if defined(_MSC_VER)
68
- #pragma warning(disable: 4244 4267) // possible loss of data
69
- #endif
70
-
71
- #if defined(LLAMA_USE_CURL)
72
- #ifdef __linux__
73
- #include <linux/limits.h>
74
- #elif defined(_WIN32)
75
- # if !defined(PATH_MAX)
76
- # define PATH_MAX MAX_PATH
77
- # endif
78
- #else
79
- #include <sys/syslimits.h>
80
- #endif
81
- #define LLAMA_CURL_MAX_URL_LENGTH 2084 // Maximum URL Length in Chrome: 2083
82
- #endif // LLAMA_USE_CURL
83
-
84
- using json = nlohmann::ordered_json;
85
-
86
- //
87
- // CPU utils
88
- //
89
-
90
- int32_t cpu_get_num_physical_cores() {
91
- #ifdef __linux__
92
- // enumerate the set of thread siblings, num entries is num cores
93
- std::unordered_set<std::string> siblings;
94
- for (uint32_t cpu=0; cpu < UINT32_MAX; ++cpu) {
95
- std::ifstream thread_siblings("/sys/devices/system/cpu/cpu"
96
- + std::to_string(cpu) + "/topology/thread_siblings");
97
- if (!thread_siblings.is_open()) {
98
- break; // no more cpus
99
- }
100
- std::string line;
101
- if (std::getline(thread_siblings, line)) {
102
- siblings.insert(line);
103
- }
104
- }
105
- if (!siblings.empty()) {
106
- return static_cast<int32_t>(siblings.size());
107
- }
108
- #elif defined(__APPLE__) && defined(__MACH__)
109
- int32_t num_physical_cores;
110
- size_t len = sizeof(num_physical_cores);
111
- int result = sysctlbyname("hw.perflevel0.physicalcpu", &num_physical_cores, &len, NULL, 0);
112
- if (result == 0) {
113
- return num_physical_cores;
114
- }
115
- result = sysctlbyname("hw.physicalcpu", &num_physical_cores, &len, NULL, 0);
116
- if (result == 0) {
117
- return num_physical_cores;
118
- }
119
- #elif defined(_WIN32) && (_WIN32_WINNT >= 0x0601) && !defined(__MINGW64__) // windows 7 and later
120
- // TODO: windows + arm64 + mingw64
121
- unsigned int n_threads_win = std::thread::hardware_concurrency();
122
- unsigned int default_threads = n_threads_win > 0 ? (n_threads_win <= 4 ? n_threads_win : n_threads_win / 2) : 4;
123
-
124
- DWORD buffer_size = 0;
125
- if (!GetLogicalProcessorInformationEx(RelationProcessorCore, nullptr, &buffer_size)) {
126
- if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
127
- return default_threads;
128
- }
129
- }
130
-
131
- std::vector<char> buffer(buffer_size);
132
- if (!GetLogicalProcessorInformationEx(RelationProcessorCore, reinterpret_cast<PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX>(buffer.data()), &buffer_size)) {
133
- return default_threads;
134
- }
135
-
136
- int32_t num_physical_cores = 0;
137
- PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX info = reinterpret_cast<PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX>(buffer.data());
138
- while (buffer_size > 0) {
139
- if (info->Relationship == RelationProcessorCore) {
140
- num_physical_cores += info->Processor.GroupCount;
141
- }
142
- buffer_size -= info->Size;
143
- info = reinterpret_cast<PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX>(reinterpret_cast<char*>(info) + info->Size);
144
- }
145
-
146
- return num_physical_cores > 0 ? num_physical_cores : default_threads;
147
- #endif
148
- unsigned int n_threads = std::thread::hardware_concurrency();
149
- return n_threads > 0 ? (n_threads <= 4 ? n_threads : n_threads / 2) : 4;
150
- }
151
-
152
- #if defined(__x86_64__) && defined(__linux__) && !defined(__ANDROID__)
153
- #include <pthread.h>
154
-
155
- static void cpuid(unsigned leaf, unsigned subleaf,
156
- unsigned *eax, unsigned *ebx, unsigned *ecx, unsigned *edx) {
157
- __asm__("movq\t%%rbx,%%rsi\n\t"
158
- "cpuid\n\t"
159
- "xchgq\t%%rbx,%%rsi"
160
- : "=a"(*eax), "=S"(*ebx), "=c"(*ecx), "=d"(*edx)
161
- : "0"(leaf), "2"(subleaf));
162
- }
163
-
164
- static int pin_cpu(int cpu) {
165
- cpu_set_t mask;
166
- CPU_ZERO(&mask);
167
- CPU_SET(cpu, &mask);
168
- return pthread_setaffinity_np(pthread_self(), sizeof(mask), &mask);
169
- }
170
-
171
- static bool is_hybrid_cpu(void) {
172
- unsigned eax, ebx, ecx, edx;
173
- cpuid(7, 0, &eax, &ebx, &ecx, &edx);
174
- return !!(edx & (1u << 15));
175
- }
176
-
177
- static bool is_running_on_efficiency_core(void) {
178
- unsigned eax, ebx, ecx, edx;
179
- cpuid(0x1a, 0, &eax, &ebx, &ecx, &edx);
180
- int intel_atom = 0x20;
181
- int core_type = (eax & 0xff000000u) >> 24;
182
- return core_type == intel_atom;
183
- }
184
-
185
- static int cpu_count_math_cpus(int n_cpu) {
186
- int result = 0;
187
- for (int cpu = 0; cpu < n_cpu; ++cpu) {
188
- if (pin_cpu(cpu)) {
189
- return -1;
190
- }
191
- if (is_running_on_efficiency_core()) {
192
- continue; // efficiency cores harm lockstep threading
193
- }
194
- ++cpu; // hyperthreading isn't useful for linear algebra
195
- ++result;
196
- }
197
- return result;
198
- }
199
-
200
- #endif // __x86_64__ && __linux__
201
-
202
- /**
203
- * Returns number of CPUs on system that are useful for math.
204
- */
205
- int32_t cpu_get_num_math() {
206
- #if defined(__x86_64__) && defined(__linux__) && !defined(__ANDROID__)
207
- int n_cpu = sysconf(_SC_NPROCESSORS_ONLN);
208
- if (n_cpu < 1) {
209
- return cpu_get_num_physical_cores();
210
- }
211
- if (is_hybrid_cpu()) {
212
- cpu_set_t affinity;
213
- if (!pthread_getaffinity_np(pthread_self(), sizeof(affinity), &affinity)) {
214
- int result = cpu_count_math_cpus(n_cpu);
215
- pthread_setaffinity_np(pthread_self(), sizeof(affinity), &affinity);
216
- if (result > 0) {
217
- return result;
218
- }
219
- }
220
- }
221
- #endif
222
- return cpu_get_num_physical_cores();
223
- }
224
-
225
- // Helper for setting process priority
226
-
227
- #if defined(_WIN32)
228
-
229
- bool set_process_priority(enum lm_ggml_sched_priority prio) {
230
- if (prio == LM_GGML_SCHED_PRIO_NORMAL) {
231
- return true;
232
- }
233
-
234
- DWORD p = NORMAL_PRIORITY_CLASS;
235
- switch (prio) {
236
- case LM_GGML_SCHED_PRIO_NORMAL: p = NORMAL_PRIORITY_CLASS; break;
237
- case LM_GGML_SCHED_PRIO_MEDIUM: p = ABOVE_NORMAL_PRIORITY_CLASS; break;
238
- case LM_GGML_SCHED_PRIO_HIGH: p = HIGH_PRIORITY_CLASS; break;
239
- case LM_GGML_SCHED_PRIO_REALTIME: p = REALTIME_PRIORITY_CLASS; break;
240
- }
241
-
242
- if (!SetPriorityClass(GetCurrentProcess(), p)) {
243
- LOG_WRN("failed to set process priority class %d : (%d)\n", prio, (int) GetLastError());
244
- return false;
245
- }
246
-
247
- return true;
248
- }
249
-
250
- #else // MacOS and POSIX
251
- #include <sys/types.h>
252
- #include <sys/resource.h>
253
-
254
- bool set_process_priority(enum lm_ggml_sched_priority prio) {
255
- if (prio == LM_GGML_SCHED_PRIO_NORMAL) {
256
- return true;
257
- }
258
-
259
- int p = 0;
260
- switch (prio) {
261
- case LM_GGML_SCHED_PRIO_NORMAL: p = 0; break;
262
- case LM_GGML_SCHED_PRIO_MEDIUM: p = -5; break;
263
- case LM_GGML_SCHED_PRIO_HIGH: p = -10; break;
264
- case LM_GGML_SCHED_PRIO_REALTIME: p = -20; break;
265
- }
266
-
267
- if (!setpriority(PRIO_PROCESS, 0, p)) {
268
- LOG_WRN("failed to set process priority %d : %s (%d)\n", prio, strerror(errno), errno);
269
- return false;
270
- }
271
- return true;
272
- }
273
-
274
- #endif
275
-
276
- //
277
- // CLI argument parsing
278
- //
279
-
280
-
281
- void postprocess_cpu_params(cpu_params& cpuparams, const cpu_params* role_model) {
282
- int32_t n_set = 0;
283
-
284
- if (cpuparams.n_threads < 0) {
285
- // Assuming everything about cpuparams is invalid
286
- if (role_model != nullptr) {
287
- cpuparams = *role_model;
288
- } else {
289
- cpuparams.n_threads = cpu_get_num_math();
290
- }
291
- }
292
-
293
- for (int32_t i = 0; i < LM_GGML_MAX_N_THREADS; i++) {
294
- if (cpuparams.cpumask[i]) {
295
- n_set++;
296
- }
297
- }
298
-
299
- if (n_set && n_set < cpuparams.n_threads) {
300
- // Not enough set bits, may experience performance issues.
301
- LOG_WRN("Not enough set bits in CPU mask (%d) to satisfy requested thread count: %d\n", n_set, cpuparams.n_threads);
302
- }
303
- }
304
-
305
- bool parse_cpu_range(const std::string & range, bool (&boolmask)[LM_GGML_MAX_N_THREADS]) {
306
- size_t dash_loc = range.find('-');
307
- if (dash_loc == std::string::npos) {
308
- LOG_ERR("Format of CPU range is invalid! Expected [<start>]-[<end>].\n");
309
- return false;
310
- }
311
-
312
- size_t start_i;
313
- size_t end_i;
314
-
315
- if (dash_loc == 0) {
316
- start_i = 0;
317
- } else {
318
- start_i = std::stoull(range.substr(0, dash_loc));
319
- if (start_i >= LM_GGML_MAX_N_THREADS) {
320
- LOG_ERR("Start index out of bounds!\n");
321
- return false;
322
- }
323
- }
324
-
325
- if (dash_loc == range.length() - 1) {
326
- end_i = LM_GGML_MAX_N_THREADS - 1;
327
- } else {
328
- end_i = std::stoull(range.substr(dash_loc + 1));
329
- if (end_i >= LM_GGML_MAX_N_THREADS) {
330
- LOG_ERR("End index out of bounds!\n");
331
- return false;
332
- }
333
- }
334
-
335
- for (size_t i = start_i; i <= end_i; i++) {
336
- boolmask[i] = true;
337
- }
338
-
339
- return true;
340
- }
341
-
342
- bool parse_cpu_mask(const std::string & mask, bool (&boolmask)[LM_GGML_MAX_N_THREADS]) {
343
- // Discard potential 0x prefix
344
- size_t start_i = 0;
345
- if (mask.length() >= 2 && mask.substr(0, 2) == "0x") {
346
- start_i = 2;
347
- }
348
-
349
- size_t num_digits = mask.length() - start_i;
350
- if (num_digits > 128) num_digits = 128;
351
-
352
- size_t end_i = num_digits + start_i;
353
-
354
- for (size_t i = start_i, n = (num_digits*4 - 1); i < end_i; i++, n-=4) {
355
- char c = mask.at(i);
356
- int8_t id = c;
357
-
358
- if ((c >= '0' && c <= '9')) {
359
- id -= '0';
360
- } else if (c >= 'a' && c <= 'f') {
361
- id -= 'a' - 10;
362
- } else if (c >= 'A' && c <= 'F') {
363
- id -= 'A' - 10;
364
- } else {
365
- LOG_ERR("Invalid hex character '%c' at position %d\n", c, int32_t(i));
366
- return false;
367
- }
368
-
369
- boolmask[ n ] = boolmask[ n ] || ((id & 8) != 0);
370
- boolmask[n - 1] = boolmask[n - 1] || ((id & 4) != 0);
371
- boolmask[n - 2] = boolmask[n - 2] || ((id & 2) != 0);
372
- boolmask[n - 3] = boolmask[n - 3] || ((id & 1) != 0);
373
- }
374
-
375
- return true;
376
- }
377
-
378
- void common_init() {
379
- llama_log_set([](lm_ggml_log_level level, const char * text, void * /*user_data*/) {
380
- if (LOG_DEFAULT_LLAMA <= common_log_verbosity_thold) {
381
- common_log_add(common_log_main(), level, "%s", text);
382
- }
383
- }, NULL);
384
-
385
- #ifdef NDEBUG
386
- const char * build_type = "";
387
- #else
388
- const char * build_type = " (debug)";
389
- #endif
390
-
391
- LOG_INF("build: %d (%s) with %s for %s%s\n", LLAMA_BUILD_NUMBER, LLAMA_COMMIT, LLAMA_COMPILER, LLAMA_BUILD_TARGET, build_type);
392
- }
393
-
394
- std::string common_params_get_system_info(const common_params & params) {
395
- std::ostringstream os;
396
-
397
- os << "system_info: n_threads = " << params.cpuparams.n_threads;
398
- if (params.cpuparams_batch.n_threads != -1) {
399
- os << " (n_threads_batch = " << params.cpuparams_batch.n_threads << ")";
400
- }
401
- #if defined(_WIN32) && (_WIN32_WINNT >= 0x0601) && !defined(__MINGW64__) // windows 7 and later
402
- // TODO: windows + arm64 + mingw64
403
- DWORD logicalProcessorCount = GetActiveProcessorCount(ALL_PROCESSOR_GROUPS);
404
- os << " / " << logicalProcessorCount << " | " << llama_print_system_info();
405
- #else
406
- os << " / " << std::thread::hardware_concurrency() << " | " << llama_print_system_info();
407
- #endif
408
-
409
- return os.str();
410
- }
411
-
412
- //
413
- // String utils
414
- //
415
-
416
- std::string string_format(const char * fmt, ...) {
417
- va_list ap;
418
- va_list ap2;
419
- va_start(ap, fmt);
420
- va_copy(ap2, ap);
421
- int size = vsnprintf(NULL, 0, fmt, ap);
422
- LM_GGML_ASSERT(size >= 0 && size < INT_MAX); // NOLINT
423
- std::vector<char> buf(size + 1);
424
- int size2 = vsnprintf(buf.data(), size + 1, fmt, ap2);
425
- LM_GGML_ASSERT(size2 == size);
426
- va_end(ap2);
427
- va_end(ap);
428
- return std::string(buf.data(), size);
429
- }
430
-
431
- std::string string_strip(const std::string & str) {
432
- size_t start = 0;
433
- size_t end = str.size();
434
- while (start < end && std::isspace(str[start])) {
435
- start++;
436
- }
437
- while (end > start && std::isspace(str[end - 1])) {
438
- end--;
439
- }
440
- return str.substr(start, end - start);
441
- }
442
-
443
- std::string string_get_sortable_timestamp() {
444
- using clock = std::chrono::system_clock;
445
-
446
- const clock::time_point current_time = clock::now();
447
- const time_t as_time_t = clock::to_time_t(current_time);
448
- char timestamp_no_ns[100];
449
- std::strftime(timestamp_no_ns, 100, "%Y_%m_%d-%H_%M_%S", std::localtime(&as_time_t));
450
-
451
- const int64_t ns = std::chrono::duration_cast<std::chrono::nanoseconds>(
452
- current_time.time_since_epoch() % 1000000000).count();
453
- char timestamp_ns[11];
454
- snprintf(timestamp_ns, 11, "%09" PRId64, ns);
455
-
456
- return std::string(timestamp_no_ns) + "." + std::string(timestamp_ns);
457
- }
458
-
459
- void string_replace_all(std::string & s, const std::string & search, const std::string & replace) {
460
- if (search.empty()) {
461
- return;
462
- }
463
- std::string builder;
464
- builder.reserve(s.length());
465
- size_t pos = 0;
466
- size_t last_pos = 0;
467
- while ((pos = s.find(search, last_pos)) != std::string::npos) {
468
- builder.append(s, last_pos, pos - last_pos);
469
- builder.append(replace);
470
- last_pos = pos + search.length();
471
- }
472
- builder.append(s, last_pos, std::string::npos);
473
- s = std::move(builder);
474
- }
475
-
476
- std::string string_from(bool value) {
477
- return value ? "true" : "false";
478
- }
479
-
480
- std::string string_from(const std::vector<int> & values) {
481
- std::stringstream buf;
482
-
483
- buf << "[ ";
484
- bool first = true;
485
- for (auto e : values) {
486
- if (first) {
487
- first = false;
488
- } else {
489
- buf << ", ";
490
- }
491
- buf << std::to_string(e);
492
- }
493
- buf << " ]";
494
-
495
- return buf.str();
496
- }
497
-
498
- std::string string_from(const struct llama_context * ctx, const std::vector<llama_token> & tokens) {
499
- std::stringstream buf;
500
-
501
- buf << "[ ";
502
-
503
- bool first = true;
504
- for (const auto & token : tokens) {
505
- if (!first) {
506
- buf << ", ";
507
- } else {
508
- first = false;
509
- }
510
-
511
- auto detokenized = common_token_to_piece(ctx, token);
512
-
513
- detokenized.erase(
514
- std::remove_if(
515
- detokenized.begin(),
516
- detokenized.end(),
517
- [](const unsigned char c) { return !std::isprint(c); }),
518
- detokenized.end());
519
-
520
- buf << "'" << detokenized << "'"
521
- << ":" << std::to_string(token);
522
- }
523
-
524
- buf << " ]";
525
-
526
- return buf.str();
527
- }
528
-
529
- std::string string_from(const struct llama_context * ctx, const struct llama_batch & batch) {
530
- std::stringstream buf;
531
-
532
- buf << "[ ";
533
-
534
- bool first = true;
535
- for (int i = 0; i < batch.n_tokens; ++i) {
536
- if (!first) {
537
- buf << ", ";
538
- } else {
539
- first = false;
540
- }
541
-
542
- auto detokenized = common_token_to_piece(ctx, batch.token[i]);
543
-
544
- detokenized.erase(
545
- std::remove_if(
546
- detokenized.begin(),
547
- detokenized.end(),
548
- [](const unsigned char c) { return !std::isprint(c); }),
549
- detokenized.end());
550
-
551
- buf << "\n" << std::to_string(i)
552
- << ", token '" << detokenized << "'"
553
- << ", pos " << std::to_string(batch.pos[i])
554
- << ", n_seq_id " << std::to_string(batch.n_seq_id[i])
555
- << ", seq_id " << std::to_string(batch.seq_id[i][0])
556
- << ", logits " << std::to_string(batch.logits[i]);
557
- }
558
-
559
- buf << " ]";
560
-
561
- return buf.str();
562
- }
563
-
564
- void string_process_escapes(std::string & input) {
565
- std::size_t input_len = input.length();
566
- std::size_t output_idx = 0;
567
-
568
- for (std::size_t input_idx = 0; input_idx < input_len; ++input_idx) {
569
- if (input[input_idx] == '\\' && input_idx + 1 < input_len) {
570
- switch (input[++input_idx]) {
571
- case 'n': input[output_idx++] = '\n'; break;
572
- case 'r': input[output_idx++] = '\r'; break;
573
- case 't': input[output_idx++] = '\t'; break;
574
- case '\'': input[output_idx++] = '\''; break;
575
- case '\"': input[output_idx++] = '\"'; break;
576
- case '\\': input[output_idx++] = '\\'; break;
577
- case 'x':
578
- // Handle \x12, etc
579
- if (input_idx + 2 < input_len) {
580
- const char x[3] = { input[input_idx + 1], input[input_idx + 2], 0 };
581
- char *err_p = nullptr;
582
- const long val = std::strtol(x, &err_p, 16);
583
- if (err_p == x + 2) {
584
- input_idx += 2;
585
- input[output_idx++] = char(val);
586
- break;
587
- }
588
- }
589
- // fall through
590
- default: input[output_idx++] = '\\';
591
- input[output_idx++] = input[input_idx]; break;
592
- }
593
- } else {
594
- input[output_idx++] = input[input_idx];
595
- }
596
- }
597
-
598
- input.resize(output_idx);
599
- }
600
-
601
- bool string_parse_kv_override(const char * data, std::vector<llama_model_kv_override> & overrides) {
602
- const char * sep = strchr(data, '=');
603
- if (sep == nullptr || sep - data >= 128) {
604
- LOG_ERR("%s: malformed KV override '%s'\n", __func__, data);
605
- return false;
606
- }
607
- llama_model_kv_override kvo;
608
- std::strncpy(kvo.key, data, sep - data);
609
- kvo.key[sep - data] = 0;
610
- sep++;
611
- if (strncmp(sep, "int:", 4) == 0) {
612
- sep += 4;
613
- kvo.tag = LLAMA_KV_OVERRIDE_TYPE_INT;
614
- kvo.val_i64 = std::atol(sep);
615
- } else if (strncmp(sep, "float:", 6) == 0) {
616
- sep += 6;
617
- kvo.tag = LLAMA_KV_OVERRIDE_TYPE_FLOAT;
618
- kvo.val_f64 = std::atof(sep);
619
- } else if (strncmp(sep, "bool:", 5) == 0) {
620
- sep += 5;
621
- kvo.tag = LLAMA_KV_OVERRIDE_TYPE_BOOL;
622
- if (std::strcmp(sep, "true") == 0) {
623
- kvo.val_bool = true;
624
- } else if (std::strcmp(sep, "false") == 0) {
625
- kvo.val_bool = false;
626
- } else {
627
- LOG_ERR("%s: invalid boolean value for KV override '%s'\n", __func__, data);
628
- return false;
629
- }
630
- } else if (strncmp(sep, "str:", 4) == 0) {
631
- sep += 4;
632
- kvo.tag = LLAMA_KV_OVERRIDE_TYPE_STR;
633
- if (strlen(sep) > 127) {
634
- LOG_ERR("%s: malformed KV override '%s', value cannot exceed 127 chars\n", __func__, data);
635
- return false;
636
- }
637
- strncpy(kvo.val_str, sep, 127);
638
- kvo.val_str[127] = '\0';
639
- } else {
640
- LOG_ERR("%s: invalid type for KV override '%s'\n", __func__, data);
641
- return false;
642
- }
643
- overrides.emplace_back(std::move(kvo));
644
- return true;
645
- }
646
-
647
- //
648
- // Filesystem utils
649
- //
650
-
651
- // Validate if a filename is safe to use
652
- // To validate a full path, split the path by the OS-specific path separator, and validate each part with this function
653
- bool fs_validate_filename(const std::string & filename) {
654
- if (!filename.length()) {
655
- // Empty filename invalid
656
- return false;
657
- }
658
- if (filename.length() > 255) {
659
- // Limit at common largest possible filename on Linux filesystems
660
- // to avoid unnecessary further validation
661
- // (On systems with smaller limits it will be caught by the OS)
662
- return false;
663
- }
664
-
665
- std::u32string filename_utf32;
666
- try {
667
- #if defined(__clang__)
668
- // disable C++17 deprecation warning for std::codecvt_utf8
669
- # pragma clang diagnostic push
670
- # pragma clang diagnostic ignored "-Wdeprecated-declarations"
671
- #endif
672
- std::wstring_convert<std::codecvt_utf8<char32_t>, char32_t> converter;
673
-
674
- #if defined(__clang__)
675
- # pragma clang diagnostic pop
676
- #endif
677
-
678
- filename_utf32 = converter.from_bytes(filename);
679
-
680
- // If the reverse conversion mismatches, it means overlong UTF-8 sequences were used,
681
- // or invalid encodings were encountered. Reject such attempts
682
- std::string filename_reencoded = converter.to_bytes(filename_utf32);
683
- if (filename_reencoded != filename) {
684
- return false;
685
- }
686
- } catch (const std::exception &) {
687
- return false;
688
- }
689
-
690
- // Check for forbidden codepoints:
691
- // - Control characters
692
- // - Unicode equivalents of illegal characters
693
- // - UTF-16 surrogate pairs
694
- // - UTF-8 replacement character
695
- // - Byte order mark (BOM)
696
- // - Illegal characters: / \ : * ? " < > |
697
- for (char32_t c : filename_utf32) {
698
- if (c <= 0x1F // Control characters (C0)
699
- || c == 0x7F // Control characters (DEL)
700
- || (c >= 0x80 && c <= 0x9F) // Control characters (C1)
701
- || c == 0xFF0E // Fullwidth Full Stop (period equivalent)
702
- || c == 0x2215 // Division Slash (forward slash equivalent)
703
- || c == 0x2216 // Set Minus (backslash equivalent)
704
- || (c >= 0xD800 && c <= 0xDFFF) // UTF-16 surrogate pairs
705
- || c == 0xFFFD // Replacement Character (UTF-8)
706
- || c == 0xFEFF // Byte Order Mark (BOM)
707
- || c == '/' || c == '\\' || c == ':' || c == '*' // Illegal characters
708
- || c == '?' || c == '"' || c == '<' || c == '>' || c == '|') {
709
- return false;
710
- }
711
- }
712
-
713
- // Reject any leading or trailing ' ', or any trailing '.', these are stripped on Windows and will cause a different filename
714
- // Unicode and other whitespace is not affected, only 0x20 space
715
- if (filename.front() == ' ' || filename.back() == ' ' || filename.back() == '.') {
716
- return false;
717
- }
718
-
719
- // Reject any ".." (currently stricter than necessary, it should be fine to just check for == ".." instead)
720
- if (filename.find("..") != std::string::npos) {
721
- return false;
722
- }
723
-
724
- // Reject "."
725
- if (filename == ".") {
726
- return false;
727
- }
728
-
729
- return true;
730
- }
731
-
732
- // returns true if successful, false otherwise
733
- bool fs_create_directory_with_parents(const std::string & path) {
734
- #ifdef _WIN32
735
- std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;
736
- std::wstring wpath = converter.from_bytes(path);
737
-
738
- // if the path already exists, check whether it's a directory
739
- const DWORD attributes = GetFileAttributesW(wpath.c_str());
740
- if ((attributes != INVALID_FILE_ATTRIBUTES) && (attributes & FILE_ATTRIBUTE_DIRECTORY)) {
741
- return true;
742
- }
743
-
744
- size_t pos_slash = 0;
745
-
746
- // process path from front to back, procedurally creating directories
747
- while ((pos_slash = path.find('\\', pos_slash)) != std::string::npos) {
748
- const std::wstring subpath = wpath.substr(0, pos_slash);
749
- const wchar_t * test = subpath.c_str();
750
-
751
- const bool success = CreateDirectoryW(test, NULL);
752
- if (!success) {
753
- const DWORD error = GetLastError();
754
-
755
- // if the path already exists, ensure that it's a directory
756
- if (error == ERROR_ALREADY_EXISTS) {
757
- const DWORD attributes = GetFileAttributesW(subpath.c_str());
758
- if (attributes == INVALID_FILE_ATTRIBUTES || !(attributes & FILE_ATTRIBUTE_DIRECTORY)) {
759
- return false;
760
- }
761
- } else {
762
- return false;
763
- }
764
- }
765
-
766
- pos_slash += 1;
767
- }
768
-
769
- return true;
770
- #else
771
- // if the path already exists, check whether it's a directory
772
- struct stat info;
773
- if (stat(path.c_str(), &info) == 0) {
774
- return S_ISDIR(info.st_mode);
775
- }
776
-
777
- size_t pos_slash = 1; // skip leading slashes for directory creation
778
-
779
- // process path from front to back, procedurally creating directories
780
- while ((pos_slash = path.find('/', pos_slash)) != std::string::npos) {
781
- const std::string subpath = path.substr(0, pos_slash);
782
- struct stat info;
783
-
784
- // if the path already exists, ensure that it's a directory
785
- if (stat(subpath.c_str(), &info) == 0) {
786
- if (!S_ISDIR(info.st_mode)) {
787
- return false;
788
- }
789
- } else {
790
- // create parent directories
791
- const int ret = mkdir(subpath.c_str(), 0755);
792
- if (ret != 0) {
793
- return false;
794
- }
795
- }
796
-
797
- pos_slash += 1;
798
- }
799
-
800
- return true;
801
- #endif // _WIN32
802
- }
803
-
804
- std::string fs_get_cache_directory() {
805
- std::string cache_directory = "";
806
- auto ensure_trailing_slash = [](std::string p) {
807
- // Make sure to add trailing slash
808
- if (p.back() != DIRECTORY_SEPARATOR) {
809
- p += DIRECTORY_SEPARATOR;
810
- }
811
- return p;
812
- };
813
- if (getenv("LLAMA_CACHE")) {
814
- cache_directory = std::getenv("LLAMA_CACHE");
815
- } else {
816
- #ifdef __linux__
817
- if (std::getenv("XDG_CACHE_HOME")) {
818
- cache_directory = std::getenv("XDG_CACHE_HOME");
819
- } else {
820
- cache_directory = std::getenv("HOME") + std::string("/.cache/");
821
- }
822
- #elif defined(__APPLE__)
823
- cache_directory = std::getenv("HOME") + std::string("/Library/Caches/");
824
- #elif defined(_WIN32)
825
- cache_directory = std::getenv("LOCALAPPDATA");
826
- #endif // __linux__
827
- cache_directory = ensure_trailing_slash(cache_directory);
828
- cache_directory += "llama.cpp";
829
- }
830
- return ensure_trailing_slash(cache_directory);
831
- }
832
-
833
- std::string fs_get_cache_file(const std::string & filename) {
834
- LM_GGML_ASSERT(filename.find(DIRECTORY_SEPARATOR) == std::string::npos);
835
- std::string cache_directory = fs_get_cache_directory();
836
- const bool success = fs_create_directory_with_parents(cache_directory);
837
- if (!success) {
838
- throw std::runtime_error("failed to create cache directory: " + cache_directory);
839
- }
840
- return cache_directory + filename;
841
- }
842
-
843
-
844
- //
845
- // Model utils
846
- //
847
- struct common_init_result common_init_from_params(common_params & params) {
848
- common_init_result iparams;
849
- auto mparams = common_model_params_to_llama(params);
850
-
851
- llama_model * model = nullptr;
852
-
853
- if (!params.hf_repo.empty() && !params.hf_file.empty()) {
854
- model = common_load_model_from_hf(params.hf_repo, params.hf_file, params.model, params.hf_token, mparams);
855
- } else if (!params.model_url.empty()) {
856
- model = common_load_model_from_url(params.model_url, params.model, params.hf_token, mparams);
857
- } else {
858
- model = llama_model_load_from_file(params.model.c_str(), mparams);
859
- }
860
-
861
- if (model == NULL) {
862
- LOG_ERR("%s: failed to load model '%s'\n", __func__, params.model.c_str());
863
- return iparams;
864
- }
865
-
866
- if (params.reranking) {
867
- bool ok = true;
868
-
869
- if (llama_token_bos(model) == LLAMA_TOKEN_NULL) {
870
- LOG_WRN("%s: warning: model does not have a BOS token, reranking will not work\n", __func__);
871
- ok = false;
872
- }
873
-
874
- if (llama_token_eos(model) == LLAMA_TOKEN_NULL) {
875
- LOG_WRN("%s: warning: model does not have an EOS token, reranking will not work\n", __func__);
876
- ok = false;
877
- }
878
-
879
- if (llama_token_sep(model) == LLAMA_TOKEN_NULL) {
880
- LOG_WRN("%s: warning: model does not have a SEP token, reranking will not work\n", __func__);
881
- ok = false;
882
- }
883
-
884
- if (!ok) {
885
- llama_model_free(model);
886
-
887
- return iparams;
888
- }
889
- }
890
-
891
- auto cparams = common_context_params_to_llama(params);
892
-
893
- llama_context * lctx = llama_new_context_with_model(model, cparams);
894
- if (lctx == NULL) {
895
- LOG_ERR("%s: failed to create context with model '%s'\n", __func__, params.model.c_str());
896
- llama_model_free(model);
897
- return iparams;
898
- }
899
-
900
- if (params.ctx_shift && !llama_kv_cache_can_shift(lctx)) {
901
- LOG_WRN("%s: KV cache shifting is not supported for this model, disabling KV cache shifting\n", __func__);
902
- params.ctx_shift = false;
903
- }
904
-
905
- if (!params.control_vectors.empty()) {
906
- if (params.control_vector_layer_start <= 0) params.control_vector_layer_start = 1;
907
- if (params.control_vector_layer_end <= 0) params.control_vector_layer_end = llama_n_layer(model);
908
-
909
- const auto cvec = common_control_vector_load(params.control_vectors);
910
- if (cvec.n_embd == -1) {
911
- llama_free(lctx);
912
- llama_model_free(model);
913
-
914
- return iparams;
915
- }
916
-
917
- int err = llama_control_vector_apply(lctx,
918
- cvec.data.data(),
919
- cvec.data.size(),
920
- cvec.n_embd,
921
- params.control_vector_layer_start,
922
- params.control_vector_layer_end);
923
- if (err) {
924
- llama_free(lctx);
925
- llama_model_free(model);
926
-
927
- return iparams;
928
- }
929
- }
930
-
931
- // load and optionally apply lora adapters
932
- for (auto & la : params.lora_adapters) {
933
- llama_lora_adapter_ptr lora;
934
- lora.reset(llama_lora_adapter_init(model, la.path.c_str()));
935
- if (lora == nullptr) {
936
- LOG_ERR("%s: failed to apply lora adapter '%s'\n", __func__, la.path.c_str());
937
- llama_free(lctx);
938
- llama_model_free(model);
939
- return iparams;
940
- }
941
-
942
- la.ptr = lora.get();
943
- iparams.lora.emplace_back(std::move(lora)); // copy to list of loaded adapters
944
- }
945
-
946
- if (!params.lora_init_without_apply) {
947
- common_lora_adapters_apply(lctx, params.lora_adapters);
948
- }
949
-
950
- if (params.sampling.ignore_eos && llama_token_eos(model) == LLAMA_TOKEN_NULL) {
951
- LOG_WRN("%s: warning: model does not have an EOS token, ignoring --ignore-eos\n", __func__);
952
- params.sampling.ignore_eos = false;
953
- }
954
-
955
- if (params.sampling.ignore_eos) {
956
- for (llama_token i = 0; i < llama_n_vocab(model); i++) {
957
- if (llama_token_is_eog(model, i)) {
958
- LOG_INF("%s: added %s logit bias = %f\n", __func__, common_token_to_piece(lctx, i).c_str(), -INFINITY);
959
- params.sampling.logit_bias.push_back({i, -INFINITY});
960
- }
961
- }
962
- }
963
-
964
- if (params.sampling.penalty_last_n == -1) {
965
- LOG_INF("%s: setting penalty_last_n to ctx_size = %d\n", __func__, llama_n_ctx(lctx));
966
- params.sampling.penalty_last_n = llama_n_ctx(lctx);
967
- }
968
-
969
- if (params.sampling.dry_penalty_last_n == -1) {
970
- LOG_INF("%s: setting dry_penalty_last_n to ctx_size = %d\n", __func__, llama_n_ctx(lctx));
971
- params.sampling.dry_penalty_last_n = llama_n_ctx(lctx);
972
- }
973
-
974
- if (params.warmup) {
975
- LOG_WRN("%s: warming up the model with an empty run - please wait ... (--no-warmup to disable)\n", __func__);
976
-
977
- std::vector<llama_token> tmp;
978
- llama_token bos = llama_token_bos(model);
979
- llama_token eos = llama_token_eos(model);
980
- // some models (e.g. T5) don't have a BOS token
981
- if (bos != LLAMA_TOKEN_NULL) {
982
- tmp.push_back(bos);
983
- }
984
- if (eos != LLAMA_TOKEN_NULL) {
985
- tmp.push_back(eos);
986
- }
987
- if (tmp.empty()) {
988
- tmp.push_back(0);
989
- }
990
-
991
- if (llama_model_has_encoder(model)) {
992
- llama_encode(lctx, llama_batch_get_one(tmp.data(), tmp.size()));
993
- llama_token decoder_start_token_id = llama_model_decoder_start_token(model);
994
- if (decoder_start_token_id == LLAMA_TOKEN_NULL) {
995
- decoder_start_token_id = bos;
996
- }
997
- tmp.clear();
998
- tmp.push_back(decoder_start_token_id);
999
- }
1000
- if (llama_model_has_decoder(model)) {
1001
- llama_decode(lctx, llama_batch_get_one(tmp.data(), std::min(tmp.size(), (size_t) params.n_batch)));
1002
- }
1003
- llama_kv_cache_clear(lctx);
1004
- llama_synchronize(lctx);
1005
- llama_perf_context_reset(lctx);
1006
- }
1007
-
1008
- iparams.model.reset(model);
1009
- iparams.context.reset(lctx);
1010
-
1011
- return iparams;
1012
- }
1013
-
1014
- void common_lora_adapters_apply(struct llama_context * ctx, std::vector<common_lora_adapter_info> & lora) {
1015
- llama_lora_adapter_clear(ctx);
1016
- for (auto & la : lora) {
1017
- if (la.scale != 0.0f) {
1018
- llama_lora_adapter_set(ctx, la.ptr, la.scale);
1019
- }
1020
- }
1021
- }
1022
-
1023
- struct llama_model_params common_model_params_to_llama(common_params & params) {
1024
- auto mparams = llama_model_default_params();
1025
-
1026
- if (!params.devices.empty()) {
1027
- mparams.devices = params.devices.data();
1028
- }
1029
- if (params.n_gpu_layers != -1) {
1030
- mparams.n_gpu_layers = params.n_gpu_layers;
1031
- }
1032
-
1033
- mparams.progress_callback_user_data = params.progress_callback_user_data;
1034
- mparams.progress_callback = params.progress_callback;
1035
- mparams.vocab_only = params.vocab_only;
1036
- mparams.rpc_servers = params.rpc_servers.c_str();
1037
- mparams.main_gpu = params.main_gpu;
1038
- mparams.split_mode = params.split_mode;
1039
- mparams.tensor_split = params.tensor_split;
1040
- mparams.use_mmap = params.use_mmap;
1041
- mparams.use_mlock = params.use_mlock;
1042
- mparams.check_tensors = params.check_tensors;
1043
- if (params.kv_overrides.empty()) {
1044
- mparams.kv_overrides = NULL;
1045
- } else {
1046
- LM_GGML_ASSERT(params.kv_overrides.back().key[0] == 0 && "KV overrides not terminated with empty key");
1047
- mparams.kv_overrides = params.kv_overrides.data();
1048
- }
1049
-
1050
- return mparams;
1051
- }
1052
-
1053
- struct llama_context_params common_context_params_to_llama(const common_params & params) {
1054
- auto cparams = llama_context_default_params();
1055
-
1056
- cparams.n_ctx = params.n_ctx;
1057
- cparams.n_seq_max = params.n_parallel;
1058
- cparams.n_batch = params.n_batch;
1059
- cparams.n_ubatch = params.n_ubatch;
1060
- cparams.n_threads = params.cpuparams.n_threads;
1061
- cparams.n_threads_batch = params.cpuparams_batch.n_threads == -1 ?
1062
- params.cpuparams.n_threads : params.cpuparams_batch.n_threads;
1063
- cparams.logits_all = params.logits_all;
1064
- cparams.embeddings = params.embedding;
1065
- cparams.rope_scaling_type = params.rope_scaling_type;
1066
- cparams.rope_freq_base = params.rope_freq_base;
1067
- cparams.rope_freq_scale = params.rope_freq_scale;
1068
- cparams.yarn_ext_factor = params.yarn_ext_factor;
1069
- cparams.yarn_attn_factor = params.yarn_attn_factor;
1070
- cparams.yarn_beta_fast = params.yarn_beta_fast;
1071
- cparams.yarn_beta_slow = params.yarn_beta_slow;
1072
- cparams.yarn_orig_ctx = params.yarn_orig_ctx;
1073
- cparams.pooling_type = params.pooling_type;
1074
- cparams.attention_type = params.attention_type;
1075
- cparams.defrag_thold = params.defrag_thold;
1076
- cparams.cb_eval = params.cb_eval;
1077
- cparams.cb_eval_user_data = params.cb_eval_user_data;
1078
- cparams.offload_kqv = !params.no_kv_offload;
1079
- cparams.flash_attn = params.flash_attn;
1080
- cparams.no_perf = params.no_perf;
1081
-
1082
- if (params.reranking) {
1083
- cparams.embeddings = true;
1084
- cparams.pooling_type = LLAMA_POOLING_TYPE_RANK;
1085
- }
1086
-
1087
- cparams.type_k = params.cache_type_k;
1088
- cparams.type_v = params.cache_type_v;
1089
-
1090
- return cparams;
1091
- }
1092
-
1093
- struct lm_ggml_threadpool_params lm_ggml_threadpool_params_from_cpu_params(const cpu_params & params) {
1094
- struct lm_ggml_threadpool_params tpp;
1095
-
1096
- lm_ggml_threadpool_params_init(&tpp, params.n_threads); // setup the defaults
1097
-
1098
- if (params.mask_valid) {
1099
- std::memcpy(&tpp.cpumask, &params.cpumask, LM_GGML_MAX_N_THREADS);
1100
- }
1101
-
1102
- tpp.prio = params.priority;
1103
- tpp.poll = params.poll;
1104
- tpp.strict_cpu = params.strict_cpu;
1105
-
1106
- return tpp;
1107
- }
1108
-
1109
- #ifdef LLAMA_USE_CURL
1110
-
1111
- #define CURL_MAX_RETRY 3
1112
- #define CURL_RETRY_DELAY_SECONDS 2
1113
-
1114
- static bool curl_perform_with_retry(const std::string & url, CURL * curl, int max_attempts, int retry_delay_seconds) {
1115
- int remaining_attempts = max_attempts;
1116
-
1117
- while (remaining_attempts > 0) {
1118
- LOG_INF("%s: Trying to download from %s (attempt %d of %d)...\n", __func__ , url.c_str(), max_attempts - remaining_attempts + 1, max_attempts);
1119
-
1120
- CURLcode res = curl_easy_perform(curl);
1121
- if (res == CURLE_OK) {
1122
- return true;
1123
- }
1124
-
1125
- int exponential_backoff_delay = std::pow(retry_delay_seconds, max_attempts - remaining_attempts) * 1000;
1126
- LOG_WRN("%s: curl_easy_perform() failed: %s, retrying after %d milliseconds...\n", __func__, curl_easy_strerror(res), exponential_backoff_delay);
1127
-
1128
- remaining_attempts--;
1129
- std::this_thread::sleep_for(std::chrono::milliseconds(exponential_backoff_delay));
1130
- }
1131
-
1132
- LOG_ERR("%s: curl_easy_perform() failed after %d attempts\n", __func__, max_attempts);
1133
-
1134
- return false;
1135
- }
1136
-
1137
- static bool common_download_file(const std::string & url, const std::string & path, const std::string & hf_token) {
1138
- // Initialize libcurl
1139
- std::unique_ptr<CURL, decltype(&curl_easy_cleanup)> curl(curl_easy_init(), &curl_easy_cleanup);
1140
- if (!curl) {
1141
- LOG_ERR("%s: error initializing libcurl\n", __func__);
1142
- return false;
1143
- }
1144
-
1145
- bool force_download = false;
1146
-
1147
- // Set the URL, allow to follow http redirection
1148
- curl_easy_setopt(curl.get(), CURLOPT_URL, url.c_str());
1149
- curl_easy_setopt(curl.get(), CURLOPT_FOLLOWLOCATION, 1L);
1150
-
1151
- // Check if hf-token or bearer-token was specified
1152
- if (!hf_token.empty()) {
1153
- std::string auth_header = "Authorization: Bearer ";
1154
- auth_header += hf_token.c_str();
1155
- struct curl_slist *http_headers = NULL;
1156
- http_headers = curl_slist_append(http_headers, auth_header.c_str());
1157
- curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, http_headers);
1158
- }
1159
-
1160
- #if defined(_WIN32)
1161
- // CURLSSLOPT_NATIVE_CA tells libcurl to use standard certificate store of
1162
- // operating system. Currently implemented under MS-Windows.
1163
- curl_easy_setopt(curl.get(), CURLOPT_SSL_OPTIONS, CURLSSLOPT_NATIVE_CA);
1164
- #endif
1165
-
1166
- // Check if the file already exists locally
1167
- auto file_exists = std::filesystem::exists(path);
1168
-
1169
- // If the file exists, check its JSON metadata companion file.
1170
- std::string metadata_path = path + ".json";
1171
- nlohmann::json metadata;
1172
- std::string etag;
1173
- std::string last_modified;
1174
-
1175
- if (file_exists) {
1176
- // Try and read the JSON metadata file (note: stream autoclosed upon exiting this block).
1177
- std::ifstream metadata_in(metadata_path);
1178
- if (metadata_in.good()) {
1179
- try {
1180
- metadata_in >> metadata;
1181
- LOG_INF("%s: previous metadata file found %s: %s\n", __func__, metadata_path.c_str(), metadata.dump().c_str());
1182
- if (metadata.contains("url") && metadata.at("url").is_string()) {
1183
- auto previous_url = metadata.at("url").get<std::string>();
1184
- if (previous_url != url) {
1185
- LOG_ERR("%s: Model URL mismatch: %s != %s\n", __func__, url.c_str(), previous_url.c_str());
1186
- return false;
1187
- }
1188
- }
1189
- if (metadata.contains("etag") && metadata.at("etag").is_string()) {
1190
- etag = metadata.at("etag");
1191
- }
1192
- if (metadata.contains("lastModified") && metadata.at("lastModified").is_string()) {
1193
- last_modified = metadata.at("lastModified");
1194
- }
1195
- } catch (const nlohmann::json::exception & e) {
1196
- LOG_ERR("%s: error reading metadata file %s: %s\n", __func__, metadata_path.c_str(), e.what());
1197
- return false;
1198
- }
1199
- }
1200
- } else {
1201
- LOG_INF("%s: no previous model file found %s\n", __func__, path.c_str());
1202
- }
1203
-
1204
- // Send a HEAD request to retrieve the etag and last-modified headers
1205
- struct common_load_model_from_url_headers {
1206
- std::string etag;
1207
- std::string last_modified;
1208
- };
1209
-
1210
- common_load_model_from_url_headers headers;
1211
-
1212
- {
1213
- typedef size_t(*CURLOPT_HEADERFUNCTION_PTR)(char *, size_t, size_t, void *);
1214
- auto header_callback = [](char * buffer, size_t /*size*/, size_t n_items, void * userdata) -> size_t {
1215
- common_load_model_from_url_headers * headers = (common_load_model_from_url_headers *) userdata;
1216
-
1217
- static std::regex header_regex("([^:]+): (.*)\r\n");
1218
- static std::regex etag_regex("ETag", std::regex_constants::icase);
1219
- static std::regex last_modified_regex("Last-Modified", std::regex_constants::icase);
1220
-
1221
- std::string header(buffer, n_items);
1222
- std::smatch match;
1223
- if (std::regex_match(header, match, header_regex)) {
1224
- const std::string & key = match[1];
1225
- const std::string & value = match[2];
1226
- if (std::regex_match(key, match, etag_regex)) {
1227
- headers->etag = value;
1228
- } else if (std::regex_match(key, match, last_modified_regex)) {
1229
- headers->last_modified = value;
1230
- }
1231
- }
1232
- return n_items;
1233
- };
1234
-
1235
- curl_easy_setopt(curl.get(), CURLOPT_NOBODY, 1L); // will trigger the HEAD verb
1236
- curl_easy_setopt(curl.get(), CURLOPT_NOPROGRESS, 1L); // hide head request progress
1237
- curl_easy_setopt(curl.get(), CURLOPT_HEADERFUNCTION, static_cast<CURLOPT_HEADERFUNCTION_PTR>(header_callback));
1238
- curl_easy_setopt(curl.get(), CURLOPT_HEADERDATA, &headers);
1239
-
1240
- bool was_perform_successful = curl_perform_with_retry(url, curl.get(), CURL_MAX_RETRY, CURL_RETRY_DELAY_SECONDS);
1241
- if (!was_perform_successful) {
1242
- return false;
1243
- }
1244
-
1245
- long http_code = 0;
1246
- curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &http_code);
1247
- if (http_code != 200) {
1248
- // HEAD not supported, we don't know if the file has changed
1249
- // force trigger downloading
1250
- force_download = true;
1251
- LOG_ERR("%s: HEAD invalid http status code received: %ld\n", __func__, http_code);
1252
- }
1253
- }
1254
-
1255
- bool should_download = !file_exists || force_download;
1256
- if (!should_download) {
1257
- if (!etag.empty() && etag != headers.etag) {
1258
- LOG_WRN("%s: ETag header is different (%s != %s): triggering a new download\n", __func__, etag.c_str(), headers.etag.c_str());
1259
- should_download = true;
1260
- } else if (!last_modified.empty() && last_modified != headers.last_modified) {
1261
- LOG_WRN("%s: Last-Modified header is different (%s != %s): triggering a new download\n", __func__, last_modified.c_str(), headers.last_modified.c_str());
1262
- should_download = true;
1263
- }
1264
- }
1265
- if (should_download) {
1266
- std::string path_temporary = path + ".downloadInProgress";
1267
- if (file_exists) {
1268
- LOG_WRN("%s: deleting previous downloaded file: %s\n", __func__, path.c_str());
1269
- if (remove(path.c_str()) != 0) {
1270
- LOG_ERR("%s: unable to delete file: %s\n", __func__, path.c_str());
1271
- return false;
1272
- }
1273
- }
1274
-
1275
- // Set the output file
1276
-
1277
- struct FILE_deleter {
1278
- void operator()(FILE * f) const {
1279
- fclose(f);
1280
- }
1281
- };
1282
-
1283
- std::unique_ptr<FILE, FILE_deleter> outfile(fopen(path_temporary.c_str(), "wb"));
1284
- if (!outfile) {
1285
- LOG_ERR("%s: error opening local file for writing: %s\n", __func__, path.c_str());
1286
- return false;
1287
- }
1288
-
1289
- typedef size_t(*CURLOPT_WRITEFUNCTION_PTR)(void * data, size_t size, size_t nmemb, void * fd);
1290
- auto write_callback = [](void * data, size_t size, size_t nmemb, void * fd) -> size_t {
1291
- return fwrite(data, size, nmemb, (FILE *)fd);
1292
- };
1293
- curl_easy_setopt(curl.get(), CURLOPT_NOBODY, 0L);
1294
- curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, static_cast<CURLOPT_WRITEFUNCTION_PTR>(write_callback));
1295
- curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, outfile.get());
1296
-
1297
- // display download progress
1298
- curl_easy_setopt(curl.get(), CURLOPT_NOPROGRESS, 0L);
1299
-
1300
- // helper function to hide password in URL
1301
- auto llama_download_hide_password_in_url = [](const std::string & url) -> std::string {
1302
- std::size_t protocol_pos = url.find("://");
1303
- if (protocol_pos == std::string::npos) {
1304
- return url; // Malformed URL
1305
- }
1306
-
1307
- std::size_t at_pos = url.find('@', protocol_pos + 3);
1308
- if (at_pos == std::string::npos) {
1309
- return url; // No password in URL
1310
- }
1311
-
1312
- return url.substr(0, protocol_pos + 3) + "********" + url.substr(at_pos);
1313
- };
1314
-
1315
- // start the download
1316
- LOG_INF("%s: trying to download model from %s to %s (server_etag:%s, server_last_modified:%s)...\n", __func__,
1317
- llama_download_hide_password_in_url(url).c_str(), path.c_str(), headers.etag.c_str(), headers.last_modified.c_str());
1318
- bool was_perform_successful = curl_perform_with_retry(url, curl.get(), CURL_MAX_RETRY, CURL_RETRY_DELAY_SECONDS);
1319
- if (!was_perform_successful) {
1320
- return false;
1321
- }
1322
-
1323
- long http_code = 0;
1324
- curl_easy_getinfo (curl.get(), CURLINFO_RESPONSE_CODE, &http_code);
1325
- if (http_code < 200 || http_code >= 400) {
1326
- LOG_ERR("%s: invalid http status code received: %ld\n", __func__, http_code);
1327
- return false;
1328
- }
1329
-
1330
- // Causes file to be closed explicitly here before we rename it.
1331
- outfile.reset();
1332
-
1333
- // Write the updated JSON metadata file.
1334
- metadata.update({
1335
- {"url", url},
1336
- {"etag", headers.etag},
1337
- {"lastModified", headers.last_modified}
1338
- });
1339
- std::ofstream(metadata_path) << metadata.dump(4);
1340
- LOG_INF("%s: file metadata saved: %s\n", __func__, metadata_path.c_str());
1341
-
1342
- if (rename(path_temporary.c_str(), path.c_str()) != 0) {
1343
- LOG_ERR("%s: unable to rename file: %s to %s\n", __func__, path_temporary.c_str(), path.c_str());
1344
- return false;
1345
- }
1346
- }
1347
-
1348
- return true;
1349
- }
1350
-
1351
- struct llama_model * common_load_model_from_url(
1352
- const std::string & model_url,
1353
- const std::string & local_path,
1354
- const std::string & hf_token,
1355
- const struct llama_model_params & params) {
1356
- // Basic validation of the model_url
1357
- if (model_url.empty()) {
1358
- LOG_ERR("%s: invalid model_url\n", __func__);
1359
- return NULL;
1360
- }
1361
-
1362
- if (!common_download_file(model_url, local_path, hf_token)) {
1363
- return NULL;
1364
- }
1365
-
1366
- // check for additional GGUFs split to download
1367
- int n_split = 0;
1368
- {
1369
- struct lm_gguf_init_params lm_gguf_params = {
1370
- /*.no_alloc = */ true,
1371
- /*.ctx = */ NULL,
1372
- };
1373
- auto * ctx_gguf = lm_gguf_init_from_file(local_path.c_str(), lm_gguf_params);
1374
- if (!ctx_gguf) {
1375
- LOG_ERR("\n%s: failed to load input GGUF from %s\n", __func__, local_path.c_str());
1376
- return NULL;
1377
- }
1378
-
1379
- auto key_n_split = lm_gguf_find_key(ctx_gguf, LLM_KV_SPLIT_COUNT);
1380
- if (key_n_split >= 0) {
1381
- n_split = lm_gguf_get_val_u16(ctx_gguf, key_n_split);
1382
- }
1383
-
1384
- lm_gguf_free(ctx_gguf);
1385
- }
1386
-
1387
- if (n_split > 1) {
1388
- char split_prefix[PATH_MAX] = {0};
1389
- char split_url_prefix[LLAMA_CURL_MAX_URL_LENGTH] = {0};
1390
-
1391
- // Verify the first split file format
1392
- // and extract split URL and PATH prefixes
1393
- {
1394
- if (!llama_split_prefix(split_prefix, sizeof(split_prefix), local_path.c_str(), 0, n_split)) {
1395
- LOG_ERR("\n%s: unexpected model file name: %s n_split=%d\n", __func__, local_path.c_str(), n_split);
1396
- return NULL;
1397
- }
1398
-
1399
- if (!llama_split_prefix(split_url_prefix, sizeof(split_url_prefix), model_url.c_str(), 0, n_split)) {
1400
- LOG_ERR("\n%s: unexpected model url: %s n_split=%d\n", __func__, model_url.c_str(), n_split);
1401
- return NULL;
1402
- }
1403
- }
1404
-
1405
- // Prepare download in parallel
1406
- std::vector<std::future<bool>> futures_download;
1407
- for (int idx = 1; idx < n_split; idx++) {
1408
- futures_download.push_back(std::async(std::launch::async, [&split_prefix, &split_url_prefix, &n_split, hf_token](int download_idx) -> bool {
1409
- char split_path[PATH_MAX] = {0};
1410
- llama_split_path(split_path, sizeof(split_path), split_prefix, download_idx, n_split);
1411
-
1412
- char split_url[LLAMA_CURL_MAX_URL_LENGTH] = {0};
1413
- llama_split_path(split_url, sizeof(split_url), split_url_prefix, download_idx, n_split);
1414
-
1415
- return common_download_file(split_url, split_path, hf_token);
1416
- }, idx));
1417
- }
1418
-
1419
- // Wait for all downloads to complete
1420
- for (auto & f : futures_download) {
1421
- if (!f.get()) {
1422
- return NULL;
1423
- }
1424
- }
1425
- }
1426
-
1427
- return llama_model_load_from_file(local_path.c_str(), params);
1428
- }
1429
-
1430
- struct llama_model * common_load_model_from_hf(
1431
- const std::string & repo,
1432
- const std::string & remote_path,
1433
- const std::string & local_path,
1434
- const std::string & hf_token,
1435
- const struct llama_model_params & params) {
1436
- // construct hugging face model url:
1437
- //
1438
- // --repo ggml-org/models --file tinyllama-1.1b/ggml-model-f16.gguf
1439
- // https://huggingface.co/ggml-org/models/resolve/main/tinyllama-1.1b/ggml-model-f16.gguf
1440
- //
1441
- // --repo TheBloke/Mixtral-8x7B-v0.1-GGUF --file mixtral-8x7b-v0.1.Q4_K_M.gguf
1442
- // https://huggingface.co/TheBloke/Mixtral-8x7B-v0.1-GGUF/resolve/main/mixtral-8x7b-v0.1.Q4_K_M.gguf
1443
- //
1444
-
1445
- std::string model_url = "https://huggingface.co/";
1446
- model_url += repo;
1447
- model_url += "/resolve/main/";
1448
- model_url += remote_path;
1449
-
1450
- return common_load_model_from_url(model_url, local_path, hf_token, params);
1451
- }
1452
-
1453
- #else
1454
-
1455
- struct llama_model * common_load_model_from_url(
1456
- const std::string & /*model_url*/,
1457
- const std::string & /*local_path*/,
1458
- const std::string & /*hf_token*/,
1459
- const struct llama_model_params & /*params*/) {
1460
- LOG_WRN("%s: llama.cpp built without libcurl, downloading from an url not supported.\n", __func__);
1461
- return nullptr;
1462
- }
1463
-
1464
- struct llama_model * common_load_model_from_hf(
1465
- const std::string & /*repo*/,
1466
- const std::string & /*remote_path*/,
1467
- const std::string & /*local_path*/,
1468
- const std::string & /*hf_token*/,
1469
- const struct llama_model_params & /*params*/) {
1470
- LOG_WRN("%s: llama.cpp built without libcurl, downloading from Hugging Face not supported.\n", __func__);
1471
- return nullptr;
1472
- }
1473
-
1474
- #endif // LLAMA_USE_CURL
1475
-
1476
- //
1477
- // Batch utils
1478
- //
1479
-
1480
- void common_batch_clear(struct llama_batch & batch) {
1481
- batch.n_tokens = 0;
1482
- }
1483
-
1484
- void common_batch_add(
1485
- struct llama_batch & batch,
1486
- llama_token id,
1487
- llama_pos pos,
1488
- const std::vector<llama_seq_id> & seq_ids,
1489
- bool logits) {
1490
- LM_GGML_ASSERT(batch.seq_id[batch.n_tokens] && "llama_batch size exceeded");
1491
-
1492
- batch.token [batch.n_tokens] = id;
1493
- batch.pos [batch.n_tokens] = pos;
1494
- batch.n_seq_id[batch.n_tokens] = seq_ids.size();
1495
- for (size_t i = 0; i < seq_ids.size(); ++i) {
1496
- batch.seq_id[batch.n_tokens][i] = seq_ids[i];
1497
- }
1498
- batch.logits [batch.n_tokens] = logits;
1499
-
1500
- batch.n_tokens++;
1501
- }
1502
-
1503
- //
1504
- // Token utils
1505
- //
1506
-
1507
- size_t common_lcp(const llama_tokens & a, const llama_tokens & b) {
1508
- size_t i;
1509
- for (i = 0; i < a.size() && i < b.size() && a[i] == b[i]; i++) {}
1510
-
1511
- return i;
1512
- }
1513
-
1514
- size_t common_lcs(const llama_tokens & a, const llama_tokens & b) {
1515
- // check for empty sequences
1516
- if (a.empty() || b.empty()) {
1517
- return 0;
1518
- }
1519
-
1520
- // get the lengths of the input sequences
1521
- size_t a_len = a.size();
1522
- size_t b_len = b.size();
1523
-
1524
- // initialize the maximum length of the longest common subsequence (LCS)
1525
- size_t max_length = 0;
1526
-
1527
- // use two rows instead of a 2D matrix to optimize space
1528
- std::vector<size_t> prev_row(b_len + 1, 0);
1529
- std::vector<size_t> curr_row(b_len + 1, 0);
1530
-
1531
- // iterate through the elements of a
1532
- for (size_t i = 1; i <= a_len; i++) {
1533
- // iterate through the elements of b
1534
- for (size_t j = 1; j <= b_len; j++) {
1535
- // if elements at the current positions match
1536
- if (a[i - 1] == b[j - 1]) {
1537
- // if it's the first element of either sequences, set LCS length to 1
1538
- if (i == 1 || j == 1) {
1539
- curr_row[j] = 1;
1540
- } else {
1541
- // increment LCS length by 1 compared to the previous element
1542
- curr_row[j] = prev_row[j - 1] + 1;
1543
- }
1544
-
1545
- // update max_length if necessary
1546
- if (curr_row[j] > max_length) {
1547
- max_length = curr_row[j];
1548
- }
1549
- } else {
1550
- // reset LCS length if elements don't match
1551
- curr_row[j] = 0;
1552
- }
1553
- }
1554
-
1555
- // update the previous row for the next iteration
1556
- prev_row = curr_row;
1557
- }
1558
-
1559
- // return the maximum length of the LCS
1560
- return max_length;
1561
- }
1562
-
1563
- //
1564
- // Vocab utils
1565
- //
1566
-
1567
- std::vector<llama_token> common_tokenize(
1568
- const struct llama_context * ctx,
1569
- const std::string & text,
1570
- bool add_special,
1571
- bool parse_special) {
1572
- return common_tokenize(llama_get_model(ctx), text, add_special, parse_special);
1573
- }
1574
-
1575
- std::vector<llama_token> common_tokenize(
1576
- const struct llama_model * model,
1577
- const std::string & text,
1578
- bool add_special,
1579
- bool parse_special) {
1580
- // upper limit for the number of tokens
1581
- int n_tokens = text.length() + 2 * add_special;
1582
- std::vector<llama_token> result(n_tokens);
1583
- n_tokens = llama_tokenize(model, text.data(), text.length(), result.data(), result.size(), add_special, parse_special);
1584
- if (n_tokens < 0) {
1585
- result.resize(-n_tokens);
1586
- int check = llama_tokenize(model, text.data(), text.length(), result.data(), result.size(), add_special, parse_special);
1587
- LM_GGML_ASSERT(check == -n_tokens);
1588
- } else {
1589
- result.resize(n_tokens);
1590
- }
1591
- return result;
1592
- }
1593
-
1594
- std::string common_token_to_piece(const struct llama_context * ctx, llama_token token, bool special) {
1595
- std::string piece;
1596
- piece.resize(piece.capacity()); // using string internal cache, 15 bytes + '\n'
1597
- const int n_chars = llama_token_to_piece(llama_get_model(ctx), token, &piece[0], piece.size(), 0, special);
1598
- if (n_chars < 0) {
1599
- piece.resize(-n_chars);
1600
- int check = llama_token_to_piece(llama_get_model(ctx), token, &piece[0], piece.size(), 0, special);
1601
- LM_GGML_ASSERT(check == -n_chars);
1602
- }
1603
- else {
1604
- piece.resize(n_chars);
1605
- }
1606
-
1607
- return piece;
1608
- }
1609
-
1610
- std::string common_detokenize(llama_context * ctx, const std::vector<llama_token> & tokens, bool special) {
1611
- std::string text;
1612
- text.resize(std::max(text.capacity(), tokens.size()));
1613
- int32_t n_chars = llama_detokenize(llama_get_model(ctx), tokens.data(), (int32_t)tokens.size(), &text[0], (int32_t)text.size(), false, special);
1614
- if (n_chars < 0) {
1615
- text.resize(-n_chars);
1616
- n_chars = llama_detokenize(llama_get_model(ctx), tokens.data(), (int32_t)tokens.size(), &text[0], (int32_t)text.size(), false, special);
1617
- LM_GGML_ASSERT(n_chars <= (int32_t)text.size()); // whitespace trimming is performed after per-token detokenization
1618
- }
1619
-
1620
- text.resize(n_chars);
1621
-
1622
- // NOTE: the original tokenizer decodes bytes after collecting the pieces.
1623
- return text;
1624
- }
1625
-
1626
- //
1627
- // Chat template utils
1628
- //
1629
-
1630
- std::string common_get_builtin_chat_template(const struct llama_model * model) {
1631
- static const char * template_key = "tokenizer.chat_template";
1632
- // call with NULL buffer to get the total size of the string
1633
- int32_t res = llama_model_meta_val_str(model, template_key, NULL, 0);
1634
- if (res > 0) {
1635
- std::vector<char> model_template(res + 1, 0);
1636
- llama_model_meta_val_str(model, template_key, model_template.data(), model_template.size());
1637
- return std::string(model_template.data(), model_template.size() - 1);
1638
- }
1639
- return "";
1640
- }
1641
-
1642
- bool common_chat_verify_template(const std::string & tmpl) {
1643
- llama_chat_message chat[] = {{"user", "test"}};
1644
- int res = llama_chat_apply_template(nullptr, tmpl.c_str(), chat, 1, true, nullptr, 0);
1645
- return res >= 0;
1646
- }
1647
-
1648
- std::string common_chat_apply_template(const struct llama_model * model,
1649
- const std::string & tmpl,
1650
- const std::vector<common_chat_msg> & msgs,
1651
- bool add_ass) {
1652
- int alloc_size = 0;
1653
- bool fallback = false; // indicate if we must fallback to default chatml
1654
- std::vector<llama_chat_message> chat;
1655
- for (auto & msg : msgs) {
1656
- chat.push_back({msg.role.c_str(), msg.content.c_str()});
1657
- alloc_size += (msg.role.size() + msg.content.size()) * 1.25;
1658
- }
1659
-
1660
- const char * ptr_tmpl = tmpl.empty() ? nullptr : tmpl.c_str();
1661
- std::vector<char> buf(alloc_size);
1662
-
1663
- // run the first time to get the total output length
1664
- int32_t res = llama_chat_apply_template(model, ptr_tmpl, chat.data(), chat.size(), add_ass, buf.data(), buf.size());
1665
-
1666
- // error: chat template is not supported
1667
- if (res < 0) {
1668
- if (ptr_tmpl != nullptr) {
1669
- // if the custom "tmpl" is not supported, we throw an error
1670
- // this is a bit redundant (for good), since we're not sure if user validated the custom template with llama_chat_verify_template()
1671
- throw std::runtime_error("this custom template is not supported");
1672
- } else {
1673
- // If the built-in template is not supported, we default to chatml
1674
- res = llama_chat_apply_template(nullptr, "chatml", chat.data(), chat.size(), add_ass, buf.data(), buf.size());
1675
- fallback = true;
1676
- }
1677
- }
1678
-
1679
- // if it turns out that our buffer is too small, we resize it
1680
- if ((size_t) res > buf.size()) {
1681
- buf.resize(res);
1682
- res = llama_chat_apply_template(
1683
- fallback ? nullptr : model,
1684
- fallback ? "chatml" : ptr_tmpl,
1685
- chat.data(), chat.size(), add_ass, buf.data(), buf.size());
1686
- }
1687
-
1688
- std::string formatted_chat(buf.data(), res);
1689
- return formatted_chat;
1690
- }
1691
-
1692
- std::string common_chat_format_single(const struct llama_model * model,
1693
- const std::string & tmpl,
1694
- const std::vector<common_chat_msg> & past_msg,
1695
- const common_chat_msg & new_msg,
1696
- bool add_ass) {
1697
- std::ostringstream ss;
1698
- auto fmt_past_msg = past_msg.empty() ? "" : common_chat_apply_template(model, tmpl, past_msg, false);
1699
- std::vector<common_chat_msg> chat_new(past_msg);
1700
- // if the past_msg ends with a newline, we must preserve it in the formatted version
1701
- if (add_ass && !fmt_past_msg.empty() && fmt_past_msg.back() == '\n') {
1702
- ss << "\n";
1703
- };
1704
- // format chat with new_msg
1705
- chat_new.push_back(new_msg);
1706
- auto fmt_new_msg = common_chat_apply_template(model, tmpl, chat_new, add_ass);
1707
- // get the diff part
1708
- ss << fmt_new_msg.substr(fmt_past_msg.size(), fmt_new_msg.size() - fmt_past_msg.size());
1709
- return ss.str();
1710
- }
1711
-
1712
- std::string common_chat_format_example(const struct llama_model * model,
1713
- const std::string & tmpl) {
1714
- std::vector<common_chat_msg> msgs = {
1715
- {"system", "You are a helpful assistant"},
1716
- {"user", "Hello"},
1717
- {"assistant", "Hi there"},
1718
- {"user", "How are you?"},
1719
- };
1720
- return common_chat_apply_template(model, tmpl, msgs, true);
1721
- }
1722
-
1723
- //
1724
- // KV cache utils
1725
- //
1726
-
1727
- void common_kv_cache_dump_view(const llama_kv_cache_view & view, int row_size) {
1728
- static const char slot_chars[] = ".123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+";
1729
-
1730
- printf("=== Dumping KV cache. total cells %d, max sequences per cell %d, populated cells %d, total tokens in cache %d, largest empty slot=%d @ %d",
1731
- view.n_cells, view.n_seq_max, view.used_cells, view.token_count, view.max_contiguous, view.max_contiguous_idx);
1732
-
1733
- llama_kv_cache_view_cell * c_curr = view.cells;
1734
- llama_seq_id * cs_curr = view.cells_sequences;
1735
-
1736
- for (int i = 0; i < view.n_cells; i++, c_curr++, cs_curr += view.n_seq_max) {
1737
- if (i % row_size == 0) {
1738
- printf("\n%5d: ", i);
1739
- }
1740
- int seq_count = 0;
1741
- for (int j = 0; j < view.n_seq_max; j++) {
1742
- if (cs_curr[j] >= 0) { seq_count++; }
1743
- }
1744
- putchar(slot_chars[std::min(sizeof(slot_chars) - 2, size_t(seq_count))]);
1745
- }
1746
-
1747
- printf("\n=== Done dumping\n");
1748
- }
1749
-
1750
- void common_kv_cache_dump_view_seqs(const llama_kv_cache_view & view, int row_size) {
1751
- static const char slot_chars[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
1752
-
1753
- printf("=== Dumping KV cache. total cells %d, max sequences per cell %d, populated cells %d, total tokens in cache %d, largest empty slot=%d @ %d\n",
1754
- view.n_cells, view.n_seq_max, view.used_cells, view.token_count, view.max_contiguous, view.max_contiguous_idx);
1755
-
1756
- std::unordered_map<llama_seq_id, size_t> seqs;
1757
- llama_kv_cache_view_cell * c_curr = view.cells;
1758
- llama_seq_id * cs_curr = view.cells_sequences;
1759
-
1760
- for (int i = 0; i < view.n_cells; i++, c_curr++, cs_curr += view.n_seq_max) {
1761
- for (int j = 0; j < view.n_seq_max; j++) {
1762
- if (cs_curr[j] < 0) { continue; }
1763
- if (seqs.find(cs_curr[j]) == seqs.end()) {
1764
- if (seqs.size() + 1 >= sizeof(slot_chars)) { break; }
1765
- const size_t sz = seqs.size();
1766
- seqs[cs_curr[j]] = sz;
1767
- }
1768
- }
1769
- if (seqs.size() + 1 >= sizeof(slot_chars)) { break; }
1770
- }
1771
-
1772
- printf("=== Sequence legend: ");
1773
- for (const auto & it : seqs) {
1774
- printf("%zu=%d, ", it.second, it.first);
1775
- }
1776
- printf("'+'=other sequence ids");
1777
-
1778
- c_curr = view.cells;
1779
- cs_curr = view.cells_sequences;
1780
- for (int i = 0; i < view.n_cells; i++, c_curr++, cs_curr += view.n_seq_max) {
1781
- if (i % row_size == 0) {
1782
- printf("\n%5d: ", i);
1783
- }
1784
- for (int j = 0; j < view.n_seq_max; j++) {
1785
- if (cs_curr[j] >= 0) {
1786
- const auto & it = seqs.find(cs_curr[j]);
1787
- putchar(it != seqs.end() ? int(slot_chars[it->second]) : '+');
1788
- } else {
1789
- putchar('.');
1790
- }
1791
- }
1792
- putchar(' ');
1793
- }
1794
-
1795
- printf("\n=== Done dumping\n");
1796
- }
1797
-
1798
- //
1799
- // Embedding utils
1800
- //
1801
-
1802
- void common_embd_normalize(const float * inp, float * out, int n, int embd_norm) {
1803
- double sum = 0.0;
1804
-
1805
- switch (embd_norm) {
1806
- case -1: // no normalisation
1807
- sum = 1.0;
1808
- break;
1809
- case 0: // max absolute
1810
- for (int i = 0; i < n; i++) {
1811
- if (sum < std::abs(inp[i])) {
1812
- sum = std::abs(inp[i]);
1813
- }
1814
- }
1815
- sum /= 32760.0; // make an int16 range
1816
- break;
1817
- case 2: // euclidean
1818
- for (int i = 0; i < n; i++) {
1819
- sum += inp[i] * inp[i];
1820
- }
1821
- sum = std::sqrt(sum);
1822
- break;
1823
- default: // p-norm (euclidean is p-norm p=2)
1824
- for (int i = 0; i < n; i++) {
1825
- sum += std::pow(std::abs(inp[i]), embd_norm);
1826
- }
1827
- sum = std::pow(sum, 1.0 / embd_norm);
1828
- break;
1829
- }
1830
-
1831
- const float norm = sum > 0.0 ? 1.0 / sum : 0.0f;
1832
-
1833
- for (int i = 0; i < n; i++) {
1834
- out[i] = inp[i] * norm;
1835
- }
1836
- }
1837
-
1838
- float common_embd_similarity_cos(const float * embd1, const float * embd2, int n){
1839
- double sum = 0.0;
1840
- double sum1 = 0.0;
1841
- double sum2 = 0.0;
1842
-
1843
- for (int i = 0; i < n; i++) {
1844
- sum += embd1[i] * embd2[i];
1845
- sum1 += embd1[i] * embd1[i];
1846
- sum2 += embd2[i] * embd2[i];
1847
- }
1848
-
1849
- // Handle the case where one or both vectors are zero vectors
1850
- if (sum1 == 0.0 || sum2 == 0.0) {
1851
- if (sum1 == 0.0 && sum2 == 0.0) {
1852
- return 1.0f; // two zero vectors are similar
1853
- }
1854
- return 0.0f;
1855
- }
1856
-
1857
- return sum / (sqrt(sum1) * sqrt(sum2));
1858
- }
1859
-
1860
- //
1861
- // Control vector utils
1862
- //
1863
-
1864
- static common_control_vector_data common_control_vector_load_one(const common_control_vector_load_info & load_info) {
1865
- common_control_vector_data result = { -1, {} };
1866
-
1867
- lm_ggml_context * ctx = nullptr;
1868
- struct lm_gguf_init_params meta_lm_gguf_params = {
1869
- /* .no_alloc = */ false,
1870
- /* .ctx = */ &ctx,
1871
- };
1872
- struct lm_gguf_context * ctx_gguf = lm_gguf_init_from_file(load_info.fname.c_str(), meta_lm_gguf_params);
1873
- if (!ctx_gguf) {
1874
- LOG_ERR("%s: failed to load control vector file from %s\n", __func__, load_info.fname.c_str());
1875
- return result;
1876
- }
1877
-
1878
- int32_t n_tensors = lm_gguf_get_n_tensors(ctx_gguf);
1879
- if (n_tensors == 0) {
1880
- LOG_WRN("%s: no direction tensors found in %s\n", __func__, load_info.fname.c_str());
1881
- }
1882
-
1883
- for (int i = 0; i < n_tensors; i++) {
1884
- std::string name = lm_gguf_get_tensor_name(ctx_gguf, i);
1885
-
1886
- int layer_idx = -1;
1887
-
1888
- // split on '.'
1889
- size_t dotpos = name.find('.');
1890
- if (dotpos != std::string::npos && name.substr(0, dotpos) == "direction") {
1891
- try {
1892
- layer_idx = std::stoi(name.substr(dotpos + 1));
1893
- } catch (...) {
1894
- layer_idx = -1;
1895
- }
1896
- }
1897
- if (layer_idx < 0) {
1898
- LOG_ERR("%s: invalid/unparsable direction tensor layer index in %s\n", __func__, load_info.fname.c_str());
1899
- result.n_embd = -1;
1900
- break;
1901
- } else if (layer_idx == 0) {
1902
- LOG_ERR("%s: invalid (zero) direction tensor layer index in %s\n", __func__, load_info.fname.c_str());
1903
- result.n_embd = -1;
1904
- break;
1905
- }
1906
-
1907
- struct lm_ggml_tensor * tensor = lm_ggml_get_tensor(ctx, name.c_str());
1908
- if (tensor->type != LM_GGML_TYPE_F32) {
1909
- LOG_ERR("%s: invalid (non-F32) direction tensor type in %s\n", __func__, load_info.fname.c_str());
1910
- result.n_embd = -1;
1911
- break;
1912
- }
1913
- if (lm_ggml_n_dims(tensor) != 1) {
1914
- LOG_ERR("%s: invalid (non-1D) direction tensor shape in %s\n", __func__, load_info.fname.c_str());
1915
- result.n_embd = -1;
1916
- break;
1917
- }
1918
-
1919
- if (result.n_embd == -1) {
1920
- result.n_embd = lm_ggml_nelements(tensor);
1921
- } else if (lm_ggml_nelements(tensor) != result.n_embd) {
1922
- LOG_ERR("%s: direction tensor in %s does not match previous dimensions\n", __func__, load_info.fname.c_str());
1923
- result.n_embd = -1;
1924
- break;
1925
- }
1926
-
1927
- // extend if necessary - do not store data for layer 0 (it's not used)
1928
- result.data.resize(std::max(result.data.size(), static_cast<size_t>(result.n_embd * layer_idx)), 0.0f);
1929
-
1930
- const float * src = (const float *) tensor->data;
1931
- float * dst = result.data.data() + result.n_embd * (layer_idx - 1); // layer 1 at [0]
1932
- for (int j = 0; j < result.n_embd; j++) {
1933
- dst[j] += src[j] * load_info.strength; // allows multiple directions for same layer in same file
1934
- }
1935
-
1936
- }
1937
-
1938
- if (result.n_embd == -1) {
1939
- LOG_WRN("%s: skipping %s due to invalid direction tensors\n", __func__, load_info.fname.c_str());
1940
- result.data.clear();
1941
- }
1942
-
1943
- lm_gguf_free(ctx_gguf);
1944
- lm_ggml_free(ctx);
1945
-
1946
- return result;
1947
- }
1948
-
1949
- common_control_vector_data common_control_vector_load(const std::vector<common_control_vector_load_info> & load_infos) {
1950
- common_control_vector_data result = { -1, {} };
1951
-
1952
- for (const auto & info : load_infos) {
1953
- auto cur = common_control_vector_load_one(info);
1954
-
1955
- if (cur.n_embd == -1) {
1956
- result.n_embd = -1;
1957
- break;
1958
- }
1959
- if (result.n_embd != -1 && result.n_embd != cur.n_embd) {
1960
- LOG_ERR("%s: control vectors in %s does not match previous dimensions\n", __func__, info.fname.c_str());
1961
- result.n_embd = -1;
1962
- break;
1963
- }
1964
-
1965
- if (result.n_embd == -1) {
1966
- result = std::move(cur);
1967
- } else {
1968
- result.data.resize(std::max(result.data.size(), cur.data.size()), 0.0f); // extend if necessary
1969
- for (size_t i = 0; i < cur.data.size(); i++) {
1970
- result.data[i] += cur.data[i];
1971
- }
1972
- }
1973
- }
1974
-
1975
- if (result.n_embd == -1) {
1976
- LOG_ERR("%s: no valid control vector files passed\n", __func__);
1977
- result.data.clear();
1978
- }
1979
-
1980
- return result;
1981
- }
1982
-
1
+ #if defined(_MSC_VER)
2
+ #define _SILENCE_CXX17_CODECVT_HEADER_DEPRECATION_WARNING
3
+ #endif
4
+
5
+ #include "ggml.h"
6
+ #include "gguf.h"
7
+
8
+ #include "common.h"
9
+ #include "log.h"
10
+ // Change JSON_ASSERT from assert() to LM_GGML_ASSERT:
11
+ #define JSON_ASSERT LM_GGML_ASSERT
12
+ #include "json.hpp"
13
+ #include "json-schema-to-grammar.h"
14
+ #include "llama.h"
15
+
16
+ #include <algorithm>
17
+ #include <cinttypes>
18
+ #include <climits>
19
+ #include <cmath>
20
+ #include <codecvt>
21
+ #include <cstdarg>
22
+ #include <cstring>
23
+ #include <ctime>
24
+ #include <filesystem>
25
+ #include <fstream>
26
+ #include <iostream>
27
+ #include <iterator>
28
+ #include <regex>
29
+ #include <sstream>
30
+ #include <string>
31
+ #include <thread>
32
+ #include <unordered_map>
33
+ #include <unordered_set>
34
+ #include <vector>
35
+
36
+ #if defined(__APPLE__) && defined(__MACH__)
37
+ #include <sys/types.h>
38
+ #include <sys/sysctl.h>
39
+ #endif
40
+
41
+ #if defined(_WIN32)
42
+ #define WIN32_LEAN_AND_MEAN
43
+ #ifndef NOMINMAX
44
+ # define NOMINMAX
45
+ #endif
46
+ #include <locale>
47
+ #include <windows.h>
48
+ #include <fcntl.h>
49
+ #include <io.h>
50
+ #else
51
+ #include <sys/ioctl.h>
52
+ #include <sys/stat.h>
53
+ #include <unistd.h>
54
+ #endif
55
+ #if defined(LLAMA_USE_CURL)
56
+ #include <curl/curl.h>
57
+ #include <curl/easy.h>
58
+ #include <future>
59
+ #endif
60
+
61
+ // build info
62
+ int LLAMA_BUILD_NUMBER = 0;
63
+ char const *LLAMA_COMMIT = "unknown";
64
+ char const *LLAMA_COMPILER = "unknown";
65
+ char const *LLAMA_BUILD_TARGET = "unknown";
66
+
67
+ #if defined(_MSC_VER)
68
+ #pragma warning(disable: 4244 4267) // possible loss of data
69
+ #endif
70
+
71
+ #if defined(LLAMA_USE_CURL)
72
+ #ifdef __linux__
73
+ #include <linux/limits.h>
74
+ #elif defined(_WIN32)
75
+ # if !defined(PATH_MAX)
76
+ # define PATH_MAX MAX_PATH
77
+ # endif
78
+ #else
79
+ #include <sys/syslimits.h>
80
+ #endif
81
+ #define LLAMA_CURL_MAX_URL_LENGTH 2084 // Maximum URL Length in Chrome: 2083
82
+
83
+ //
84
+ // CURL utils
85
+ //
86
+
87
+ using curl_ptr = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>;
88
+
89
+ // cannot use unique_ptr for curl_slist, because we cannot update without destroying the old one
90
+ struct curl_slist_ptr {
91
+ struct curl_slist * ptr = nullptr;
92
+ ~curl_slist_ptr() {
93
+ if (ptr) {
94
+ curl_slist_free_all(ptr);
95
+ }
96
+ }
97
+ };
98
+ #endif // LLAMA_USE_CURL
99
+
100
+ using json = nlohmann::ordered_json;
101
+
102
+ //
103
+ // CPU utils
104
+ //
105
+
106
+ int32_t cpu_get_num_physical_cores() {
107
+ #ifdef __linux__
108
+ // enumerate the set of thread siblings, num entries is num cores
109
+ std::unordered_set<std::string> siblings;
110
+ for (uint32_t cpu=0; cpu < UINT32_MAX; ++cpu) {
111
+ std::ifstream thread_siblings("/sys/devices/system/cpu/cpu"
112
+ + std::to_string(cpu) + "/topology/thread_siblings");
113
+ if (!thread_siblings.is_open()) {
114
+ break; // no more cpus
115
+ }
116
+ std::string line;
117
+ if (std::getline(thread_siblings, line)) {
118
+ siblings.insert(line);
119
+ }
120
+ }
121
+ if (!siblings.empty()) {
122
+ return static_cast<int32_t>(siblings.size());
123
+ }
124
+ #elif defined(__APPLE__) && defined(__MACH__)
125
+ int32_t num_physical_cores;
126
+ size_t len = sizeof(num_physical_cores);
127
+ int result = sysctlbyname("hw.perflevel0.physicalcpu", &num_physical_cores, &len, NULL, 0);
128
+ if (result == 0) {
129
+ return num_physical_cores;
130
+ }
131
+ result = sysctlbyname("hw.physicalcpu", &num_physical_cores, &len, NULL, 0);
132
+ if (result == 0) {
133
+ return num_physical_cores;
134
+ }
135
+ #elif defined(_WIN32) && (_WIN32_WINNT >= 0x0601) && !defined(__MINGW64__) // windows 7 and later
136
+ // TODO: windows + arm64 + mingw64
137
+ unsigned int n_threads_win = std::thread::hardware_concurrency();
138
+ unsigned int default_threads = n_threads_win > 0 ? (n_threads_win <= 4 ? n_threads_win : n_threads_win / 2) : 4;
139
+
140
+ DWORD buffer_size = 0;
141
+ if (!GetLogicalProcessorInformationEx(RelationProcessorCore, nullptr, &buffer_size)) {
142
+ if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
143
+ return default_threads;
144
+ }
145
+ }
146
+
147
+ std::vector<char> buffer(buffer_size);
148
+ if (!GetLogicalProcessorInformationEx(RelationProcessorCore, reinterpret_cast<PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX>(buffer.data()), &buffer_size)) {
149
+ return default_threads;
150
+ }
151
+
152
+ int32_t num_physical_cores = 0;
153
+ PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX info = reinterpret_cast<PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX>(buffer.data());
154
+ while (buffer_size > 0) {
155
+ if (info->Relationship == RelationProcessorCore) {
156
+ num_physical_cores += info->Processor.GroupCount;
157
+ }
158
+ buffer_size -= info->Size;
159
+ info = reinterpret_cast<PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX>(reinterpret_cast<char*>(info) + info->Size);
160
+ }
161
+
162
+ return num_physical_cores > 0 ? num_physical_cores : default_threads;
163
+ #endif
164
+ unsigned int n_threads = std::thread::hardware_concurrency();
165
+ return n_threads > 0 ? (n_threads <= 4 ? n_threads : n_threads / 2) : 4;
166
+ }
167
+
168
+ #if defined(__x86_64__) && defined(__linux__) && !defined(__ANDROID__)
169
+ #include <pthread.h>
170
+
171
+ static void cpuid(unsigned leaf, unsigned subleaf,
172
+ unsigned *eax, unsigned *ebx, unsigned *ecx, unsigned *edx) {
173
+ __asm__("movq\t%%rbx,%%rsi\n\t"
174
+ "cpuid\n\t"
175
+ "xchgq\t%%rbx,%%rsi"
176
+ : "=a"(*eax), "=S"(*ebx), "=c"(*ecx), "=d"(*edx)
177
+ : "0"(leaf), "2"(subleaf));
178
+ }
179
+
180
+ static int pin_cpu(int cpu) {
181
+ cpu_set_t mask;
182
+ CPU_ZERO(&mask);
183
+ CPU_SET(cpu, &mask);
184
+ return pthread_setaffinity_np(pthread_self(), sizeof(mask), &mask);
185
+ }
186
+
187
+ static bool is_hybrid_cpu(void) {
188
+ unsigned eax, ebx, ecx, edx;
189
+ cpuid(7, 0, &eax, &ebx, &ecx, &edx);
190
+ return !!(edx & (1u << 15));
191
+ }
192
+
193
+ static bool is_running_on_efficiency_core(void) {
194
+ unsigned eax, ebx, ecx, edx;
195
+ cpuid(0x1a, 0, &eax, &ebx, &ecx, &edx);
196
+ int intel_atom = 0x20;
197
+ int core_type = (eax & 0xff000000u) >> 24;
198
+ return core_type == intel_atom;
199
+ }
200
+
201
+ static int cpu_count_math_cpus(int n_cpu) {
202
+ int result = 0;
203
+ for (int cpu = 0; cpu < n_cpu; ++cpu) {
204
+ if (pin_cpu(cpu)) {
205
+ return -1;
206
+ }
207
+ if (is_running_on_efficiency_core()) {
208
+ continue; // efficiency cores harm lockstep threading
209
+ }
210
+ ++cpu; // hyperthreading isn't useful for linear algebra
211
+ ++result;
212
+ }
213
+ return result;
214
+ }
215
+
216
+ #endif // __x86_64__ && __linux__
217
+
218
+ /**
219
+ * Returns number of CPUs on system that are useful for math.
220
+ */
221
+ int32_t cpu_get_num_math() {
222
+ #if defined(__x86_64__) && defined(__linux__) && !defined(__ANDROID__)
223
+ int n_cpu = sysconf(_SC_NPROCESSORS_ONLN);
224
+ if (n_cpu < 1) {
225
+ return cpu_get_num_physical_cores();
226
+ }
227
+ if (is_hybrid_cpu()) {
228
+ cpu_set_t affinity;
229
+ if (!pthread_getaffinity_np(pthread_self(), sizeof(affinity), &affinity)) {
230
+ int result = cpu_count_math_cpus(n_cpu);
231
+ pthread_setaffinity_np(pthread_self(), sizeof(affinity), &affinity);
232
+ if (result > 0) {
233
+ return result;
234
+ }
235
+ }
236
+ }
237
+ #endif
238
+ return cpu_get_num_physical_cores();
239
+ }
240
+
241
+ // Helper for setting process priority
242
+
243
+ #if defined(_WIN32)
244
+
245
+ bool set_process_priority(enum lm_ggml_sched_priority prio) {
246
+ if (prio == LM_GGML_SCHED_PRIO_NORMAL) {
247
+ return true;
248
+ }
249
+
250
+ DWORD p = NORMAL_PRIORITY_CLASS;
251
+ switch (prio) {
252
+ case LM_GGML_SCHED_PRIO_NORMAL: p = NORMAL_PRIORITY_CLASS; break;
253
+ case LM_GGML_SCHED_PRIO_MEDIUM: p = ABOVE_NORMAL_PRIORITY_CLASS; break;
254
+ case LM_GGML_SCHED_PRIO_HIGH: p = HIGH_PRIORITY_CLASS; break;
255
+ case LM_GGML_SCHED_PRIO_REALTIME: p = REALTIME_PRIORITY_CLASS; break;
256
+ }
257
+
258
+ if (!SetPriorityClass(GetCurrentProcess(), p)) {
259
+ LOG_WRN("failed to set process priority class %d : (%d)\n", prio, (int) GetLastError());
260
+ return false;
261
+ }
262
+
263
+ return true;
264
+ }
265
+
266
+ #else // MacOS and POSIX
267
+ #include <sys/types.h>
268
+ #include <sys/resource.h>
269
+
270
+ bool set_process_priority(enum lm_ggml_sched_priority prio) {
271
+ if (prio == LM_GGML_SCHED_PRIO_NORMAL) {
272
+ return true;
273
+ }
274
+
275
+ int p = 0;
276
+ switch (prio) {
277
+ case LM_GGML_SCHED_PRIO_NORMAL: p = 0; break;
278
+ case LM_GGML_SCHED_PRIO_MEDIUM: p = -5; break;
279
+ case LM_GGML_SCHED_PRIO_HIGH: p = -10; break;
280
+ case LM_GGML_SCHED_PRIO_REALTIME: p = -20; break;
281
+ }
282
+
283
+ if (!setpriority(PRIO_PROCESS, 0, p)) {
284
+ LOG_WRN("failed to set process priority %d : %s (%d)\n", prio, strerror(errno), errno);
285
+ return false;
286
+ }
287
+ return true;
288
+ }
289
+
290
+ #endif
291
+
292
+ //
293
+ // CLI argument parsing
294
+ //
295
+
296
+
297
+ void postprocess_cpu_params(cpu_params& cpuparams, const cpu_params* role_model) {
298
+ int32_t n_set = 0;
299
+
300
+ if (cpuparams.n_threads < 0) {
301
+ // Assuming everything about cpuparams is invalid
302
+ if (role_model != nullptr) {
303
+ cpuparams = *role_model;
304
+ } else {
305
+ cpuparams.n_threads = cpu_get_num_math();
306
+ }
307
+ }
308
+
309
+ for (int32_t i = 0; i < LM_GGML_MAX_N_THREADS; i++) {
310
+ if (cpuparams.cpumask[i]) {
311
+ n_set++;
312
+ }
313
+ }
314
+
315
+ if (n_set && n_set < cpuparams.n_threads) {
316
+ // Not enough set bits, may experience performance issues.
317
+ LOG_WRN("Not enough set bits in CPU mask (%d) to satisfy requested thread count: %d\n", n_set, cpuparams.n_threads);
318
+ }
319
+ }
320
+
321
+ bool parse_cpu_range(const std::string & range, bool (&boolmask)[LM_GGML_MAX_N_THREADS]) {
322
+ size_t dash_loc = range.find('-');
323
+ if (dash_loc == std::string::npos) {
324
+ LOG_ERR("Format of CPU range is invalid! Expected [<start>]-[<end>].\n");
325
+ return false;
326
+ }
327
+
328
+ size_t start_i;
329
+ size_t end_i;
330
+
331
+ if (dash_loc == 0) {
332
+ start_i = 0;
333
+ } else {
334
+ start_i = std::stoull(range.substr(0, dash_loc));
335
+ if (start_i >= LM_GGML_MAX_N_THREADS) {
336
+ LOG_ERR("Start index out of bounds!\n");
337
+ return false;
338
+ }
339
+ }
340
+
341
+ if (dash_loc == range.length() - 1) {
342
+ end_i = LM_GGML_MAX_N_THREADS - 1;
343
+ } else {
344
+ end_i = std::stoull(range.substr(dash_loc + 1));
345
+ if (end_i >= LM_GGML_MAX_N_THREADS) {
346
+ LOG_ERR("End index out of bounds!\n");
347
+ return false;
348
+ }
349
+ }
350
+
351
+ for (size_t i = start_i; i <= end_i; i++) {
352
+ boolmask[i] = true;
353
+ }
354
+
355
+ return true;
356
+ }
357
+
358
+ bool parse_cpu_mask(const std::string & mask, bool (&boolmask)[LM_GGML_MAX_N_THREADS]) {
359
+ // Discard potential 0x prefix
360
+ size_t start_i = 0;
361
+ if (mask.length() >= 2 && mask.substr(0, 2) == "0x") {
362
+ start_i = 2;
363
+ }
364
+
365
+ size_t num_digits = mask.length() - start_i;
366
+ if (num_digits > 128) num_digits = 128;
367
+
368
+ size_t end_i = num_digits + start_i;
369
+
370
+ for (size_t i = start_i, n = (num_digits*4 - 1); i < end_i; i++, n-=4) {
371
+ char c = mask.at(i);
372
+ int8_t id = c;
373
+
374
+ if ((c >= '0' && c <= '9')) {
375
+ id -= '0';
376
+ } else if (c >= 'a' && c <= 'f') {
377
+ id -= 'a' - 10;
378
+ } else if (c >= 'A' && c <= 'F') {
379
+ id -= 'A' - 10;
380
+ } else {
381
+ LOG_ERR("Invalid hex character '%c' at position %d\n", c, int32_t(i));
382
+ return false;
383
+ }
384
+
385
+ boolmask[ n ] = boolmask[ n ] || ((id & 8) != 0);
386
+ boolmask[n - 1] = boolmask[n - 1] || ((id & 4) != 0);
387
+ boolmask[n - 2] = boolmask[n - 2] || ((id & 2) != 0);
388
+ boolmask[n - 3] = boolmask[n - 3] || ((id & 1) != 0);
389
+ }
390
+
391
+ return true;
392
+ }
393
+
394
+ void common_init() {
395
+ llama_log_set([](lm_ggml_log_level level, const char * text, void * /*user_data*/) {
396
+ if (LOG_DEFAULT_LLAMA <= common_log_verbosity_thold) {
397
+ common_log_add(common_log_main(), level, "%s", text);
398
+ }
399
+ }, NULL);
400
+
401
+ #ifdef NDEBUG
402
+ const char * build_type = "";
403
+ #else
404
+ const char * build_type = " (debug)";
405
+ #endif
406
+
407
+ LOG_INF("build: %d (%s) with %s for %s%s\n", LLAMA_BUILD_NUMBER, LLAMA_COMMIT, LLAMA_COMPILER, LLAMA_BUILD_TARGET, build_type);
408
+ }
409
+
410
+ std::string common_params_get_system_info(const common_params & params) {
411
+ std::ostringstream os;
412
+
413
+ os << "system_info: n_threads = " << params.cpuparams.n_threads;
414
+ if (params.cpuparams_batch.n_threads != -1) {
415
+ os << " (n_threads_batch = " << params.cpuparams_batch.n_threads << ")";
416
+ }
417
+ #if defined(_WIN32) && (_WIN32_WINNT >= 0x0601) && !defined(__MINGW64__) // windows 7 and later
418
+ // TODO: windows + arm64 + mingw64
419
+ DWORD logicalProcessorCount = GetActiveProcessorCount(ALL_PROCESSOR_GROUPS);
420
+ os << " / " << logicalProcessorCount << " | " << llama_print_system_info();
421
+ #else
422
+ os << " / " << std::thread::hardware_concurrency() << " | " << llama_print_system_info();
423
+ #endif
424
+
425
+ return os.str();
426
+ }
427
+
428
+ //
429
+ // String utils
430
+ //
431
+
432
+ std::string string_format(const char * fmt, ...) {
433
+ va_list ap;
434
+ va_list ap2;
435
+ va_start(ap, fmt);
436
+ va_copy(ap2, ap);
437
+ int size = vsnprintf(NULL, 0, fmt, ap);
438
+ LM_GGML_ASSERT(size >= 0 && size < INT_MAX); // NOLINT
439
+ std::vector<char> buf(size + 1);
440
+ int size2 = vsnprintf(buf.data(), size + 1, fmt, ap2);
441
+ LM_GGML_ASSERT(size2 == size);
442
+ va_end(ap2);
443
+ va_end(ap);
444
+ return std::string(buf.data(), size);
445
+ }
446
+
447
+ std::string string_strip(const std::string & str) {
448
+ size_t start = 0;
449
+ size_t end = str.size();
450
+ while (start < end && std::isspace(str[start])) {
451
+ start++;
452
+ }
453
+ while (end > start && std::isspace(str[end - 1])) {
454
+ end--;
455
+ }
456
+ return str.substr(start, end - start);
457
+ }
458
+
459
+ std::string string_get_sortable_timestamp() {
460
+ using clock = std::chrono::system_clock;
461
+
462
+ const clock::time_point current_time = clock::now();
463
+ const time_t as_time_t = clock::to_time_t(current_time);
464
+ char timestamp_no_ns[100];
465
+ std::strftime(timestamp_no_ns, 100, "%Y_%m_%d-%H_%M_%S", std::localtime(&as_time_t));
466
+
467
+ const int64_t ns = std::chrono::duration_cast<std::chrono::nanoseconds>(
468
+ current_time.time_since_epoch() % 1000000000).count();
469
+ char timestamp_ns[11];
470
+ snprintf(timestamp_ns, 11, "%09" PRId64, ns);
471
+
472
+ return std::string(timestamp_no_ns) + "." + std::string(timestamp_ns);
473
+ }
474
+
475
+ void string_replace_all(std::string & s, const std::string & search, const std::string & replace) {
476
+ if (search.empty()) {
477
+ return;
478
+ }
479
+ std::string builder;
480
+ builder.reserve(s.length());
481
+ size_t pos = 0;
482
+ size_t last_pos = 0;
483
+ while ((pos = s.find(search, last_pos)) != std::string::npos) {
484
+ builder.append(s, last_pos, pos - last_pos);
485
+ builder.append(replace);
486
+ last_pos = pos + search.length();
487
+ }
488
+ builder.append(s, last_pos, std::string::npos);
489
+ s = std::move(builder);
490
+ }
491
+
492
+ std::string string_from(bool value) {
493
+ return value ? "true" : "false";
494
+ }
495
+
496
+ std::string string_from(const std::vector<int> & values) {
497
+ std::stringstream buf;
498
+
499
+ buf << "[ ";
500
+ bool first = true;
501
+ for (auto e : values) {
502
+ if (first) {
503
+ first = false;
504
+ } else {
505
+ buf << ", ";
506
+ }
507
+ buf << std::to_string(e);
508
+ }
509
+ buf << " ]";
510
+
511
+ return buf.str();
512
+ }
513
+
514
+ std::string string_from(const struct llama_context * ctx, const std::vector<llama_token> & tokens) {
515
+ std::stringstream buf;
516
+
517
+ buf << "[ ";
518
+
519
+ bool first = true;
520
+ for (const auto & token : tokens) {
521
+ if (!first) {
522
+ buf << ", ";
523
+ } else {
524
+ first = false;
525
+ }
526
+
527
+ auto detokenized = common_token_to_piece(ctx, token);
528
+
529
+ detokenized.erase(
530
+ std::remove_if(
531
+ detokenized.begin(),
532
+ detokenized.end(),
533
+ [](const unsigned char c) { return !std::isprint(c); }),
534
+ detokenized.end());
535
+
536
+ buf << "'" << detokenized << "'"
537
+ << ":" << std::to_string(token);
538
+ }
539
+
540
+ buf << " ]";
541
+
542
+ return buf.str();
543
+ }
544
+
545
+ std::string string_from(const struct llama_context * ctx, const struct llama_batch & batch) {
546
+ std::stringstream buf;
547
+
548
+ buf << "[ ";
549
+
550
+ bool first = true;
551
+ for (int i = 0; i < batch.n_tokens; ++i) {
552
+ if (!first) {
553
+ buf << ", ";
554
+ } else {
555
+ first = false;
556
+ }
557
+
558
+ auto detokenized = common_token_to_piece(ctx, batch.token[i]);
559
+
560
+ detokenized.erase(
561
+ std::remove_if(
562
+ detokenized.begin(),
563
+ detokenized.end(),
564
+ [](const unsigned char c) { return !std::isprint(c); }),
565
+ detokenized.end());
566
+
567
+ buf << "\n" << std::to_string(i)
568
+ << ", token '" << detokenized << "'"
569
+ << ", pos " << std::to_string(batch.pos[i])
570
+ << ", n_seq_id " << std::to_string(batch.n_seq_id[i])
571
+ << ", seq_id " << std::to_string(batch.seq_id[i][0])
572
+ << ", logits " << std::to_string(batch.logits[i]);
573
+ }
574
+
575
+ buf << " ]";
576
+
577
+ return buf.str();
578
+ }
579
+
580
+ void string_process_escapes(std::string & input) {
581
+ std::size_t input_len = input.length();
582
+ std::size_t output_idx = 0;
583
+
584
+ for (std::size_t input_idx = 0; input_idx < input_len; ++input_idx) {
585
+ if (input[input_idx] == '\\' && input_idx + 1 < input_len) {
586
+ switch (input[++input_idx]) {
587
+ case 'n': input[output_idx++] = '\n'; break;
588
+ case 'r': input[output_idx++] = '\r'; break;
589
+ case 't': input[output_idx++] = '\t'; break;
590
+ case '\'': input[output_idx++] = '\''; break;
591
+ case '\"': input[output_idx++] = '\"'; break;
592
+ case '\\': input[output_idx++] = '\\'; break;
593
+ case 'x':
594
+ // Handle \x12, etc
595
+ if (input_idx + 2 < input_len) {
596
+ const char x[3] = { input[input_idx + 1], input[input_idx + 2], 0 };
597
+ char *err_p = nullptr;
598
+ const long val = std::strtol(x, &err_p, 16);
599
+ if (err_p == x + 2) {
600
+ input_idx += 2;
601
+ input[output_idx++] = char(val);
602
+ break;
603
+ }
604
+ }
605
+ // fall through
606
+ default: input[output_idx++] = '\\';
607
+ input[output_idx++] = input[input_idx]; break;
608
+ }
609
+ } else {
610
+ input[output_idx++] = input[input_idx];
611
+ }
612
+ }
613
+
614
+ input.resize(output_idx);
615
+ }
616
+
617
+ bool string_parse_kv_override(const char * data, std::vector<llama_model_kv_override> & overrides) {
618
+ const char * sep = strchr(data, '=');
619
+ if (sep == nullptr || sep - data >= 128) {
620
+ LOG_ERR("%s: malformed KV override '%s'\n", __func__, data);
621
+ return false;
622
+ }
623
+ llama_model_kv_override kvo;
624
+ std::strncpy(kvo.key, data, sep - data);
625
+ kvo.key[sep - data] = 0;
626
+ sep++;
627
+ if (strncmp(sep, "int:", 4) == 0) {
628
+ sep += 4;
629
+ kvo.tag = LLAMA_KV_OVERRIDE_TYPE_INT;
630
+ kvo.val_i64 = std::atol(sep);
631
+ } else if (strncmp(sep, "float:", 6) == 0) {
632
+ sep += 6;
633
+ kvo.tag = LLAMA_KV_OVERRIDE_TYPE_FLOAT;
634
+ kvo.val_f64 = std::atof(sep);
635
+ } else if (strncmp(sep, "bool:", 5) == 0) {
636
+ sep += 5;
637
+ kvo.tag = LLAMA_KV_OVERRIDE_TYPE_BOOL;
638
+ if (std::strcmp(sep, "true") == 0) {
639
+ kvo.val_bool = true;
640
+ } else if (std::strcmp(sep, "false") == 0) {
641
+ kvo.val_bool = false;
642
+ } else {
643
+ LOG_ERR("%s: invalid boolean value for KV override '%s'\n", __func__, data);
644
+ return false;
645
+ }
646
+ } else if (strncmp(sep, "str:", 4) == 0) {
647
+ sep += 4;
648
+ kvo.tag = LLAMA_KV_OVERRIDE_TYPE_STR;
649
+ if (strlen(sep) > 127) {
650
+ LOG_ERR("%s: malformed KV override '%s', value cannot exceed 127 chars\n", __func__, data);
651
+ return false;
652
+ }
653
+ strncpy(kvo.val_str, sep, 127);
654
+ kvo.val_str[127] = '\0';
655
+ } else {
656
+ LOG_ERR("%s: invalid type for KV override '%s'\n", __func__, data);
657
+ return false;
658
+ }
659
+ overrides.emplace_back(std::move(kvo));
660
+ return true;
661
+ }
662
+
663
+ //
664
+ // Filesystem utils
665
+ //
666
+
667
+ // Validate if a filename is safe to use
668
+ // To validate a full path, split the path by the OS-specific path separator, and validate each part with this function
669
+ bool fs_validate_filename(const std::string & filename) {
670
+ if (!filename.length()) {
671
+ // Empty filename invalid
672
+ return false;
673
+ }
674
+ if (filename.length() > 255) {
675
+ // Limit at common largest possible filename on Linux filesystems
676
+ // to avoid unnecessary further validation
677
+ // (On systems with smaller limits it will be caught by the OS)
678
+ return false;
679
+ }
680
+
681
+ std::u32string filename_utf32;
682
+ try {
683
+ #if defined(__clang__)
684
+ // disable C++17 deprecation warning for std::codecvt_utf8
685
+ # pragma clang diagnostic push
686
+ # pragma clang diagnostic ignored "-Wdeprecated-declarations"
687
+ #endif
688
+ std::wstring_convert<std::codecvt_utf8<char32_t>, char32_t> converter;
689
+
690
+ #if defined(__clang__)
691
+ # pragma clang diagnostic pop
692
+ #endif
693
+
694
+ filename_utf32 = converter.from_bytes(filename);
695
+
696
+ // If the reverse conversion mismatches, it means overlong UTF-8 sequences were used,
697
+ // or invalid encodings were encountered. Reject such attempts
698
+ std::string filename_reencoded = converter.to_bytes(filename_utf32);
699
+ if (filename_reencoded != filename) {
700
+ return false;
701
+ }
702
+ } catch (const std::exception &) {
703
+ return false;
704
+ }
705
+
706
+ // Check for forbidden codepoints:
707
+ // - Control characters
708
+ // - Unicode equivalents of illegal characters
709
+ // - UTF-16 surrogate pairs
710
+ // - UTF-8 replacement character
711
+ // - Byte order mark (BOM)
712
+ // - Illegal characters: / \ : * ? " < > |
713
+ for (char32_t c : filename_utf32) {
714
+ if (c <= 0x1F // Control characters (C0)
715
+ || c == 0x7F // Control characters (DEL)
716
+ || (c >= 0x80 && c <= 0x9F) // Control characters (C1)
717
+ || c == 0xFF0E // Fullwidth Full Stop (period equivalent)
718
+ || c == 0x2215 // Division Slash (forward slash equivalent)
719
+ || c == 0x2216 // Set Minus (backslash equivalent)
720
+ || (c >= 0xD800 && c <= 0xDFFF) // UTF-16 surrogate pairs
721
+ || c == 0xFFFD // Replacement Character (UTF-8)
722
+ || c == 0xFEFF // Byte Order Mark (BOM)
723
+ || c == '/' || c == '\\' || c == ':' || c == '*' // Illegal characters
724
+ || c == '?' || c == '"' || c == '<' || c == '>' || c == '|') {
725
+ return false;
726
+ }
727
+ }
728
+
729
+ // Reject any leading or trailing ' ', or any trailing '.', these are stripped on Windows and will cause a different filename
730
+ // Unicode and other whitespace is not affected, only 0x20 space
731
+ if (filename.front() == ' ' || filename.back() == ' ' || filename.back() == '.') {
732
+ return false;
733
+ }
734
+
735
+ // Reject any ".." (currently stricter than necessary, it should be fine to just check for == ".." instead)
736
+ if (filename.find("..") != std::string::npos) {
737
+ return false;
738
+ }
739
+
740
+ // Reject "."
741
+ if (filename == ".") {
742
+ return false;
743
+ }
744
+
745
+ return true;
746
+ }
747
+
748
+ // returns true if successful, false otherwise
749
+ bool fs_create_directory_with_parents(const std::string & path) {
750
+ #ifdef _WIN32
751
+ std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;
752
+ std::wstring wpath = converter.from_bytes(path);
753
+
754
+ // if the path already exists, check whether it's a directory
755
+ const DWORD attributes = GetFileAttributesW(wpath.c_str());
756
+ if ((attributes != INVALID_FILE_ATTRIBUTES) && (attributes & FILE_ATTRIBUTE_DIRECTORY)) {
757
+ return true;
758
+ }
759
+
760
+ size_t pos_slash = 0;
761
+
762
+ // process path from front to back, procedurally creating directories
763
+ while ((pos_slash = path.find('\\', pos_slash)) != std::string::npos) {
764
+ const std::wstring subpath = wpath.substr(0, pos_slash);
765
+ const wchar_t * test = subpath.c_str();
766
+
767
+ const bool success = CreateDirectoryW(test, NULL);
768
+ if (!success) {
769
+ const DWORD error = GetLastError();
770
+
771
+ // if the path already exists, ensure that it's a directory
772
+ if (error == ERROR_ALREADY_EXISTS) {
773
+ const DWORD attributes = GetFileAttributesW(subpath.c_str());
774
+ if (attributes == INVALID_FILE_ATTRIBUTES || !(attributes & FILE_ATTRIBUTE_DIRECTORY)) {
775
+ return false;
776
+ }
777
+ } else {
778
+ return false;
779
+ }
780
+ }
781
+
782
+ pos_slash += 1;
783
+ }
784
+
785
+ return true;
786
+ #else
787
+ // if the path already exists, check whether it's a directory
788
+ struct stat info;
789
+ if (stat(path.c_str(), &info) == 0) {
790
+ return S_ISDIR(info.st_mode);
791
+ }
792
+
793
+ size_t pos_slash = 1; // skip leading slashes for directory creation
794
+
795
+ // process path from front to back, procedurally creating directories
796
+ while ((pos_slash = path.find('/', pos_slash)) != std::string::npos) {
797
+ const std::string subpath = path.substr(0, pos_slash);
798
+ struct stat info;
799
+
800
+ // if the path already exists, ensure that it's a directory
801
+ if (stat(subpath.c_str(), &info) == 0) {
802
+ if (!S_ISDIR(info.st_mode)) {
803
+ return false;
804
+ }
805
+ } else {
806
+ // create parent directories
807
+ const int ret = mkdir(subpath.c_str(), 0755);
808
+ if (ret != 0) {
809
+ return false;
810
+ }
811
+ }
812
+
813
+ pos_slash += 1;
814
+ }
815
+
816
+ return true;
817
+ #endif // _WIN32
818
+ }
819
+
820
+ std::string fs_get_cache_directory() {
821
+ std::string cache_directory = "";
822
+ auto ensure_trailing_slash = [](std::string p) {
823
+ // Make sure to add trailing slash
824
+ if (p.back() != DIRECTORY_SEPARATOR) {
825
+ p += DIRECTORY_SEPARATOR;
826
+ }
827
+ return p;
828
+ };
829
+ if (getenv("LLAMA_CACHE")) {
830
+ cache_directory = std::getenv("LLAMA_CACHE");
831
+ } else {
832
+ #ifdef __linux__
833
+ if (std::getenv("XDG_CACHE_HOME")) {
834
+ cache_directory = std::getenv("XDG_CACHE_HOME");
835
+ } else {
836
+ cache_directory = std::getenv("HOME") + std::string("/.cache/");
837
+ }
838
+ #elif defined(__APPLE__)
839
+ cache_directory = std::getenv("HOME") + std::string("/Library/Caches/");
840
+ #elif defined(_WIN32)
841
+ cache_directory = std::getenv("LOCALAPPDATA");
842
+ #endif // __linux__
843
+ cache_directory = ensure_trailing_slash(cache_directory);
844
+ cache_directory += "llama.cpp";
845
+ }
846
+ return ensure_trailing_slash(cache_directory);
847
+ }
848
+
849
+ std::string fs_get_cache_file(const std::string & filename) {
850
+ LM_GGML_ASSERT(filename.find(DIRECTORY_SEPARATOR) == std::string::npos);
851
+ std::string cache_directory = fs_get_cache_directory();
852
+ const bool success = fs_create_directory_with_parents(cache_directory);
853
+ if (!success) {
854
+ throw std::runtime_error("failed to create cache directory: " + cache_directory);
855
+ }
856
+ return cache_directory + filename;
857
+ }
858
+
859
+
860
+ //
861
+ // Model utils
862
+ //
863
+ struct common_init_result common_init_from_params(common_params & params) {
864
+ common_init_result iparams;
865
+ auto mparams = common_model_params_to_llama(params);
866
+
867
+ llama_model * model = nullptr;
868
+
869
+ if (!params.hf_repo.empty() && !params.hf_file.empty()) {
870
+ model = common_load_model_from_hf(params.hf_repo, params.hf_file, params.model, params.hf_token, mparams);
871
+ } else if (!params.model_url.empty()) {
872
+ model = common_load_model_from_url(params.model_url, params.model, params.hf_token, mparams);
873
+ } else {
874
+ model = llama_model_load_from_file(params.model.c_str(), mparams);
875
+ }
876
+
877
+ if (model == NULL) {
878
+ LOG_ERR("%s: failed to load model '%s'\n", __func__, params.model.c_str());
879
+ return iparams;
880
+ }
881
+
882
+ const llama_vocab * vocab = llama_model_get_vocab(model);
883
+
884
+ if (params.reranking) {
885
+ bool ok = true;
886
+
887
+ if (llama_vocab_bos(vocab) == LLAMA_TOKEN_NULL) {
888
+ LOG_WRN("%s: warning: vocab does not have a BOS token, reranking will not work\n", __func__);
889
+ ok = false;
890
+ }
891
+
892
+ if (llama_vocab_eos(vocab) == LLAMA_TOKEN_NULL) {
893
+ LOG_WRN("%s: warning: vocab does not have an EOS token, reranking will not work\n", __func__);
894
+ ok = false;
895
+ }
896
+
897
+ if (llama_vocab_sep(vocab) == LLAMA_TOKEN_NULL) {
898
+ LOG_WRN("%s: warning: vocab does not have a SEP token, reranking will not work\n", __func__);
899
+ ok = false;
900
+ }
901
+
902
+ if (!ok) {
903
+ llama_model_free(model);
904
+
905
+ return iparams;
906
+ }
907
+ }
908
+
909
+ auto cparams = common_context_params_to_llama(params);
910
+
911
+ llama_context * lctx = llama_init_from_model(model, cparams);
912
+ if (lctx == NULL) {
913
+ LOG_ERR("%s: failed to create context with model '%s'\n", __func__, params.model.c_str());
914
+ llama_model_free(model);
915
+ return iparams;
916
+ }
917
+
918
+ if (params.ctx_shift && !llama_kv_cache_can_shift(lctx)) {
919
+ LOG_WRN("%s: KV cache shifting is not supported for this model, disabling KV cache shifting\n", __func__);
920
+ params.ctx_shift = false;
921
+ }
922
+
923
+ if (!params.control_vectors.empty()) {
924
+ if (params.control_vector_layer_start <= 0) params.control_vector_layer_start = 1;
925
+ if (params.control_vector_layer_end <= 0) params.control_vector_layer_end = llama_model_n_layer(model);
926
+
927
+ const auto cvec = common_control_vector_load(params.control_vectors);
928
+ if (cvec.n_embd == -1) {
929
+ llama_free(lctx);
930
+ llama_model_free(model);
931
+
932
+ return iparams;
933
+ }
934
+
935
+ int err = llama_apply_adapter_cvec(
936
+ lctx,
937
+ cvec.data.data(),
938
+ cvec.data.size(),
939
+ cvec.n_embd,
940
+ params.control_vector_layer_start,
941
+ params.control_vector_layer_end);
942
+ if (err) {
943
+ llama_free(lctx);
944
+ llama_model_free(model);
945
+
946
+ return iparams;
947
+ }
948
+ }
949
+
950
+ // load and optionally apply lora adapters
951
+ for (auto & la : params.lora_adapters) {
952
+ llama_adapter_lora_ptr lora;
953
+ lora.reset(llama_adapter_lora_init(model, la.path.c_str()));
954
+ if (lora == nullptr) {
955
+ LOG_ERR("%s: failed to apply lora adapter '%s'\n", __func__, la.path.c_str());
956
+ llama_free(lctx);
957
+ llama_model_free(model);
958
+ return iparams;
959
+ }
960
+
961
+ la.ptr = lora.get();
962
+ iparams.lora.emplace_back(std::move(lora)); // copy to list of loaded adapters
963
+ }
964
+
965
+ if (!params.lora_init_without_apply) {
966
+ common_set_adapter_lora(lctx, params.lora_adapters);
967
+ }
968
+
969
+ if (params.sampling.ignore_eos && llama_vocab_eos(vocab) == LLAMA_TOKEN_NULL) {
970
+ LOG_WRN("%s: warning: vocab does not have an EOS token, ignoring --ignore-eos\n", __func__);
971
+ params.sampling.ignore_eos = false;
972
+ }
973
+
974
+ if (params.sampling.ignore_eos) {
975
+ for (llama_token i = 0; i < llama_vocab_n_tokens(vocab); i++) {
976
+ if (llama_vocab_is_eog(vocab, i)) {
977
+ LOG_INF("%s: added %s logit bias = %f\n", __func__, common_token_to_piece(lctx, i).c_str(), -INFINITY);
978
+ params.sampling.logit_bias.push_back({i, -INFINITY});
979
+ }
980
+ }
981
+ }
982
+
983
+ if (params.sampling.penalty_last_n == -1) {
984
+ LOG_INF("%s: setting penalty_last_n to ctx_size = %d\n", __func__, llama_n_ctx(lctx));
985
+ params.sampling.penalty_last_n = llama_n_ctx(lctx);
986
+ }
987
+
988
+ if (params.sampling.dry_penalty_last_n == -1) {
989
+ LOG_INF("%s: setting dry_penalty_last_n to ctx_size = %d\n", __func__, llama_n_ctx(lctx));
990
+ params.sampling.dry_penalty_last_n = llama_n_ctx(lctx);
991
+ }
992
+
993
+ if (params.warmup) {
994
+ LOG_WRN("%s: warming up the model with an empty run - please wait ... (--no-warmup to disable)\n", __func__);
995
+
996
+ std::vector<llama_token> tmp;
997
+ llama_token bos = llama_vocab_bos(vocab);
998
+ llama_token eos = llama_vocab_eos(vocab);
999
+
1000
+ // some models (e.g. T5) don't have a BOS token
1001
+ if (bos != LLAMA_TOKEN_NULL) {
1002
+ tmp.push_back(bos);
1003
+ }
1004
+ if (eos != LLAMA_TOKEN_NULL) {
1005
+ tmp.push_back(eos);
1006
+ }
1007
+ if (tmp.empty()) {
1008
+ tmp.push_back(0);
1009
+ }
1010
+
1011
+ if (llama_model_has_encoder(model)) {
1012
+ llama_encode(lctx, llama_batch_get_one(tmp.data(), tmp.size()));
1013
+ llama_token decoder_start_token_id = llama_model_decoder_start_token(model);
1014
+ if (decoder_start_token_id == LLAMA_TOKEN_NULL) {
1015
+ decoder_start_token_id = bos;
1016
+ }
1017
+ tmp.clear();
1018
+ tmp.push_back(decoder_start_token_id);
1019
+ }
1020
+ if (llama_model_has_decoder(model)) {
1021
+ llama_decode(lctx, llama_batch_get_one(tmp.data(), std::min(tmp.size(), (size_t) params.n_batch)));
1022
+ }
1023
+ llama_kv_cache_clear(lctx);
1024
+ llama_synchronize(lctx);
1025
+ llama_perf_context_reset(lctx);
1026
+ }
1027
+
1028
+ iparams.model.reset(model);
1029
+ iparams.context.reset(lctx);
1030
+
1031
+ return iparams;
1032
+ }
1033
+
1034
+ void common_set_adapter_lora(struct llama_context * ctx, std::vector<common_adapter_lora_info> & lora) {
1035
+ llama_clear_adapter_lora(ctx);
1036
+ for (auto & la : lora) {
1037
+ if (la.scale != 0.0f) {
1038
+ llama_set_adapter_lora(ctx, la.ptr, la.scale);
1039
+ }
1040
+ }
1041
+ }
1042
+
1043
+ struct llama_model_params common_model_params_to_llama(common_params & params) {
1044
+ auto mparams = llama_model_default_params();
1045
+
1046
+ if (!params.devices.empty()) {
1047
+ mparams.devices = params.devices.data();
1048
+ }
1049
+ if (params.n_gpu_layers != -1) {
1050
+ mparams.n_gpu_layers = params.n_gpu_layers;
1051
+ }
1052
+
1053
+ mparams.progress_callback_user_data = params.progress_callback_user_data;
1054
+ mparams.progress_callback = params.progress_callback;
1055
+ mparams.vocab_only = params.vocab_only;
1056
+ mparams.main_gpu = params.main_gpu;
1057
+ mparams.split_mode = params.split_mode;
1058
+ mparams.tensor_split = params.tensor_split;
1059
+ mparams.use_mmap = params.use_mmap;
1060
+ mparams.use_mlock = params.use_mlock;
1061
+ mparams.check_tensors = params.check_tensors;
1062
+ if (params.kv_overrides.empty()) {
1063
+ mparams.kv_overrides = NULL;
1064
+ } else {
1065
+ LM_GGML_ASSERT(params.kv_overrides.back().key[0] == 0 && "KV overrides not terminated with empty key");
1066
+ mparams.kv_overrides = params.kv_overrides.data();
1067
+ }
1068
+
1069
+ return mparams;
1070
+ }
1071
+
1072
+ struct llama_context_params common_context_params_to_llama(const common_params & params) {
1073
+ auto cparams = llama_context_default_params();
1074
+
1075
+ cparams.n_ctx = params.n_ctx;
1076
+ cparams.n_seq_max = params.n_parallel;
1077
+ cparams.n_batch = params.n_batch;
1078
+ cparams.n_ubatch = params.n_ubatch;
1079
+ cparams.n_threads = params.cpuparams.n_threads;
1080
+ cparams.n_threads_batch = params.cpuparams_batch.n_threads == -1 ?
1081
+ params.cpuparams.n_threads : params.cpuparams_batch.n_threads;
1082
+ cparams.logits_all = params.logits_all;
1083
+ cparams.embeddings = params.embedding;
1084
+ cparams.rope_scaling_type = params.rope_scaling_type;
1085
+ cparams.rope_freq_base = params.rope_freq_base;
1086
+ cparams.rope_freq_scale = params.rope_freq_scale;
1087
+ cparams.yarn_ext_factor = params.yarn_ext_factor;
1088
+ cparams.yarn_attn_factor = params.yarn_attn_factor;
1089
+ cparams.yarn_beta_fast = params.yarn_beta_fast;
1090
+ cparams.yarn_beta_slow = params.yarn_beta_slow;
1091
+ cparams.yarn_orig_ctx = params.yarn_orig_ctx;
1092
+ cparams.pooling_type = params.pooling_type;
1093
+ cparams.attention_type = params.attention_type;
1094
+ cparams.defrag_thold = params.defrag_thold;
1095
+ cparams.cb_eval = params.cb_eval;
1096
+ cparams.cb_eval_user_data = params.cb_eval_user_data;
1097
+ cparams.offload_kqv = !params.no_kv_offload;
1098
+ cparams.flash_attn = params.flash_attn;
1099
+ cparams.no_perf = params.no_perf;
1100
+
1101
+ if (params.reranking) {
1102
+ cparams.embeddings = true;
1103
+ cparams.pooling_type = LLAMA_POOLING_TYPE_RANK;
1104
+ }
1105
+
1106
+ cparams.type_k = params.cache_type_k;
1107
+ cparams.type_v = params.cache_type_v;
1108
+
1109
+ return cparams;
1110
+ }
1111
+
1112
+ struct lm_ggml_threadpool_params lm_ggml_threadpool_params_from_cpu_params(const cpu_params & params) {
1113
+ struct lm_ggml_threadpool_params tpp;
1114
+
1115
+ lm_ggml_threadpool_params_init(&tpp, params.n_threads); // setup the defaults
1116
+
1117
+ if (params.mask_valid) {
1118
+ std::memcpy(&tpp.cpumask, &params.cpumask, LM_GGML_MAX_N_THREADS);
1119
+ }
1120
+
1121
+ tpp.prio = params.priority;
1122
+ tpp.poll = params.poll;
1123
+ tpp.strict_cpu = params.strict_cpu;
1124
+
1125
+ return tpp;
1126
+ }
1127
+
1128
+ #ifdef LLAMA_USE_CURL
1129
+
1130
+ #define CURL_MAX_RETRY 3
1131
+ #define CURL_RETRY_DELAY_SECONDS 2
1132
+
1133
+ static bool curl_perform_with_retry(const std::string & url, CURL * curl, int max_attempts, int retry_delay_seconds) {
1134
+ int remaining_attempts = max_attempts;
1135
+
1136
+ while (remaining_attempts > 0) {
1137
+ LOG_INF("%s: Trying to download from %s (attempt %d of %d)...\n", __func__ , url.c_str(), max_attempts - remaining_attempts + 1, max_attempts);
1138
+
1139
+ CURLcode res = curl_easy_perform(curl);
1140
+ if (res == CURLE_OK) {
1141
+ return true;
1142
+ }
1143
+
1144
+ int exponential_backoff_delay = std::pow(retry_delay_seconds, max_attempts - remaining_attempts) * 1000;
1145
+ LOG_WRN("%s: curl_easy_perform() failed: %s, retrying after %d milliseconds...\n", __func__, curl_easy_strerror(res), exponential_backoff_delay);
1146
+
1147
+ remaining_attempts--;
1148
+ std::this_thread::sleep_for(std::chrono::milliseconds(exponential_backoff_delay));
1149
+ }
1150
+
1151
+ LOG_ERR("%s: curl_easy_perform() failed after %d attempts\n", __func__, max_attempts);
1152
+
1153
+ return false;
1154
+ }
1155
+
1156
+ static bool common_download_file(const std::string & url, const std::string & path, const std::string & hf_token) {
1157
+ // Initialize libcurl
1158
+ curl_ptr curl(curl_easy_init(), &curl_easy_cleanup);
1159
+ curl_slist_ptr http_headers;
1160
+ if (!curl) {
1161
+ LOG_ERR("%s: error initializing libcurl\n", __func__);
1162
+ return false;
1163
+ }
1164
+
1165
+ bool force_download = false;
1166
+
1167
+ // Set the URL, allow to follow http redirection
1168
+ curl_easy_setopt(curl.get(), CURLOPT_URL, url.c_str());
1169
+ curl_easy_setopt(curl.get(), CURLOPT_FOLLOWLOCATION, 1L);
1170
+
1171
+ // Check if hf-token or bearer-token was specified
1172
+ if (!hf_token.empty()) {
1173
+ std::string auth_header = "Authorization: Bearer " + hf_token;
1174
+ http_headers.ptr = curl_slist_append(http_headers.ptr, auth_header.c_str());
1175
+ curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, http_headers.ptr);
1176
+ }
1177
+
1178
+ #if defined(_WIN32)
1179
+ // CURLSSLOPT_NATIVE_CA tells libcurl to use standard certificate store of
1180
+ // operating system. Currently implemented under MS-Windows.
1181
+ curl_easy_setopt(curl.get(), CURLOPT_SSL_OPTIONS, CURLSSLOPT_NATIVE_CA);
1182
+ #endif
1183
+
1184
+ // Check if the file already exists locally
1185
+ auto file_exists = std::filesystem::exists(path);
1186
+
1187
+ // If the file exists, check its JSON metadata companion file.
1188
+ std::string metadata_path = path + ".json";
1189
+ nlohmann::json metadata;
1190
+ std::string etag;
1191
+ std::string last_modified;
1192
+
1193
+ if (file_exists) {
1194
+ // Try and read the JSON metadata file (note: stream autoclosed upon exiting this block).
1195
+ std::ifstream metadata_in(metadata_path);
1196
+ if (metadata_in.good()) {
1197
+ try {
1198
+ metadata_in >> metadata;
1199
+ LOG_INF("%s: previous metadata file found %s: %s\n", __func__, metadata_path.c_str(), metadata.dump().c_str());
1200
+ if (metadata.contains("url") && metadata.at("url").is_string()) {
1201
+ auto previous_url = metadata.at("url").get<std::string>();
1202
+ if (previous_url != url) {
1203
+ LOG_ERR("%s: Model URL mismatch: %s != %s\n", __func__, url.c_str(), previous_url.c_str());
1204
+ return false;
1205
+ }
1206
+ }
1207
+ if (metadata.contains("etag") && metadata.at("etag").is_string()) {
1208
+ etag = metadata.at("etag");
1209
+ }
1210
+ if (metadata.contains("lastModified") && metadata.at("lastModified").is_string()) {
1211
+ last_modified = metadata.at("lastModified");
1212
+ }
1213
+ } catch (const nlohmann::json::exception & e) {
1214
+ LOG_ERR("%s: error reading metadata file %s: %s\n", __func__, metadata_path.c_str(), e.what());
1215
+ return false;
1216
+ }
1217
+ }
1218
+ } else {
1219
+ LOG_INF("%s: no previous model file found %s\n", __func__, path.c_str());
1220
+ }
1221
+
1222
+ // Send a HEAD request to retrieve the etag and last-modified headers
1223
+ struct common_load_model_from_url_headers {
1224
+ std::string etag;
1225
+ std::string last_modified;
1226
+ };
1227
+
1228
+ common_load_model_from_url_headers headers;
1229
+
1230
+ {
1231
+ typedef size_t(*CURLOPT_HEADERFUNCTION_PTR)(char *, size_t, size_t, void *);
1232
+ auto header_callback = [](char * buffer, size_t /*size*/, size_t n_items, void * userdata) -> size_t {
1233
+ common_load_model_from_url_headers * headers = (common_load_model_from_url_headers *) userdata;
1234
+
1235
+ static std::regex header_regex("([^:]+): (.*)\r\n");
1236
+ static std::regex etag_regex("ETag", std::regex_constants::icase);
1237
+ static std::regex last_modified_regex("Last-Modified", std::regex_constants::icase);
1238
+
1239
+ std::string header(buffer, n_items);
1240
+ std::smatch match;
1241
+ if (std::regex_match(header, match, header_regex)) {
1242
+ const std::string & key = match[1];
1243
+ const std::string & value = match[2];
1244
+ if (std::regex_match(key, match, etag_regex)) {
1245
+ headers->etag = value;
1246
+ } else if (std::regex_match(key, match, last_modified_regex)) {
1247
+ headers->last_modified = value;
1248
+ }
1249
+ }
1250
+ return n_items;
1251
+ };
1252
+
1253
+ curl_easy_setopt(curl.get(), CURLOPT_NOBODY, 1L); // will trigger the HEAD verb
1254
+ curl_easy_setopt(curl.get(), CURLOPT_NOPROGRESS, 1L); // hide head request progress
1255
+ curl_easy_setopt(curl.get(), CURLOPT_HEADERFUNCTION, static_cast<CURLOPT_HEADERFUNCTION_PTR>(header_callback));
1256
+ curl_easy_setopt(curl.get(), CURLOPT_HEADERDATA, &headers);
1257
+
1258
+ bool was_perform_successful = curl_perform_with_retry(url, curl.get(), CURL_MAX_RETRY, CURL_RETRY_DELAY_SECONDS);
1259
+ if (!was_perform_successful) {
1260
+ return false;
1261
+ }
1262
+
1263
+ long http_code = 0;
1264
+ curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &http_code);
1265
+ if (http_code != 200) {
1266
+ // HEAD not supported, we don't know if the file has changed
1267
+ // force trigger downloading
1268
+ force_download = true;
1269
+ LOG_ERR("%s: HEAD invalid http status code received: %ld\n", __func__, http_code);
1270
+ }
1271
+ }
1272
+
1273
+ bool should_download = !file_exists || force_download;
1274
+ if (!should_download) {
1275
+ if (!etag.empty() && etag != headers.etag) {
1276
+ LOG_WRN("%s: ETag header is different (%s != %s): triggering a new download\n", __func__, etag.c_str(), headers.etag.c_str());
1277
+ should_download = true;
1278
+ } else if (!last_modified.empty() && last_modified != headers.last_modified) {
1279
+ LOG_WRN("%s: Last-Modified header is different (%s != %s): triggering a new download\n", __func__, last_modified.c_str(), headers.last_modified.c_str());
1280
+ should_download = true;
1281
+ }
1282
+ }
1283
+ if (should_download) {
1284
+ std::string path_temporary = path + ".downloadInProgress";
1285
+ if (file_exists) {
1286
+ LOG_WRN("%s: deleting previous downloaded file: %s\n", __func__, path.c_str());
1287
+ if (remove(path.c_str()) != 0) {
1288
+ LOG_ERR("%s: unable to delete file: %s\n", __func__, path.c_str());
1289
+ return false;
1290
+ }
1291
+ }
1292
+
1293
+ // Set the output file
1294
+
1295
+ struct FILE_deleter {
1296
+ void operator()(FILE * f) const {
1297
+ fclose(f);
1298
+ }
1299
+ };
1300
+
1301
+ std::unique_ptr<FILE, FILE_deleter> outfile(fopen(path_temporary.c_str(), "wb"));
1302
+ if (!outfile) {
1303
+ LOG_ERR("%s: error opening local file for writing: %s\n", __func__, path.c_str());
1304
+ return false;
1305
+ }
1306
+
1307
+ typedef size_t(*CURLOPT_WRITEFUNCTION_PTR)(void * data, size_t size, size_t nmemb, void * fd);
1308
+ auto write_callback = [](void * data, size_t size, size_t nmemb, void * fd) -> size_t {
1309
+ return fwrite(data, size, nmemb, (FILE *)fd);
1310
+ };
1311
+ curl_easy_setopt(curl.get(), CURLOPT_NOBODY, 0L);
1312
+ curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, static_cast<CURLOPT_WRITEFUNCTION_PTR>(write_callback));
1313
+ curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, outfile.get());
1314
+
1315
+ // display download progress
1316
+ curl_easy_setopt(curl.get(), CURLOPT_NOPROGRESS, 0L);
1317
+
1318
+ // helper function to hide password in URL
1319
+ auto llama_download_hide_password_in_url = [](const std::string & url) -> std::string {
1320
+ std::size_t protocol_pos = url.find("://");
1321
+ if (protocol_pos == std::string::npos) {
1322
+ return url; // Malformed URL
1323
+ }
1324
+
1325
+ std::size_t at_pos = url.find('@', protocol_pos + 3);
1326
+ if (at_pos == std::string::npos) {
1327
+ return url; // No password in URL
1328
+ }
1329
+
1330
+ return url.substr(0, protocol_pos + 3) + "********" + url.substr(at_pos);
1331
+ };
1332
+
1333
+ // start the download
1334
+ LOG_INF("%s: trying to download model from %s to %s (server_etag:%s, server_last_modified:%s)...\n", __func__,
1335
+ llama_download_hide_password_in_url(url).c_str(), path.c_str(), headers.etag.c_str(), headers.last_modified.c_str());
1336
+ bool was_perform_successful = curl_perform_with_retry(url, curl.get(), CURL_MAX_RETRY, CURL_RETRY_DELAY_SECONDS);
1337
+ if (!was_perform_successful) {
1338
+ return false;
1339
+ }
1340
+
1341
+ long http_code = 0;
1342
+ curl_easy_getinfo (curl.get(), CURLINFO_RESPONSE_CODE, &http_code);
1343
+ if (http_code < 200 || http_code >= 400) {
1344
+ LOG_ERR("%s: invalid http status code received: %ld\n", __func__, http_code);
1345
+ return false;
1346
+ }
1347
+
1348
+ // Causes file to be closed explicitly here before we rename it.
1349
+ outfile.reset();
1350
+
1351
+ // Write the updated JSON metadata file.
1352
+ metadata.update({
1353
+ {"url", url},
1354
+ {"etag", headers.etag},
1355
+ {"lastModified", headers.last_modified}
1356
+ });
1357
+ std::ofstream(metadata_path) << metadata.dump(4);
1358
+ LOG_INF("%s: file metadata saved: %s\n", __func__, metadata_path.c_str());
1359
+
1360
+ if (rename(path_temporary.c_str(), path.c_str()) != 0) {
1361
+ LOG_ERR("%s: unable to rename file: %s to %s\n", __func__, path_temporary.c_str(), path.c_str());
1362
+ return false;
1363
+ }
1364
+ }
1365
+
1366
+ return true;
1367
+ }
1368
+
1369
+ struct llama_model * common_load_model_from_url(
1370
+ const std::string & model_url,
1371
+ const std::string & local_path,
1372
+ const std::string & hf_token,
1373
+ const struct llama_model_params & params) {
1374
+ // Basic validation of the model_url
1375
+ if (model_url.empty()) {
1376
+ LOG_ERR("%s: invalid model_url\n", __func__);
1377
+ return NULL;
1378
+ }
1379
+
1380
+ if (!common_download_file(model_url, local_path, hf_token)) {
1381
+ return NULL;
1382
+ }
1383
+
1384
+ // check for additional GGUFs split to download
1385
+ int n_split = 0;
1386
+ {
1387
+ struct lm_gguf_init_params lm_gguf_params = {
1388
+ /*.no_alloc = */ true,
1389
+ /*.ctx = */ NULL,
1390
+ };
1391
+ auto * ctx_gguf = lm_gguf_init_from_file(local_path.c_str(), lm_gguf_params);
1392
+ if (!ctx_gguf) {
1393
+ LOG_ERR("\n%s: failed to load input GGUF from %s\n", __func__, local_path.c_str());
1394
+ return NULL;
1395
+ }
1396
+
1397
+ auto key_n_split = lm_gguf_find_key(ctx_gguf, LLM_KV_SPLIT_COUNT);
1398
+ if (key_n_split >= 0) {
1399
+ n_split = lm_gguf_get_val_u16(ctx_gguf, key_n_split);
1400
+ }
1401
+
1402
+ lm_gguf_free(ctx_gguf);
1403
+ }
1404
+
1405
+ if (n_split > 1) {
1406
+ char split_prefix[PATH_MAX] = {0};
1407
+ char split_url_prefix[LLAMA_CURL_MAX_URL_LENGTH] = {0};
1408
+
1409
+ // Verify the first split file format
1410
+ // and extract split URL and PATH prefixes
1411
+ {
1412
+ if (!llama_split_prefix(split_prefix, sizeof(split_prefix), local_path.c_str(), 0, n_split)) {
1413
+ LOG_ERR("\n%s: unexpected model file name: %s n_split=%d\n", __func__, local_path.c_str(), n_split);
1414
+ return NULL;
1415
+ }
1416
+
1417
+ if (!llama_split_prefix(split_url_prefix, sizeof(split_url_prefix), model_url.c_str(), 0, n_split)) {
1418
+ LOG_ERR("\n%s: unexpected model url: %s n_split=%d\n", __func__, model_url.c_str(), n_split);
1419
+ return NULL;
1420
+ }
1421
+ }
1422
+
1423
+ // Prepare download in parallel
1424
+ std::vector<std::future<bool>> futures_download;
1425
+ for (int idx = 1; idx < n_split; idx++) {
1426
+ futures_download.push_back(std::async(std::launch::async, [&split_prefix, &split_url_prefix, &n_split, hf_token](int download_idx) -> bool {
1427
+ char split_path[PATH_MAX] = {0};
1428
+ llama_split_path(split_path, sizeof(split_path), split_prefix, download_idx, n_split);
1429
+
1430
+ char split_url[LLAMA_CURL_MAX_URL_LENGTH] = {0};
1431
+ llama_split_path(split_url, sizeof(split_url), split_url_prefix, download_idx, n_split);
1432
+
1433
+ return common_download_file(split_url, split_path, hf_token);
1434
+ }, idx));
1435
+ }
1436
+
1437
+ // Wait for all downloads to complete
1438
+ for (auto & f : futures_download) {
1439
+ if (!f.get()) {
1440
+ return NULL;
1441
+ }
1442
+ }
1443
+ }
1444
+
1445
+ return llama_model_load_from_file(local_path.c_str(), params);
1446
+ }
1447
+
1448
+ struct llama_model * common_load_model_from_hf(
1449
+ const std::string & repo,
1450
+ const std::string & remote_path,
1451
+ const std::string & local_path,
1452
+ const std::string & hf_token,
1453
+ const struct llama_model_params & params) {
1454
+ // construct hugging face model url:
1455
+ //
1456
+ // --repo ggml-org/models --file tinyllama-1.1b/ggml-model-f16.gguf
1457
+ // https://huggingface.co/ggml-org/models/resolve/main/tinyllama-1.1b/ggml-model-f16.gguf
1458
+ //
1459
+ // --repo TheBloke/Mixtral-8x7B-v0.1-GGUF --file mixtral-8x7b-v0.1.Q4_K_M.gguf
1460
+ // https://huggingface.co/TheBloke/Mixtral-8x7B-v0.1-GGUF/resolve/main/mixtral-8x7b-v0.1.Q4_K_M.gguf
1461
+ //
1462
+
1463
+ std::string model_url = "https://huggingface.co/";
1464
+ model_url += repo;
1465
+ model_url += "/resolve/main/";
1466
+ model_url += remote_path;
1467
+
1468
+ return common_load_model_from_url(model_url, local_path, hf_token, params);
1469
+ }
1470
+
1471
+ /**
1472
+ * Allow getting the HF file from the HF repo with tag (like ollama), for example:
1473
+ * - bartowski/Llama-3.2-3B-Instruct-GGUF:q4
1474
+ * - bartowski/Llama-3.2-3B-Instruct-GGUF:Q4_K_M
1475
+ * - bartowski/Llama-3.2-3B-Instruct-GGUF:q5_k_s
1476
+ * Tag is optional, default to "latest" (meaning it checks for Q4_K_M first, then Q4, then if not found, return the first GGUF file in repo)
1477
+ *
1478
+ * Return pair of <repo, file> (with "repo" already having tag removed)
1479
+ *
1480
+ * Note: we use the Ollama-compatible HF API, but not using the blobId. Instead, we use the special "ggufFile" field which returns the value for "hf_file". This is done to be backward-compatible with existing cache files.
1481
+ */
1482
+ std::pair<std::string, std::string> common_get_hf_file(const std::string & hf_repo_with_tag, const std::string & hf_token) {
1483
+ auto parts = string_split<std::string>(hf_repo_with_tag, ':');
1484
+ std::string tag = parts.size() > 1 ? parts.back() : "latest";
1485
+ std::string hf_repo = parts[0];
1486
+ if (string_split<std::string>(hf_repo, '/').size() != 2) {
1487
+ throw std::invalid_argument("error: invalid HF repo format, expected <user>/<model>[:quant]\n");
1488
+ }
1489
+
1490
+ // fetch model info from Hugging Face Hub API
1491
+ json model_info;
1492
+ curl_ptr curl(curl_easy_init(), &curl_easy_cleanup);
1493
+ curl_slist_ptr http_headers;
1494
+ std::string res_str;
1495
+ std::string url = "https://huggingface.co/v2/" + hf_repo + "/manifests/" + tag;
1496
+ curl_easy_setopt(curl.get(), CURLOPT_URL, url.c_str());
1497
+ curl_easy_setopt(curl.get(), CURLOPT_NOPROGRESS, 1L);
1498
+ typedef size_t(*CURLOPT_WRITEFUNCTION_PTR)(void * ptr, size_t size, size_t nmemb, void * data);
1499
+ auto write_callback = [](void * ptr, size_t size, size_t nmemb, void * data) -> size_t {
1500
+ static_cast<std::string *>(data)->append((char * ) ptr, size * nmemb);
1501
+ return size * nmemb;
1502
+ };
1503
+ curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, static_cast<CURLOPT_WRITEFUNCTION_PTR>(write_callback));
1504
+ curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &res_str);
1505
+ #if defined(_WIN32)
1506
+ curl_easy_setopt(curl.get(), CURLOPT_SSL_OPTIONS, CURLSSLOPT_NATIVE_CA);
1507
+ #endif
1508
+ if (!hf_token.empty()) {
1509
+ std::string auth_header = "Authorization: Bearer " + hf_token;
1510
+ http_headers.ptr = curl_slist_append(http_headers.ptr, auth_header.c_str());
1511
+ }
1512
+ // Important: the User-Agent must be "llama-cpp" to get the "ggufFile" field in the response
1513
+ http_headers.ptr = curl_slist_append(http_headers.ptr, "User-Agent: llama-cpp");
1514
+ http_headers.ptr = curl_slist_append(http_headers.ptr, "Accept: application/json");
1515
+ curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, http_headers.ptr);
1516
+
1517
+ CURLcode res = curl_easy_perform(curl.get());
1518
+
1519
+ if (res != CURLE_OK) {
1520
+ throw std::runtime_error("error: cannot make GET request to HF API");
1521
+ }
1522
+
1523
+ long res_code;
1524
+ curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &res_code);
1525
+ if (res_code == 200) {
1526
+ model_info = json::parse(res_str);
1527
+ } else if (res_code == 401) {
1528
+ throw std::runtime_error("error: model is private or does not exist; if you are accessing a gated model, please provide a valid HF token");
1529
+ } else {
1530
+ throw std::runtime_error(string_format("error from HF API, response code: %ld, data: %s", res_code, res_str.c_str()));
1531
+ }
1532
+
1533
+ // check response
1534
+ if (!model_info.contains("ggufFile")) {
1535
+ throw std::runtime_error("error: model does not have ggufFile");
1536
+ }
1537
+ json & lm_gguf_file = model_info.at("ggufFile");
1538
+ if (!lm_gguf_file.contains("rfilename")) {
1539
+ throw std::runtime_error("error: ggufFile does not have rfilename");
1540
+ }
1541
+
1542
+ return std::make_pair(hf_repo, lm_gguf_file.at("rfilename"));
1543
+ }
1544
+
1545
+ #else
1546
+
1547
+ struct llama_model * common_load_model_from_url(
1548
+ const std::string & /*model_url*/,
1549
+ const std::string & /*local_path*/,
1550
+ const std::string & /*hf_token*/,
1551
+ const struct llama_model_params & /*params*/) {
1552
+ LOG_WRN("%s: llama.cpp built without libcurl, downloading from an url not supported.\n", __func__);
1553
+ return nullptr;
1554
+ }
1555
+
1556
+ struct llama_model * common_load_model_from_hf(
1557
+ const std::string & /*repo*/,
1558
+ const std::string & /*remote_path*/,
1559
+ const std::string & /*local_path*/,
1560
+ const std::string & /*hf_token*/,
1561
+ const struct llama_model_params & /*params*/) {
1562
+ LOG_WRN("%s: llama.cpp built without libcurl, downloading from Hugging Face not supported.\n", __func__);
1563
+ return nullptr;
1564
+ }
1565
+
1566
+ std::pair<std::string, std::string> common_get_hf_file(const std::string &, const std::string &) {
1567
+ LOG_WRN("%s: llama.cpp built without libcurl, downloading from Hugging Face not supported.\n", __func__);
1568
+ return std::make_pair("", "");
1569
+ }
1570
+
1571
+ #endif // LLAMA_USE_CURL
1572
+
1573
+ //
1574
+ // Batch utils
1575
+ //
1576
+
1577
+ void common_batch_clear(struct llama_batch & batch) {
1578
+ batch.n_tokens = 0;
1579
+ }
1580
+
1581
+ void common_batch_add(
1582
+ struct llama_batch & batch,
1583
+ llama_token id,
1584
+ llama_pos pos,
1585
+ const std::vector<llama_seq_id> & seq_ids,
1586
+ bool logits) {
1587
+ LM_GGML_ASSERT(batch.seq_id[batch.n_tokens] && "llama_batch size exceeded");
1588
+
1589
+ batch.token [batch.n_tokens] = id;
1590
+ batch.pos [batch.n_tokens] = pos;
1591
+ batch.n_seq_id[batch.n_tokens] = seq_ids.size();
1592
+ for (size_t i = 0; i < seq_ids.size(); ++i) {
1593
+ batch.seq_id[batch.n_tokens][i] = seq_ids[i];
1594
+ }
1595
+ batch.logits [batch.n_tokens] = logits;
1596
+
1597
+ batch.n_tokens++;
1598
+ }
1599
+
1600
+ //
1601
+ // Token utils
1602
+ //
1603
+
1604
+ size_t common_lcp(const llama_tokens & a, const llama_tokens & b) {
1605
+ size_t i;
1606
+ for (i = 0; i < a.size() && i < b.size() && a[i] == b[i]; i++) {}
1607
+
1608
+ return i;
1609
+ }
1610
+
1611
+ size_t common_lcs(const llama_tokens & a, const llama_tokens & b) {
1612
+ // check for empty sequences
1613
+ if (a.empty() || b.empty()) {
1614
+ return 0;
1615
+ }
1616
+
1617
+ // get the lengths of the input sequences
1618
+ size_t a_len = a.size();
1619
+ size_t b_len = b.size();
1620
+
1621
+ // initialize the maximum length of the longest common subsequence (LCS)
1622
+ size_t max_length = 0;
1623
+
1624
+ // use two rows instead of a 2D matrix to optimize space
1625
+ std::vector<size_t> prev_row(b_len + 1, 0);
1626
+ std::vector<size_t> curr_row(b_len + 1, 0);
1627
+
1628
+ // iterate through the elements of a
1629
+ for (size_t i = 1; i <= a_len; i++) {
1630
+ // iterate through the elements of b
1631
+ for (size_t j = 1; j <= b_len; j++) {
1632
+ // if elements at the current positions match
1633
+ if (a[i - 1] == b[j - 1]) {
1634
+ // if it's the first element of either sequences, set LCS length to 1
1635
+ if (i == 1 || j == 1) {
1636
+ curr_row[j] = 1;
1637
+ } else {
1638
+ // increment LCS length by 1 compared to the previous element
1639
+ curr_row[j] = prev_row[j - 1] + 1;
1640
+ }
1641
+
1642
+ // update max_length if necessary
1643
+ if (curr_row[j] > max_length) {
1644
+ max_length = curr_row[j];
1645
+ }
1646
+ } else {
1647
+ // reset LCS length if elements don't match
1648
+ curr_row[j] = 0;
1649
+ }
1650
+ }
1651
+
1652
+ // update the previous row for the next iteration
1653
+ prev_row = curr_row;
1654
+ }
1655
+
1656
+ // return the maximum length of the LCS
1657
+ return max_length;
1658
+ }
1659
+
1660
+ //
1661
+ // Vocab utils
1662
+ //
1663
+
1664
+ std::vector<llama_token> common_tokenize(
1665
+ const struct llama_context * ctx,
1666
+ const std::string & text,
1667
+ bool add_special,
1668
+ bool parse_special) {
1669
+ const llama_model * model = llama_get_model(ctx);
1670
+ const llama_vocab * vocab = llama_model_get_vocab(model);
1671
+ return common_tokenize(vocab, text, add_special, parse_special);
1672
+ }
1673
+
1674
+ std::vector<llama_token> common_tokenize(
1675
+ const struct llama_vocab * vocab,
1676
+ const std::string & text,
1677
+ bool add_special,
1678
+ bool parse_special) {
1679
+ // upper limit for the number of tokens
1680
+ int n_tokens = text.length() + 2 * add_special;
1681
+ std::vector<llama_token> result(n_tokens);
1682
+ n_tokens = llama_tokenize(vocab, text.data(), text.length(), result.data(), result.size(), add_special, parse_special);
1683
+ if (n_tokens < 0) {
1684
+ result.resize(-n_tokens);
1685
+ int check = llama_tokenize(vocab, text.data(), text.length(), result.data(), result.size(), add_special, parse_special);
1686
+ LM_GGML_ASSERT(check == -n_tokens);
1687
+ } else {
1688
+ result.resize(n_tokens);
1689
+ }
1690
+ return result;
1691
+ }
1692
+
1693
+ std::string common_token_to_piece(const struct llama_context * ctx, llama_token token, bool special) {
1694
+ const llama_model * model = llama_get_model(ctx);
1695
+ const llama_vocab * vocab = llama_model_get_vocab(model);
1696
+ return common_token_to_piece(vocab, token, special);
1697
+ }
1698
+
1699
+ std::string common_token_to_piece(const struct llama_vocab * vocab, llama_token token, bool special) {
1700
+ std::string piece;
1701
+ piece.resize(piece.capacity()); // using string internal cache, 15 bytes + '\n'
1702
+ const int n_chars = llama_token_to_piece(vocab, token, &piece[0], piece.size(), 0, special);
1703
+ if (n_chars < 0) {
1704
+ piece.resize(-n_chars);
1705
+ int check = llama_token_to_piece(vocab, token, &piece[0], piece.size(), 0, special);
1706
+ LM_GGML_ASSERT(check == -n_chars);
1707
+ }
1708
+ else {
1709
+ piece.resize(n_chars);
1710
+ }
1711
+
1712
+ return piece;
1713
+ }
1714
+
1715
+ std::string common_detokenize(const struct llama_context * ctx, const std::vector<llama_token> & tokens, bool special) {
1716
+ const llama_model * model = llama_get_model(ctx);
1717
+ const llama_vocab * vocab = llama_model_get_vocab(model);
1718
+ return common_detokenize(vocab, tokens, special);
1719
+ }
1720
+
1721
+ std::string common_detokenize(const struct llama_vocab * vocab, const std::vector<llama_token> & tokens, bool special) {
1722
+ std::string text;
1723
+ text.resize(std::max(text.capacity(), tokens.size()));
1724
+ int32_t n_chars = llama_detokenize(vocab, tokens.data(), (int32_t)tokens.size(), &text[0], (int32_t)text.size(), false, special);
1725
+ if (n_chars < 0) {
1726
+ text.resize(-n_chars);
1727
+ n_chars = llama_detokenize(vocab, tokens.data(), (int32_t)tokens.size(), &text[0], (int32_t)text.size(), false, special);
1728
+ LM_GGML_ASSERT(n_chars <= (int32_t)text.size()); // whitespace trimming is performed after per-token detokenization
1729
+ }
1730
+
1731
+ text.resize(n_chars);
1732
+
1733
+ // NOTE: the original tokenizer decodes bytes after collecting the pieces.
1734
+ return text;
1735
+ }
1736
+
1737
+ //
1738
+ // Chat template utils
1739
+ //
1740
+
1741
+ std::string common_get_builtin_chat_template(const struct llama_model * model) {
1742
+ const char * ptr_tmpl = llama_model_chat_template(model);
1743
+ return ptr_tmpl == nullptr ? "" : ptr_tmpl;
1744
+ }
1745
+
1746
+ bool common_chat_verify_template(const std::string & tmpl) {
1747
+ llama_chat_message chat[] = {{"user", "test"}};
1748
+ const int res = llama_chat_apply_template(tmpl.c_str(), chat, 1, true, nullptr, 0);
1749
+ return res >= 0;
1750
+ }
1751
+
1752
+ std::string common_chat_apply_template(const struct llama_model * model,
1753
+ const std::string & tmpl,
1754
+ const std::vector<common_chat_msg> & msgs,
1755
+ bool add_ass) {
1756
+ int alloc_size = 0;
1757
+ bool fallback = false; // indicate if we must fallback to default chatml
1758
+ std::vector<llama_chat_message> chat;
1759
+ for (const auto & msg : msgs) {
1760
+ chat.push_back({msg.role.c_str(), msg.content.c_str()});
1761
+ alloc_size += (msg.role.size() + msg.content.size()) * 1.25;
1762
+ }
1763
+
1764
+ const char * ptr_tmpl = tmpl.empty() ? llama_model_chat_template(model) : tmpl.c_str();
1765
+ std::vector<char> buf(alloc_size);
1766
+
1767
+ // run the first time to get the total output length
1768
+ int32_t res = llama_chat_apply_template(ptr_tmpl, chat.data(), chat.size(), add_ass, buf.data(), buf.size());
1769
+
1770
+ // error: chat template is not supported
1771
+ if (res < 0) {
1772
+ if (ptr_tmpl != nullptr) {
1773
+ // if the custom "tmpl" is not supported, we throw an error
1774
+ // this is a bit redundant (for good), since we're not sure if user validated the custom template with llama_chat_verify_template()
1775
+ throw std::runtime_error("this custom template is not supported");
1776
+ }
1777
+
1778
+ // If the built-in template is not supported, we default to chatml
1779
+ res = llama_chat_apply_template("chatml", chat.data(), chat.size(), add_ass, buf.data(), buf.size());
1780
+ fallback = true;
1781
+ }
1782
+
1783
+ // if it turns out that our buffer is too small, we resize it
1784
+ if ((size_t) res > buf.size()) {
1785
+ buf.resize(res);
1786
+ res = llama_chat_apply_template(
1787
+ fallback ? "chatml" : ptr_tmpl,
1788
+ chat.data(), chat.size(), add_ass, buf.data(), buf.size());
1789
+ }
1790
+
1791
+ std::string formatted_chat(buf.data(), res);
1792
+ return formatted_chat;
1793
+ }
1794
+
1795
+ std::string common_chat_format_single(const struct llama_model * model,
1796
+ const std::string & tmpl,
1797
+ const std::vector<common_chat_msg> & past_msg,
1798
+ const common_chat_msg & new_msg,
1799
+ bool add_ass) {
1800
+ std::ostringstream ss;
1801
+ auto fmt_past_msg = past_msg.empty() ? "" : common_chat_apply_template(model, tmpl, past_msg, false);
1802
+ std::vector<common_chat_msg> chat_new(past_msg);
1803
+ // if the past_msg ends with a newline, we must preserve it in the formatted version
1804
+ if (add_ass && !fmt_past_msg.empty() && fmt_past_msg.back() == '\n') {
1805
+ ss << "\n";
1806
+ };
1807
+ // format chat with new_msg
1808
+ chat_new.push_back(new_msg);
1809
+ auto fmt_new_msg = common_chat_apply_template(model, tmpl, chat_new, add_ass);
1810
+ // get the diff part
1811
+ ss << fmt_new_msg.substr(fmt_past_msg.size(), fmt_new_msg.size() - fmt_past_msg.size());
1812
+ return ss.str();
1813
+ }
1814
+
1815
+ std::string common_chat_format_example(const struct llama_model * model,
1816
+ const std::string & tmpl) {
1817
+ std::vector<common_chat_msg> msgs = {
1818
+ {"system", "You are a helpful assistant"},
1819
+ {"user", "Hello"},
1820
+ {"assistant", "Hi there"},
1821
+ {"user", "How are you?"},
1822
+ };
1823
+ return common_chat_apply_template(model, tmpl, msgs, true);
1824
+ }
1825
+
1826
+ //
1827
+ // KV cache utils
1828
+ //
1829
+
1830
+ void common_kv_cache_dump_view(const llama_kv_cache_view & view, int row_size) {
1831
+ static const char slot_chars[] = ".123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+";
1832
+
1833
+ printf("=== Dumping KV cache. total cells %d, max sequences per cell %d, populated cells %d, total tokens in cache %d, largest empty slot=%d @ %d",
1834
+ view.n_cells, view.n_seq_max, view.used_cells, view.token_count, view.max_contiguous, view.max_contiguous_idx);
1835
+
1836
+ llama_kv_cache_view_cell * c_curr = view.cells;
1837
+ llama_seq_id * cs_curr = view.cells_sequences;
1838
+
1839
+ for (int i = 0; i < view.n_cells; i++, c_curr++, cs_curr += view.n_seq_max) {
1840
+ if (i % row_size == 0) {
1841
+ printf("\n%5d: ", i);
1842
+ }
1843
+ int seq_count = 0;
1844
+ for (int j = 0; j < view.n_seq_max; j++) {
1845
+ if (cs_curr[j] >= 0) { seq_count++; }
1846
+ }
1847
+ putchar(slot_chars[std::min(sizeof(slot_chars) - 2, size_t(seq_count))]);
1848
+ }
1849
+
1850
+ printf("\n=== Done dumping\n");
1851
+ }
1852
+
1853
+ void common_kv_cache_dump_view_seqs(const llama_kv_cache_view & view, int row_size) {
1854
+ static const char slot_chars[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
1855
+
1856
+ printf("=== Dumping KV cache. total cells %d, max sequences per cell %d, populated cells %d, total tokens in cache %d, largest empty slot=%d @ %d\n",
1857
+ view.n_cells, view.n_seq_max, view.used_cells, view.token_count, view.max_contiguous, view.max_contiguous_idx);
1858
+
1859
+ std::unordered_map<llama_seq_id, size_t> seqs;
1860
+ llama_kv_cache_view_cell * c_curr = view.cells;
1861
+ llama_seq_id * cs_curr = view.cells_sequences;
1862
+
1863
+ for (int i = 0; i < view.n_cells; i++, c_curr++, cs_curr += view.n_seq_max) {
1864
+ for (int j = 0; j < view.n_seq_max; j++) {
1865
+ if (cs_curr[j] < 0) { continue; }
1866
+ if (seqs.find(cs_curr[j]) == seqs.end()) {
1867
+ if (seqs.size() + 1 >= sizeof(slot_chars)) { break; }
1868
+ const size_t sz = seqs.size();
1869
+ seqs[cs_curr[j]] = sz;
1870
+ }
1871
+ }
1872
+ if (seqs.size() + 1 >= sizeof(slot_chars)) { break; }
1873
+ }
1874
+
1875
+ printf("=== Sequence legend: ");
1876
+ for (const auto & it : seqs) {
1877
+ printf("%zu=%d, ", it.second, it.first);
1878
+ }
1879
+ printf("'+'=other sequence ids");
1880
+
1881
+ c_curr = view.cells;
1882
+ cs_curr = view.cells_sequences;
1883
+ for (int i = 0; i < view.n_cells; i++, c_curr++, cs_curr += view.n_seq_max) {
1884
+ if (i % row_size == 0) {
1885
+ printf("\n%5d: ", i);
1886
+ }
1887
+ for (int j = 0; j < view.n_seq_max; j++) {
1888
+ if (cs_curr[j] >= 0) {
1889
+ const auto & it = seqs.find(cs_curr[j]);
1890
+ putchar(it != seqs.end() ? int(slot_chars[it->second]) : '+');
1891
+ } else {
1892
+ putchar('.');
1893
+ }
1894
+ }
1895
+ putchar(' ');
1896
+ }
1897
+
1898
+ printf("\n=== Done dumping\n");
1899
+ }
1900
+
1901
+ //
1902
+ // Embedding utils
1903
+ //
1904
+
1905
+ void common_embd_normalize(const float * inp, float * out, int n, int embd_norm) {
1906
+ double sum = 0.0;
1907
+
1908
+ switch (embd_norm) {
1909
+ case -1: // no normalisation
1910
+ sum = 1.0;
1911
+ break;
1912
+ case 0: // max absolute
1913
+ for (int i = 0; i < n; i++) {
1914
+ if (sum < std::abs(inp[i])) {
1915
+ sum = std::abs(inp[i]);
1916
+ }
1917
+ }
1918
+ sum /= 32760.0; // make an int16 range
1919
+ break;
1920
+ case 2: // euclidean
1921
+ for (int i = 0; i < n; i++) {
1922
+ sum += inp[i] * inp[i];
1923
+ }
1924
+ sum = std::sqrt(sum);
1925
+ break;
1926
+ default: // p-norm (euclidean is p-norm p=2)
1927
+ for (int i = 0; i < n; i++) {
1928
+ sum += std::pow(std::abs(inp[i]), embd_norm);
1929
+ }
1930
+ sum = std::pow(sum, 1.0 / embd_norm);
1931
+ break;
1932
+ }
1933
+
1934
+ const float norm = sum > 0.0 ? 1.0 / sum : 0.0f;
1935
+
1936
+ for (int i = 0; i < n; i++) {
1937
+ out[i] = inp[i] * norm;
1938
+ }
1939
+ }
1940
+
1941
+ float common_embd_similarity_cos(const float * embd1, const float * embd2, int n){
1942
+ double sum = 0.0;
1943
+ double sum1 = 0.0;
1944
+ double sum2 = 0.0;
1945
+
1946
+ for (int i = 0; i < n; i++) {
1947
+ sum += embd1[i] * embd2[i];
1948
+ sum1 += embd1[i] * embd1[i];
1949
+ sum2 += embd2[i] * embd2[i];
1950
+ }
1951
+
1952
+ // Handle the case where one or both vectors are zero vectors
1953
+ if (sum1 == 0.0 || sum2 == 0.0) {
1954
+ if (sum1 == 0.0 && sum2 == 0.0) {
1955
+ return 1.0f; // two zero vectors are similar
1956
+ }
1957
+ return 0.0f;
1958
+ }
1959
+
1960
+ return sum / (sqrt(sum1) * sqrt(sum2));
1961
+ }
1962
+
1963
+ //
1964
+ // Control vector utils
1965
+ //
1966
+
1967
+ static common_control_vector_data common_control_vector_load_one(const common_control_vector_load_info & load_info) {
1968
+ common_control_vector_data result = { -1, {} };
1969
+
1970
+ lm_ggml_context * ctx = nullptr;
1971
+ struct lm_gguf_init_params meta_lm_gguf_params = {
1972
+ /* .no_alloc = */ false,
1973
+ /* .ctx = */ &ctx,
1974
+ };
1975
+ struct lm_gguf_context * ctx_gguf = lm_gguf_init_from_file(load_info.fname.c_str(), meta_lm_gguf_params);
1976
+ if (!ctx_gguf) {
1977
+ LOG_ERR("%s: failed to load control vector file from %s\n", __func__, load_info.fname.c_str());
1978
+ return result;
1979
+ }
1980
+
1981
+ int32_t n_tensors = lm_gguf_get_n_tensors(ctx_gguf);
1982
+ if (n_tensors == 0) {
1983
+ LOG_WRN("%s: no direction tensors found in %s\n", __func__, load_info.fname.c_str());
1984
+ }
1985
+
1986
+ for (int i = 0; i < n_tensors; i++) {
1987
+ std::string name = lm_gguf_get_tensor_name(ctx_gguf, i);
1988
+
1989
+ int layer_idx = -1;
1990
+
1991
+ // split on '.'
1992
+ size_t dotpos = name.find('.');
1993
+ if (dotpos != std::string::npos && name.substr(0, dotpos) == "direction") {
1994
+ try {
1995
+ layer_idx = std::stoi(name.substr(dotpos + 1));
1996
+ } catch (...) {
1997
+ layer_idx = -1;
1998
+ }
1999
+ }
2000
+ if (layer_idx < 0) {
2001
+ LOG_ERR("%s: invalid/unparsable direction tensor layer index in %s\n", __func__, load_info.fname.c_str());
2002
+ result.n_embd = -1;
2003
+ break;
2004
+ } else if (layer_idx == 0) {
2005
+ LOG_ERR("%s: invalid (zero) direction tensor layer index in %s\n", __func__, load_info.fname.c_str());
2006
+ result.n_embd = -1;
2007
+ break;
2008
+ }
2009
+
2010
+ struct lm_ggml_tensor * tensor = lm_ggml_get_tensor(ctx, name.c_str());
2011
+ if (tensor->type != LM_GGML_TYPE_F32) {
2012
+ LOG_ERR("%s: invalid (non-F32) direction tensor type in %s\n", __func__, load_info.fname.c_str());
2013
+ result.n_embd = -1;
2014
+ break;
2015
+ }
2016
+ if (lm_ggml_n_dims(tensor) != 1) {
2017
+ LOG_ERR("%s: invalid (non-1D) direction tensor shape in %s\n", __func__, load_info.fname.c_str());
2018
+ result.n_embd = -1;
2019
+ break;
2020
+ }
2021
+
2022
+ if (result.n_embd == -1) {
2023
+ result.n_embd = lm_ggml_nelements(tensor);
2024
+ } else if (lm_ggml_nelements(tensor) != result.n_embd) {
2025
+ LOG_ERR("%s: direction tensor in %s does not match previous dimensions\n", __func__, load_info.fname.c_str());
2026
+ result.n_embd = -1;
2027
+ break;
2028
+ }
2029
+
2030
+ // extend if necessary - do not store data for layer 0 (it's not used)
2031
+ result.data.resize(std::max(result.data.size(), static_cast<size_t>(result.n_embd * layer_idx)), 0.0f);
2032
+
2033
+ const float * src = (const float *) tensor->data;
2034
+ float * dst = result.data.data() + result.n_embd * (layer_idx - 1); // layer 1 at [0]
2035
+ for (int j = 0; j < result.n_embd; j++) {
2036
+ dst[j] += src[j] * load_info.strength; // allows multiple directions for same layer in same file
2037
+ }
2038
+
2039
+ }
2040
+
2041
+ if (result.n_embd == -1) {
2042
+ LOG_WRN("%s: skipping %s due to invalid direction tensors\n", __func__, load_info.fname.c_str());
2043
+ result.data.clear();
2044
+ }
2045
+
2046
+ lm_gguf_free(ctx_gguf);
2047
+ lm_ggml_free(ctx);
2048
+
2049
+ return result;
2050
+ }
2051
+
2052
+ common_control_vector_data common_control_vector_load(const std::vector<common_control_vector_load_info> & load_infos) {
2053
+ common_control_vector_data result = { -1, {} };
2054
+
2055
+ for (const auto & info : load_infos) {
2056
+ auto cur = common_control_vector_load_one(info);
2057
+
2058
+ if (cur.n_embd == -1) {
2059
+ result.n_embd = -1;
2060
+ break;
2061
+ }
2062
+ if (result.n_embd != -1 && result.n_embd != cur.n_embd) {
2063
+ LOG_ERR("%s: control vectors in %s does not match previous dimensions\n", __func__, info.fname.c_str());
2064
+ result.n_embd = -1;
2065
+ break;
2066
+ }
2067
+
2068
+ if (result.n_embd == -1) {
2069
+ result = std::move(cur);
2070
+ } else {
2071
+ result.data.resize(std::max(result.data.size(), cur.data.size()), 0.0f); // extend if necessary
2072
+ for (size_t i = 0; i < cur.data.size(); i++) {
2073
+ result.data[i] += cur.data[i];
2074
+ }
2075
+ }
2076
+ }
2077
+
2078
+ if (result.n_embd == -1) {
2079
+ LOG_ERR("%s: no valid control vector files passed\n", __func__);
2080
+ result.data.clear();
2081
+ }
2082
+
2083
+ return result;
2084
+ }
2085
+