1
0

common.cpp 51 KB

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