common.cpp 54 KB

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