common.cpp 76 KB

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