common.cpp 54 KB

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