common.cpp 69 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028
  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. // Change JSON_ASSERT from assert() to GGML_ASSERT:
  9. #define JSON_ASSERT GGML_ASSERT
  10. #include "json.hpp"
  11. #include "json-schema-to-grammar.h"
  12. #include "llama.h"
  13. #include <algorithm>
  14. #include <cinttypes>
  15. #include <climits>
  16. #include <cmath>
  17. #include <codecvt>
  18. #include <cstdarg>
  19. #include <cstring>
  20. #include <ctime>
  21. #include <filesystem>
  22. #include <fstream>
  23. #include <iostream>
  24. #include <iterator>
  25. #include <regex>
  26. #include <sstream>
  27. #include <string>
  28. #include <thread>
  29. #include <unordered_map>
  30. #include <unordered_set>
  31. #include <vector>
  32. #if defined(__APPLE__) && defined(__MACH__)
  33. #include <sys/types.h>
  34. #include <sys/sysctl.h>
  35. #endif
  36. #if defined(_WIN32)
  37. #define WIN32_LEAN_AND_MEAN
  38. #ifndef NOMINMAX
  39. # define NOMINMAX
  40. #endif
  41. #include <locale>
  42. #include <windows.h>
  43. #include <fcntl.h>
  44. #include <io.h>
  45. #else
  46. #include <sys/ioctl.h>
  47. #include <sys/stat.h>
  48. #include <unistd.h>
  49. #endif
  50. #if defined(LLAMA_USE_CURL)
  51. #include <curl/curl.h>
  52. #include <curl/easy.h>
  53. #include <future>
  54. #endif
  55. #if defined(_MSC_VER)
  56. #pragma warning(disable: 4244 4267) // possible loss of data
  57. #endif
  58. #if defined(LLAMA_USE_CURL)
  59. #ifdef __linux__
  60. #include <linux/limits.h>
  61. #elif defined(_WIN32)
  62. # if !defined(PATH_MAX)
  63. # define PATH_MAX MAX_PATH
  64. # endif
  65. #else
  66. #include <sys/syslimits.h>
  67. #endif
  68. #define LLAMA_CURL_MAX_URL_LENGTH 2084 // Maximum URL Length in Chrome: 2083
  69. //
  70. // CURL utils
  71. //
  72. using curl_ptr = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>;
  73. // cannot use unique_ptr for curl_slist, because we cannot update without destroying the old one
  74. struct curl_slist_ptr {
  75. struct curl_slist * ptr = nullptr;
  76. ~curl_slist_ptr() {
  77. if (ptr) {
  78. curl_slist_free_all(ptr);
  79. }
  80. }
  81. };
  82. #endif // LLAMA_USE_CURL
  83. using json = nlohmann::ordered_json;
  84. //
  85. // CPU utils
  86. //
  87. int32_t cpu_get_num_physical_cores() {
  88. #ifdef __linux__
  89. // enumerate the set of thread siblings, num entries is num cores
  90. std::unordered_set<std::string> siblings;
  91. for (uint32_t cpu=0; cpu < UINT32_MAX; ++cpu) {
  92. std::ifstream thread_siblings("/sys/devices/system/cpu/cpu"
  93. + std::to_string(cpu) + "/topology/thread_siblings");
  94. if (!thread_siblings.is_open()) {
  95. break; // no more cpus
  96. }
  97. std::string line;
  98. if (std::getline(thread_siblings, line)) {
  99. siblings.insert(line);
  100. }
  101. }
  102. if (!siblings.empty()) {
  103. return static_cast<int32_t>(siblings.size());
  104. }
  105. #elif defined(__APPLE__) && defined(__MACH__)
  106. int32_t num_physical_cores;
  107. size_t len = sizeof(num_physical_cores);
  108. int result = sysctlbyname("hw.perflevel0.physicalcpu", &num_physical_cores, &len, NULL, 0);
  109. if (result == 0) {
  110. return num_physical_cores;
  111. }
  112. result = sysctlbyname("hw.physicalcpu", &num_physical_cores, &len, NULL, 0);
  113. if (result == 0) {
  114. return num_physical_cores;
  115. }
  116. #elif defined(_WIN32) && (_WIN32_WINNT >= 0x0601) && !defined(__MINGW64__) // windows 7 and later
  117. // TODO: windows + arm64 + mingw64
  118. unsigned int n_threads_win = std::thread::hardware_concurrency();
  119. unsigned int default_threads = n_threads_win > 0 ? (n_threads_win <= 4 ? n_threads_win : n_threads_win / 2) : 4;
  120. DWORD buffer_size = 0;
  121. if (!GetLogicalProcessorInformationEx(RelationProcessorCore, nullptr, &buffer_size)) {
  122. if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
  123. return default_threads;
  124. }
  125. }
  126. std::vector<char> buffer(buffer_size);
  127. if (!GetLogicalProcessorInformationEx(RelationProcessorCore, reinterpret_cast<PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX>(buffer.data()), &buffer_size)) {
  128. return default_threads;
  129. }
  130. int32_t num_physical_cores = 0;
  131. PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX info = reinterpret_cast<PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX>(buffer.data());
  132. while (buffer_size > 0) {
  133. if (info->Relationship == RelationProcessorCore) {
  134. num_physical_cores += info->Processor.GroupCount;
  135. }
  136. buffer_size -= info->Size;
  137. info = reinterpret_cast<PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX>(reinterpret_cast<char*>(info) + info->Size);
  138. }
  139. return num_physical_cores > 0 ? num_physical_cores : default_threads;
  140. #endif
  141. unsigned int n_threads = std::thread::hardware_concurrency();
  142. return n_threads > 0 ? (n_threads <= 4 ? n_threads : n_threads / 2) : 4;
  143. }
  144. #if defined(__x86_64__) && defined(__linux__) && !defined(__ANDROID__)
  145. #include <pthread.h>
  146. static void cpuid(unsigned leaf, unsigned subleaf,
  147. unsigned *eax, unsigned *ebx, unsigned *ecx, unsigned *edx) {
  148. __asm__("movq\t%%rbx,%%rsi\n\t"
  149. "cpuid\n\t"
  150. "xchgq\t%%rbx,%%rsi"
  151. : "=a"(*eax), "=S"(*ebx), "=c"(*ecx), "=d"(*edx)
  152. : "0"(leaf), "2"(subleaf));
  153. }
  154. static int pin_cpu(int cpu) {
  155. cpu_set_t mask;
  156. CPU_ZERO(&mask);
  157. CPU_SET(cpu, &mask);
  158. return pthread_setaffinity_np(pthread_self(), sizeof(mask), &mask);
  159. }
  160. static bool is_hybrid_cpu(void) {
  161. unsigned eax, ebx, ecx, edx;
  162. cpuid(7, 0, &eax, &ebx, &ecx, &edx);
  163. return !!(edx & (1u << 15));
  164. }
  165. static bool is_running_on_efficiency_core(void) {
  166. unsigned eax, ebx, ecx, edx;
  167. cpuid(0x1a, 0, &eax, &ebx, &ecx, &edx);
  168. int intel_atom = 0x20;
  169. int core_type = (eax & 0xff000000u) >> 24;
  170. return core_type == intel_atom;
  171. }
  172. static int cpu_count_math_cpus(int n_cpu) {
  173. int result = 0;
  174. for (int cpu = 0; cpu < n_cpu; ++cpu) {
  175. if (pin_cpu(cpu)) {
  176. return -1;
  177. }
  178. if (is_running_on_efficiency_core()) {
  179. continue; // efficiency cores harm lockstep threading
  180. }
  181. ++cpu; // hyperthreading isn't useful for linear algebra
  182. ++result;
  183. }
  184. return result;
  185. }
  186. #endif // __x86_64__ && __linux__
  187. /**
  188. * Returns number of CPUs on system that are useful for math.
  189. */
  190. int32_t cpu_get_num_math() {
  191. #if defined(__x86_64__) && defined(__linux__) && !defined(__ANDROID__)
  192. int n_cpu = sysconf(_SC_NPROCESSORS_ONLN);
  193. if (n_cpu < 1) {
  194. return cpu_get_num_physical_cores();
  195. }
  196. if (is_hybrid_cpu()) {
  197. cpu_set_t affinity;
  198. if (!pthread_getaffinity_np(pthread_self(), sizeof(affinity), &affinity)) {
  199. int result = cpu_count_math_cpus(n_cpu);
  200. pthread_setaffinity_np(pthread_self(), sizeof(affinity), &affinity);
  201. if (result > 0) {
  202. return result;
  203. }
  204. }
  205. }
  206. #endif
  207. return cpu_get_num_physical_cores();
  208. }
  209. // Helper for setting process priority
  210. #if defined(_WIN32)
  211. bool set_process_priority(enum ggml_sched_priority prio) {
  212. if (prio == GGML_SCHED_PRIO_NORMAL) {
  213. return true;
  214. }
  215. DWORD p = NORMAL_PRIORITY_CLASS;
  216. switch (prio) {
  217. case GGML_SCHED_PRIO_NORMAL: p = NORMAL_PRIORITY_CLASS; break;
  218. case GGML_SCHED_PRIO_MEDIUM: p = ABOVE_NORMAL_PRIORITY_CLASS; break;
  219. case GGML_SCHED_PRIO_HIGH: p = HIGH_PRIORITY_CLASS; break;
  220. case GGML_SCHED_PRIO_REALTIME: p = REALTIME_PRIORITY_CLASS; break;
  221. }
  222. if (!SetPriorityClass(GetCurrentProcess(), p)) {
  223. LOG_WRN("failed to set process priority class %d : (%d)\n", prio, (int) GetLastError());
  224. return false;
  225. }
  226. return true;
  227. }
  228. #else // MacOS and POSIX
  229. #include <sys/types.h>
  230. #include <sys/resource.h>
  231. bool set_process_priority(enum ggml_sched_priority prio) {
  232. if (prio == GGML_SCHED_PRIO_NORMAL) {
  233. return true;
  234. }
  235. int p = 0;
  236. switch (prio) {
  237. case GGML_SCHED_PRIO_NORMAL: p = 0; break;
  238. case GGML_SCHED_PRIO_MEDIUM: p = -5; break;
  239. case GGML_SCHED_PRIO_HIGH: p = -10; break;
  240. case GGML_SCHED_PRIO_REALTIME: p = -20; break;
  241. }
  242. if (!setpriority(PRIO_PROCESS, 0, p)) {
  243. LOG_WRN("failed to set process priority %d : %s (%d)\n", prio, strerror(errno), errno);
  244. return false;
  245. }
  246. return true;
  247. }
  248. #endif
  249. //
  250. // CLI argument parsing
  251. //
  252. void postprocess_cpu_params(cpu_params& cpuparams, const cpu_params* role_model) {
  253. int32_t n_set = 0;
  254. if (cpuparams.n_threads < 0) {
  255. // Assuming everything about cpuparams is invalid
  256. if (role_model != nullptr) {
  257. cpuparams = *role_model;
  258. } else {
  259. cpuparams.n_threads = cpu_get_num_math();
  260. }
  261. }
  262. for (int32_t i = 0; i < GGML_MAX_N_THREADS; i++) {
  263. if (cpuparams.cpumask[i]) {
  264. n_set++;
  265. }
  266. }
  267. if (n_set && n_set < cpuparams.n_threads) {
  268. // Not enough set bits, may experience performance issues.
  269. LOG_WRN("Not enough set bits in CPU mask (%d) to satisfy requested thread count: %d\n", n_set, cpuparams.n_threads);
  270. }
  271. }
  272. bool parse_cpu_range(const std::string & range, bool (&boolmask)[GGML_MAX_N_THREADS]) {
  273. size_t dash_loc = range.find('-');
  274. if (dash_loc == std::string::npos) {
  275. LOG_ERR("Format of CPU range is invalid! Expected [<start>]-[<end>].\n");
  276. return false;
  277. }
  278. size_t start_i;
  279. size_t end_i;
  280. if (dash_loc == 0) {
  281. start_i = 0;
  282. } else {
  283. start_i = std::stoull(range.substr(0, dash_loc));
  284. if (start_i >= GGML_MAX_N_THREADS) {
  285. LOG_ERR("Start index out of bounds!\n");
  286. return false;
  287. }
  288. }
  289. if (dash_loc == range.length() - 1) {
  290. end_i = GGML_MAX_N_THREADS - 1;
  291. } else {
  292. end_i = std::stoull(range.substr(dash_loc + 1));
  293. if (end_i >= GGML_MAX_N_THREADS) {
  294. LOG_ERR("End index out of bounds!\n");
  295. return false;
  296. }
  297. }
  298. for (size_t i = start_i; i <= end_i; i++) {
  299. boolmask[i] = true;
  300. }
  301. return true;
  302. }
  303. bool parse_cpu_mask(const std::string & mask, bool (&boolmask)[GGML_MAX_N_THREADS]) {
  304. // Discard potential 0x prefix
  305. size_t start_i = 0;
  306. if (mask.length() >= 2 && mask.substr(0, 2) == "0x") {
  307. start_i = 2;
  308. }
  309. size_t num_digits = mask.length() - start_i;
  310. if (num_digits > 128) num_digits = 128;
  311. size_t end_i = num_digits + start_i;
  312. for (size_t i = start_i, n = (num_digits*4 - 1); i < end_i; i++, n-=4) {
  313. char c = mask.at(i);
  314. int8_t id = c;
  315. if ((c >= '0' && c <= '9')) {
  316. id -= '0';
  317. } else if (c >= 'a' && c <= 'f') {
  318. id -= 'a' - 10;
  319. } else if (c >= 'A' && c <= 'F') {
  320. id -= 'A' - 10;
  321. } else {
  322. LOG_ERR("Invalid hex character '%c' at position %d\n", c, int32_t(i));
  323. return false;
  324. }
  325. boolmask[ n ] = boolmask[ n ] || ((id & 8) != 0);
  326. boolmask[n - 1] = boolmask[n - 1] || ((id & 4) != 0);
  327. boolmask[n - 2] = boolmask[n - 2] || ((id & 2) != 0);
  328. boolmask[n - 3] = boolmask[n - 3] || ((id & 1) != 0);
  329. }
  330. return true;
  331. }
  332. void common_init() {
  333. llama_log_set([](ggml_log_level level, const char * text, void * /*user_data*/) {
  334. if (LOG_DEFAULT_LLAMA <= common_log_verbosity_thold) {
  335. common_log_add(common_log_main(), level, "%s", text);
  336. }
  337. }, NULL);
  338. #ifdef NDEBUG
  339. const char * build_type = "";
  340. #else
  341. const char * build_type = " (debug)";
  342. #endif
  343. LOG_INF("build: %d (%s) with %s for %s%s\n", LLAMA_BUILD_NUMBER, LLAMA_COMMIT, LLAMA_COMPILER, LLAMA_BUILD_TARGET, build_type);
  344. }
  345. std::string common_params_get_system_info(const common_params & params) {
  346. std::ostringstream os;
  347. os << "system_info: n_threads = " << params.cpuparams.n_threads;
  348. if (params.cpuparams_batch.n_threads != -1) {
  349. os << " (n_threads_batch = " << params.cpuparams_batch.n_threads << ")";
  350. }
  351. #if defined(_WIN32) && (_WIN32_WINNT >= 0x0601) && !defined(__MINGW64__) // windows 7 and later
  352. // TODO: windows + arm64 + mingw64
  353. DWORD logicalProcessorCount = GetActiveProcessorCount(ALL_PROCESSOR_GROUPS);
  354. os << " / " << logicalProcessorCount << " | " << llama_print_system_info();
  355. #else
  356. os << " / " << std::thread::hardware_concurrency() << " | " << llama_print_system_info();
  357. #endif
  358. return os.str();
  359. }
  360. //
  361. // String utils
  362. //
  363. std::string string_format(const char * fmt, ...) {
  364. va_list ap;
  365. va_list ap2;
  366. va_start(ap, fmt);
  367. va_copy(ap2, ap);
  368. int size = vsnprintf(NULL, 0, fmt, ap);
  369. GGML_ASSERT(size >= 0 && size < INT_MAX); // NOLINT
  370. std::vector<char> buf(size + 1);
  371. int size2 = vsnprintf(buf.data(), size + 1, fmt, ap2);
  372. GGML_ASSERT(size2 == size);
  373. va_end(ap2);
  374. va_end(ap);
  375. return std::string(buf.data(), size);
  376. }
  377. std::string string_strip(const std::string & str) {
  378. size_t start = 0;
  379. size_t end = str.size();
  380. while (start < end && std::isspace(str[start])) {
  381. start++;
  382. }
  383. while (end > start && std::isspace(str[end - 1])) {
  384. end--;
  385. }
  386. return str.substr(start, end - start);
  387. }
  388. std::string string_get_sortable_timestamp() {
  389. using clock = std::chrono::system_clock;
  390. const clock::time_point current_time = clock::now();
  391. const time_t as_time_t = clock::to_time_t(current_time);
  392. char timestamp_no_ns[100];
  393. std::strftime(timestamp_no_ns, 100, "%Y_%m_%d-%H_%M_%S", std::localtime(&as_time_t));
  394. const int64_t ns = std::chrono::duration_cast<std::chrono::nanoseconds>(
  395. current_time.time_since_epoch() % 1000000000).count();
  396. char timestamp_ns[11];
  397. snprintf(timestamp_ns, 11, "%09" PRId64, ns);
  398. return std::string(timestamp_no_ns) + "." + std::string(timestamp_ns);
  399. }
  400. void string_replace_all(std::string & s, const std::string & search, const std::string & replace) {
  401. if (search.empty()) {
  402. return;
  403. }
  404. std::string builder;
  405. builder.reserve(s.length());
  406. size_t pos = 0;
  407. size_t last_pos = 0;
  408. while ((pos = s.find(search, last_pos)) != std::string::npos) {
  409. builder.append(s, last_pos, pos - last_pos);
  410. builder.append(replace);
  411. last_pos = pos + search.length();
  412. }
  413. builder.append(s, last_pos, std::string::npos);
  414. s = std::move(builder);
  415. }
  416. std::string string_join(const std::vector<std::string> & values, const std::string & separator) {
  417. std::ostringstream result;
  418. for (size_t i = 0; i < values.size(); ++i) {
  419. if (i > 0) {
  420. result << separator;
  421. }
  422. result << values[i];
  423. }
  424. return result.str();
  425. }
  426. std::vector<std::string> string_split(const std::string & str, const std::string & delimiter) {
  427. std::vector<std::string> parts;
  428. size_t start = 0;
  429. size_t end = str.find(delimiter);
  430. while (end != std::string::npos) {
  431. parts.push_back(str.substr(start, end - start));
  432. start = end + delimiter.length();
  433. end = str.find(delimiter, start);
  434. }
  435. parts.push_back(str.substr(start));
  436. return parts;
  437. }
  438. std::string string_repeat(const std::string & str, size_t n) {
  439. if (n == 0) {
  440. return "";
  441. }
  442. std::string result;
  443. result.reserve(str.length() * n);
  444. for (size_t i = 0; i < n; ++i) {
  445. result += str;
  446. }
  447. return result;
  448. }
  449. std::string string_from(bool value) {
  450. return value ? "true" : "false";
  451. }
  452. std::string string_from(const std::vector<int> & values) {
  453. std::stringstream buf;
  454. buf << "[ ";
  455. bool first = true;
  456. for (auto e : values) {
  457. if (first) {
  458. first = false;
  459. } else {
  460. buf << ", ";
  461. }
  462. buf << std::to_string(e);
  463. }
  464. buf << " ]";
  465. return buf.str();
  466. }
  467. std::string string_from(const struct llama_context * ctx, const std::vector<llama_token> & tokens) {
  468. std::stringstream buf;
  469. buf << "[ ";
  470. bool first = true;
  471. for (const auto & token : tokens) {
  472. if (!first) {
  473. buf << ", ";
  474. } else {
  475. first = false;
  476. }
  477. auto detokenized = common_token_to_piece(ctx, token);
  478. detokenized.erase(
  479. std::remove_if(
  480. detokenized.begin(),
  481. detokenized.end(),
  482. [](const unsigned char c) { return !std::isprint(c); }),
  483. detokenized.end());
  484. buf << "'" << detokenized << "'"
  485. << ":" << std::to_string(token);
  486. }
  487. buf << " ]";
  488. return buf.str();
  489. }
  490. std::string string_from(const struct llama_context * ctx, const struct llama_batch & batch) {
  491. std::stringstream buf;
  492. buf << "[ ";
  493. bool first = true;
  494. for (int i = 0; i < batch.n_tokens; ++i) {
  495. if (!first) {
  496. buf << ", ";
  497. } else {
  498. first = false;
  499. }
  500. auto detokenized = common_token_to_piece(ctx, batch.token[i]);
  501. detokenized.erase(
  502. std::remove_if(
  503. detokenized.begin(),
  504. detokenized.end(),
  505. [](const unsigned char c) { return !std::isprint(c); }),
  506. detokenized.end());
  507. buf << "\n" << std::to_string(i)
  508. << ", token '" << detokenized << "'"
  509. << ", pos " << std::to_string(batch.pos[i])
  510. << ", n_seq_id " << std::to_string(batch.n_seq_id[i])
  511. << ", seq_id " << std::to_string(batch.seq_id[i][0])
  512. << ", logits " << std::to_string(batch.logits[i]);
  513. }
  514. buf << " ]";
  515. return buf.str();
  516. }
  517. void string_process_escapes(std::string & input) {
  518. std::size_t input_len = input.length();
  519. std::size_t output_idx = 0;
  520. for (std::size_t input_idx = 0; input_idx < input_len; ++input_idx) {
  521. if (input[input_idx] == '\\' && input_idx + 1 < input_len) {
  522. switch (input[++input_idx]) {
  523. case 'n': input[output_idx++] = '\n'; break;
  524. case 'r': input[output_idx++] = '\r'; break;
  525. case 't': input[output_idx++] = '\t'; break;
  526. case '\'': input[output_idx++] = '\''; break;
  527. case '\"': input[output_idx++] = '\"'; break;
  528. case '\\': input[output_idx++] = '\\'; break;
  529. case 'x':
  530. // Handle \x12, etc
  531. if (input_idx + 2 < input_len) {
  532. const char x[3] = { input[input_idx + 1], input[input_idx + 2], 0 };
  533. char *err_p = nullptr;
  534. const long val = std::strtol(x, &err_p, 16);
  535. if (err_p == x + 2) {
  536. input_idx += 2;
  537. input[output_idx++] = char(val);
  538. break;
  539. }
  540. }
  541. // fall through
  542. default: input[output_idx++] = '\\';
  543. input[output_idx++] = input[input_idx]; break;
  544. }
  545. } else {
  546. input[output_idx++] = input[input_idx];
  547. }
  548. }
  549. input.resize(output_idx);
  550. }
  551. bool string_parse_kv_override(const char * data, std::vector<llama_model_kv_override> & overrides) {
  552. const char * sep = strchr(data, '=');
  553. if (sep == nullptr || sep - data >= 128) {
  554. LOG_ERR("%s: malformed KV override '%s'\n", __func__, data);
  555. return false;
  556. }
  557. llama_model_kv_override kvo;
  558. std::strncpy(kvo.key, data, sep - data);
  559. kvo.key[sep - data] = 0;
  560. sep++;
  561. if (strncmp(sep, "int:", 4) == 0) {
  562. sep += 4;
  563. kvo.tag = LLAMA_KV_OVERRIDE_TYPE_INT;
  564. kvo.val_i64 = std::atol(sep);
  565. } else if (strncmp(sep, "float:", 6) == 0) {
  566. sep += 6;
  567. kvo.tag = LLAMA_KV_OVERRIDE_TYPE_FLOAT;
  568. kvo.val_f64 = std::atof(sep);
  569. } else if (strncmp(sep, "bool:", 5) == 0) {
  570. sep += 5;
  571. kvo.tag = LLAMA_KV_OVERRIDE_TYPE_BOOL;
  572. if (std::strcmp(sep, "true") == 0) {
  573. kvo.val_bool = true;
  574. } else if (std::strcmp(sep, "false") == 0) {
  575. kvo.val_bool = false;
  576. } else {
  577. LOG_ERR("%s: invalid boolean value for KV override '%s'\n", __func__, data);
  578. return false;
  579. }
  580. } else if (strncmp(sep, "str:", 4) == 0) {
  581. sep += 4;
  582. kvo.tag = LLAMA_KV_OVERRIDE_TYPE_STR;
  583. if (strlen(sep) > 127) {
  584. LOG_ERR("%s: malformed KV override '%s', value cannot exceed 127 chars\n", __func__, data);
  585. return false;
  586. }
  587. strncpy(kvo.val_str, sep, 127);
  588. kvo.val_str[127] = '\0';
  589. } else {
  590. LOG_ERR("%s: invalid type for KV override '%s'\n", __func__, data);
  591. return false;
  592. }
  593. overrides.emplace_back(std::move(kvo));
  594. return true;
  595. }
  596. //
  597. // Filesystem utils
  598. //
  599. // Validate if a filename is safe to use
  600. // To validate a full path, split the path by the OS-specific path separator, and validate each part with this function
  601. bool fs_validate_filename(const std::string & filename) {
  602. if (!filename.length()) {
  603. // Empty filename invalid
  604. return false;
  605. }
  606. if (filename.length() > 255) {
  607. // Limit at common largest possible filename on Linux filesystems
  608. // to avoid unnecessary further validation
  609. // (On systems with smaller limits it will be caught by the OS)
  610. return false;
  611. }
  612. std::u32string filename_utf32;
  613. try {
  614. #if defined(__clang__)
  615. // disable C++17 deprecation warning for std::codecvt_utf8
  616. # pragma clang diagnostic push
  617. # pragma clang diagnostic ignored "-Wdeprecated-declarations"
  618. #endif
  619. std::wstring_convert<std::codecvt_utf8<char32_t>, char32_t> converter;
  620. #if defined(__clang__)
  621. # pragma clang 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. // returns true if successful, false otherwise
  671. bool fs_create_directory_with_parents(const std::string & path) {
  672. #ifdef _WIN32
  673. std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;
  674. std::wstring wpath = converter.from_bytes(path);
  675. // if the path already exists, check whether it's a directory
  676. const DWORD attributes = GetFileAttributesW(wpath.c_str());
  677. if ((attributes != INVALID_FILE_ATTRIBUTES) && (attributes & FILE_ATTRIBUTE_DIRECTORY)) {
  678. return true;
  679. }
  680. size_t pos_slash = 0;
  681. // process path from front to back, procedurally creating directories
  682. while ((pos_slash = path.find('\\', pos_slash)) != std::string::npos) {
  683. const std::wstring subpath = wpath.substr(0, pos_slash);
  684. const wchar_t * test = subpath.c_str();
  685. const bool success = CreateDirectoryW(test, NULL);
  686. if (!success) {
  687. const DWORD error = GetLastError();
  688. // if the path already exists, ensure that it's a directory
  689. if (error == ERROR_ALREADY_EXISTS) {
  690. const DWORD attributes = GetFileAttributesW(subpath.c_str());
  691. if (attributes == INVALID_FILE_ATTRIBUTES || !(attributes & FILE_ATTRIBUTE_DIRECTORY)) {
  692. return false;
  693. }
  694. } else {
  695. return false;
  696. }
  697. }
  698. pos_slash += 1;
  699. }
  700. return true;
  701. #else
  702. // if the path already exists, check whether it's a directory
  703. struct stat info;
  704. if (stat(path.c_str(), &info) == 0) {
  705. return S_ISDIR(info.st_mode);
  706. }
  707. size_t pos_slash = 1; // skip leading slashes for directory creation
  708. // process path from front to back, procedurally creating directories
  709. while ((pos_slash = path.find('/', pos_slash)) != std::string::npos) {
  710. const std::string subpath = path.substr(0, pos_slash);
  711. struct stat info;
  712. // if the path already exists, ensure that it's a directory
  713. if (stat(subpath.c_str(), &info) == 0) {
  714. if (!S_ISDIR(info.st_mode)) {
  715. return false;
  716. }
  717. } else {
  718. // create parent directories
  719. const int ret = mkdir(subpath.c_str(), 0755);
  720. if (ret != 0) {
  721. return false;
  722. }
  723. }
  724. pos_slash += 1;
  725. }
  726. return true;
  727. #endif // _WIN32
  728. }
  729. std::string fs_get_cache_directory() {
  730. std::string cache_directory = "";
  731. auto ensure_trailing_slash = [](std::string p) {
  732. // Make sure to add trailing slash
  733. if (p.back() != DIRECTORY_SEPARATOR) {
  734. p += DIRECTORY_SEPARATOR;
  735. }
  736. return p;
  737. };
  738. if (getenv("LLAMA_CACHE")) {
  739. cache_directory = std::getenv("LLAMA_CACHE");
  740. } else {
  741. #ifdef __linux__
  742. if (std::getenv("XDG_CACHE_HOME")) {
  743. cache_directory = std::getenv("XDG_CACHE_HOME");
  744. } else {
  745. cache_directory = std::getenv("HOME") + std::string("/.cache/");
  746. }
  747. #elif defined(__APPLE__)
  748. cache_directory = std::getenv("HOME") + std::string("/Library/Caches/");
  749. #elif defined(_WIN32)
  750. cache_directory = std::getenv("LOCALAPPDATA");
  751. #endif // __linux__
  752. cache_directory = ensure_trailing_slash(cache_directory);
  753. cache_directory += "llama.cpp";
  754. }
  755. return ensure_trailing_slash(cache_directory);
  756. }
  757. std::string fs_get_cache_file(const std::string & filename) {
  758. GGML_ASSERT(filename.find(DIRECTORY_SEPARATOR) == std::string::npos);
  759. std::string cache_directory = fs_get_cache_directory();
  760. const bool success = fs_create_directory_with_parents(cache_directory);
  761. if (!success) {
  762. throw std::runtime_error("failed to create cache directory: " + cache_directory);
  763. }
  764. return cache_directory + filename;
  765. }
  766. //
  767. // Model utils
  768. //
  769. struct common_init_result common_init_from_params(common_params & params) {
  770. common_init_result iparams;
  771. auto mparams = common_model_params_to_llama(params);
  772. llama_model * model = nullptr;
  773. if (!params.hf_repo.empty() && !params.hf_file.empty()) {
  774. model = common_load_model_from_hf(params.hf_repo, params.hf_file, params.model, params.hf_token, mparams);
  775. } else if (!params.model_url.empty()) {
  776. model = common_load_model_from_url(params.model_url, params.model, params.hf_token, mparams);
  777. } else {
  778. model = llama_model_load_from_file(params.model.c_str(), mparams);
  779. }
  780. if (model == NULL) {
  781. LOG_ERR("%s: failed to load model '%s'\n", __func__, params.model.c_str());
  782. return iparams;
  783. }
  784. const llama_vocab * vocab = llama_model_get_vocab(model);
  785. if (params.reranking) {
  786. bool ok = true;
  787. if (llama_vocab_bos(vocab) == LLAMA_TOKEN_NULL) {
  788. LOG_WRN("%s: warning: vocab does not have a BOS token, reranking will not work\n", __func__);
  789. ok = false;
  790. }
  791. if (llama_vocab_eos(vocab) == LLAMA_TOKEN_NULL) {
  792. LOG_WRN("%s: warning: vocab does not have an EOS token, reranking will not work\n", __func__);
  793. ok = false;
  794. }
  795. if (llama_vocab_sep(vocab) == LLAMA_TOKEN_NULL) {
  796. LOG_WRN("%s: warning: vocab does not have a SEP token, reranking will not work\n", __func__);
  797. ok = false;
  798. }
  799. if (!ok) {
  800. llama_model_free(model);
  801. return iparams;
  802. }
  803. }
  804. auto cparams = common_context_params_to_llama(params);
  805. llama_context * lctx = llama_init_from_model(model, cparams);
  806. if (lctx == NULL) {
  807. LOG_ERR("%s: failed to create context with model '%s'\n", __func__, params.model.c_str());
  808. llama_model_free(model);
  809. return iparams;
  810. }
  811. if (params.ctx_shift && !llama_kv_cache_can_shift(lctx)) {
  812. LOG_WRN("%s: KV cache shifting is not supported for this model, disabling KV cache shifting\n", __func__);
  813. params.ctx_shift = false;
  814. }
  815. if (!params.control_vectors.empty()) {
  816. if (params.control_vector_layer_start <= 0) params.control_vector_layer_start = 1;
  817. if (params.control_vector_layer_end <= 0) params.control_vector_layer_end = llama_model_n_layer(model);
  818. const auto cvec = common_control_vector_load(params.control_vectors);
  819. if (cvec.n_embd == -1) {
  820. llama_free(lctx);
  821. llama_model_free(model);
  822. return iparams;
  823. }
  824. int err = llama_apply_adapter_cvec(
  825. lctx,
  826. cvec.data.data(),
  827. cvec.data.size(),
  828. cvec.n_embd,
  829. params.control_vector_layer_start,
  830. params.control_vector_layer_end);
  831. if (err) {
  832. llama_free(lctx);
  833. llama_model_free(model);
  834. return iparams;
  835. }
  836. }
  837. // load and optionally apply lora adapters
  838. for (auto & la : params.lora_adapters) {
  839. llama_adapter_lora_ptr lora;
  840. lora.reset(llama_adapter_lora_init(model, la.path.c_str()));
  841. if (lora == nullptr) {
  842. LOG_ERR("%s: failed to apply lora adapter '%s'\n", __func__, la.path.c_str());
  843. llama_free(lctx);
  844. llama_model_free(model);
  845. return iparams;
  846. }
  847. la.ptr = lora.get();
  848. iparams.lora.emplace_back(std::move(lora)); // copy to list of loaded adapters
  849. }
  850. if (!params.lora_init_without_apply) {
  851. common_set_adapter_lora(lctx, params.lora_adapters);
  852. }
  853. if (params.sampling.ignore_eos && llama_vocab_eos(vocab) == LLAMA_TOKEN_NULL) {
  854. LOG_WRN("%s: warning: vocab does not have an EOS token, ignoring --ignore-eos\n", __func__);
  855. params.sampling.ignore_eos = false;
  856. }
  857. if (params.sampling.ignore_eos) {
  858. for (llama_token i = 0; i < llama_vocab_n_tokens(vocab); i++) {
  859. if (llama_vocab_is_eog(vocab, i)) {
  860. LOG_INF("%s: added %s logit bias = %f\n", __func__, common_token_to_piece(lctx, i).c_str(), -INFINITY);
  861. params.sampling.logit_bias.push_back({i, -INFINITY});
  862. }
  863. }
  864. }
  865. if (params.sampling.penalty_last_n == -1) {
  866. LOG_INF("%s: setting penalty_last_n to ctx_size = %d\n", __func__, llama_n_ctx(lctx));
  867. params.sampling.penalty_last_n = llama_n_ctx(lctx);
  868. }
  869. if (params.sampling.dry_penalty_last_n == -1) {
  870. LOG_INF("%s: setting dry_penalty_last_n to ctx_size = %d\n", __func__, llama_n_ctx(lctx));
  871. params.sampling.dry_penalty_last_n = llama_n_ctx(lctx);
  872. }
  873. if (params.warmup) {
  874. LOG_WRN("%s: warming up the model with an empty run - please wait ... (--no-warmup to disable)\n", __func__);
  875. std::vector<llama_token> tmp;
  876. llama_token bos = llama_vocab_bos(vocab);
  877. llama_token eos = llama_vocab_eos(vocab);
  878. // some models (e.g. T5) don't have a BOS token
  879. if (bos != LLAMA_TOKEN_NULL) {
  880. tmp.push_back(bos);
  881. }
  882. if (eos != LLAMA_TOKEN_NULL) {
  883. tmp.push_back(eos);
  884. }
  885. if (tmp.empty()) {
  886. tmp.push_back(0);
  887. }
  888. if (llama_model_has_encoder(model)) {
  889. llama_encode(lctx, llama_batch_get_one(tmp.data(), tmp.size()));
  890. llama_token decoder_start_token_id = llama_model_decoder_start_token(model);
  891. if (decoder_start_token_id == LLAMA_TOKEN_NULL) {
  892. decoder_start_token_id = bos;
  893. }
  894. tmp.clear();
  895. tmp.push_back(decoder_start_token_id);
  896. }
  897. if (llama_model_has_decoder(model)) {
  898. llama_decode(lctx, llama_batch_get_one(tmp.data(), std::min(tmp.size(), (size_t) params.n_batch)));
  899. }
  900. llama_kv_cache_clear(lctx);
  901. llama_synchronize(lctx);
  902. llama_perf_context_reset(lctx);
  903. }
  904. iparams.model.reset(model);
  905. iparams.context.reset(lctx);
  906. return iparams;
  907. }
  908. void common_set_adapter_lora(struct llama_context * ctx, std::vector<common_adapter_lora_info> & lora) {
  909. llama_clear_adapter_lora(ctx);
  910. for (auto & la : lora) {
  911. if (la.scale != 0.0f) {
  912. llama_set_adapter_lora(ctx, la.ptr, la.scale);
  913. }
  914. }
  915. }
  916. struct llama_model_params common_model_params_to_llama(common_params & params) {
  917. auto mparams = llama_model_default_params();
  918. if (!params.devices.empty()) {
  919. mparams.devices = params.devices.data();
  920. }
  921. if (params.n_gpu_layers != -1) {
  922. mparams.n_gpu_layers = params.n_gpu_layers;
  923. }
  924. mparams.main_gpu = params.main_gpu;
  925. mparams.split_mode = params.split_mode;
  926. mparams.tensor_split = params.tensor_split;
  927. mparams.use_mmap = params.use_mmap;
  928. mparams.use_mlock = params.use_mlock;
  929. mparams.check_tensors = params.check_tensors;
  930. if (params.kv_overrides.empty()) {
  931. mparams.kv_overrides = NULL;
  932. } else {
  933. GGML_ASSERT(params.kv_overrides.back().key[0] == 0 && "KV overrides not terminated with empty key");
  934. mparams.kv_overrides = params.kv_overrides.data();
  935. }
  936. return mparams;
  937. }
  938. struct llama_context_params common_context_params_to_llama(const common_params & params) {
  939. auto cparams = llama_context_default_params();
  940. cparams.n_ctx = params.n_ctx;
  941. cparams.n_seq_max = params.n_parallel;
  942. cparams.n_batch = params.n_batch;
  943. cparams.n_ubatch = params.n_ubatch;
  944. cparams.n_threads = params.cpuparams.n_threads;
  945. cparams.n_threads_batch = params.cpuparams_batch.n_threads == -1 ?
  946. params.cpuparams.n_threads : params.cpuparams_batch.n_threads;
  947. cparams.logits_all = params.logits_all;
  948. cparams.embeddings = params.embedding;
  949. cparams.rope_scaling_type = params.rope_scaling_type;
  950. cparams.rope_freq_base = params.rope_freq_base;
  951. cparams.rope_freq_scale = params.rope_freq_scale;
  952. cparams.yarn_ext_factor = params.yarn_ext_factor;
  953. cparams.yarn_attn_factor = params.yarn_attn_factor;
  954. cparams.yarn_beta_fast = params.yarn_beta_fast;
  955. cparams.yarn_beta_slow = params.yarn_beta_slow;
  956. cparams.yarn_orig_ctx = params.yarn_orig_ctx;
  957. cparams.pooling_type = params.pooling_type;
  958. cparams.attention_type = params.attention_type;
  959. cparams.defrag_thold = params.defrag_thold;
  960. cparams.cb_eval = params.cb_eval;
  961. cparams.cb_eval_user_data = params.cb_eval_user_data;
  962. cparams.offload_kqv = !params.no_kv_offload;
  963. cparams.flash_attn = params.flash_attn;
  964. cparams.no_perf = params.no_perf;
  965. if (params.reranking) {
  966. cparams.embeddings = true;
  967. cparams.pooling_type = LLAMA_POOLING_TYPE_RANK;
  968. }
  969. cparams.type_k = params.cache_type_k;
  970. cparams.type_v = params.cache_type_v;
  971. return cparams;
  972. }
  973. struct ggml_threadpool_params ggml_threadpool_params_from_cpu_params(const cpu_params & params) {
  974. struct ggml_threadpool_params tpp;
  975. ggml_threadpool_params_init(&tpp, params.n_threads); // setup the defaults
  976. if (params.mask_valid) {
  977. std::memcpy(&tpp.cpumask, &params.cpumask, GGML_MAX_N_THREADS);
  978. }
  979. tpp.prio = params.priority;
  980. tpp.poll = params.poll;
  981. tpp.strict_cpu = params.strict_cpu;
  982. return tpp;
  983. }
  984. #ifdef LLAMA_USE_CURL
  985. #define CURL_MAX_RETRY 3
  986. #define CURL_RETRY_DELAY_SECONDS 2
  987. static bool curl_perform_with_retry(const std::string & url, CURL * curl, int max_attempts, int retry_delay_seconds) {
  988. int remaining_attempts = max_attempts;
  989. while (remaining_attempts > 0) {
  990. LOG_INF("%s: Trying to download from %s (attempt %d of %d)...\n", __func__ , url.c_str(), max_attempts - remaining_attempts + 1, max_attempts);
  991. CURLcode res = curl_easy_perform(curl);
  992. if (res == CURLE_OK) {
  993. return true;
  994. }
  995. int exponential_backoff_delay = std::pow(retry_delay_seconds, max_attempts - remaining_attempts) * 1000;
  996. LOG_WRN("%s: curl_easy_perform() failed: %s, retrying after %d milliseconds...\n", __func__, curl_easy_strerror(res), exponential_backoff_delay);
  997. remaining_attempts--;
  998. std::this_thread::sleep_for(std::chrono::milliseconds(exponential_backoff_delay));
  999. }
  1000. LOG_ERR("%s: curl_easy_perform() failed after %d attempts\n", __func__, max_attempts);
  1001. return false;
  1002. }
  1003. static bool common_download_file(const std::string & url, const std::string & path, const std::string & hf_token) {
  1004. // Initialize libcurl
  1005. curl_ptr curl(curl_easy_init(), &curl_easy_cleanup);
  1006. curl_slist_ptr http_headers;
  1007. if (!curl) {
  1008. LOG_ERR("%s: error initializing libcurl\n", __func__);
  1009. return false;
  1010. }
  1011. bool force_download = false;
  1012. // Set the URL, allow to follow http redirection
  1013. curl_easy_setopt(curl.get(), CURLOPT_URL, url.c_str());
  1014. curl_easy_setopt(curl.get(), CURLOPT_FOLLOWLOCATION, 1L);
  1015. // Check if hf-token or bearer-token was specified
  1016. if (!hf_token.empty()) {
  1017. std::string auth_header = "Authorization: Bearer " + hf_token;
  1018. http_headers.ptr = curl_slist_append(http_headers.ptr, auth_header.c_str());
  1019. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, http_headers.ptr);
  1020. }
  1021. #if defined(_WIN32)
  1022. // CURLSSLOPT_NATIVE_CA tells libcurl to use standard certificate store of
  1023. // operating system. Currently implemented under MS-Windows.
  1024. curl_easy_setopt(curl.get(), CURLOPT_SSL_OPTIONS, CURLSSLOPT_NATIVE_CA);
  1025. #endif
  1026. // Check if the file already exists locally
  1027. auto file_exists = std::filesystem::exists(path);
  1028. // If the file exists, check its JSON metadata companion file.
  1029. std::string metadata_path = path + ".json";
  1030. nlohmann::json metadata;
  1031. std::string etag;
  1032. std::string last_modified;
  1033. if (file_exists) {
  1034. // Try and read the JSON metadata file (note: stream autoclosed upon exiting this block).
  1035. std::ifstream metadata_in(metadata_path);
  1036. if (metadata_in.good()) {
  1037. try {
  1038. metadata_in >> metadata;
  1039. LOG_INF("%s: previous metadata file found %s: %s\n", __func__, metadata_path.c_str(), metadata.dump().c_str());
  1040. if (metadata.contains("url") && metadata.at("url").is_string()) {
  1041. auto previous_url = metadata.at("url").get<std::string>();
  1042. if (previous_url != url) {
  1043. LOG_ERR("%s: Model URL mismatch: %s != %s\n", __func__, url.c_str(), previous_url.c_str());
  1044. return false;
  1045. }
  1046. }
  1047. if (metadata.contains("etag") && metadata.at("etag").is_string()) {
  1048. etag = metadata.at("etag");
  1049. }
  1050. if (metadata.contains("lastModified") && metadata.at("lastModified").is_string()) {
  1051. last_modified = metadata.at("lastModified");
  1052. }
  1053. } catch (const nlohmann::json::exception & e) {
  1054. LOG_ERR("%s: error reading metadata file %s: %s\n", __func__, metadata_path.c_str(), e.what());
  1055. return false;
  1056. }
  1057. }
  1058. } else {
  1059. LOG_INF("%s: no previous model file found %s\n", __func__, path.c_str());
  1060. }
  1061. // Send a HEAD request to retrieve the etag and last-modified headers
  1062. struct common_load_model_from_url_headers {
  1063. std::string etag;
  1064. std::string last_modified;
  1065. };
  1066. common_load_model_from_url_headers headers;
  1067. {
  1068. typedef size_t(*CURLOPT_HEADERFUNCTION_PTR)(char *, size_t, size_t, void *);
  1069. auto header_callback = [](char * buffer, size_t /*size*/, size_t n_items, void * userdata) -> size_t {
  1070. common_load_model_from_url_headers * headers = (common_load_model_from_url_headers *) userdata;
  1071. static std::regex header_regex("([^:]+): (.*)\r\n");
  1072. static std::regex etag_regex("ETag", std::regex_constants::icase);
  1073. static std::regex last_modified_regex("Last-Modified", std::regex_constants::icase);
  1074. std::string header(buffer, n_items);
  1075. std::smatch match;
  1076. if (std::regex_match(header, match, header_regex)) {
  1077. const std::string & key = match[1];
  1078. const std::string & value = match[2];
  1079. if (std::regex_match(key, match, etag_regex)) {
  1080. headers->etag = value;
  1081. } else if (std::regex_match(key, match, last_modified_regex)) {
  1082. headers->last_modified = value;
  1083. }
  1084. }
  1085. return n_items;
  1086. };
  1087. curl_easy_setopt(curl.get(), CURLOPT_NOBODY, 1L); // will trigger the HEAD verb
  1088. curl_easy_setopt(curl.get(), CURLOPT_NOPROGRESS, 1L); // hide head request progress
  1089. curl_easy_setopt(curl.get(), CURLOPT_HEADERFUNCTION, static_cast<CURLOPT_HEADERFUNCTION_PTR>(header_callback));
  1090. curl_easy_setopt(curl.get(), CURLOPT_HEADERDATA, &headers);
  1091. bool was_perform_successful = curl_perform_with_retry(url, curl.get(), CURL_MAX_RETRY, CURL_RETRY_DELAY_SECONDS);
  1092. if (!was_perform_successful) {
  1093. return false;
  1094. }
  1095. long http_code = 0;
  1096. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &http_code);
  1097. if (http_code != 200) {
  1098. // HEAD not supported, we don't know if the file has changed
  1099. // force trigger downloading
  1100. force_download = true;
  1101. LOG_ERR("%s: HEAD invalid http status code received: %ld\n", __func__, http_code);
  1102. }
  1103. }
  1104. bool should_download = !file_exists || force_download;
  1105. if (!should_download) {
  1106. if (!etag.empty() && etag != headers.etag) {
  1107. LOG_WRN("%s: ETag header is different (%s != %s): triggering a new download\n", __func__, etag.c_str(), headers.etag.c_str());
  1108. should_download = true;
  1109. } else if (!last_modified.empty() && last_modified != headers.last_modified) {
  1110. LOG_WRN("%s: Last-Modified header is different (%s != %s): triggering a new download\n", __func__, last_modified.c_str(), headers.last_modified.c_str());
  1111. should_download = true;
  1112. }
  1113. }
  1114. if (should_download) {
  1115. std::string path_temporary = path + ".downloadInProgress";
  1116. if (file_exists) {
  1117. LOG_WRN("%s: deleting previous downloaded file: %s\n", __func__, path.c_str());
  1118. if (remove(path.c_str()) != 0) {
  1119. LOG_ERR("%s: unable to delete file: %s\n", __func__, path.c_str());
  1120. return false;
  1121. }
  1122. }
  1123. // Set the output file
  1124. struct FILE_deleter {
  1125. void operator()(FILE * f) const {
  1126. fclose(f);
  1127. }
  1128. };
  1129. std::unique_ptr<FILE, FILE_deleter> outfile(fopen(path_temporary.c_str(), "wb"));
  1130. if (!outfile) {
  1131. LOG_ERR("%s: error opening local file for writing: %s\n", __func__, path.c_str());
  1132. return false;
  1133. }
  1134. typedef size_t(*CURLOPT_WRITEFUNCTION_PTR)(void * data, size_t size, size_t nmemb, void * fd);
  1135. auto write_callback = [](void * data, size_t size, size_t nmemb, void * fd) -> size_t {
  1136. return fwrite(data, size, nmemb, (FILE *)fd);
  1137. };
  1138. curl_easy_setopt(curl.get(), CURLOPT_NOBODY, 0L);
  1139. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, static_cast<CURLOPT_WRITEFUNCTION_PTR>(write_callback));
  1140. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, outfile.get());
  1141. // display download progress
  1142. curl_easy_setopt(curl.get(), CURLOPT_NOPROGRESS, 0L);
  1143. // helper function to hide password in URL
  1144. auto llama_download_hide_password_in_url = [](const std::string & url) -> std::string {
  1145. std::size_t protocol_pos = url.find("://");
  1146. if (protocol_pos == std::string::npos) {
  1147. return url; // Malformed URL
  1148. }
  1149. std::size_t at_pos = url.find('@', protocol_pos + 3);
  1150. if (at_pos == std::string::npos) {
  1151. return url; // No password in URL
  1152. }
  1153. return url.substr(0, protocol_pos + 3) + "********" + url.substr(at_pos);
  1154. };
  1155. // start the download
  1156. LOG_INF("%s: trying to download model from %s to %s (server_etag:%s, server_last_modified:%s)...\n", __func__,
  1157. llama_download_hide_password_in_url(url).c_str(), path.c_str(), headers.etag.c_str(), headers.last_modified.c_str());
  1158. bool was_perform_successful = curl_perform_with_retry(url, curl.get(), CURL_MAX_RETRY, CURL_RETRY_DELAY_SECONDS);
  1159. if (!was_perform_successful) {
  1160. return false;
  1161. }
  1162. long http_code = 0;
  1163. curl_easy_getinfo (curl.get(), CURLINFO_RESPONSE_CODE, &http_code);
  1164. if (http_code < 200 || http_code >= 400) {
  1165. LOG_ERR("%s: invalid http status code received: %ld\n", __func__, http_code);
  1166. return false;
  1167. }
  1168. // Causes file to be closed explicitly here before we rename it.
  1169. outfile.reset();
  1170. // Write the updated JSON metadata file.
  1171. metadata.update({
  1172. {"url", url},
  1173. {"etag", headers.etag},
  1174. {"lastModified", headers.last_modified}
  1175. });
  1176. std::ofstream(metadata_path) << metadata.dump(4);
  1177. LOG_INF("%s: file metadata saved: %s\n", __func__, metadata_path.c_str());
  1178. if (rename(path_temporary.c_str(), path.c_str()) != 0) {
  1179. LOG_ERR("%s: unable to rename file: %s to %s\n", __func__, path_temporary.c_str(), path.c_str());
  1180. return false;
  1181. }
  1182. }
  1183. return true;
  1184. }
  1185. struct llama_model * common_load_model_from_url(
  1186. const std::string & model_url,
  1187. const std::string & local_path,
  1188. const std::string & hf_token,
  1189. const struct llama_model_params & params) {
  1190. // Basic validation of the model_url
  1191. if (model_url.empty()) {
  1192. LOG_ERR("%s: invalid model_url\n", __func__);
  1193. return NULL;
  1194. }
  1195. if (!common_download_file(model_url, local_path, hf_token)) {
  1196. return NULL;
  1197. }
  1198. // check for additional GGUFs split to download
  1199. int n_split = 0;
  1200. {
  1201. struct gguf_init_params gguf_params = {
  1202. /*.no_alloc = */ true,
  1203. /*.ctx = */ NULL,
  1204. };
  1205. auto * ctx_gguf = gguf_init_from_file(local_path.c_str(), gguf_params);
  1206. if (!ctx_gguf) {
  1207. LOG_ERR("\n%s: failed to load input GGUF from %s\n", __func__, local_path.c_str());
  1208. return NULL;
  1209. }
  1210. auto key_n_split = gguf_find_key(ctx_gguf, LLM_KV_SPLIT_COUNT);
  1211. if (key_n_split >= 0) {
  1212. n_split = gguf_get_val_u16(ctx_gguf, key_n_split);
  1213. }
  1214. gguf_free(ctx_gguf);
  1215. }
  1216. if (n_split > 1) {
  1217. char split_prefix[PATH_MAX] = {0};
  1218. char split_url_prefix[LLAMA_CURL_MAX_URL_LENGTH] = {0};
  1219. // Verify the first split file format
  1220. // and extract split URL and PATH prefixes
  1221. {
  1222. if (!llama_split_prefix(split_prefix, sizeof(split_prefix), local_path.c_str(), 0, n_split)) {
  1223. LOG_ERR("\n%s: unexpected model file name: %s n_split=%d\n", __func__, local_path.c_str(), n_split);
  1224. return NULL;
  1225. }
  1226. if (!llama_split_prefix(split_url_prefix, sizeof(split_url_prefix), model_url.c_str(), 0, n_split)) {
  1227. LOG_ERR("\n%s: unexpected model url: %s n_split=%d\n", __func__, model_url.c_str(), n_split);
  1228. return NULL;
  1229. }
  1230. }
  1231. // Prepare download in parallel
  1232. std::vector<std::future<bool>> futures_download;
  1233. for (int idx = 1; idx < n_split; idx++) {
  1234. futures_download.push_back(std::async(std::launch::async, [&split_prefix, &split_url_prefix, &n_split, hf_token](int download_idx) -> bool {
  1235. char split_path[PATH_MAX] = {0};
  1236. llama_split_path(split_path, sizeof(split_path), split_prefix, download_idx, n_split);
  1237. char split_url[LLAMA_CURL_MAX_URL_LENGTH] = {0};
  1238. llama_split_path(split_url, sizeof(split_url), split_url_prefix, download_idx, n_split);
  1239. return common_download_file(split_url, split_path, hf_token);
  1240. }, idx));
  1241. }
  1242. // Wait for all downloads to complete
  1243. for (auto & f : futures_download) {
  1244. if (!f.get()) {
  1245. return NULL;
  1246. }
  1247. }
  1248. }
  1249. return llama_model_load_from_file(local_path.c_str(), params);
  1250. }
  1251. struct llama_model * common_load_model_from_hf(
  1252. const std::string & repo,
  1253. const std::string & remote_path,
  1254. const std::string & local_path,
  1255. const std::string & hf_token,
  1256. const struct llama_model_params & params) {
  1257. // construct hugging face model url:
  1258. //
  1259. // --repo ggml-org/models --file tinyllama-1.1b/ggml-model-f16.gguf
  1260. // https://huggingface.co/ggml-org/models/resolve/main/tinyllama-1.1b/ggml-model-f16.gguf
  1261. //
  1262. // --repo TheBloke/Mixtral-8x7B-v0.1-GGUF --file mixtral-8x7b-v0.1.Q4_K_M.gguf
  1263. // https://huggingface.co/TheBloke/Mixtral-8x7B-v0.1-GGUF/resolve/main/mixtral-8x7b-v0.1.Q4_K_M.gguf
  1264. //
  1265. std::string model_url = "https://huggingface.co/";
  1266. model_url += repo;
  1267. model_url += "/resolve/main/";
  1268. model_url += remote_path;
  1269. return common_load_model_from_url(model_url, local_path, hf_token, params);
  1270. }
  1271. /**
  1272. * Allow getting the HF file from the HF repo with tag (like ollama), for example:
  1273. * - bartowski/Llama-3.2-3B-Instruct-GGUF:q4
  1274. * - bartowski/Llama-3.2-3B-Instruct-GGUF:Q4_K_M
  1275. * - bartowski/Llama-3.2-3B-Instruct-GGUF:q5_k_s
  1276. * Tag is optional, default to "latest" (meaning it checks for Q4_K_M first, then Q4, then if not found, return the first GGUF file in repo)
  1277. *
  1278. * Return pair of <repo, file> (with "repo" already having tag removed)
  1279. *
  1280. * Note: we use the Ollama-compatible HF API, but not using the blobId. Instead, we use the special "ggufFile" field which returns the value for "hf_file". This is done to be backward-compatible with existing cache files.
  1281. */
  1282. std::pair<std::string, std::string> common_get_hf_file(const std::string & hf_repo_with_tag, const std::string & hf_token) {
  1283. auto parts = string_split<std::string>(hf_repo_with_tag, ':');
  1284. std::string tag = parts.size() > 1 ? parts.back() : "latest";
  1285. std::string hf_repo = parts[0];
  1286. if (string_split<std::string>(hf_repo, '/').size() != 2) {
  1287. throw std::invalid_argument("error: invalid HF repo format, expected <user>/<model>[:quant]\n");
  1288. }
  1289. // fetch model info from Hugging Face Hub API
  1290. json model_info;
  1291. curl_ptr curl(curl_easy_init(), &curl_easy_cleanup);
  1292. curl_slist_ptr http_headers;
  1293. std::string res_str;
  1294. std::string url = "https://huggingface.co/v2/" + hf_repo + "/manifests/" + tag;
  1295. curl_easy_setopt(curl.get(), CURLOPT_URL, url.c_str());
  1296. curl_easy_setopt(curl.get(), CURLOPT_NOPROGRESS, 1L);
  1297. typedef size_t(*CURLOPT_WRITEFUNCTION_PTR)(void * ptr, size_t size, size_t nmemb, void * data);
  1298. auto write_callback = [](void * ptr, size_t size, size_t nmemb, void * data) -> size_t {
  1299. static_cast<std::string *>(data)->append((char * ) ptr, size * nmemb);
  1300. return size * nmemb;
  1301. };
  1302. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, static_cast<CURLOPT_WRITEFUNCTION_PTR>(write_callback));
  1303. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &res_str);
  1304. #if defined(_WIN32)
  1305. curl_easy_setopt(curl.get(), CURLOPT_SSL_OPTIONS, CURLSSLOPT_NATIVE_CA);
  1306. #endif
  1307. if (!hf_token.empty()) {
  1308. std::string auth_header = "Authorization: Bearer " + hf_token;
  1309. http_headers.ptr = curl_slist_append(http_headers.ptr, auth_header.c_str());
  1310. }
  1311. // Important: the User-Agent must be "llama-cpp" to get the "ggufFile" field in the response
  1312. http_headers.ptr = curl_slist_append(http_headers.ptr, "User-Agent: llama-cpp");
  1313. http_headers.ptr = curl_slist_append(http_headers.ptr, "Accept: application/json");
  1314. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, http_headers.ptr);
  1315. CURLcode res = curl_easy_perform(curl.get());
  1316. if (res != CURLE_OK) {
  1317. throw std::runtime_error("error: cannot make GET request to HF API");
  1318. }
  1319. long res_code;
  1320. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &res_code);
  1321. if (res_code == 200) {
  1322. model_info = json::parse(res_str);
  1323. } else if (res_code == 401) {
  1324. throw std::runtime_error("error: model is private or does not exist; if you are accessing a gated model, please provide a valid HF token");
  1325. } else {
  1326. throw std::runtime_error(string_format("error from HF API, response code: %ld, data: %s", res_code, res_str.c_str()));
  1327. }
  1328. // check response
  1329. if (!model_info.contains("ggufFile")) {
  1330. throw std::runtime_error("error: model does not have ggufFile");
  1331. }
  1332. json & gguf_file = model_info.at("ggufFile");
  1333. if (!gguf_file.contains("rfilename")) {
  1334. throw std::runtime_error("error: ggufFile does not have rfilename");
  1335. }
  1336. return std::make_pair(hf_repo, gguf_file.at("rfilename"));
  1337. }
  1338. #else
  1339. struct llama_model * common_load_model_from_url(
  1340. const std::string & /*model_url*/,
  1341. const std::string & /*local_path*/,
  1342. const std::string & /*hf_token*/,
  1343. const struct llama_model_params & /*params*/) {
  1344. LOG_WRN("%s: llama.cpp built without libcurl, downloading from an url not supported.\n", __func__);
  1345. return nullptr;
  1346. }
  1347. struct llama_model * common_load_model_from_hf(
  1348. const std::string & /*repo*/,
  1349. const std::string & /*remote_path*/,
  1350. const std::string & /*local_path*/,
  1351. const std::string & /*hf_token*/,
  1352. const struct llama_model_params & /*params*/) {
  1353. LOG_WRN("%s: llama.cpp built without libcurl, downloading from Hugging Face not supported.\n", __func__);
  1354. return nullptr;
  1355. }
  1356. std::pair<std::string, std::string> common_get_hf_file(const std::string &, const std::string &) {
  1357. LOG_WRN("%s: llama.cpp built without libcurl, downloading from Hugging Face not supported.\n", __func__);
  1358. return std::make_pair("", "");
  1359. }
  1360. #endif // LLAMA_USE_CURL
  1361. //
  1362. // Batch utils
  1363. //
  1364. void common_batch_clear(struct llama_batch & batch) {
  1365. batch.n_tokens = 0;
  1366. }
  1367. void common_batch_add(
  1368. struct llama_batch & batch,
  1369. llama_token id,
  1370. llama_pos pos,
  1371. const std::vector<llama_seq_id> & seq_ids,
  1372. bool logits) {
  1373. GGML_ASSERT(batch.seq_id[batch.n_tokens] && "llama_batch size exceeded");
  1374. batch.token [batch.n_tokens] = id;
  1375. batch.pos [batch.n_tokens] = pos;
  1376. batch.n_seq_id[batch.n_tokens] = seq_ids.size();
  1377. for (size_t i = 0; i < seq_ids.size(); ++i) {
  1378. batch.seq_id[batch.n_tokens][i] = seq_ids[i];
  1379. }
  1380. batch.logits [batch.n_tokens] = logits;
  1381. batch.n_tokens++;
  1382. }
  1383. //
  1384. // Token utils
  1385. //
  1386. size_t common_lcp(const llama_tokens & a, const llama_tokens & b) {
  1387. size_t i;
  1388. for (i = 0; i < a.size() && i < b.size() && a[i] == b[i]; i++) {}
  1389. return i;
  1390. }
  1391. size_t common_lcs(const llama_tokens & a, const llama_tokens & b) {
  1392. // check for empty sequences
  1393. if (a.empty() || b.empty()) {
  1394. return 0;
  1395. }
  1396. // get the lengths of the input sequences
  1397. size_t a_len = a.size();
  1398. size_t b_len = b.size();
  1399. // initialize the maximum length of the longest common subsequence (LCS)
  1400. size_t max_length = 0;
  1401. // use two rows instead of a 2D matrix to optimize space
  1402. std::vector<size_t> prev_row(b_len + 1, 0);
  1403. std::vector<size_t> curr_row(b_len + 1, 0);
  1404. // iterate through the elements of a
  1405. for (size_t i = 1; i <= a_len; i++) {
  1406. // iterate through the elements of b
  1407. for (size_t j = 1; j <= b_len; j++) {
  1408. // if elements at the current positions match
  1409. if (a[i - 1] == b[j - 1]) {
  1410. // if it's the first element of either sequences, set LCS length to 1
  1411. if (i == 1 || j == 1) {
  1412. curr_row[j] = 1;
  1413. } else {
  1414. // increment LCS length by 1 compared to the previous element
  1415. curr_row[j] = prev_row[j - 1] + 1;
  1416. }
  1417. // update max_length if necessary
  1418. if (curr_row[j] > max_length) {
  1419. max_length = curr_row[j];
  1420. }
  1421. } else {
  1422. // reset LCS length if elements don't match
  1423. curr_row[j] = 0;
  1424. }
  1425. }
  1426. // update the previous row for the next iteration
  1427. prev_row = curr_row;
  1428. }
  1429. // return the maximum length of the LCS
  1430. return max_length;
  1431. }
  1432. //
  1433. // Vocab utils
  1434. //
  1435. std::vector<llama_token> common_tokenize(
  1436. const struct llama_context * ctx,
  1437. const std::string & text,
  1438. bool add_special,
  1439. bool parse_special) {
  1440. const llama_model * model = llama_get_model(ctx);
  1441. const llama_vocab * vocab = llama_model_get_vocab(model);
  1442. return common_tokenize(vocab, text, add_special, parse_special);
  1443. }
  1444. std::vector<llama_token> common_tokenize(
  1445. const struct llama_vocab * vocab,
  1446. const std::string & text,
  1447. bool add_special,
  1448. bool parse_special) {
  1449. // upper limit for the number of tokens
  1450. int n_tokens = text.length() + 2 * add_special;
  1451. std::vector<llama_token> result(n_tokens);
  1452. n_tokens = llama_tokenize(vocab, text.data(), text.length(), result.data(), result.size(), add_special, parse_special);
  1453. if (n_tokens < 0) {
  1454. result.resize(-n_tokens);
  1455. int check = llama_tokenize(vocab, text.data(), text.length(), result.data(), result.size(), add_special, parse_special);
  1456. GGML_ASSERT(check == -n_tokens);
  1457. } else {
  1458. result.resize(n_tokens);
  1459. }
  1460. return result;
  1461. }
  1462. std::string common_token_to_piece(const struct llama_context * ctx, llama_token token, bool special) {
  1463. const llama_model * model = llama_get_model(ctx);
  1464. const llama_vocab * vocab = llama_model_get_vocab(model);
  1465. return common_token_to_piece(vocab, token, special);
  1466. }
  1467. std::string common_token_to_piece(const struct llama_vocab * vocab, llama_token token, bool special) {
  1468. std::string piece;
  1469. piece.resize(piece.capacity()); // using string internal cache, 15 bytes + '\n'
  1470. const int n_chars = llama_token_to_piece(vocab, token, &piece[0], piece.size(), 0, special);
  1471. if (n_chars < 0) {
  1472. piece.resize(-n_chars);
  1473. int check = llama_token_to_piece(vocab, token, &piece[0], piece.size(), 0, special);
  1474. GGML_ASSERT(check == -n_chars);
  1475. }
  1476. else {
  1477. piece.resize(n_chars);
  1478. }
  1479. return piece;
  1480. }
  1481. std::string common_detokenize(const struct llama_context * ctx, const std::vector<llama_token> & tokens, bool special) {
  1482. const llama_model * model = llama_get_model(ctx);
  1483. const llama_vocab * vocab = llama_model_get_vocab(model);
  1484. return common_detokenize(vocab, tokens, special);
  1485. }
  1486. std::string common_detokenize(const struct llama_vocab * vocab, const std::vector<llama_token> & tokens, bool special) {
  1487. std::string text;
  1488. text.resize(std::max(text.capacity(), tokens.size()));
  1489. int32_t n_chars = llama_detokenize(vocab, tokens.data(), (int32_t)tokens.size(), &text[0], (int32_t)text.size(), false, special);
  1490. if (n_chars < 0) {
  1491. text.resize(-n_chars);
  1492. n_chars = llama_detokenize(vocab, tokens.data(), (int32_t)tokens.size(), &text[0], (int32_t)text.size(), false, special);
  1493. GGML_ASSERT(n_chars <= (int32_t)text.size()); // whitespace trimming is performed after per-token detokenization
  1494. }
  1495. text.resize(n_chars);
  1496. // NOTE: the original tokenizer decodes bytes after collecting the pieces.
  1497. return text;
  1498. }
  1499. //
  1500. // KV cache utils
  1501. //
  1502. void common_kv_cache_dump_view(const llama_kv_cache_view & view, int row_size) {
  1503. static const char slot_chars[] = ".123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+";
  1504. printf("=== Dumping KV cache. total cells %d, max sequences per cell %d, populated cells %d, total tokens in cache %d, largest empty slot=%d @ %d",
  1505. view.n_cells, view.n_seq_max, view.used_cells, view.token_count, view.max_contiguous, view.max_contiguous_idx);
  1506. llama_kv_cache_view_cell * c_curr = view.cells;
  1507. llama_seq_id * cs_curr = view.cells_sequences;
  1508. for (int i = 0; i < view.n_cells; i++, c_curr++, cs_curr += view.n_seq_max) {
  1509. if (i % row_size == 0) {
  1510. printf("\n%5d: ", i);
  1511. }
  1512. int seq_count = 0;
  1513. for (int j = 0; j < view.n_seq_max; j++) {
  1514. if (cs_curr[j] >= 0) { seq_count++; }
  1515. }
  1516. putchar(slot_chars[std::min(sizeof(slot_chars) - 2, size_t(seq_count))]);
  1517. }
  1518. printf("\n=== Done dumping\n");
  1519. }
  1520. void common_kv_cache_dump_view_seqs(const llama_kv_cache_view & view, int row_size) {
  1521. static const char slot_chars[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  1522. printf("=== Dumping KV cache. total cells %d, max sequences per cell %d, populated cells %d, total tokens in cache %d, largest empty slot=%d @ %d\n",
  1523. view.n_cells, view.n_seq_max, view.used_cells, view.token_count, view.max_contiguous, view.max_contiguous_idx);
  1524. std::unordered_map<llama_seq_id, size_t> seqs;
  1525. llama_kv_cache_view_cell * c_curr = view.cells;
  1526. llama_seq_id * cs_curr = view.cells_sequences;
  1527. for (int i = 0; i < view.n_cells; i++, c_curr++, cs_curr += view.n_seq_max) {
  1528. for (int j = 0; j < view.n_seq_max; j++) {
  1529. if (cs_curr[j] < 0) { continue; }
  1530. if (seqs.find(cs_curr[j]) == seqs.end()) {
  1531. if (seqs.size() + 1 >= sizeof(slot_chars)) { break; }
  1532. const size_t sz = seqs.size();
  1533. seqs[cs_curr[j]] = sz;
  1534. }
  1535. }
  1536. if (seqs.size() + 1 >= sizeof(slot_chars)) { break; }
  1537. }
  1538. printf("=== Sequence legend: ");
  1539. for (const auto & it : seqs) {
  1540. printf("%zu=%d, ", it.second, it.first);
  1541. }
  1542. printf("'+'=other sequence ids");
  1543. c_curr = view.cells;
  1544. cs_curr = view.cells_sequences;
  1545. for (int i = 0; i < view.n_cells; i++, c_curr++, cs_curr += view.n_seq_max) {
  1546. if (i % row_size == 0) {
  1547. printf("\n%5d: ", i);
  1548. }
  1549. for (int j = 0; j < view.n_seq_max; j++) {
  1550. if (cs_curr[j] >= 0) {
  1551. const auto & it = seqs.find(cs_curr[j]);
  1552. putchar(it != seqs.end() ? int(slot_chars[it->second]) : '+');
  1553. } else {
  1554. putchar('.');
  1555. }
  1556. }
  1557. putchar(' ');
  1558. }
  1559. printf("\n=== Done dumping\n");
  1560. }
  1561. //
  1562. // Embedding utils
  1563. //
  1564. void common_embd_normalize(const float * inp, float * out, int n, int embd_norm) {
  1565. double sum = 0.0;
  1566. switch (embd_norm) {
  1567. case -1: // no normalisation
  1568. sum = 1.0;
  1569. break;
  1570. case 0: // max absolute
  1571. for (int i = 0; i < n; i++) {
  1572. if (sum < std::abs(inp[i])) {
  1573. sum = std::abs(inp[i]);
  1574. }
  1575. }
  1576. sum /= 32760.0; // make an int16 range
  1577. break;
  1578. case 2: // euclidean
  1579. for (int i = 0; i < n; i++) {
  1580. sum += inp[i] * inp[i];
  1581. }
  1582. sum = std::sqrt(sum);
  1583. break;
  1584. default: // p-norm (euclidean is p-norm p=2)
  1585. for (int i = 0; i < n; i++) {
  1586. sum += std::pow(std::abs(inp[i]), embd_norm);
  1587. }
  1588. sum = std::pow(sum, 1.0 / embd_norm);
  1589. break;
  1590. }
  1591. const float norm = sum > 0.0 ? 1.0 / sum : 0.0f;
  1592. for (int i = 0; i < n; i++) {
  1593. out[i] = inp[i] * norm;
  1594. }
  1595. }
  1596. float common_embd_similarity_cos(const float * embd1, const float * embd2, int n){
  1597. double sum = 0.0;
  1598. double sum1 = 0.0;
  1599. double sum2 = 0.0;
  1600. for (int i = 0; i < n; i++) {
  1601. sum += embd1[i] * embd2[i];
  1602. sum1 += embd1[i] * embd1[i];
  1603. sum2 += embd2[i] * embd2[i];
  1604. }
  1605. // Handle the case where one or both vectors are zero vectors
  1606. if (sum1 == 0.0 || sum2 == 0.0) {
  1607. if (sum1 == 0.0 && sum2 == 0.0) {
  1608. return 1.0f; // two zero vectors are similar
  1609. }
  1610. return 0.0f;
  1611. }
  1612. return sum / (sqrt(sum1) * sqrt(sum2));
  1613. }
  1614. //
  1615. // Control vector utils
  1616. //
  1617. static common_control_vector_data common_control_vector_load_one(const common_control_vector_load_info & load_info) {
  1618. common_control_vector_data result = { -1, {} };
  1619. ggml_context * ctx = nullptr;
  1620. struct gguf_init_params meta_gguf_params = {
  1621. /* .no_alloc = */ false,
  1622. /* .ctx = */ &ctx,
  1623. };
  1624. struct gguf_context * ctx_gguf = gguf_init_from_file(load_info.fname.c_str(), meta_gguf_params);
  1625. if (!ctx_gguf) {
  1626. LOG_ERR("%s: failed to load control vector file from %s\n", __func__, load_info.fname.c_str());
  1627. return result;
  1628. }
  1629. int32_t n_tensors = gguf_get_n_tensors(ctx_gguf);
  1630. if (n_tensors == 0) {
  1631. LOG_WRN("%s: no direction tensors found in %s\n", __func__, load_info.fname.c_str());
  1632. }
  1633. for (int i = 0; i < n_tensors; i++) {
  1634. std::string name = gguf_get_tensor_name(ctx_gguf, i);
  1635. int layer_idx = -1;
  1636. // split on '.'
  1637. size_t dotpos = name.find('.');
  1638. if (dotpos != std::string::npos && name.substr(0, dotpos) == "direction") {
  1639. try {
  1640. layer_idx = std::stoi(name.substr(dotpos + 1));
  1641. } catch (...) {
  1642. layer_idx = -1;
  1643. }
  1644. }
  1645. if (layer_idx < 0) {
  1646. LOG_ERR("%s: invalid/unparsable direction tensor layer index in %s\n", __func__, load_info.fname.c_str());
  1647. result.n_embd = -1;
  1648. break;
  1649. } else if (layer_idx == 0) {
  1650. LOG_ERR("%s: invalid (zero) direction tensor layer index in %s\n", __func__, load_info.fname.c_str());
  1651. result.n_embd = -1;
  1652. break;
  1653. }
  1654. struct ggml_tensor * tensor = ggml_get_tensor(ctx, name.c_str());
  1655. if (tensor->type != GGML_TYPE_F32) {
  1656. LOG_ERR("%s: invalid (non-F32) direction tensor type in %s\n", __func__, load_info.fname.c_str());
  1657. result.n_embd = -1;
  1658. break;
  1659. }
  1660. if (ggml_n_dims(tensor) != 1) {
  1661. LOG_ERR("%s: invalid (non-1D) direction tensor shape in %s\n", __func__, load_info.fname.c_str());
  1662. result.n_embd = -1;
  1663. break;
  1664. }
  1665. if (result.n_embd == -1) {
  1666. result.n_embd = ggml_nelements(tensor);
  1667. } else if (ggml_nelements(tensor) != result.n_embd) {
  1668. LOG_ERR("%s: direction tensor in %s does not match previous dimensions\n", __func__, load_info.fname.c_str());
  1669. result.n_embd = -1;
  1670. break;
  1671. }
  1672. // extend if necessary - do not store data for layer 0 (it's not used)
  1673. result.data.resize(std::max(result.data.size(), static_cast<size_t>(result.n_embd * layer_idx)), 0.0f);
  1674. const float * src = (const float *) tensor->data;
  1675. float * dst = result.data.data() + result.n_embd * (layer_idx - 1); // layer 1 at [0]
  1676. for (int j = 0; j < result.n_embd; j++) {
  1677. dst[j] += src[j] * load_info.strength; // allows multiple directions for same layer in same file
  1678. }
  1679. }
  1680. if (result.n_embd == -1) {
  1681. LOG_WRN("%s: skipping %s due to invalid direction tensors\n", __func__, load_info.fname.c_str());
  1682. result.data.clear();
  1683. }
  1684. gguf_free(ctx_gguf);
  1685. ggml_free(ctx);
  1686. return result;
  1687. }
  1688. common_control_vector_data common_control_vector_load(const std::vector<common_control_vector_load_info> & load_infos) {
  1689. common_control_vector_data result = { -1, {} };
  1690. for (const auto & info : load_infos) {
  1691. auto cur = common_control_vector_load_one(info);
  1692. if (cur.n_embd == -1) {
  1693. result.n_embd = -1;
  1694. break;
  1695. }
  1696. if (result.n_embd != -1 && result.n_embd != cur.n_embd) {
  1697. LOG_ERR("%s: control vectors in %s does not match previous dimensions\n", __func__, info.fname.c_str());
  1698. result.n_embd = -1;
  1699. break;
  1700. }
  1701. if (result.n_embd == -1) {
  1702. result = std::move(cur);
  1703. } else {
  1704. result.data.resize(std::max(result.data.size(), cur.data.size()), 0.0f); // extend if necessary
  1705. for (size_t i = 0; i < cur.data.size(); i++) {
  1706. result.data[i] += cur.data[i];
  1707. }
  1708. }
  1709. }
  1710. if (result.n_embd == -1) {
  1711. LOG_ERR("%s: no valid control vector files passed\n", __func__);
  1712. result.data.clear();
  1713. }
  1714. return result;
  1715. }