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