common.cpp 67 KB

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