common.cpp 58 KB

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