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