common.cpp 54 KB

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