common.cpp 53 KB

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