common.cpp 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612
  1. #if defined(_MSC_VER)
  2. #define _SILENCE_CXX17_CODECVT_HEADER_DEPRECATION_WARNING
  3. #endif
  4. #include "ggml.h"
  5. #include "gguf.h"
  6. #include "common.h"
  7. #include "log.h"
  8. #include "llama.h"
  9. #include <algorithm>
  10. #include <cinttypes>
  11. #include <climits>
  12. #include <cmath>
  13. #include <codecvt>
  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_map>
  27. #include <unordered_set>
  28. #include <vector>
  29. #if defined(__APPLE__) && defined(__MACH__)
  30. #include <sys/types.h>
  31. #include <sys/sysctl.h>
  32. #endif
  33. #if defined(_WIN32)
  34. #define WIN32_LEAN_AND_MEAN
  35. #ifndef NOMINMAX
  36. # define NOMINMAX
  37. #endif
  38. #include <locale>
  39. #include <windows.h>
  40. #include <string.h>
  41. #include <fcntl.h>
  42. #include <io.h>
  43. #else
  44. #include <sys/ioctl.h>
  45. #include <sys/stat.h>
  46. #include <unistd.h>
  47. #endif
  48. #if defined(_MSC_VER)
  49. #pragma warning(disable: 4244 4267) // possible loss of data
  50. #endif
  51. //
  52. // CPU utils
  53. //
  54. int32_t cpu_get_num_physical_cores() {
  55. #ifdef __linux__
  56. // enumerate the set of thread siblings, num entries is num cores
  57. std::unordered_set<std::string> siblings;
  58. for (uint32_t cpu=0; cpu < UINT32_MAX; ++cpu) {
  59. std::ifstream thread_siblings("/sys/devices/system/cpu/cpu"
  60. + std::to_string(cpu) + "/topology/thread_siblings");
  61. if (!thread_siblings.is_open()) {
  62. break; // no more cpus
  63. }
  64. std::string line;
  65. if (std::getline(thread_siblings, line)) {
  66. siblings.insert(line);
  67. }
  68. }
  69. if (!siblings.empty()) {
  70. return static_cast<int32_t>(siblings.size());
  71. }
  72. #elif defined(__APPLE__) && defined(__MACH__)
  73. int32_t num_physical_cores;
  74. size_t len = sizeof(num_physical_cores);
  75. int result = sysctlbyname("hw.perflevel0.physicalcpu", &num_physical_cores, &len, NULL, 0);
  76. if (result == 0) {
  77. return num_physical_cores;
  78. }
  79. result = sysctlbyname("hw.physicalcpu", &num_physical_cores, &len, NULL, 0);
  80. if (result == 0) {
  81. return num_physical_cores;
  82. }
  83. #elif defined(_WIN32) && (_WIN32_WINNT >= 0x0601) && !defined(__MINGW64__) // windows 7 and later
  84. // TODO: windows + arm64 + mingw64
  85. unsigned int n_threads_win = std::thread::hardware_concurrency();
  86. unsigned int default_threads = n_threads_win > 0 ? (n_threads_win <= 4 ? n_threads_win : n_threads_win / 2) : 4;
  87. DWORD buffer_size = 0;
  88. if (!GetLogicalProcessorInformationEx(RelationProcessorCore, nullptr, &buffer_size)) {
  89. if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
  90. return default_threads;
  91. }
  92. }
  93. std::vector<char> buffer(buffer_size);
  94. if (!GetLogicalProcessorInformationEx(RelationProcessorCore, reinterpret_cast<PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX>(buffer.data()), &buffer_size)) {
  95. return default_threads;
  96. }
  97. int32_t num_physical_cores = 0;
  98. PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX info = reinterpret_cast<PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX>(buffer.data());
  99. while (buffer_size > 0) {
  100. if (info->Relationship == RelationProcessorCore) {
  101. num_physical_cores += info->Processor.GroupCount;
  102. }
  103. buffer_size -= info->Size;
  104. info = reinterpret_cast<PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX>(reinterpret_cast<char*>(info) + info->Size);
  105. }
  106. return num_physical_cores > 0 ? num_physical_cores : default_threads;
  107. #endif
  108. unsigned int n_threads = std::thread::hardware_concurrency();
  109. return n_threads > 0 ? (n_threads <= 4 ? n_threads : n_threads / 2) : 4;
  110. }
  111. #if defined(__x86_64__) && defined(__linux__) && !defined(__ANDROID__)
  112. #include <pthread.h>
  113. static void cpuid(unsigned leaf, unsigned subleaf,
  114. unsigned *eax, unsigned *ebx, unsigned *ecx, unsigned *edx) {
  115. __asm__("movq\t%%rbx,%%rsi\n\t"
  116. "cpuid\n\t"
  117. "xchgq\t%%rbx,%%rsi"
  118. : "=a"(*eax), "=S"(*ebx), "=c"(*ecx), "=d"(*edx)
  119. : "0"(leaf), "2"(subleaf));
  120. }
  121. static int pin_cpu(int cpu) {
  122. cpu_set_t mask;
  123. CPU_ZERO(&mask);
  124. CPU_SET(cpu, &mask);
  125. return pthread_setaffinity_np(pthread_self(), sizeof(mask), &mask);
  126. }
  127. static bool is_hybrid_cpu(void) {
  128. unsigned eax, ebx, ecx, edx;
  129. cpuid(7, 0, &eax, &ebx, &ecx, &edx);
  130. return !!(edx & (1u << 15));
  131. }
  132. static bool is_running_on_efficiency_core(void) {
  133. unsigned eax, ebx, ecx, edx;
  134. cpuid(0x1a, 0, &eax, &ebx, &ecx, &edx);
  135. int intel_atom = 0x20;
  136. int core_type = (eax & 0xff000000u) >> 24;
  137. return core_type == intel_atom;
  138. }
  139. static int cpu_count_math_cpus(int n_cpu) {
  140. int result = 0;
  141. for (int cpu = 0; cpu < n_cpu; ++cpu) {
  142. if (pin_cpu(cpu)) {
  143. return -1;
  144. }
  145. if (is_running_on_efficiency_core()) {
  146. continue; // efficiency cores harm lockstep threading
  147. }
  148. ++cpu; // hyperthreading isn't useful for linear algebra
  149. ++result;
  150. }
  151. return result;
  152. }
  153. #endif // __x86_64__ && __linux__
  154. /**
  155. * Returns number of CPUs on system that are useful for math.
  156. */
  157. int32_t cpu_get_num_math() {
  158. #if defined(__x86_64__) && defined(__linux__) && !defined(__ANDROID__)
  159. int n_cpu = sysconf(_SC_NPROCESSORS_ONLN);
  160. if (n_cpu < 1) {
  161. return cpu_get_num_physical_cores();
  162. }
  163. if (is_hybrid_cpu()) {
  164. cpu_set_t affinity;
  165. if (!pthread_getaffinity_np(pthread_self(), sizeof(affinity), &affinity)) {
  166. int result = cpu_count_math_cpus(n_cpu);
  167. pthread_setaffinity_np(pthread_self(), sizeof(affinity), &affinity);
  168. if (result > 0) {
  169. return result;
  170. }
  171. }
  172. }
  173. #endif
  174. return cpu_get_num_physical_cores();
  175. }
  176. // Helper for setting process priority
  177. #if defined(_WIN32)
  178. bool set_process_priority(enum ggml_sched_priority prio) {
  179. if (prio == GGML_SCHED_PRIO_NORMAL) {
  180. return true;
  181. }
  182. DWORD p = NORMAL_PRIORITY_CLASS;
  183. switch (prio) {
  184. case GGML_SCHED_PRIO_LOW: p = BELOW_NORMAL_PRIORITY_CLASS; break;
  185. case GGML_SCHED_PRIO_NORMAL: p = NORMAL_PRIORITY_CLASS; break;
  186. case GGML_SCHED_PRIO_MEDIUM: p = ABOVE_NORMAL_PRIORITY_CLASS; break;
  187. case GGML_SCHED_PRIO_HIGH: p = HIGH_PRIORITY_CLASS; break;
  188. case GGML_SCHED_PRIO_REALTIME: p = REALTIME_PRIORITY_CLASS; break;
  189. }
  190. if (!SetPriorityClass(GetCurrentProcess(), p)) {
  191. LOG_WRN("failed to set process priority class %d : (%d)\n", prio, (int) GetLastError());
  192. return false;
  193. }
  194. return true;
  195. }
  196. #else // MacOS and POSIX
  197. #include <sys/types.h>
  198. #include <sys/resource.h>
  199. bool set_process_priority(enum ggml_sched_priority prio) {
  200. if (prio == GGML_SCHED_PRIO_NORMAL) {
  201. return true;
  202. }
  203. int p = 0;
  204. switch (prio) {
  205. case GGML_SCHED_PRIO_LOW: p = 5; break;
  206. case GGML_SCHED_PRIO_NORMAL: p = 0; break;
  207. case GGML_SCHED_PRIO_MEDIUM: p = -5; break;
  208. case GGML_SCHED_PRIO_HIGH: p = -10; break;
  209. case GGML_SCHED_PRIO_REALTIME: p = -20; break;
  210. }
  211. if (!setpriority(PRIO_PROCESS, 0, p)) {
  212. LOG_WRN("failed to set process priority %d : %s (%d)\n", prio, strerror(errno), errno);
  213. return false;
  214. }
  215. return true;
  216. }
  217. #endif
  218. //
  219. // CLI argument parsing
  220. //
  221. void postprocess_cpu_params(cpu_params& cpuparams, const cpu_params* role_model) {
  222. int32_t n_set = 0;
  223. if (cpuparams.n_threads < 0) {
  224. // Assuming everything about cpuparams is invalid
  225. if (role_model != nullptr) {
  226. cpuparams = *role_model;
  227. } else {
  228. cpuparams.n_threads = cpu_get_num_math();
  229. }
  230. }
  231. for (int32_t i = 0; i < GGML_MAX_N_THREADS; i++) {
  232. if (cpuparams.cpumask[i]) {
  233. n_set++;
  234. }
  235. }
  236. if (n_set && n_set < cpuparams.n_threads) {
  237. // Not enough set bits, may experience performance issues.
  238. LOG_WRN("Not enough set bits in CPU mask (%d) to satisfy requested thread count: %d\n", n_set, cpuparams.n_threads);
  239. }
  240. }
  241. bool parse_cpu_range(const std::string & range, bool (&boolmask)[GGML_MAX_N_THREADS]) {
  242. size_t dash_loc = range.find('-');
  243. if (dash_loc == std::string::npos) {
  244. LOG_ERR("Format of CPU range is invalid! Expected [<start>]-[<end>].\n");
  245. return false;
  246. }
  247. size_t start_i;
  248. size_t end_i;
  249. if (dash_loc == 0) {
  250. start_i = 0;
  251. } else {
  252. start_i = std::stoull(range.substr(0, dash_loc));
  253. if (start_i >= GGML_MAX_N_THREADS) {
  254. LOG_ERR("Start index out of bounds!\n");
  255. return false;
  256. }
  257. }
  258. if (dash_loc == range.length() - 1) {
  259. end_i = GGML_MAX_N_THREADS - 1;
  260. } else {
  261. end_i = std::stoull(range.substr(dash_loc + 1));
  262. if (end_i >= GGML_MAX_N_THREADS) {
  263. LOG_ERR("End index out of bounds!\n");
  264. return false;
  265. }
  266. }
  267. for (size_t i = start_i; i <= end_i; i++) {
  268. boolmask[i] = true;
  269. }
  270. return true;
  271. }
  272. bool parse_cpu_mask(const std::string & mask, bool (&boolmask)[GGML_MAX_N_THREADS]) {
  273. // Discard potential 0x prefix
  274. size_t start_i = 0;
  275. if (mask.length() >= 2 && mask.substr(0, 2) == "0x") {
  276. start_i = 2;
  277. }
  278. size_t num_digits = mask.length() - start_i;
  279. if (num_digits > 128) num_digits = 128;
  280. size_t end_i = num_digits + start_i;
  281. for (size_t i = start_i, n = (num_digits*4 - 1); i < end_i; i++, n-=4) {
  282. char c = mask.at(i);
  283. int8_t id = c;
  284. if ((c >= '0' && c <= '9')) {
  285. id -= '0';
  286. } else if (c >= 'a' && c <= 'f') {
  287. id -= 'a' - 10;
  288. } else if (c >= 'A' && c <= 'F') {
  289. id -= 'A' - 10;
  290. } else {
  291. LOG_ERR("Invalid hex character '%c' at position %d\n", c, int32_t(i));
  292. return false;
  293. }
  294. boolmask[ n ] = boolmask[ n ] || ((id & 8) != 0);
  295. boolmask[n - 1] = boolmask[n - 1] || ((id & 4) != 0);
  296. boolmask[n - 2] = boolmask[n - 2] || ((id & 2) != 0);
  297. boolmask[n - 3] = boolmask[n - 3] || ((id & 1) != 0);
  298. }
  299. return true;
  300. }
  301. void common_init() {
  302. llama_log_set([](ggml_log_level level, const char * text, void * /*user_data*/) {
  303. if (LOG_DEFAULT_LLAMA <= common_log_verbosity_thold) {
  304. common_log_add(common_log_main(), level, "%s", text);
  305. }
  306. }, NULL);
  307. #ifdef NDEBUG
  308. const char * build_type = "";
  309. #else
  310. const char * build_type = " (debug)";
  311. #endif
  312. LOG_INF("build: %d (%s) with %s for %s%s\n", LLAMA_BUILD_NUMBER, LLAMA_COMMIT, LLAMA_COMPILER, LLAMA_BUILD_TARGET, build_type);
  313. }
  314. std::string common_params_get_system_info(const common_params & params) {
  315. std::ostringstream os;
  316. os << "system_info: n_threads = " << params.cpuparams.n_threads;
  317. if (params.cpuparams_batch.n_threads != -1) {
  318. os << " (n_threads_batch = " << params.cpuparams_batch.n_threads << ")";
  319. }
  320. #if defined(_WIN32) && (_WIN32_WINNT >= 0x0601) && !defined(__MINGW64__) // windows 7 and later
  321. // TODO: windows + arm64 + mingw64
  322. DWORD logicalProcessorCount = GetActiveProcessorCount(ALL_PROCESSOR_GROUPS);
  323. os << " / " << logicalProcessorCount << " | " << llama_print_system_info();
  324. #else
  325. os << " / " << std::thread::hardware_concurrency() << " | " << llama_print_system_info();
  326. #endif
  327. return os.str();
  328. }
  329. //
  330. // String utils
  331. //
  332. std::string string_format(const char * fmt, ...) {
  333. va_list ap;
  334. va_list ap2;
  335. va_start(ap, fmt);
  336. va_copy(ap2, ap);
  337. int size = vsnprintf(NULL, 0, fmt, ap);
  338. GGML_ASSERT(size >= 0 && size < INT_MAX); // NOLINT
  339. std::vector<char> buf(size + 1);
  340. int size2 = vsnprintf(buf.data(), size + 1, fmt, ap2);
  341. GGML_ASSERT(size2 == size);
  342. va_end(ap2);
  343. va_end(ap);
  344. return std::string(buf.data(), size);
  345. }
  346. std::string string_strip(const std::string & str) {
  347. size_t start = 0;
  348. size_t end = str.size();
  349. while (start < end && std::isspace(str[start])) {
  350. start++;
  351. }
  352. while (end > start && std::isspace(str[end - 1])) {
  353. end--;
  354. }
  355. return str.substr(start, end - start);
  356. }
  357. std::string string_get_sortable_timestamp() {
  358. using clock = std::chrono::system_clock;
  359. const clock::time_point current_time = clock::now();
  360. const time_t as_time_t = clock::to_time_t(current_time);
  361. char timestamp_no_ns[100];
  362. std::strftime(timestamp_no_ns, 100, "%Y_%m_%d-%H_%M_%S", std::localtime(&as_time_t));
  363. const int64_t ns = std::chrono::duration_cast<std::chrono::nanoseconds>(
  364. current_time.time_since_epoch() % 1000000000).count();
  365. char timestamp_ns[11];
  366. snprintf(timestamp_ns, 11, "%09" PRId64, ns);
  367. return std::string(timestamp_no_ns) + "." + std::string(timestamp_ns);
  368. }
  369. void string_replace_all(std::string & s, const std::string & search, const std::string & replace) {
  370. if (search.empty()) {
  371. return;
  372. }
  373. std::string builder;
  374. builder.reserve(s.length());
  375. size_t pos = 0;
  376. size_t last_pos = 0;
  377. while ((pos = s.find(search, last_pos)) != std::string::npos) {
  378. builder.append(s, last_pos, pos - last_pos);
  379. builder.append(replace);
  380. last_pos = pos + search.length();
  381. }
  382. builder.append(s, last_pos, std::string::npos);
  383. s = std::move(builder);
  384. }
  385. bool string_ends_with(const std::string_view & str, const std::string_view & suffix) {
  386. return str.size() >= suffix.size() && str.compare(str.size()-suffix.size(), suffix.size(), suffix) == 0;
  387. }
  388. bool string_remove_suffix(std::string & str, const std::string_view & suffix) {
  389. bool has_suffix = string_ends_with(str, suffix);
  390. if (has_suffix) {
  391. str = str.substr(0, str.size() - suffix.size());
  392. }
  393. return has_suffix;
  394. }
  395. size_t string_find_partial_stop(const std::string_view & str, const std::string_view & stop) {
  396. if (!str.empty() && !stop.empty()) {
  397. const char text_last_char = str.back();
  398. for (int64_t char_index = stop.size() - 1; char_index >= 0; char_index--) {
  399. if (stop[char_index] == text_last_char) {
  400. const auto current_partial = stop.substr(0, char_index + 1);
  401. if (string_ends_with(str, current_partial)) {
  402. return str.size() - char_index - 1;
  403. }
  404. }
  405. }
  406. }
  407. return std::string::npos;
  408. }
  409. std::string regex_escape(const std::string & s) {
  410. static const std::regex special_chars("[.^$|()*+?\\[\\]{}\\\\]");
  411. return std::regex_replace(s, special_chars, "\\$&");
  412. }
  413. std::string string_join(const std::vector<std::string> & values, const std::string & separator) {
  414. std::ostringstream result;
  415. for (size_t i = 0; i < values.size(); ++i) {
  416. if (i > 0) {
  417. result << separator;
  418. }
  419. result << values[i];
  420. }
  421. return result.str();
  422. }
  423. std::vector<std::string> string_split(const std::string & str, const std::string & delimiter) {
  424. std::vector<std::string> parts;
  425. size_t start = 0;
  426. size_t end = str.find(delimiter);
  427. while (end != std::string::npos) {
  428. parts.push_back(str.substr(start, end - start));
  429. start = end + delimiter.length();
  430. end = str.find(delimiter, start);
  431. }
  432. parts.push_back(str.substr(start));
  433. return parts;
  434. }
  435. std::string string_repeat(const std::string & str, size_t n) {
  436. if (n == 0) {
  437. return "";
  438. }
  439. std::string result;
  440. result.reserve(str.length() * n);
  441. for (size_t i = 0; i < n; ++i) {
  442. result += str;
  443. }
  444. return result;
  445. }
  446. std::string string_from(bool value) {
  447. return value ? "true" : "false";
  448. }
  449. std::string string_from(const std::vector<int> & values) {
  450. std::stringstream buf;
  451. buf << "[ ";
  452. bool first = true;
  453. for (auto e : values) {
  454. if (first) {
  455. first = false;
  456. } else {
  457. buf << ", ";
  458. }
  459. buf << std::to_string(e);
  460. }
  461. buf << " ]";
  462. return buf.str();
  463. }
  464. std::string string_from(const struct llama_context * ctx, const std::vector<llama_token> & tokens) {
  465. std::stringstream buf;
  466. buf << "[ ";
  467. bool first = true;
  468. for (const auto & token : tokens) {
  469. if (!first) {
  470. buf << ", ";
  471. } else {
  472. first = false;
  473. }
  474. auto detokenized = common_token_to_piece(ctx, token);
  475. buf << "'" << detokenized << "'"
  476. << ":" << std::to_string(token);
  477. }
  478. buf << " ]";
  479. return buf.str();
  480. }
  481. std::string string_from(const struct llama_context * ctx, const struct llama_batch & batch) {
  482. std::stringstream buf;
  483. buf << "[ ";
  484. bool first = true;
  485. for (int i = 0; i < batch.n_tokens; ++i) {
  486. if (!first) {
  487. buf << ", ";
  488. } else {
  489. first = false;
  490. }
  491. auto detokenized = common_token_to_piece(ctx, batch.token[i]);
  492. buf << "\n" << std::to_string(i)
  493. << ", token '" << detokenized << "'"
  494. << ", pos " << std::to_string(batch.pos[i])
  495. << ", n_seq_id " << std::to_string(batch.n_seq_id[i])
  496. << ", seq_id " << std::to_string(batch.seq_id[i][0])
  497. << ", logits " << std::to_string(batch.logits[i]);
  498. }
  499. buf << " ]";
  500. return buf.str();
  501. }
  502. void string_process_escapes(std::string & input) {
  503. std::size_t input_len = input.length();
  504. std::size_t output_idx = 0;
  505. for (std::size_t input_idx = 0; input_idx < input_len; ++input_idx) {
  506. if (input[input_idx] == '\\' && input_idx + 1 < input_len) {
  507. switch (input[++input_idx]) {
  508. case 'n': input[output_idx++] = '\n'; break;
  509. case 'r': input[output_idx++] = '\r'; break;
  510. case 't': input[output_idx++] = '\t'; break;
  511. case '\'': input[output_idx++] = '\''; break;
  512. case '\"': input[output_idx++] = '\"'; break;
  513. case '\\': input[output_idx++] = '\\'; break;
  514. case 'x':
  515. // Handle \x12, etc
  516. if (input_idx + 2 < input_len) {
  517. const char x[3] = { input[input_idx + 1], input[input_idx + 2], 0 };
  518. char *err_p = nullptr;
  519. const long val = std::strtol(x, &err_p, 16);
  520. if (err_p == x + 2) {
  521. input_idx += 2;
  522. input[output_idx++] = char(val);
  523. break;
  524. }
  525. }
  526. // fall through
  527. default: input[output_idx++] = '\\';
  528. input[output_idx++] = input[input_idx]; break;
  529. }
  530. } else {
  531. input[output_idx++] = input[input_idx];
  532. }
  533. }
  534. input.resize(output_idx);
  535. }
  536. bool string_parse_kv_override(const char * data, std::vector<llama_model_kv_override> & overrides) {
  537. const char * sep = strchr(data, '=');
  538. if (sep == nullptr || sep - data >= 128) {
  539. LOG_ERR("%s: malformed KV override '%s'\n", __func__, data);
  540. return false;
  541. }
  542. llama_model_kv_override kvo;
  543. std::strncpy(kvo.key, data, sep - data);
  544. kvo.key[sep - data] = 0;
  545. sep++;
  546. if (strncmp(sep, "int:", 4) == 0) {
  547. sep += 4;
  548. kvo.tag = LLAMA_KV_OVERRIDE_TYPE_INT;
  549. kvo.val_i64 = std::atol(sep);
  550. } else if (strncmp(sep, "float:", 6) == 0) {
  551. sep += 6;
  552. kvo.tag = LLAMA_KV_OVERRIDE_TYPE_FLOAT;
  553. kvo.val_f64 = std::atof(sep);
  554. } else if (strncmp(sep, "bool:", 5) == 0) {
  555. sep += 5;
  556. kvo.tag = LLAMA_KV_OVERRIDE_TYPE_BOOL;
  557. if (std::strcmp(sep, "true") == 0) {
  558. kvo.val_bool = true;
  559. } else if (std::strcmp(sep, "false") == 0) {
  560. kvo.val_bool = false;
  561. } else {
  562. LOG_ERR("%s: invalid boolean value for KV override '%s'\n", __func__, data);
  563. return false;
  564. }
  565. } else if (strncmp(sep, "str:", 4) == 0) {
  566. sep += 4;
  567. kvo.tag = LLAMA_KV_OVERRIDE_TYPE_STR;
  568. if (strlen(sep) > 127) {
  569. LOG_ERR("%s: malformed KV override '%s', value cannot exceed 127 chars\n", __func__, data);
  570. return false;
  571. }
  572. strncpy(kvo.val_str, sep, 127);
  573. kvo.val_str[127] = '\0';
  574. } else {
  575. LOG_ERR("%s: invalid type for KV override '%s'\n", __func__, data);
  576. return false;
  577. }
  578. overrides.emplace_back(std::move(kvo));
  579. return true;
  580. }
  581. //
  582. // Filesystem utils
  583. //
  584. // Validate if a filename is safe to use
  585. // To validate a full path, split the path by the OS-specific path separator, and validate each part with this function
  586. bool fs_validate_filename(const std::string & filename) {
  587. if (!filename.length()) {
  588. // Empty filename invalid
  589. return false;
  590. }
  591. if (filename.length() > 255) {
  592. // Limit at common largest possible filename on Linux filesystems
  593. // to avoid unnecessary further validation
  594. // (On systems with smaller limits it will be caught by the OS)
  595. return false;
  596. }
  597. std::u32string filename_utf32;
  598. try {
  599. #if defined(__clang__)
  600. // disable C++17 deprecation warning for std::codecvt_utf8
  601. # pragma clang diagnostic push
  602. # pragma clang diagnostic ignored "-Wdeprecated-declarations"
  603. #elif defined(__GNUC__)
  604. # pragma GCC diagnostic push
  605. # pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  606. #endif
  607. std::wstring_convert<std::codecvt_utf8<char32_t>, char32_t> converter;
  608. #if defined(__clang__)
  609. # pragma clang diagnostic pop
  610. #elif defined(__GNUC__)
  611. # pragma GCC diagnostic pop
  612. #endif
  613. filename_utf32 = converter.from_bytes(filename);
  614. // If the reverse conversion mismatches, it means overlong UTF-8 sequences were used,
  615. // or invalid encodings were encountered. Reject such attempts
  616. std::string filename_reencoded = converter.to_bytes(filename_utf32);
  617. if (filename_reencoded != filename) {
  618. return false;
  619. }
  620. } catch (const std::exception &) {
  621. return false;
  622. }
  623. // Check for forbidden codepoints:
  624. // - Control characters
  625. // - Unicode equivalents of illegal characters
  626. // - UTF-16 surrogate pairs
  627. // - UTF-8 replacement character
  628. // - Byte order mark (BOM)
  629. // - Illegal characters: / \ : * ? " < > |
  630. for (char32_t c : filename_utf32) {
  631. if (c <= 0x1F // Control characters (C0)
  632. || c == 0x7F // Control characters (DEL)
  633. || (c >= 0x80 && c <= 0x9F) // Control characters (C1)
  634. || c == 0xFF0E // Fullwidth Full Stop (period equivalent)
  635. || c == 0x2215 // Division Slash (forward slash equivalent)
  636. || c == 0x2216 // Set Minus (backslash equivalent)
  637. || (c >= 0xD800 && c <= 0xDFFF) // UTF-16 surrogate pairs
  638. || c == 0xFFFD // Replacement Character (UTF-8)
  639. || c == 0xFEFF // Byte Order Mark (BOM)
  640. || c == '/' || c == '\\' || c == ':' || c == '*' // Illegal characters
  641. || c == '?' || c == '"' || c == '<' || c == '>' || c == '|') {
  642. return false;
  643. }
  644. }
  645. // Reject any leading or trailing ' ', or any trailing '.', these are stripped on Windows and will cause a different filename
  646. // Unicode and other whitespace is not affected, only 0x20 space
  647. if (filename.front() == ' ' || filename.back() == ' ' || filename.back() == '.') {
  648. return false;
  649. }
  650. // Reject any ".." (currently stricter than necessary, it should be fine to just check for == ".." instead)
  651. if (filename.find("..") != std::string::npos) {
  652. return false;
  653. }
  654. // Reject "."
  655. if (filename == ".") {
  656. return false;
  657. }
  658. return true;
  659. }
  660. #include <iostream>
  661. // returns true if successful, false otherwise
  662. bool fs_create_directory_with_parents(const std::string & path) {
  663. #ifdef _WIN32
  664. std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;
  665. std::wstring wpath = converter.from_bytes(path);
  666. // if the path already exists, check whether it's a directory
  667. const DWORD attributes = GetFileAttributesW(wpath.c_str());
  668. if ((attributes != INVALID_FILE_ATTRIBUTES) && (attributes & FILE_ATTRIBUTE_DIRECTORY)) {
  669. return true;
  670. }
  671. size_t pos_slash = 0;
  672. // process path from front to back, procedurally creating directories
  673. while ((pos_slash = path.find('\\', pos_slash)) != std::string::npos) {
  674. const std::wstring subpath = wpath.substr(0, pos_slash);
  675. pos_slash += 1;
  676. // skip the drive letter, in some systems it can return an access denied error
  677. if (subpath.length() == 2 && subpath[1] == ':') {
  678. continue;
  679. }
  680. const bool success = CreateDirectoryW(subpath.c_str(), NULL);
  681. if (!success) {
  682. const DWORD error = GetLastError();
  683. // if the path already exists, ensure that it's a directory
  684. if (error == ERROR_ALREADY_EXISTS) {
  685. const DWORD attributes = GetFileAttributesW(subpath.c_str());
  686. if (attributes == INVALID_FILE_ATTRIBUTES || !(attributes & FILE_ATTRIBUTE_DIRECTORY)) {
  687. return false;
  688. }
  689. } else {
  690. return false;
  691. }
  692. }
  693. }
  694. return true;
  695. #else
  696. // if the path already exists, check whether it's a directory
  697. struct stat info;
  698. if (stat(path.c_str(), &info) == 0) {
  699. return S_ISDIR(info.st_mode);
  700. }
  701. size_t pos_slash = 1; // skip leading slashes for directory creation
  702. // process path from front to back, procedurally creating directories
  703. while ((pos_slash = path.find('/', pos_slash)) != std::string::npos) {
  704. const std::string subpath = path.substr(0, pos_slash);
  705. struct stat info;
  706. // if the path already exists, ensure that it's a directory
  707. if (stat(subpath.c_str(), &info) == 0) {
  708. if (!S_ISDIR(info.st_mode)) {
  709. return false;
  710. }
  711. } else {
  712. // create parent directories
  713. const int ret = mkdir(subpath.c_str(), 0755);
  714. if (ret != 0) {
  715. return false;
  716. }
  717. }
  718. pos_slash += 1;
  719. }
  720. return true;
  721. #endif // _WIN32
  722. }
  723. std::string fs_get_cache_directory() {
  724. std::string cache_directory = "";
  725. auto ensure_trailing_slash = [](std::string p) {
  726. // Make sure to add trailing slash
  727. if (p.back() != DIRECTORY_SEPARATOR) {
  728. p += DIRECTORY_SEPARATOR;
  729. }
  730. return p;
  731. };
  732. if (getenv("LLAMA_CACHE")) {
  733. cache_directory = std::getenv("LLAMA_CACHE");
  734. } else {
  735. #if defined(__linux__) || defined(__FreeBSD__) || defined(_AIX) || defined(__OpenBSD__)
  736. if (std::getenv("XDG_CACHE_HOME")) {
  737. cache_directory = std::getenv("XDG_CACHE_HOME");
  738. } else {
  739. cache_directory = std::getenv("HOME") + std::string("/.cache/");
  740. }
  741. #elif defined(__APPLE__)
  742. cache_directory = std::getenv("HOME") + std::string("/Library/Caches/");
  743. #elif defined(_WIN32)
  744. cache_directory = std::getenv("LOCALAPPDATA");
  745. #else
  746. # error Unknown architecture
  747. #endif
  748. cache_directory = ensure_trailing_slash(cache_directory);
  749. cache_directory += "llama.cpp";
  750. }
  751. return ensure_trailing_slash(cache_directory);
  752. }
  753. std::string fs_get_cache_file(const std::string & filename) {
  754. GGML_ASSERT(filename.find(DIRECTORY_SEPARATOR) == std::string::npos);
  755. std::string cache_directory = fs_get_cache_directory();
  756. const bool success = fs_create_directory_with_parents(cache_directory);
  757. if (!success) {
  758. throw std::runtime_error("failed to create cache directory: " + cache_directory);
  759. }
  760. return cache_directory + filename;
  761. }
  762. //
  763. // Model utils
  764. //
  765. struct common_init_result common_init_from_params(common_params & params) {
  766. common_init_result iparams;
  767. auto mparams = common_model_params_to_llama(params);
  768. llama_model * model = llama_model_load_from_file(params.model.path.c_str(), mparams);
  769. if (model == NULL) {
  770. LOG_ERR("%s: failed to load model '%s', try reducing --n-gpu-layers if you're running out of VRAM\n",
  771. __func__, params.model.path.c_str());
  772. return iparams;
  773. }
  774. const llama_vocab * vocab = llama_model_get_vocab(model);
  775. auto cparams = common_context_params_to_llama(params);
  776. llama_context * lctx = llama_init_from_model(model, cparams);
  777. if (lctx == NULL) {
  778. LOG_ERR("%s: failed to create context with model '%s', try reducing --n-gpu-layers if you're running out of VRAM\n",
  779. __func__, params.model.path.c_str());
  780. llama_model_free(model);
  781. return iparams;
  782. }
  783. if (params.ctx_shift && !llama_memory_can_shift(llama_get_memory(lctx))) {
  784. LOG_WRN("%s: KV cache shifting is not supported for this context, disabling KV cache shifting\n", __func__);
  785. params.ctx_shift = false;
  786. }
  787. if (!params.control_vectors.empty()) {
  788. if (params.control_vector_layer_start <= 0) params.control_vector_layer_start = 1;
  789. if (params.control_vector_layer_end <= 0) params.control_vector_layer_end = llama_model_n_layer(model);
  790. const auto cvec = common_control_vector_load(params.control_vectors);
  791. if (cvec.n_embd == -1) {
  792. llama_free(lctx);
  793. llama_model_free(model);
  794. return iparams;
  795. }
  796. int err = llama_apply_adapter_cvec(
  797. lctx,
  798. cvec.data.data(),
  799. cvec.data.size(),
  800. cvec.n_embd,
  801. params.control_vector_layer_start,
  802. params.control_vector_layer_end);
  803. if (err) {
  804. llama_free(lctx);
  805. llama_model_free(model);
  806. return iparams;
  807. }
  808. }
  809. if (llama_pooling_type(lctx) == LLAMA_POOLING_TYPE_RANK) {
  810. bool ok = true;
  811. if (llama_vocab_bos(vocab) == LLAMA_TOKEN_NULL) {
  812. LOG_WRN("%s: warning: vocab does not have a BOS token, reranking will not work\n", __func__);
  813. ok = false;
  814. }
  815. bool has_eos = llama_vocab_eos(vocab) != LLAMA_TOKEN_NULL;
  816. bool has_sep = llama_vocab_sep(vocab) != LLAMA_TOKEN_NULL;
  817. bool has_rerank_prompt = llama_model_chat_template(model, "rerank") != NULL;
  818. if (!has_eos && !has_sep && !has_rerank_prompt) {
  819. LOG_WRN("%s: warning: vocab does not have an EOS token, SEP token, or rerank prompt. Reranking will not work\n", __func__);
  820. ok = false;
  821. } else if (!has_eos) {
  822. LOG_WRN("%s: warning: vocab does not have an EOS token, using SEP token as fallback\n", __func__);
  823. }
  824. if (!ok) {
  825. llama_free(lctx);
  826. llama_model_free(model);
  827. return iparams;
  828. }
  829. }
  830. // load and optionally apply lora adapters
  831. for (auto & la : params.lora_adapters) {
  832. llama_adapter_lora_ptr lora;
  833. lora.reset(llama_adapter_lora_init(model, la.path.c_str()));
  834. if (lora == nullptr) {
  835. LOG_ERR("%s: failed to apply lora adapter '%s'\n", __func__, la.path.c_str());
  836. llama_free(lctx);
  837. llama_model_free(model);
  838. return iparams;
  839. }
  840. char buf[1024];
  841. la.ptr = lora.get();
  842. llama_adapter_meta_val_str(la.ptr, "adapter.lora.task_name", buf, sizeof(buf));
  843. la.task_name = buf;
  844. llama_adapter_meta_val_str(la.ptr, "adapter.lora.prompt_prefix", buf, sizeof(buf));
  845. la.prompt_prefix = buf;
  846. iparams.lora.emplace_back(std::move(lora)); // copy to list of loaded adapters
  847. }
  848. if (!params.lora_init_without_apply) {
  849. common_set_adapter_lora(lctx, params.lora_adapters);
  850. }
  851. if (params.sampling.ignore_eos && llama_vocab_eos(vocab) == LLAMA_TOKEN_NULL) {
  852. LOG_WRN("%s: warning: vocab does not have an EOS token, ignoring --ignore-eos\n", __func__);
  853. params.sampling.ignore_eos = false;
  854. }
  855. // initialize once
  856. for (llama_token i = 0; i < llama_vocab_n_tokens(vocab); i++) {
  857. if (llama_vocab_is_eog(vocab, i)) {
  858. LOG_INF("%s: added %s logit bias = %f\n", __func__, common_token_to_piece(lctx, i).c_str(), -INFINITY);
  859. params.sampling.logit_bias_eog.push_back({i, -INFINITY});
  860. }
  861. }
  862. if (params.sampling.ignore_eos) {
  863. // add EOG biases to the active set of logit biases
  864. params.sampling.logit_bias.insert(
  865. params.sampling.logit_bias.end(),
  866. params.sampling.logit_bias_eog.begin(), params.sampling.logit_bias_eog.end());
  867. }
  868. if (params.sampling.penalty_last_n == -1) {
  869. LOG_INF("%s: setting penalty_last_n to ctx_size = %d\n", __func__, llama_n_ctx(lctx));
  870. params.sampling.penalty_last_n = llama_n_ctx(lctx);
  871. }
  872. if (params.sampling.dry_penalty_last_n == -1) {
  873. LOG_INF("%s: setting dry_penalty_last_n to ctx_size = %d\n", __func__, llama_n_ctx(lctx));
  874. params.sampling.dry_penalty_last_n = llama_n_ctx(lctx);
  875. }
  876. if (params.warmup) {
  877. LOG_WRN("%s: warming up the model with an empty run - please wait ... (--no-warmup to disable)\n", __func__);
  878. llama_set_warmup(lctx, true);
  879. std::vector<llama_token> tmp;
  880. llama_token bos = llama_vocab_bos(vocab);
  881. llama_token eos = llama_vocab_eos(vocab);
  882. // some models (e.g. T5) don't have a BOS token
  883. if (bos != LLAMA_TOKEN_NULL) {
  884. tmp.push_back(bos);
  885. }
  886. if (eos != LLAMA_TOKEN_NULL) {
  887. tmp.push_back(eos);
  888. }
  889. if (tmp.empty()) {
  890. tmp.push_back(0);
  891. }
  892. if (llama_model_has_encoder(model)) {
  893. llama_encode(lctx, llama_batch_get_one(tmp.data(), tmp.size()));
  894. llama_token decoder_start_token_id = llama_model_decoder_start_token(model);
  895. if (decoder_start_token_id == LLAMA_TOKEN_NULL) {
  896. decoder_start_token_id = bos;
  897. }
  898. tmp.clear();
  899. tmp.push_back(decoder_start_token_id);
  900. }
  901. if (llama_model_has_decoder(model)) {
  902. llama_decode(lctx, llama_batch_get_one(tmp.data(), std::min(tmp.size(), (size_t) params.n_batch)));
  903. }
  904. llama_memory_clear(llama_get_memory(lctx), true);
  905. llama_synchronize(lctx);
  906. llama_perf_context_reset(lctx);
  907. llama_set_warmup(lctx, false);
  908. }
  909. iparams.model.reset(model);
  910. iparams.context.reset(lctx);
  911. return iparams;
  912. }
  913. std::string get_model_endpoint() {
  914. const char * model_endpoint_env = getenv("MODEL_ENDPOINT");
  915. // We still respect the use of environment-variable "HF_ENDPOINT" for backward-compatibility.
  916. const char * hf_endpoint_env = getenv("HF_ENDPOINT");
  917. const char * endpoint_env = model_endpoint_env ? model_endpoint_env : hf_endpoint_env;
  918. std::string model_endpoint = "https://huggingface.co/";
  919. if (endpoint_env) {
  920. model_endpoint = endpoint_env;
  921. if (model_endpoint.back() != '/') model_endpoint += '/';
  922. }
  923. return model_endpoint;
  924. }
  925. void common_set_adapter_lora(struct llama_context * ctx, std::vector<common_adapter_lora_info> & lora) {
  926. llama_clear_adapter_lora(ctx);
  927. for (auto & la : lora) {
  928. if (la.scale != 0.0f) {
  929. llama_set_adapter_lora(ctx, la.ptr, la.scale);
  930. }
  931. }
  932. }
  933. struct llama_model_params common_model_params_to_llama(common_params & params) {
  934. auto mparams = llama_model_default_params();
  935. if (!params.devices.empty()) {
  936. mparams.devices = params.devices.data();
  937. }
  938. if (params.n_gpu_layers != -1) {
  939. mparams.n_gpu_layers = params.n_gpu_layers;
  940. }
  941. mparams.main_gpu = params.main_gpu;
  942. mparams.split_mode = params.split_mode;
  943. mparams.tensor_split = params.tensor_split;
  944. mparams.use_mmap = params.use_mmap;
  945. mparams.use_mlock = params.use_mlock;
  946. mparams.check_tensors = params.check_tensors;
  947. mparams.use_extra_bufts = !params.no_extra_bufts;
  948. if (params.kv_overrides.empty()) {
  949. mparams.kv_overrides = NULL;
  950. } else {
  951. GGML_ASSERT(params.kv_overrides.back().key[0] == 0 && "KV overrides not terminated with empty key");
  952. mparams.kv_overrides = params.kv_overrides.data();
  953. }
  954. if (params.tensor_buft_overrides.empty()) {
  955. mparams.tensor_buft_overrides = NULL;
  956. } else {
  957. GGML_ASSERT(params.tensor_buft_overrides.back().pattern == nullptr && "Tensor buffer overrides not terminated with empty pattern");
  958. mparams.tensor_buft_overrides = params.tensor_buft_overrides.data();
  959. }
  960. mparams.progress_callback = params.load_progress_callback;
  961. mparams.progress_callback_user_data = params.load_progress_callback_user_data;
  962. return mparams;
  963. }
  964. struct llama_context_params common_context_params_to_llama(const common_params & params) {
  965. auto cparams = llama_context_default_params();
  966. cparams.n_ctx = params.n_ctx;
  967. cparams.n_seq_max = params.n_parallel;
  968. cparams.n_batch = params.n_batch;
  969. cparams.n_ubatch = params.n_ubatch;
  970. cparams.n_threads = params.cpuparams.n_threads;
  971. cparams.n_threads_batch = params.cpuparams_batch.n_threads == -1 ?
  972. params.cpuparams.n_threads : params.cpuparams_batch.n_threads;
  973. cparams.embeddings = params.embedding;
  974. cparams.rope_scaling_type = params.rope_scaling_type;
  975. cparams.rope_freq_base = params.rope_freq_base;
  976. cparams.rope_freq_scale = params.rope_freq_scale;
  977. cparams.yarn_ext_factor = params.yarn_ext_factor;
  978. cparams.yarn_attn_factor = params.yarn_attn_factor;
  979. cparams.yarn_beta_fast = params.yarn_beta_fast;
  980. cparams.yarn_beta_slow = params.yarn_beta_slow;
  981. cparams.yarn_orig_ctx = params.yarn_orig_ctx;
  982. cparams.pooling_type = params.pooling_type;
  983. cparams.attention_type = params.attention_type;
  984. cparams.flash_attn_type = params.flash_attn_type;
  985. cparams.cb_eval = params.cb_eval;
  986. cparams.cb_eval_user_data = params.cb_eval_user_data;
  987. cparams.offload_kqv = !params.no_kv_offload;
  988. cparams.no_perf = params.no_perf;
  989. cparams.op_offload = !params.no_op_offload;
  990. cparams.swa_full = params.swa_full;
  991. cparams.kv_unified = params.kv_unified;
  992. cparams.type_k = params.cache_type_k;
  993. cparams.type_v = params.cache_type_v;
  994. return cparams;
  995. }
  996. struct ggml_threadpool_params ggml_threadpool_params_from_cpu_params(const cpu_params & params) {
  997. struct ggml_threadpool_params tpp;
  998. ggml_threadpool_params_init(&tpp, params.n_threads); // setup the defaults
  999. if (params.mask_valid) {
  1000. std::memcpy(&tpp.cpumask, &params.cpumask, GGML_MAX_N_THREADS);
  1001. }
  1002. tpp.prio = params.priority;
  1003. tpp.poll = params.poll;
  1004. tpp.strict_cpu = params.strict_cpu;
  1005. return tpp;
  1006. }
  1007. //
  1008. // Batch utils
  1009. //
  1010. void common_batch_clear(struct llama_batch & batch) {
  1011. batch.n_tokens = 0;
  1012. }
  1013. void common_batch_add(
  1014. struct llama_batch & batch,
  1015. llama_token id,
  1016. llama_pos pos,
  1017. const std::vector<llama_seq_id> & seq_ids,
  1018. bool logits) {
  1019. GGML_ASSERT(batch.seq_id[batch.n_tokens] && "llama_batch size exceeded");
  1020. batch.token [batch.n_tokens] = id;
  1021. batch.pos [batch.n_tokens] = pos;
  1022. batch.n_seq_id[batch.n_tokens] = seq_ids.size();
  1023. for (size_t i = 0; i < seq_ids.size(); ++i) {
  1024. batch.seq_id[batch.n_tokens][i] = seq_ids[i];
  1025. }
  1026. batch.logits [batch.n_tokens] = logits;
  1027. batch.n_tokens++;
  1028. }
  1029. //
  1030. // Token utils
  1031. //
  1032. size_t common_lcp(const llama_tokens & a, const llama_tokens & b) {
  1033. size_t i;
  1034. for (i = 0; i < a.size() && i < b.size() && a[i] == b[i]; i++) {}
  1035. return i;
  1036. }
  1037. size_t common_lcs(const llama_tokens & a, const llama_tokens & b) {
  1038. // check for empty sequences
  1039. if (a.empty() || b.empty()) {
  1040. return 0;
  1041. }
  1042. // get the lengths of the input sequences
  1043. size_t a_len = a.size();
  1044. size_t b_len = b.size();
  1045. // initialize the maximum length of the longest common subsequence (LCS)
  1046. size_t max_length = 0;
  1047. // use two rows instead of a 2D matrix to optimize space
  1048. std::vector<size_t> prev_row(b_len + 1, 0);
  1049. std::vector<size_t> curr_row(b_len + 1, 0);
  1050. // iterate through the elements of a
  1051. for (size_t i = 1; i <= a_len; i++) {
  1052. // iterate through the elements of b
  1053. for (size_t j = 1; j <= b_len; j++) {
  1054. // if elements at the current positions match
  1055. if (a[i - 1] == b[j - 1]) {
  1056. // if it's the first element of either sequences, set LCS length to 1
  1057. if (i == 1 || j == 1) {
  1058. curr_row[j] = 1;
  1059. } else {
  1060. // increment LCS length by 1 compared to the previous element
  1061. curr_row[j] = prev_row[j - 1] + 1;
  1062. }
  1063. // update max_length if necessary
  1064. if (curr_row[j] > max_length) {
  1065. max_length = curr_row[j];
  1066. }
  1067. } else {
  1068. // reset LCS length if elements don't match
  1069. curr_row[j] = 0;
  1070. }
  1071. }
  1072. // update the previous row for the next iteration
  1073. prev_row = curr_row;
  1074. }
  1075. // return the maximum length of the LCS
  1076. return max_length;
  1077. }
  1078. //
  1079. // Vocab utils
  1080. //
  1081. std::vector<llama_token> common_tokenize(
  1082. const struct llama_context * ctx,
  1083. const std::string & text,
  1084. bool add_special,
  1085. bool parse_special) {
  1086. const llama_model * model = llama_get_model(ctx);
  1087. const llama_vocab * vocab = llama_model_get_vocab(model);
  1088. return common_tokenize(vocab, text, add_special, parse_special);
  1089. }
  1090. std::vector<llama_token> common_tokenize(
  1091. const struct llama_vocab * vocab,
  1092. const std::string & text,
  1093. bool add_special,
  1094. bool parse_special) {
  1095. // upper limit for the number of tokens
  1096. int n_tokens = text.length() + 2 * add_special;
  1097. std::vector<llama_token> result(n_tokens);
  1098. n_tokens = llama_tokenize(vocab, text.data(), text.length(), result.data(), result.size(), add_special, parse_special);
  1099. if (n_tokens == std::numeric_limits<int32_t>::min()) {
  1100. throw std::runtime_error("Tokenization failed: input text too large, tokenization result exceeds int32_t limit");
  1101. }
  1102. if (n_tokens < 0) {
  1103. result.resize(-n_tokens);
  1104. int check = llama_tokenize(vocab, text.data(), text.length(), result.data(), result.size(), add_special, parse_special);
  1105. GGML_ASSERT(check == -n_tokens);
  1106. } else {
  1107. result.resize(n_tokens);
  1108. }
  1109. return result;
  1110. }
  1111. std::string common_token_to_piece(const struct llama_context * ctx, llama_token token, bool special) {
  1112. const llama_model * model = llama_get_model(ctx);
  1113. const llama_vocab * vocab = llama_model_get_vocab(model);
  1114. return common_token_to_piece(vocab, token, special);
  1115. }
  1116. std::string common_token_to_piece(const struct llama_vocab * vocab, llama_token token, bool special) {
  1117. std::string piece;
  1118. piece.resize(piece.capacity()); // using string internal cache, 15 bytes + '\n'
  1119. const int n_chars = llama_token_to_piece(vocab, token, &piece[0], piece.size(), 0, special);
  1120. if (n_chars < 0) {
  1121. piece.resize(-n_chars);
  1122. int check = llama_token_to_piece(vocab, token, &piece[0], piece.size(), 0, special);
  1123. GGML_ASSERT(check == -n_chars);
  1124. }
  1125. else {
  1126. piece.resize(n_chars);
  1127. }
  1128. return piece;
  1129. }
  1130. std::string common_detokenize(const struct llama_context * ctx, const std::vector<llama_token> & tokens, bool special) {
  1131. const llama_model * model = llama_get_model(ctx);
  1132. const llama_vocab * vocab = llama_model_get_vocab(model);
  1133. return common_detokenize(vocab, tokens, special);
  1134. }
  1135. std::string common_detokenize(const struct llama_vocab * vocab, const std::vector<llama_token> & tokens, bool special) {
  1136. std::string text;
  1137. text.resize(std::max(text.capacity(), tokens.size()));
  1138. int32_t n_chars = llama_detokenize(vocab, tokens.data(), (int32_t)tokens.size(), &text[0], (int32_t)text.size(), false, special);
  1139. if (n_chars < 0) {
  1140. text.resize(-n_chars);
  1141. n_chars = llama_detokenize(vocab, tokens.data(), (int32_t)tokens.size(), &text[0], (int32_t)text.size(), false, special);
  1142. GGML_ASSERT(n_chars <= (int32_t)text.size()); // whitespace trimming is performed after per-token detokenization
  1143. }
  1144. text.resize(n_chars);
  1145. // NOTE: the original tokenizer decodes bytes after collecting the pieces.
  1146. return text;
  1147. }
  1148. //
  1149. // Embedding utils
  1150. //
  1151. void common_embd_normalize(const float * inp, float * out, int n, int embd_norm) {
  1152. double sum = 0.0;
  1153. switch (embd_norm) {
  1154. case -1: // no normalisation
  1155. sum = 1.0;
  1156. break;
  1157. case 0: // max absolute
  1158. for (int i = 0; i < n; i++) {
  1159. if (sum < std::abs(inp[i])) {
  1160. sum = std::abs(inp[i]);
  1161. }
  1162. }
  1163. sum /= 32760.0; // make an int16 range
  1164. break;
  1165. case 2: // euclidean
  1166. for (int i = 0; i < n; i++) {
  1167. sum += inp[i] * inp[i];
  1168. }
  1169. sum = std::sqrt(sum);
  1170. break;
  1171. default: // p-norm (euclidean is p-norm p=2)
  1172. for (int i = 0; i < n; i++) {
  1173. sum += std::pow(std::abs(inp[i]), embd_norm);
  1174. }
  1175. sum = std::pow(sum, 1.0 / embd_norm);
  1176. break;
  1177. }
  1178. const float norm = sum > 0.0 ? 1.0 / sum : 0.0f;
  1179. for (int i = 0; i < n; i++) {
  1180. out[i] = inp[i] * norm;
  1181. }
  1182. }
  1183. float common_embd_similarity_cos(const float * embd1, const float * embd2, int n){
  1184. double sum = 0.0;
  1185. double sum1 = 0.0;
  1186. double sum2 = 0.0;
  1187. for (int i = 0; i < n; i++) {
  1188. sum += embd1[i] * embd2[i];
  1189. sum1 += embd1[i] * embd1[i];
  1190. sum2 += embd2[i] * embd2[i];
  1191. }
  1192. // Handle the case where one or both vectors are zero vectors
  1193. if (sum1 == 0.0 || sum2 == 0.0) {
  1194. if (sum1 == 0.0 && sum2 == 0.0) {
  1195. return 1.0f; // two zero vectors are similar
  1196. }
  1197. return 0.0f;
  1198. }
  1199. return sum / (sqrt(sum1) * sqrt(sum2));
  1200. }
  1201. //
  1202. // Control vector utils
  1203. //
  1204. static common_control_vector_data common_control_vector_load_one(const common_control_vector_load_info & load_info) {
  1205. common_control_vector_data result = { -1, {} };
  1206. ggml_context * ctx = nullptr;
  1207. struct gguf_init_params meta_gguf_params = {
  1208. /* .no_alloc = */ false,
  1209. /* .ctx = */ &ctx,
  1210. };
  1211. struct gguf_context * ctx_gguf = gguf_init_from_file(load_info.fname.c_str(), meta_gguf_params);
  1212. if (!ctx_gguf) {
  1213. LOG_ERR("%s: failed to load control vector file from %s\n", __func__, load_info.fname.c_str());
  1214. return result;
  1215. }
  1216. int32_t n_tensors = gguf_get_n_tensors(ctx_gguf);
  1217. if (n_tensors == 0) {
  1218. LOG_WRN("%s: no direction tensors found in %s\n", __func__, load_info.fname.c_str());
  1219. }
  1220. for (int i = 0; i < n_tensors; i++) {
  1221. std::string name = gguf_get_tensor_name(ctx_gguf, i);
  1222. int layer_idx = -1;
  1223. // split on '.'
  1224. size_t dotpos = name.find('.');
  1225. if (dotpos != std::string::npos && name.substr(0, dotpos) == "direction") {
  1226. try {
  1227. layer_idx = std::stoi(name.substr(dotpos + 1));
  1228. } catch (...) {
  1229. layer_idx = -1;
  1230. }
  1231. }
  1232. if (layer_idx < 0) {
  1233. LOG_ERR("%s: invalid/unparsable direction tensor layer index in %s\n", __func__, load_info.fname.c_str());
  1234. result.n_embd = -1;
  1235. break;
  1236. } else if (layer_idx == 0) {
  1237. LOG_ERR("%s: invalid (zero) direction tensor layer index in %s\n", __func__, load_info.fname.c_str());
  1238. result.n_embd = -1;
  1239. break;
  1240. }
  1241. struct ggml_tensor * tensor = ggml_get_tensor(ctx, name.c_str());
  1242. if (tensor->type != GGML_TYPE_F32) {
  1243. LOG_ERR("%s: invalid (non-F32) direction tensor type in %s\n", __func__, load_info.fname.c_str());
  1244. result.n_embd = -1;
  1245. break;
  1246. }
  1247. if (ggml_n_dims(tensor) != 1) {
  1248. LOG_ERR("%s: invalid (non-1D) direction tensor shape in %s\n", __func__, load_info.fname.c_str());
  1249. result.n_embd = -1;
  1250. break;
  1251. }
  1252. if (result.n_embd == -1) {
  1253. result.n_embd = ggml_nelements(tensor);
  1254. } else if (ggml_nelements(tensor) != result.n_embd) {
  1255. LOG_ERR("%s: direction tensor in %s does not match previous dimensions\n", __func__, load_info.fname.c_str());
  1256. result.n_embd = -1;
  1257. break;
  1258. }
  1259. // extend if necessary - do not store data for layer 0 (it's not used)
  1260. result.data.resize(std::max(result.data.size(), static_cast<size_t>(result.n_embd * layer_idx)), 0.0f);
  1261. const float * src = (const float *) tensor->data;
  1262. float * dst = result.data.data() + result.n_embd * (layer_idx - 1); // layer 1 at [0]
  1263. for (int j = 0; j < result.n_embd; j++) {
  1264. dst[j] += src[j] * load_info.strength; // allows multiple directions for same layer in same file
  1265. }
  1266. }
  1267. if (result.n_embd == -1) {
  1268. LOG_WRN("%s: skipping %s due to invalid direction tensors\n", __func__, load_info.fname.c_str());
  1269. result.data.clear();
  1270. }
  1271. gguf_free(ctx_gguf);
  1272. ggml_free(ctx);
  1273. return result;
  1274. }
  1275. common_control_vector_data common_control_vector_load(const std::vector<common_control_vector_load_info> & load_infos) {
  1276. common_control_vector_data result = { -1, {} };
  1277. for (const auto & info : load_infos) {
  1278. auto cur = common_control_vector_load_one(info);
  1279. if (cur.n_embd == -1) {
  1280. result.n_embd = -1;
  1281. break;
  1282. }
  1283. if (result.n_embd != -1 && result.n_embd != cur.n_embd) {
  1284. LOG_ERR("%s: control vectors in %s does not match previous dimensions\n", __func__, info.fname.c_str());
  1285. result.n_embd = -1;
  1286. break;
  1287. }
  1288. if (result.n_embd == -1) {
  1289. result = std::move(cur);
  1290. } else {
  1291. result.data.resize(std::max(result.data.size(), cur.data.size()), 0.0f); // extend if necessary
  1292. for (size_t i = 0; i < cur.data.size(); i++) {
  1293. result.data[i] += cur.data[i];
  1294. }
  1295. }
  1296. }
  1297. if (result.n_embd == -1) {
  1298. LOG_ERR("%s: no valid control vector files passed\n", __func__);
  1299. result.data.clear();
  1300. }
  1301. return result;
  1302. }
  1303. ggml_opt_dataset_t common_opt_dataset_init(struct llama_context * ctx, const std::vector<llama_token> & tokens, int64_t stride) {
  1304. const int64_t ne_datapoint = llama_n_ctx(ctx);
  1305. const int64_t ndata = (tokens.size() - ne_datapoint - 1) / stride;
  1306. ggml_opt_dataset_t result = ggml_opt_dataset_init(
  1307. GGML_TYPE_I32, GGML_TYPE_I32, ne_datapoint, ne_datapoint, ndata, /*ndata_shard =*/ 1);
  1308. llama_token * data = (llama_token *) ggml_opt_dataset_data(result)->data;
  1309. llama_token * labels = (llama_token *) ggml_opt_dataset_labels(result)->data;
  1310. for (int64_t idata = 0; idata < ndata; ++idata) {
  1311. memcpy(data + idata*ne_datapoint, tokens.data() + idata*stride + 0, ne_datapoint*sizeof(llama_token));
  1312. memcpy(labels + idata*ne_datapoint, tokens.data() + idata*stride + 1, ne_datapoint*sizeof(llama_token));
  1313. }
  1314. return result;
  1315. }
  1316. ggml_opt_optimizer_params common_opt_lr_pars(void * userdata) {
  1317. ggml_opt_optimizer_params result = ggml_opt_get_default_optimizer_params(nullptr);
  1318. const lr_opt & d = *(lr_opt *) userdata;
  1319. result.adamw.alpha = result.sgd.alpha = d.get_lr(d.epoch);
  1320. result.sgd.wd = result.adamw.wd = d.wd;
  1321. return result;
  1322. }
  1323. // TODO make all command line args case-insensitive
  1324. static inline bool eq_case_insensitive(char const* a, char const* b) {
  1325. return !
  1326. #if defined(_MSC_VER)
  1327. _stricmp
  1328. #else
  1329. strcasecmp
  1330. #endif // defined(_MSC_VER)
  1331. (a, b);
  1332. }
  1333. enum ggml_opt_optimizer_type common_opt_get_optimizer(const char * n) {
  1334. if (eq_case_insensitive("adamw", n)) {
  1335. return GGML_OPT_OPTIMIZER_TYPE_ADAMW;
  1336. }
  1337. if (eq_case_insensitive("sgd", n)) {
  1338. return GGML_OPT_OPTIMIZER_TYPE_SGD;
  1339. }
  1340. return GGML_OPT_OPTIMIZER_TYPE_COUNT;
  1341. }
  1342. // TODO simplify to use just log and exp
  1343. static float const k_log_2 = std::log(2.f);
  1344. void lr_opt::init() {
  1345. if (lr_min > 0 && lr_min < lr0) {
  1346. float nhalf = std::log(lr0 / lr_min) / k_log_2;
  1347. float e = epochs;
  1348. if (decay_epochs > 0 && decay_epochs < e) {
  1349. e = decay_epochs;
  1350. } else {
  1351. decay_epochs = e;
  1352. }
  1353. scale_epoch = nhalf / e;
  1354. }
  1355. }
  1356. float lr_opt::get_lr(float epoch) const {
  1357. float r = lr_min <= 0 ? lr0 :
  1358. epoch >= decay_epochs ? lr_min :
  1359. lr0 * std::pow(0.5f, epoch * scale_epoch);
  1360. LOG_INF("epoch %.2g lr=%.2g\n", epoch, r);
  1361. return r;
  1362. }