common.cpp 68 KB

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