common.cpp 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971
  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::string string_strip(const std::string & str) {
  360. size_t start = 0;
  361. size_t end = str.size();
  362. while (start < end && std::isspace(str[start])) {
  363. start++;
  364. }
  365. while (end > start && std::isspace(str[end - 1])) {
  366. end--;
  367. }
  368. return str.substr(start, end - start);
  369. }
  370. std::string string_get_sortable_timestamp() {
  371. using clock = std::chrono::system_clock;
  372. const clock::time_point current_time = clock::now();
  373. const time_t as_time_t = clock::to_time_t(current_time);
  374. char timestamp_no_ns[100];
  375. std::strftime(timestamp_no_ns, 100, "%Y_%m_%d-%H_%M_%S", std::localtime(&as_time_t));
  376. const int64_t ns = std::chrono::duration_cast<std::chrono::nanoseconds>(
  377. current_time.time_since_epoch() % 1000000000).count();
  378. char timestamp_ns[11];
  379. snprintf(timestamp_ns, 11, "%09" PRId64, ns);
  380. return std::string(timestamp_no_ns) + "." + std::string(timestamp_ns);
  381. }
  382. void string_replace_all(std::string & s, const std::string & search, const std::string & replace) {
  383. if (search.empty()) {
  384. return;
  385. }
  386. std::string builder;
  387. builder.reserve(s.length());
  388. size_t pos = 0;
  389. size_t last_pos = 0;
  390. while ((pos = s.find(search, last_pos)) != std::string::npos) {
  391. builder.append(s, last_pos, pos - last_pos);
  392. builder.append(replace);
  393. last_pos = pos + search.length();
  394. }
  395. builder.append(s, last_pos, std::string::npos);
  396. s = std::move(builder);
  397. }
  398. std::string string_from(bool value) {
  399. return value ? "true" : "false";
  400. }
  401. std::string string_from(const std::vector<int> & values) {
  402. std::stringstream buf;
  403. buf << "[ ";
  404. bool first = true;
  405. for (auto e : values) {
  406. if (first) {
  407. first = false;
  408. } else {
  409. buf << ", ";
  410. }
  411. buf << std::to_string(e);
  412. }
  413. buf << " ]";
  414. return buf.str();
  415. }
  416. std::string string_from(const struct llama_context * ctx, const std::vector<llama_token> & tokens) {
  417. std::stringstream buf;
  418. buf << "[ ";
  419. bool first = true;
  420. for (const auto & token : tokens) {
  421. if (!first) {
  422. buf << ", ";
  423. } else {
  424. first = false;
  425. }
  426. auto detokenized = common_token_to_piece(ctx, token);
  427. detokenized.erase(
  428. std::remove_if(
  429. detokenized.begin(),
  430. detokenized.end(),
  431. [](const unsigned char c) { return !std::isprint(c); }),
  432. detokenized.end());
  433. buf << "'" << detokenized << "'"
  434. << ":" << std::to_string(token);
  435. }
  436. buf << " ]";
  437. return buf.str();
  438. }
  439. std::string string_from(const struct llama_context * ctx, const struct llama_batch & batch) {
  440. std::stringstream buf;
  441. buf << "[ ";
  442. bool first = true;
  443. for (int i = 0; i < batch.n_tokens; ++i) {
  444. if (!first) {
  445. buf << ", ";
  446. } else {
  447. first = false;
  448. }
  449. auto detokenized = common_token_to_piece(ctx, batch.token[i]);
  450. detokenized.erase(
  451. std::remove_if(
  452. detokenized.begin(),
  453. detokenized.end(),
  454. [](const unsigned char c) { return !std::isprint(c); }),
  455. detokenized.end());
  456. buf << "\n" << std::to_string(i)
  457. << ", token '" << detokenized << "'"
  458. << ", pos " << std::to_string(batch.pos[i])
  459. << ", n_seq_id " << std::to_string(batch.n_seq_id[i])
  460. << ", seq_id " << std::to_string(batch.seq_id[i][0])
  461. << ", logits " << std::to_string(batch.logits[i]);
  462. }
  463. buf << " ]";
  464. return buf.str();
  465. }
  466. void string_process_escapes(std::string & input) {
  467. std::size_t input_len = input.length();
  468. std::size_t output_idx = 0;
  469. for (std::size_t input_idx = 0; input_idx < input_len; ++input_idx) {
  470. if (input[input_idx] == '\\' && input_idx + 1 < input_len) {
  471. switch (input[++input_idx]) {
  472. case 'n': input[output_idx++] = '\n'; break;
  473. case 'r': input[output_idx++] = '\r'; break;
  474. case 't': input[output_idx++] = '\t'; break;
  475. case '\'': input[output_idx++] = '\''; break;
  476. case '\"': input[output_idx++] = '\"'; break;
  477. case '\\': input[output_idx++] = '\\'; break;
  478. case 'x':
  479. // Handle \x12, etc
  480. if (input_idx + 2 < input_len) {
  481. const char x[3] = { input[input_idx + 1], input[input_idx + 2], 0 };
  482. char *err_p = nullptr;
  483. const long val = std::strtol(x, &err_p, 16);
  484. if (err_p == x + 2) {
  485. input_idx += 2;
  486. input[output_idx++] = char(val);
  487. break;
  488. }
  489. }
  490. // fall through
  491. default: input[output_idx++] = '\\';
  492. input[output_idx++] = input[input_idx]; break;
  493. }
  494. } else {
  495. input[output_idx++] = input[input_idx];
  496. }
  497. }
  498. input.resize(output_idx);
  499. }
  500. bool string_parse_kv_override(const char * data, std::vector<llama_model_kv_override> & overrides) {
  501. const char * sep = strchr(data, '=');
  502. if (sep == nullptr || sep - data >= 128) {
  503. LOG_ERR("%s: malformed KV override '%s'\n", __func__, data);
  504. return false;
  505. }
  506. llama_model_kv_override kvo;
  507. std::strncpy(kvo.key, data, sep - data);
  508. kvo.key[sep - data] = 0;
  509. sep++;
  510. if (strncmp(sep, "int:", 4) == 0) {
  511. sep += 4;
  512. kvo.tag = LLAMA_KV_OVERRIDE_TYPE_INT;
  513. kvo.val_i64 = std::atol(sep);
  514. } else if (strncmp(sep, "float:", 6) == 0) {
  515. sep += 6;
  516. kvo.tag = LLAMA_KV_OVERRIDE_TYPE_FLOAT;
  517. kvo.val_f64 = std::atof(sep);
  518. } else if (strncmp(sep, "bool:", 5) == 0) {
  519. sep += 5;
  520. kvo.tag = LLAMA_KV_OVERRIDE_TYPE_BOOL;
  521. if (std::strcmp(sep, "true") == 0) {
  522. kvo.val_bool = true;
  523. } else if (std::strcmp(sep, "false") == 0) {
  524. kvo.val_bool = false;
  525. } else {
  526. LOG_ERR("%s: invalid boolean value for KV override '%s'\n", __func__, data);
  527. return false;
  528. }
  529. } else if (strncmp(sep, "str:", 4) == 0) {
  530. sep += 4;
  531. kvo.tag = LLAMA_KV_OVERRIDE_TYPE_STR;
  532. if (strlen(sep) > 127) {
  533. LOG_ERR("%s: malformed KV override '%s', value cannot exceed 127 chars\n", __func__, data);
  534. return false;
  535. }
  536. strncpy(kvo.val_str, sep, 127);
  537. kvo.val_str[127] = '\0';
  538. } else {
  539. LOG_ERR("%s: invalid type for KV override '%s'\n", __func__, data);
  540. return false;
  541. }
  542. overrides.emplace_back(std::move(kvo));
  543. return true;
  544. }
  545. //
  546. // Filesystem utils
  547. //
  548. // Validate if a filename is safe to use
  549. // To validate a full path, split the path by the OS-specific path separator, and validate each part with this function
  550. bool fs_validate_filename(const std::string & filename) {
  551. if (!filename.length()) {
  552. // Empty filename invalid
  553. return false;
  554. }
  555. if (filename.length() > 255) {
  556. // Limit at common largest possible filename on Linux filesystems
  557. // to avoid unnecessary further validation
  558. // (On systems with smaller limits it will be caught by the OS)
  559. return false;
  560. }
  561. std::u32string filename_utf32;
  562. try {
  563. #if defined(__clang__)
  564. // disable C++17 deprecation warning for std::codecvt_utf8
  565. # pragma clang diagnostic push
  566. # pragma clang diagnostic ignored "-Wdeprecated-declarations"
  567. #endif
  568. std::wstring_convert<std::codecvt_utf8<char32_t>, char32_t> converter;
  569. #if defined(__clang__)
  570. # pragma clang diagnostic pop
  571. #endif
  572. filename_utf32 = converter.from_bytes(filename);
  573. // If the reverse conversion mismatches, it means overlong UTF-8 sequences were used,
  574. // or invalid encodings were encountered. Reject such attempts
  575. std::string filename_reencoded = converter.to_bytes(filename_utf32);
  576. if (filename_reencoded != filename) {
  577. return false;
  578. }
  579. } catch (const std::exception &) {
  580. return false;
  581. }
  582. // Check for forbidden codepoints:
  583. // - Control characters
  584. // - Unicode equivalents of illegal characters
  585. // - UTF-16 surrogate pairs
  586. // - UTF-8 replacement character
  587. // - Byte order mark (BOM)
  588. // - Illegal characters: / \ : * ? " < > |
  589. for (char32_t c : filename_utf32) {
  590. if (c <= 0x1F // Control characters (C0)
  591. || c == 0x7F // Control characters (DEL)
  592. || (c >= 0x80 && c <= 0x9F) // Control characters (C1)
  593. || c == 0xFF0E // Fullwidth Full Stop (period equivalent)
  594. || c == 0x2215 // Division Slash (forward slash equivalent)
  595. || c == 0x2216 // Set Minus (backslash equivalent)
  596. || (c >= 0xD800 && c <= 0xDFFF) // UTF-16 surrogate pairs
  597. || c == 0xFFFD // Replacement Character (UTF-8)
  598. || c == 0xFEFF // Byte Order Mark (BOM)
  599. || c == '/' || c == '\\' || c == ':' || c == '*' // Illegal characters
  600. || c == '?' || c == '"' || c == '<' || c == '>' || c == '|') {
  601. return false;
  602. }
  603. }
  604. // Reject any leading or trailing ' ', or any trailing '.', these are stripped on Windows and will cause a different filename
  605. // Unicode and other whitespace is not affected, only 0x20 space
  606. if (filename.front() == ' ' || filename.back() == ' ' || filename.back() == '.') {
  607. return false;
  608. }
  609. // Reject any ".." (currently stricter than necessary, it should be fine to just check for == ".." instead)
  610. if (filename.find("..") != std::string::npos) {
  611. return false;
  612. }
  613. // Reject "."
  614. if (filename == ".") {
  615. return false;
  616. }
  617. return true;
  618. }
  619. // returns true if successful, false otherwise
  620. bool fs_create_directory_with_parents(const std::string & path) {
  621. #ifdef _WIN32
  622. std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;
  623. std::wstring wpath = converter.from_bytes(path);
  624. // if the path already exists, check whether it's a directory
  625. const DWORD attributes = GetFileAttributesW(wpath.c_str());
  626. if ((attributes != INVALID_FILE_ATTRIBUTES) && (attributes & FILE_ATTRIBUTE_DIRECTORY)) {
  627. return true;
  628. }
  629. size_t pos_slash = 0;
  630. // process path from front to back, procedurally creating directories
  631. while ((pos_slash = path.find('\\', pos_slash)) != std::string::npos) {
  632. const std::wstring subpath = wpath.substr(0, pos_slash);
  633. const wchar_t * test = subpath.c_str();
  634. const bool success = CreateDirectoryW(test, NULL);
  635. if (!success) {
  636. const DWORD error = GetLastError();
  637. // if the path already exists, ensure that it's a directory
  638. if (error == ERROR_ALREADY_EXISTS) {
  639. const DWORD attributes = GetFileAttributesW(subpath.c_str());
  640. if (attributes == INVALID_FILE_ATTRIBUTES || !(attributes & FILE_ATTRIBUTE_DIRECTORY)) {
  641. return false;
  642. }
  643. } else {
  644. return false;
  645. }
  646. }
  647. pos_slash += 1;
  648. }
  649. return true;
  650. #else
  651. // if the path already exists, check whether it's a directory
  652. struct stat info;
  653. if (stat(path.c_str(), &info) == 0) {
  654. return S_ISDIR(info.st_mode);
  655. }
  656. size_t pos_slash = 1; // skip leading slashes for directory creation
  657. // process path from front to back, procedurally creating directories
  658. while ((pos_slash = path.find('/', pos_slash)) != std::string::npos) {
  659. const std::string subpath = path.substr(0, pos_slash);
  660. struct stat info;
  661. // if the path already exists, ensure that it's a directory
  662. if (stat(subpath.c_str(), &info) == 0) {
  663. if (!S_ISDIR(info.st_mode)) {
  664. return false;
  665. }
  666. } else {
  667. // create parent directories
  668. const int ret = mkdir(subpath.c_str(), 0755);
  669. if (ret != 0) {
  670. return false;
  671. }
  672. }
  673. pos_slash += 1;
  674. }
  675. return true;
  676. #endif // _WIN32
  677. }
  678. std::string fs_get_cache_directory() {
  679. std::string cache_directory = "";
  680. auto ensure_trailing_slash = [](std::string p) {
  681. // Make sure to add trailing slash
  682. if (p.back() != DIRECTORY_SEPARATOR) {
  683. p += DIRECTORY_SEPARATOR;
  684. }
  685. return p;
  686. };
  687. if (getenv("LLAMA_CACHE")) {
  688. cache_directory = std::getenv("LLAMA_CACHE");
  689. } else {
  690. #ifdef __linux__
  691. if (std::getenv("XDG_CACHE_HOME")) {
  692. cache_directory = std::getenv("XDG_CACHE_HOME");
  693. } else {
  694. cache_directory = std::getenv("HOME") + std::string("/.cache/");
  695. }
  696. #elif defined(__APPLE__)
  697. cache_directory = std::getenv("HOME") + std::string("/Library/Caches/");
  698. #elif defined(_WIN32)
  699. cache_directory = std::getenv("LOCALAPPDATA");
  700. #endif // __linux__
  701. cache_directory = ensure_trailing_slash(cache_directory);
  702. cache_directory += "llama.cpp";
  703. }
  704. return ensure_trailing_slash(cache_directory);
  705. }
  706. std::string fs_get_cache_file(const std::string & filename) {
  707. GGML_ASSERT(filename.find(DIRECTORY_SEPARATOR) == std::string::npos);
  708. std::string cache_directory = fs_get_cache_directory();
  709. const bool success = fs_create_directory_with_parents(cache_directory);
  710. if (!success) {
  711. throw std::runtime_error("failed to create cache directory: " + cache_directory);
  712. }
  713. return cache_directory + filename;
  714. }
  715. //
  716. // Model utils
  717. //
  718. struct common_init_result common_init_from_params(common_params & params) {
  719. common_init_result iparams;
  720. auto mparams = common_model_params_to_llama(params);
  721. llama_model * model = nullptr;
  722. if (!params.hf_repo.empty() && !params.hf_file.empty()) {
  723. model = common_load_model_from_hf(params.hf_repo, params.hf_file, params.model, params.hf_token, mparams);
  724. } else if (!params.model_url.empty()) {
  725. model = common_load_model_from_url(params.model_url, params.model, params.hf_token, mparams);
  726. } else {
  727. model = llama_load_model_from_file(params.model.c_str(), mparams);
  728. }
  729. if (model == NULL) {
  730. LOG_ERR("%s: failed to load model '%s'\n", __func__, params.model.c_str());
  731. return iparams;
  732. }
  733. if (params.reranking) {
  734. bool ok = true;
  735. if (llama_token_bos(model) == LLAMA_TOKEN_NULL) {
  736. LOG_WRN("%s: warning: model does not have a BOS token, reranking will not work\n", __func__);
  737. ok = false;
  738. }
  739. if (llama_token_eos(model) == LLAMA_TOKEN_NULL) {
  740. LOG_WRN("%s: warning: model does not have an EOS token, reranking will not work\n", __func__);
  741. ok = false;
  742. }
  743. if (llama_token_sep(model) == LLAMA_TOKEN_NULL) {
  744. LOG_WRN("%s: warning: model does not have a SEP token, reranking will not work\n", __func__);
  745. ok = false;
  746. }
  747. if (!ok) {
  748. llama_free_model(model);
  749. return iparams;
  750. }
  751. }
  752. auto cparams = common_context_params_to_llama(params);
  753. llama_context * lctx = llama_new_context_with_model(model, cparams);
  754. if (lctx == NULL) {
  755. LOG_ERR("%s: failed to create context with model '%s'\n", __func__, params.model.c_str());
  756. llama_free_model(model);
  757. return iparams;
  758. }
  759. if (params.ctx_shift && !llama_kv_cache_can_shift(lctx)) {
  760. LOG_ERR("%s: KV cache shifting is not supported for this model (--no-context-shift to disable)'\n", __func__);
  761. llama_free_model(model);
  762. return iparams;
  763. }
  764. if (!params.control_vectors.empty()) {
  765. if (params.control_vector_layer_start <= 0) params.control_vector_layer_start = 1;
  766. if (params.control_vector_layer_end <= 0) params.control_vector_layer_end = llama_n_layer(model);
  767. const auto cvec = common_control_vector_load(params.control_vectors);
  768. if (cvec.n_embd == -1) {
  769. llama_free(lctx);
  770. llama_free_model(model);
  771. return iparams;
  772. }
  773. int err = llama_control_vector_apply(lctx,
  774. cvec.data.data(),
  775. cvec.data.size(),
  776. cvec.n_embd,
  777. params.control_vector_layer_start,
  778. params.control_vector_layer_end);
  779. if (err) {
  780. llama_free(lctx);
  781. llama_free_model(model);
  782. return iparams;
  783. }
  784. }
  785. // load and optionally apply lora adapters
  786. for (auto & la : params.lora_adapters) {
  787. common_lora_adapter_container loaded_la;
  788. loaded_la.path = la.path;
  789. loaded_la.scale = la.scale;
  790. loaded_la.adapter = llama_lora_adapter_init(model, la.path.c_str());
  791. if (loaded_la.adapter == nullptr) {
  792. LOG_ERR("%s: failed to apply lora adapter '%s'\n", __func__, la.path.c_str());
  793. llama_free(lctx);
  794. llama_free_model(model);
  795. return iparams;
  796. }
  797. iparams.lora_adapters.push_back(loaded_la); // copy to list of loaded adapters
  798. }
  799. if (!params.lora_init_without_apply) {
  800. common_lora_adapters_apply(lctx, iparams.lora_adapters);
  801. }
  802. if (params.sampling.ignore_eos && llama_token_eos(model) == LLAMA_TOKEN_NULL) {
  803. LOG_WRN("%s: warning: model does not have an EOS token, ignoring --ignore-eos\n", __func__);
  804. params.sampling.ignore_eos = false;
  805. }
  806. if (params.warmup) {
  807. LOG_WRN("%s: warming up the model with an empty run - please wait ... (--no-warmup to disable)\n", __func__);
  808. std::vector<llama_token> tmp;
  809. llama_token bos = llama_token_bos(model);
  810. llama_token eos = llama_token_eos(model);
  811. // some models (e.g. T5) don't have a BOS token
  812. if (bos != LLAMA_TOKEN_NULL) {
  813. tmp.push_back(bos);
  814. }
  815. if (eos != LLAMA_TOKEN_NULL) {
  816. tmp.push_back(eos);
  817. }
  818. if (tmp.empty()) {
  819. tmp.push_back(0);
  820. }
  821. if (llama_model_has_encoder(model)) {
  822. llama_encode(lctx, llama_batch_get_one(tmp.data(), tmp.size()));
  823. llama_token decoder_start_token_id = llama_model_decoder_start_token(model);
  824. if (decoder_start_token_id == -1) {
  825. decoder_start_token_id = bos;
  826. }
  827. tmp.clear();
  828. tmp.push_back(decoder_start_token_id);
  829. }
  830. if (llama_model_has_decoder(model)) {
  831. llama_decode(lctx, llama_batch_get_one(tmp.data(), std::min(tmp.size(), (size_t) params.n_batch)));
  832. }
  833. llama_kv_cache_clear(lctx);
  834. llama_synchronize(lctx);
  835. llama_perf_context_reset(lctx);
  836. }
  837. iparams.model = model;
  838. iparams.context = lctx;
  839. return iparams;
  840. }
  841. void common_lora_adapters_apply(struct llama_context * ctx, std::vector<common_lora_adapter_container> & lora_adapters) {
  842. llama_lora_adapter_clear(ctx);
  843. for (auto & la : lora_adapters) {
  844. if (la.scale != 0.0f) {
  845. llama_lora_adapter_set(ctx, la.adapter, la.scale);
  846. }
  847. }
  848. }
  849. struct llama_model_params common_model_params_to_llama(common_params & params) {
  850. auto mparams = llama_model_default_params();
  851. if (!params.devices.empty()) {
  852. mparams.devices = params.devices.data();
  853. }
  854. if (params.n_gpu_layers != -1) {
  855. mparams.n_gpu_layers = params.n_gpu_layers;
  856. }
  857. mparams.rpc_servers = params.rpc_servers.c_str();
  858. mparams.main_gpu = params.main_gpu;
  859. mparams.split_mode = params.split_mode;
  860. mparams.tensor_split = params.tensor_split;
  861. mparams.use_mmap = params.use_mmap;
  862. mparams.use_mlock = params.use_mlock;
  863. mparams.check_tensors = params.check_tensors;
  864. if (params.kv_overrides.empty()) {
  865. mparams.kv_overrides = NULL;
  866. } else {
  867. GGML_ASSERT(params.kv_overrides.back().key[0] == 0 && "KV overrides not terminated with empty key");
  868. mparams.kv_overrides = params.kv_overrides.data();
  869. }
  870. return mparams;
  871. }
  872. static ggml_type kv_cache_type_from_str(const std::string & s) {
  873. if (s == "f32") {
  874. return GGML_TYPE_F32;
  875. }
  876. if (s == "f16") {
  877. return GGML_TYPE_F16;
  878. }
  879. if (s == "bf16") {
  880. return GGML_TYPE_BF16;
  881. }
  882. if (s == "q8_0") {
  883. return GGML_TYPE_Q8_0;
  884. }
  885. if (s == "q4_0") {
  886. return GGML_TYPE_Q4_0;
  887. }
  888. if (s == "q4_1") {
  889. return GGML_TYPE_Q4_1;
  890. }
  891. if (s == "iq4_nl") {
  892. return GGML_TYPE_IQ4_NL;
  893. }
  894. if (s == "q5_0") {
  895. return GGML_TYPE_Q5_0;
  896. }
  897. if (s == "q5_1") {
  898. return GGML_TYPE_Q5_1;
  899. }
  900. throw std::runtime_error("Unsupported cache type: " + s);
  901. }
  902. struct llama_context_params common_context_params_to_llama(const common_params & params) {
  903. auto cparams = llama_context_default_params();
  904. cparams.n_ctx = params.n_ctx;
  905. cparams.n_seq_max = params.n_parallel;
  906. cparams.n_batch = params.n_batch;
  907. cparams.n_ubatch = params.n_ubatch;
  908. cparams.n_threads = params.cpuparams.n_threads;
  909. cparams.n_threads_batch = params.cpuparams_batch.n_threads == -1 ?
  910. params.cpuparams.n_threads : params.cpuparams_batch.n_threads;
  911. cparams.logits_all = params.logits_all;
  912. cparams.embeddings = params.embedding;
  913. cparams.rope_scaling_type = params.rope_scaling_type;
  914. cparams.rope_freq_base = params.rope_freq_base;
  915. cparams.rope_freq_scale = params.rope_freq_scale;
  916. cparams.yarn_ext_factor = params.yarn_ext_factor;
  917. cparams.yarn_attn_factor = params.yarn_attn_factor;
  918. cparams.yarn_beta_fast = params.yarn_beta_fast;
  919. cparams.yarn_beta_slow = params.yarn_beta_slow;
  920. cparams.yarn_orig_ctx = params.yarn_orig_ctx;
  921. cparams.pooling_type = params.pooling_type;
  922. cparams.attention_type = params.attention_type;
  923. cparams.defrag_thold = params.defrag_thold;
  924. cparams.cb_eval = params.cb_eval;
  925. cparams.cb_eval_user_data = params.cb_eval_user_data;
  926. cparams.offload_kqv = !params.no_kv_offload;
  927. cparams.flash_attn = params.flash_attn;
  928. cparams.no_perf = params.no_perf;
  929. if (params.reranking) {
  930. cparams.embeddings = true;
  931. cparams.pooling_type = LLAMA_POOLING_TYPE_RANK;
  932. }
  933. cparams.type_k = kv_cache_type_from_str(params.cache_type_k);
  934. cparams.type_v = kv_cache_type_from_str(params.cache_type_v);
  935. return cparams;
  936. }
  937. struct ggml_threadpool_params ggml_threadpool_params_from_cpu_params(const cpu_params & params) {
  938. struct ggml_threadpool_params tpp;
  939. ggml_threadpool_params_init(&tpp, params.n_threads); // setup the defaults
  940. if (params.mask_valid) {
  941. std::memcpy(&tpp.cpumask, &params.cpumask, GGML_MAX_N_THREADS);
  942. }
  943. tpp.prio = params.priority;
  944. tpp.poll = params.poll;
  945. tpp.strict_cpu = params.strict_cpu;
  946. return tpp;
  947. }
  948. #ifdef LLAMA_USE_CURL
  949. #define CURL_MAX_RETRY 3
  950. #define CURL_RETRY_DELAY_SECONDS 2
  951. static bool starts_with(const std::string & str, const std::string & prefix) {
  952. // While we wait for C++20's std::string::starts_with...
  953. return str.rfind(prefix, 0) == 0;
  954. }
  955. static bool curl_perform_with_retry(const std::string& url, CURL* curl, int max_attempts, int retry_delay_seconds) {
  956. int remaining_attempts = max_attempts;
  957. while (remaining_attempts > 0) {
  958. LOG_INF("%s: Trying to download from %s (attempt %d of %d)...\n", __func__ , url.c_str(), max_attempts - remaining_attempts + 1, max_attempts);
  959. CURLcode res = curl_easy_perform(curl);
  960. if (res == CURLE_OK) {
  961. return true;
  962. }
  963. int exponential_backoff_delay = std::pow(retry_delay_seconds, max_attempts - remaining_attempts) * 1000;
  964. LOG_WRN("%s: curl_easy_perform() failed: %s, retrying after %d milliseconds...\n", __func__, curl_easy_strerror(res), exponential_backoff_delay);
  965. remaining_attempts--;
  966. std::this_thread::sleep_for(std::chrono::milliseconds(exponential_backoff_delay));
  967. }
  968. LOG_ERR("%s: curl_easy_perform() failed after %d attempts\n", __func__, max_attempts);
  969. return false;
  970. }
  971. static bool common_download_file(const std::string & url, const std::string & path, const std::string & hf_token) {
  972. // Initialize libcurl
  973. std::unique_ptr<CURL, decltype(&curl_easy_cleanup)> curl(curl_easy_init(), &curl_easy_cleanup);
  974. if (!curl) {
  975. LOG_ERR("%s: error initializing libcurl\n", __func__);
  976. return false;
  977. }
  978. bool force_download = false;
  979. // Set the URL, allow to follow http redirection
  980. curl_easy_setopt(curl.get(), CURLOPT_URL, url.c_str());
  981. curl_easy_setopt(curl.get(), CURLOPT_FOLLOWLOCATION, 1L);
  982. // Check if hf-token or bearer-token was specified
  983. if (!hf_token.empty()) {
  984. std::string auth_header = "Authorization: Bearer ";
  985. auth_header += hf_token.c_str();
  986. struct curl_slist *http_headers = NULL;
  987. http_headers = curl_slist_append(http_headers, auth_header.c_str());
  988. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, http_headers);
  989. }
  990. #if defined(_WIN32)
  991. // CURLSSLOPT_NATIVE_CA tells libcurl to use standard certificate store of
  992. // operating system. Currently implemented under MS-Windows.
  993. curl_easy_setopt(curl.get(), CURLOPT_SSL_OPTIONS, CURLSSLOPT_NATIVE_CA);
  994. #endif
  995. // Check if the file already exists locally
  996. struct stat model_file_info;
  997. auto file_exists = (stat(path.c_str(), &model_file_info) == 0);
  998. // If the file exists, check its JSON metadata companion file.
  999. std::string metadata_path = path + ".json";
  1000. nlohmann::json metadata;
  1001. std::string etag;
  1002. std::string last_modified;
  1003. if (file_exists) {
  1004. // Try and read the JSON metadata file (note: stream autoclosed upon exiting this block).
  1005. std::ifstream metadata_in(metadata_path);
  1006. if (metadata_in.good()) {
  1007. try {
  1008. metadata_in >> metadata;
  1009. LOG_INF("%s: previous metadata file found %s: %s\n", __func__, metadata_path.c_str(), metadata.dump().c_str());
  1010. if (metadata.contains("url") && metadata.at("url").is_string()) {
  1011. auto previous_url = metadata.at("url").get<std::string>();
  1012. if (previous_url != url) {
  1013. LOG_ERR("%s: Model URL mismatch: %s != %s\n", __func__, url.c_str(), previous_url.c_str());
  1014. return false;
  1015. }
  1016. }
  1017. if (metadata.contains("etag") && metadata.at("etag").is_string()) {
  1018. etag = metadata.at("etag");
  1019. }
  1020. if (metadata.contains("lastModified") && metadata.at("lastModified").is_string()) {
  1021. last_modified = metadata.at("lastModified");
  1022. }
  1023. } catch (const nlohmann::json::exception & e) {
  1024. LOG_ERR("%s: error reading metadata file %s: %s\n", __func__, metadata_path.c_str(), e.what());
  1025. return false;
  1026. }
  1027. }
  1028. } else {
  1029. LOG_INF("%s: no previous model file found %s\n", __func__, path.c_str());
  1030. }
  1031. // Send a HEAD request to retrieve the etag and last-modified headers
  1032. struct common_load_model_from_url_headers {
  1033. std::string etag;
  1034. std::string last_modified;
  1035. };
  1036. common_load_model_from_url_headers headers;
  1037. {
  1038. typedef size_t(*CURLOPT_HEADERFUNCTION_PTR)(char *, size_t, size_t, void *);
  1039. auto header_callback = [](char * buffer, size_t /*size*/, size_t n_items, void * userdata) -> size_t {
  1040. common_load_model_from_url_headers *headers = (common_load_model_from_url_headers *) userdata;
  1041. static std::regex header_regex("([^:]+): (.*)\r\n");
  1042. static std::regex etag_regex("ETag", std::regex_constants::icase);
  1043. static std::regex last_modified_regex("Last-Modified", std::regex_constants::icase);
  1044. std::string header(buffer, n_items);
  1045. std::smatch match;
  1046. if (std::regex_match(header, match, header_regex)) {
  1047. const std::string & key = match[1];
  1048. const std::string & value = match[2];
  1049. if (std::regex_match(key, match, etag_regex)) {
  1050. headers->etag = value;
  1051. } else if (std::regex_match(key, match, last_modified_regex)) {
  1052. headers->last_modified = value;
  1053. }
  1054. }
  1055. return n_items;
  1056. };
  1057. curl_easy_setopt(curl.get(), CURLOPT_NOBODY, 1L); // will trigger the HEAD verb
  1058. curl_easy_setopt(curl.get(), CURLOPT_NOPROGRESS, 1L); // hide head request progress
  1059. curl_easy_setopt(curl.get(), CURLOPT_HEADERFUNCTION, static_cast<CURLOPT_HEADERFUNCTION_PTR>(header_callback));
  1060. curl_easy_setopt(curl.get(), CURLOPT_HEADERDATA, &headers);
  1061. bool was_perform_successful = curl_perform_with_retry(url, curl.get(), CURL_MAX_RETRY, CURL_RETRY_DELAY_SECONDS);
  1062. if (!was_perform_successful) {
  1063. return false;
  1064. }
  1065. long http_code = 0;
  1066. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &http_code);
  1067. if (http_code != 200) {
  1068. // HEAD not supported, we don't know if the file has changed
  1069. // force trigger downloading
  1070. force_download = true;
  1071. LOG_ERR("%s: HEAD invalid http status code received: %ld\n", __func__, http_code);
  1072. }
  1073. }
  1074. bool should_download = !file_exists || force_download;
  1075. if (!should_download) {
  1076. if (!etag.empty() && etag != headers.etag) {
  1077. LOG_WRN("%s: ETag header is different (%s != %s): triggering a new download\n", __func__, etag.c_str(), headers.etag.c_str());
  1078. should_download = true;
  1079. } else if (!last_modified.empty() && last_modified != headers.last_modified) {
  1080. 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());
  1081. should_download = true;
  1082. }
  1083. }
  1084. if (should_download) {
  1085. std::string path_temporary = path + ".downloadInProgress";
  1086. if (file_exists) {
  1087. LOG_WRN("%s: deleting previous downloaded file: %s\n", __func__, path.c_str());
  1088. if (remove(path.c_str()) != 0) {
  1089. LOG_ERR("%s: unable to delete file: %s\n", __func__, path.c_str());
  1090. return false;
  1091. }
  1092. }
  1093. // Set the output file
  1094. struct FILE_deleter {
  1095. void operator()(FILE * f) const {
  1096. fclose(f);
  1097. }
  1098. };
  1099. std::unique_ptr<FILE, FILE_deleter> outfile(fopen(path_temporary.c_str(), "wb"));
  1100. if (!outfile) {
  1101. LOG_ERR("%s: error opening local file for writing: %s\n", __func__, path.c_str());
  1102. return false;
  1103. }
  1104. typedef size_t(*CURLOPT_WRITEFUNCTION_PTR)(void * data, size_t size, size_t nmemb, void * fd);
  1105. auto write_callback = [](void * data, size_t size, size_t nmemb, void * fd) -> size_t {
  1106. return fwrite(data, size, nmemb, (FILE *)fd);
  1107. };
  1108. curl_easy_setopt(curl.get(), CURLOPT_NOBODY, 0L);
  1109. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, static_cast<CURLOPT_WRITEFUNCTION_PTR>(write_callback));
  1110. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, outfile.get());
  1111. // display download progress
  1112. curl_easy_setopt(curl.get(), CURLOPT_NOPROGRESS, 0L);
  1113. // helper function to hide password in URL
  1114. auto llama_download_hide_password_in_url = [](const std::string & url) -> std::string {
  1115. std::size_t protocol_pos = url.find("://");
  1116. if (protocol_pos == std::string::npos) {
  1117. return url; // Malformed URL
  1118. }
  1119. std::size_t at_pos = url.find('@', protocol_pos + 3);
  1120. if (at_pos == std::string::npos) {
  1121. return url; // No password in URL
  1122. }
  1123. return url.substr(0, protocol_pos + 3) + "********" + url.substr(at_pos);
  1124. };
  1125. // start the download
  1126. LOG_INF("%s: trying to download model from %s to %s (server_etag:%s, server_last_modified:%s)...\n", __func__,
  1127. llama_download_hide_password_in_url(url).c_str(), path.c_str(), headers.etag.c_str(), headers.last_modified.c_str());
  1128. bool was_perform_successful = curl_perform_with_retry(url, curl.get(), CURL_MAX_RETRY, CURL_RETRY_DELAY_SECONDS);
  1129. if (!was_perform_successful) {
  1130. return false;
  1131. }
  1132. long http_code = 0;
  1133. curl_easy_getinfo (curl.get(), CURLINFO_RESPONSE_CODE, &http_code);
  1134. if (http_code < 200 || http_code >= 400) {
  1135. LOG_ERR("%s: invalid http status code received: %ld\n", __func__, http_code);
  1136. return false;
  1137. }
  1138. // Causes file to be closed explicitly here before we rename it.
  1139. outfile.reset();
  1140. // Write the updated JSON metadata file.
  1141. metadata.update({
  1142. {"url", url},
  1143. {"etag", headers.etag},
  1144. {"lastModified", headers.last_modified}
  1145. });
  1146. std::ofstream(metadata_path) << metadata.dump(4);
  1147. LOG_INF("%s: file metadata saved: %s\n", __func__, metadata_path.c_str());
  1148. if (rename(path_temporary.c_str(), path.c_str()) != 0) {
  1149. LOG_ERR("%s: unable to rename file: %s to %s\n", __func__, path_temporary.c_str(), path.c_str());
  1150. return false;
  1151. }
  1152. }
  1153. return true;
  1154. }
  1155. struct llama_model * common_load_model_from_url(
  1156. const std::string & model_url,
  1157. const std::string & local_path,
  1158. const std::string & hf_token,
  1159. const struct llama_model_params & params) {
  1160. // Basic validation of the model_url
  1161. if (model_url.empty()) {
  1162. LOG_ERR("%s: invalid model_url\n", __func__);
  1163. return NULL;
  1164. }
  1165. if (!common_download_file(model_url, local_path, hf_token)) {
  1166. return NULL;
  1167. }
  1168. // check for additional GGUFs split to download
  1169. int n_split = 0;
  1170. {
  1171. struct gguf_init_params gguf_params = {
  1172. /*.no_alloc = */ true,
  1173. /*.ctx = */ NULL,
  1174. };
  1175. auto * ctx_gguf = gguf_init_from_file(local_path.c_str(), gguf_params);
  1176. if (!ctx_gguf) {
  1177. LOG_ERR("\n%s: failed to load input GGUF from %s\n", __func__, local_path.c_str());
  1178. return NULL;
  1179. }
  1180. auto key_n_split = gguf_find_key(ctx_gguf, LLM_KV_SPLIT_COUNT);
  1181. if (key_n_split >= 0) {
  1182. n_split = gguf_get_val_u16(ctx_gguf, key_n_split);
  1183. }
  1184. gguf_free(ctx_gguf);
  1185. }
  1186. if (n_split > 1) {
  1187. char split_prefix[PATH_MAX] = {0};
  1188. char split_url_prefix[LLAMA_CURL_MAX_URL_LENGTH] = {0};
  1189. // Verify the first split file format
  1190. // and extract split URL and PATH prefixes
  1191. {
  1192. if (!llama_split_prefix(split_prefix, sizeof(split_prefix), local_path.c_str(), 0, n_split)) {
  1193. LOG_ERR("\n%s: unexpected model file name: %s n_split=%d\n", __func__, local_path.c_str(), n_split);
  1194. return NULL;
  1195. }
  1196. if (!llama_split_prefix(split_url_prefix, sizeof(split_url_prefix), model_url.c_str(), 0, n_split)) {
  1197. LOG_ERR("\n%s: unexpected model url: %s n_split=%d\n", __func__, model_url.c_str(), n_split);
  1198. return NULL;
  1199. }
  1200. }
  1201. // Prepare download in parallel
  1202. std::vector<std::future<bool>> futures_download;
  1203. for (int idx = 1; idx < n_split; idx++) {
  1204. futures_download.push_back(std::async(std::launch::async, [&split_prefix, &split_url_prefix, &n_split, hf_token](int download_idx) -> bool {
  1205. char split_path[PATH_MAX] = {0};
  1206. llama_split_path(split_path, sizeof(split_path), split_prefix, download_idx, n_split);
  1207. char split_url[LLAMA_CURL_MAX_URL_LENGTH] = {0};
  1208. llama_split_path(split_url, sizeof(split_url), split_url_prefix, download_idx, n_split);
  1209. return common_download_file(split_url, split_path, hf_token);
  1210. }, idx));
  1211. }
  1212. // Wait for all downloads to complete
  1213. for (auto & f : futures_download) {
  1214. if (!f.get()) {
  1215. return NULL;
  1216. }
  1217. }
  1218. }
  1219. return llama_load_model_from_file(local_path.c_str(), params);
  1220. }
  1221. struct llama_model * common_load_model_from_hf(
  1222. const std::string & repo,
  1223. const std::string & remote_path,
  1224. const std::string & local_path,
  1225. const std::string & hf_token,
  1226. const struct llama_model_params & params) {
  1227. // construct hugging face model url:
  1228. //
  1229. // --repo ggml-org/models --file tinyllama-1.1b/ggml-model-f16.gguf
  1230. // https://huggingface.co/ggml-org/models/resolve/main/tinyllama-1.1b/ggml-model-f16.gguf
  1231. //
  1232. // --repo TheBloke/Mixtral-8x7B-v0.1-GGUF --file mixtral-8x7b-v0.1.Q4_K_M.gguf
  1233. // https://huggingface.co/TheBloke/Mixtral-8x7B-v0.1-GGUF/resolve/main/mixtral-8x7b-v0.1.Q4_K_M.gguf
  1234. //
  1235. std::string model_url = "https://huggingface.co/";
  1236. model_url += repo;
  1237. model_url += "/resolve/main/";
  1238. model_url += remote_path;
  1239. return common_load_model_from_url(model_url, local_path, hf_token, params);
  1240. }
  1241. #else
  1242. struct llama_model * common_load_model_from_url(
  1243. const std::string & /*model_url*/,
  1244. const std::string & /*local_path*/,
  1245. const std::string & /*hf_token*/,
  1246. const struct llama_model_params & /*params*/) {
  1247. LOG_WRN("%s: llama.cpp built without libcurl, downloading from an url not supported.\n", __func__);
  1248. return nullptr;
  1249. }
  1250. struct llama_model * common_load_model_from_hf(
  1251. const std::string & /*repo*/,
  1252. const std::string & /*remote_path*/,
  1253. const std::string & /*local_path*/,
  1254. const std::string & /*hf_token*/,
  1255. const struct llama_model_params & /*params*/) {
  1256. LOG_WRN("%s: llama.cpp built without libcurl, downloading from Hugging Face not supported.\n", __func__);
  1257. return nullptr;
  1258. }
  1259. #endif // LLAMA_USE_CURL
  1260. //
  1261. // Batch utils
  1262. //
  1263. void common_batch_clear(struct llama_batch & batch) {
  1264. batch.n_tokens = 0;
  1265. }
  1266. void common_batch_add(
  1267. struct llama_batch & batch,
  1268. llama_token id,
  1269. llama_pos pos,
  1270. const std::vector<llama_seq_id> & seq_ids,
  1271. bool logits) {
  1272. GGML_ASSERT(batch.seq_id[batch.n_tokens] && "llama_batch size exceeded");
  1273. batch.token [batch.n_tokens] = id;
  1274. batch.pos [batch.n_tokens] = pos;
  1275. batch.n_seq_id[batch.n_tokens] = seq_ids.size();
  1276. for (size_t i = 0; i < seq_ids.size(); ++i) {
  1277. batch.seq_id[batch.n_tokens][i] = seq_ids[i];
  1278. }
  1279. batch.logits [batch.n_tokens] = logits;
  1280. batch.n_tokens++;
  1281. }
  1282. //
  1283. // Token utils
  1284. //
  1285. size_t common_lcp(const llama_tokens & a, const llama_tokens & b) {
  1286. size_t i;
  1287. for (i = 0; i < a.size() && i < b.size() && a[i] == b[i]; i++) {}
  1288. return i;
  1289. }
  1290. size_t common_lcs(const llama_tokens & a, const llama_tokens & b) {
  1291. // check for empty sequences
  1292. if (a.empty() || b.empty()) {
  1293. return 0;
  1294. }
  1295. // get the lengths of the input sequences
  1296. size_t a_len = a.size();
  1297. size_t b_len = b.size();
  1298. // initialize the maximum length of the longest common subsequence (LCS)
  1299. size_t max_length = 0;
  1300. // use two rows instead of a 2D matrix to optimize space
  1301. std::vector<size_t> prev_row(b_len + 1, 0);
  1302. std::vector<size_t> curr_row(b_len + 1, 0);
  1303. // iterate through the elements of a
  1304. for (size_t i = 1; i <= a_len; i++) {
  1305. // iterate through the elements of b
  1306. for (size_t j = 1; j <= b_len; j++) {
  1307. // if elements at the current positions match
  1308. if (a[i - 1] == b[j - 1]) {
  1309. // if it's the first element of either sequences, set LCS length to 1
  1310. if (i == 1 || j == 1) {
  1311. curr_row[j] = 1;
  1312. } else {
  1313. // increment LCS length by 1 compared to the previous element
  1314. curr_row[j] = prev_row[j - 1] + 1;
  1315. }
  1316. // update max_length if necessary
  1317. if (curr_row[j] > max_length) {
  1318. max_length = curr_row[j];
  1319. }
  1320. } else {
  1321. // reset LCS length if elements don't match
  1322. curr_row[j] = 0;
  1323. }
  1324. }
  1325. // update the previous row for the next iteration
  1326. prev_row = curr_row;
  1327. }
  1328. // return the maximum length of the LCS
  1329. return max_length;
  1330. }
  1331. //
  1332. // Vocab utils
  1333. //
  1334. std::vector<llama_token> common_tokenize(
  1335. const struct llama_context * ctx,
  1336. const std::string & text,
  1337. bool add_special,
  1338. bool parse_special) {
  1339. return common_tokenize(llama_get_model(ctx), text, add_special, parse_special);
  1340. }
  1341. std::vector<llama_token> common_tokenize(
  1342. const struct llama_model * model,
  1343. const std::string & text,
  1344. bool add_special,
  1345. bool parse_special) {
  1346. // upper limit for the number of tokens
  1347. int n_tokens = text.length() + 2 * add_special;
  1348. std::vector<llama_token> result(n_tokens);
  1349. n_tokens = llama_tokenize(model, text.data(), text.length(), result.data(), result.size(), add_special, parse_special);
  1350. if (n_tokens < 0) {
  1351. result.resize(-n_tokens);
  1352. int check = llama_tokenize(model, text.data(), text.length(), result.data(), result.size(), add_special, parse_special);
  1353. GGML_ASSERT(check == -n_tokens);
  1354. } else {
  1355. result.resize(n_tokens);
  1356. }
  1357. return result;
  1358. }
  1359. std::string common_token_to_piece(const struct llama_context * ctx, llama_token token, bool special) {
  1360. std::string piece;
  1361. piece.resize(piece.capacity()); // using string internal cache, 15 bytes + '\n'
  1362. const int n_chars = llama_token_to_piece(llama_get_model(ctx), token, &piece[0], piece.size(), 0, special);
  1363. if (n_chars < 0) {
  1364. piece.resize(-n_chars);
  1365. int check = llama_token_to_piece(llama_get_model(ctx), token, &piece[0], piece.size(), 0, special);
  1366. GGML_ASSERT(check == -n_chars);
  1367. }
  1368. else {
  1369. piece.resize(n_chars);
  1370. }
  1371. return piece;
  1372. }
  1373. std::string common_detokenize(llama_context * ctx, const std::vector<llama_token> & tokens, bool special) {
  1374. std::string text;
  1375. text.resize(std::max(text.capacity(), tokens.size()));
  1376. int32_t n_chars = llama_detokenize(llama_get_model(ctx), tokens.data(), (int32_t)tokens.size(), &text[0], (int32_t)text.size(), false, special);
  1377. if (n_chars < 0) {
  1378. text.resize(-n_chars);
  1379. n_chars = llama_detokenize(llama_get_model(ctx), tokens.data(), (int32_t)tokens.size(), &text[0], (int32_t)text.size(), false, special);
  1380. GGML_ASSERT(n_chars <= (int32_t)text.size()); // whitespace trimming is performed after per-token detokenization
  1381. }
  1382. text.resize(n_chars);
  1383. // NOTE: the original tokenizer decodes bytes after collecting the pieces.
  1384. return text;
  1385. }
  1386. //
  1387. // Chat template utils
  1388. //
  1389. bool common_chat_verify_template(const std::string & tmpl) {
  1390. llama_chat_message chat[] = {{"user", "test"}};
  1391. int res = llama_chat_apply_template(nullptr, tmpl.c_str(), chat, 1, true, nullptr, 0);
  1392. return res >= 0;
  1393. }
  1394. std::string common_chat_apply_template(const struct llama_model * model,
  1395. const std::string & tmpl,
  1396. const std::vector<common_chat_msg> & msgs,
  1397. bool add_ass) {
  1398. int alloc_size = 0;
  1399. bool fallback = false; // indicate if we must fallback to default chatml
  1400. std::vector<llama_chat_message> chat;
  1401. for (auto & msg : msgs) {
  1402. chat.push_back({msg.role.c_str(), msg.content.c_str()});
  1403. alloc_size += (msg.role.size() + msg.content.size()) * 1.25;
  1404. }
  1405. const char * ptr_tmpl = tmpl.empty() ? nullptr : tmpl.c_str();
  1406. std::vector<char> buf(alloc_size);
  1407. // run the first time to get the total output length
  1408. int32_t res = llama_chat_apply_template(model, ptr_tmpl, chat.data(), chat.size(), add_ass, buf.data(), buf.size());
  1409. // error: chat template is not supported
  1410. if (res < 0) {
  1411. if (ptr_tmpl != nullptr) {
  1412. // if the custom "tmpl" is not supported, we throw an error
  1413. // this is a bit redundant (for good), since we're not sure if user validated the custom template with llama_chat_verify_template()
  1414. throw std::runtime_error("this custom template is not supported");
  1415. } else {
  1416. // If the built-in template is not supported, we default to chatml
  1417. res = llama_chat_apply_template(nullptr, "chatml", chat.data(), chat.size(), add_ass, buf.data(), buf.size());
  1418. fallback = true;
  1419. }
  1420. }
  1421. // if it turns out that our buffer is too small, we resize it
  1422. if ((size_t) res > buf.size()) {
  1423. buf.resize(res);
  1424. res = llama_chat_apply_template(
  1425. fallback ? nullptr : model,
  1426. fallback ? "chatml" : ptr_tmpl,
  1427. chat.data(), chat.size(), add_ass, buf.data(), buf.size());
  1428. }
  1429. std::string formatted_chat(buf.data(), res);
  1430. return formatted_chat;
  1431. }
  1432. std::string common_chat_format_single(const struct llama_model * model,
  1433. const std::string & tmpl,
  1434. const std::vector<common_chat_msg> & past_msg,
  1435. const common_chat_msg & new_msg,
  1436. bool add_ass) {
  1437. std::ostringstream ss;
  1438. auto fmt_past_msg = past_msg.empty() ? "" : common_chat_apply_template(model, tmpl, past_msg, false);
  1439. std::vector<common_chat_msg> chat_new(past_msg);
  1440. // if the past_msg ends with a newline, we must preserve it in the formatted version
  1441. if (add_ass && !fmt_past_msg.empty() && fmt_past_msg.back() == '\n') {
  1442. ss << "\n";
  1443. };
  1444. // format chat with new_msg
  1445. chat_new.push_back(new_msg);
  1446. auto fmt_new_msg = common_chat_apply_template(model, tmpl, chat_new, add_ass);
  1447. // get the diff part
  1448. ss << fmt_new_msg.substr(fmt_past_msg.size(), fmt_new_msg.size() - fmt_past_msg.size());
  1449. return ss.str();
  1450. }
  1451. std::string common_chat_format_example(const struct llama_model * model,
  1452. const std::string & tmpl) {
  1453. std::vector<common_chat_msg> msgs = {
  1454. {"system", "You are a helpful assistant"},
  1455. {"user", "Hello"},
  1456. {"assistant", "Hi there"},
  1457. {"user", "How are you?"},
  1458. };
  1459. return common_chat_apply_template(model, tmpl, msgs, true);
  1460. }
  1461. //
  1462. // KV cache utils
  1463. //
  1464. void common_kv_cache_dump_view(const llama_kv_cache_view & view, int row_size) {
  1465. static const char slot_chars[] = ".123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+";
  1466. 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",
  1467. view.n_cells, view.n_seq_max, view.used_cells, view.token_count, view.max_contiguous, view.max_contiguous_idx);
  1468. llama_kv_cache_view_cell * c_curr = view.cells;
  1469. llama_seq_id * cs_curr = view.cells_sequences;
  1470. for (int i = 0; i < view.n_cells; i++, c_curr++, cs_curr += view.n_seq_max) {
  1471. if (i % row_size == 0) {
  1472. printf("\n%5d: ", i);
  1473. }
  1474. int seq_count = 0;
  1475. for (int j = 0; j < view.n_seq_max; j++) {
  1476. if (cs_curr[j] >= 0) { seq_count++; }
  1477. }
  1478. putchar(slot_chars[std::min(sizeof(slot_chars) - 2, size_t(seq_count))]);
  1479. }
  1480. printf("\n=== Done dumping\n");
  1481. }
  1482. void common_kv_cache_dump_view_seqs(const llama_kv_cache_view & view, int row_size) {
  1483. static const char slot_chars[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  1484. 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",
  1485. view.n_cells, view.n_seq_max, view.used_cells, view.token_count, view.max_contiguous, view.max_contiguous_idx);
  1486. std::unordered_map<llama_seq_id, size_t> seqs;
  1487. llama_kv_cache_view_cell * c_curr = view.cells;
  1488. llama_seq_id * cs_curr = view.cells_sequences;
  1489. for (int i = 0; i < view.n_cells; i++, c_curr++, cs_curr += view.n_seq_max) {
  1490. for (int j = 0; j < view.n_seq_max; j++) {
  1491. if (cs_curr[j] < 0) { continue; }
  1492. if (seqs.find(cs_curr[j]) == seqs.end()) {
  1493. if (seqs.size() + 1 >= sizeof(slot_chars)) { break; }
  1494. const size_t sz = seqs.size();
  1495. seqs[cs_curr[j]] = sz;
  1496. }
  1497. }
  1498. if (seqs.size() + 1 >= sizeof(slot_chars)) { break; }
  1499. }
  1500. printf("=== Sequence legend: ");
  1501. for (const auto & it : seqs) {
  1502. printf("%zu=%d, ", it.second, it.first);
  1503. }
  1504. printf("'+'=other sequence ids");
  1505. c_curr = view.cells;
  1506. cs_curr = view.cells_sequences;
  1507. for (int i = 0; i < view.n_cells; i++, c_curr++, cs_curr += view.n_seq_max) {
  1508. if (i % row_size == 0) {
  1509. printf("\n%5d: ", i);
  1510. }
  1511. for (int j = 0; j < view.n_seq_max; j++) {
  1512. if (cs_curr[j] >= 0) {
  1513. const auto & it = seqs.find(cs_curr[j]);
  1514. putchar(it != seqs.end() ? int(slot_chars[it->second]) : '+');
  1515. } else {
  1516. putchar('.');
  1517. }
  1518. }
  1519. putchar(' ');
  1520. }
  1521. printf("\n=== Done dumping\n");
  1522. }
  1523. //
  1524. // Embedding utils
  1525. //
  1526. void common_embd_normalize(const float * inp, float * out, int n, int embd_norm) {
  1527. double sum = 0.0;
  1528. switch (embd_norm) {
  1529. case -1: // no normalisation
  1530. sum = 1.0;
  1531. break;
  1532. case 0: // max absolute
  1533. for (int i = 0; i < n; i++) {
  1534. if (sum < std::abs(inp[i])) sum = std::abs(inp[i]);
  1535. }
  1536. sum /= 32760.0; // make an int16 range
  1537. break;
  1538. case 2: // euclidean
  1539. for (int i = 0; i < n; i++) {
  1540. sum += inp[i] * inp[i];
  1541. }
  1542. sum = std::sqrt(sum);
  1543. break;
  1544. default: // p-norm (euclidean is p-norm p=2)
  1545. for (int i = 0; i < n; i++) {
  1546. sum += std::pow(std::abs(inp[i]), embd_norm);
  1547. }
  1548. sum = std::pow(sum, 1.0 / embd_norm);
  1549. break;
  1550. }
  1551. const float norm = sum > 0.0 ? 1.0 / sum : 0.0f;
  1552. for (int i = 0; i < n; i++) {
  1553. out[i] = inp[i] * norm;
  1554. }
  1555. }
  1556. float common_embd_similarity_cos(const float * embd1, const float * embd2, int n){
  1557. double sum = 0.0;
  1558. double sum1 = 0.0;
  1559. double sum2 = 0.0;
  1560. for (int i = 0; i < n; i++) {
  1561. sum += embd1[i] * embd2[i];
  1562. sum1 += embd1[i] * embd1[i];
  1563. sum2 += embd2[i] * embd2[i];
  1564. }
  1565. // Handle the case where one or both vectors are zero vectors
  1566. if (sum1 == 0.0 || sum2 == 0.0) {
  1567. if (sum1 == 0.0 && sum2 == 0.0) {
  1568. return 1.0f; // two zero vectors are similar
  1569. }
  1570. return 0.0f;
  1571. }
  1572. return sum / (sqrt(sum1) * sqrt(sum2));
  1573. }
  1574. //
  1575. // Control vector utils
  1576. //
  1577. static common_control_vector_data common_control_vector_load_one(const common_control_vector_load_info & load_info) {
  1578. common_control_vector_data result = { -1, {} };
  1579. ggml_context * ctx = nullptr;
  1580. struct gguf_init_params meta_gguf_params = {
  1581. /* .no_alloc = */ false,
  1582. /* .ctx = */ &ctx,
  1583. };
  1584. struct gguf_context * ctx_gguf = gguf_init_from_file(load_info.fname.c_str(), meta_gguf_params);
  1585. if (!ctx_gguf) {
  1586. LOG_ERR("%s: failed to load control vector file from %s\n", __func__, load_info.fname.c_str());
  1587. return result;
  1588. }
  1589. int32_t n_tensors = gguf_get_n_tensors(ctx_gguf);
  1590. if (n_tensors == 0) {
  1591. LOG_WRN("%s: no direction tensors found in %s\n", __func__, load_info.fname.c_str());
  1592. }
  1593. for (int i = 0; i < n_tensors; i++) {
  1594. std::string name = gguf_get_tensor_name(ctx_gguf, i);
  1595. int layer_idx = -1;
  1596. // split on '.'
  1597. size_t dotpos = name.find('.');
  1598. if (dotpos != std::string::npos && name.substr(0, dotpos) == "direction") {
  1599. try {
  1600. layer_idx = std::stoi(name.substr(dotpos + 1));
  1601. } catch (...) {
  1602. layer_idx = -1;
  1603. }
  1604. }
  1605. if (layer_idx < 0) {
  1606. LOG_ERR("%s: invalid/unparsable direction tensor layer index in %s\n", __func__, load_info.fname.c_str());
  1607. result.n_embd = -1;
  1608. break;
  1609. } else if (layer_idx == 0) {
  1610. LOG_ERR("%s: invalid (zero) direction tensor layer index in %s\n", __func__, load_info.fname.c_str());
  1611. result.n_embd = -1;
  1612. break;
  1613. }
  1614. struct ggml_tensor * tensor = ggml_get_tensor(ctx, name.c_str());
  1615. if (tensor->type != GGML_TYPE_F32) {
  1616. LOG_ERR("%s: invalid (non-F32) direction tensor type in %s\n", __func__, load_info.fname.c_str());
  1617. result.n_embd = -1;
  1618. break;
  1619. }
  1620. if (ggml_n_dims(tensor) != 1) {
  1621. LOG_ERR("%s: invalid (non-1D) direction tensor shape in %s\n", __func__, load_info.fname.c_str());
  1622. result.n_embd = -1;
  1623. break;
  1624. }
  1625. if (result.n_embd == -1) {
  1626. result.n_embd = ggml_nelements(tensor);
  1627. } else if (ggml_nelements(tensor) != result.n_embd) {
  1628. LOG_ERR("%s: direction tensor in %s does not match previous dimensions\n", __func__, load_info.fname.c_str());
  1629. result.n_embd = -1;
  1630. break;
  1631. }
  1632. // extend if necessary - do not store data for layer 0 (it's not used)
  1633. result.data.resize(std::max(result.data.size(), static_cast<size_t>(result.n_embd * layer_idx)), 0.0f);
  1634. const float * src = (const float *) tensor->data;
  1635. float * dst = result.data.data() + result.n_embd * (layer_idx - 1); // layer 1 at [0]
  1636. for (int j = 0; j < result.n_embd; j++) {
  1637. dst[j] += src[j] * load_info.strength; // allows multiple directions for same layer in same file
  1638. }
  1639. }
  1640. if (result.n_embd == -1) {
  1641. LOG_WRN("%s: skipping %s due to invalid direction tensors\n", __func__, load_info.fname.c_str());
  1642. result.data.clear();
  1643. }
  1644. gguf_free(ctx_gguf);
  1645. ggml_free(ctx);
  1646. return result;
  1647. }
  1648. common_control_vector_data common_control_vector_load(const std::vector<common_control_vector_load_info> & load_infos) {
  1649. common_control_vector_data result = { -1, {} };
  1650. for (const auto & info : load_infos) {
  1651. auto cur = common_control_vector_load_one(info);
  1652. if (cur.n_embd == -1) {
  1653. result.n_embd = -1;
  1654. break;
  1655. }
  1656. if (result.n_embd != -1 && result.n_embd != cur.n_embd) {
  1657. LOG_ERR("%s: control vectors in %s does not match previous dimensions\n", __func__, info.fname.c_str());
  1658. result.n_embd = -1;
  1659. break;
  1660. }
  1661. if (result.n_embd == -1) {
  1662. result = std::move(cur);
  1663. } else {
  1664. result.data.resize(std::max(result.data.size(), cur.data.size()), 0.0f); // extend if necessary
  1665. for (size_t i = 0; i < cur.data.size(); i++) {
  1666. result.data[i] += cur.data[i];
  1667. }
  1668. }
  1669. }
  1670. if (result.n_embd == -1) {
  1671. LOG_ERR("%s: no valid control vector files passed\n", __func__);
  1672. result.data.clear();
  1673. }
  1674. return result;
  1675. }