common.cpp 68 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978
  1. /**
  2. * llama.cpp - commit 081b29bd2a3d91e7772e3910ce223dd63b8d7d26 - 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.sampling.ignore_eos) {
  832. for (llama_token i = 0; i < llama_n_vocab(model); i++) {
  833. if (llama_token_is_eog(model, i)) {
  834. LOG_INF("%s: added %s logit bias = %f\n", __func__, common_token_to_piece(lctx, i).c_str(), -INFINITY);
  835. params.sampling.logit_bias.push_back({i, -INFINITY});
  836. }
  837. }
  838. }
  839. if (params.sampling.penalty_last_n == -1) {
  840. LOG_INF("%s: setting penalty_last_n to ctx_size = %d\n", __func__, llama_n_ctx(lctx));
  841. params.sampling.penalty_last_n = llama_n_ctx(lctx);
  842. }
  843. if (params.sampling.dry_penalty_last_n == -1) {
  844. LOG_INF("%s: setting dry_penalty_last_n to ctx_size = %d\n", __func__, llama_n_ctx(lctx));
  845. params.sampling.dry_penalty_last_n = llama_n_ctx(lctx);
  846. }
  847. if (params.warmup) {
  848. LOG_WRN("%s: warming up the model with an empty run - please wait ... (--no-warmup to disable)\n", __func__);
  849. std::vector<llama_token> tmp;
  850. llama_token bos = llama_token_bos(model);
  851. llama_token eos = llama_token_eos(model);
  852. // some models (e.g. T5) don't have a BOS token
  853. if (bos != LLAMA_TOKEN_NULL) {
  854. tmp.push_back(bos);
  855. }
  856. if (eos != LLAMA_TOKEN_NULL) {
  857. tmp.push_back(eos);
  858. }
  859. if (tmp.empty()) {
  860. tmp.push_back(0);
  861. }
  862. if (llama_model_has_encoder(model)) {
  863. llama_encode(lctx, llama_batch_get_one(tmp.data(), tmp.size()));
  864. llama_token decoder_start_token_id = llama_model_decoder_start_token(model);
  865. if (decoder_start_token_id == -1) {
  866. decoder_start_token_id = bos;
  867. }
  868. tmp.clear();
  869. tmp.push_back(decoder_start_token_id);
  870. }
  871. if (llama_model_has_decoder(model)) {
  872. llama_decode(lctx, llama_batch_get_one(tmp.data(), std::min(tmp.size(), (size_t) params.n_batch)));
  873. }
  874. llama_kv_cache_clear(lctx);
  875. llama_synchronize(lctx);
  876. llama_perf_context_reset(lctx);
  877. }
  878. iparams.model = model;
  879. iparams.context = lctx;
  880. return iparams;
  881. }
  882. void common_lora_adapters_apply(struct llama_context * ctx, std::vector<common_lora_adapter_container> & lora_adapters) {
  883. llama_lora_adapter_clear(ctx);
  884. for (auto & la : lora_adapters) {
  885. if (la.scale != 0.0f) {
  886. llama_lora_adapter_set(ctx, la.adapter, la.scale);
  887. }
  888. }
  889. }
  890. struct llama_model_params common_model_params_to_llama(common_params & params) {
  891. auto mparams = llama_model_default_params();
  892. if (!params.devices.empty()) {
  893. mparams.devices = params.devices.data();
  894. }
  895. if (params.n_gpu_layers != -1) {
  896. mparams.n_gpu_layers = params.n_gpu_layers;
  897. }
  898. mparams.rpc_servers = params.rpc_servers.c_str();
  899. mparams.main_gpu = params.main_gpu;
  900. mparams.split_mode = params.split_mode;
  901. mparams.tensor_split = params.tensor_split;
  902. mparams.use_mmap = params.use_mmap;
  903. mparams.use_mlock = params.use_mlock;
  904. mparams.check_tensors = params.check_tensors;
  905. if (params.kv_overrides.empty()) {
  906. mparams.kv_overrides = NULL;
  907. } else {
  908. GGML_ASSERT(params.kv_overrides.back().key[0] == 0 && "KV overrides not terminated with empty key");
  909. mparams.kv_overrides = params.kv_overrides.data();
  910. }
  911. return mparams;
  912. }
  913. struct llama_context_params common_context_params_to_llama(const common_params & params) {
  914. auto cparams = llama_context_default_params();
  915. cparams.n_ctx = params.n_ctx;
  916. cparams.n_seq_max = params.n_parallel;
  917. cparams.n_batch = params.n_batch;
  918. cparams.n_ubatch = params.n_ubatch;
  919. cparams.n_threads = params.cpuparams.n_threads;
  920. cparams.n_threads_batch = params.cpuparams_batch.n_threads == -1 ?
  921. params.cpuparams.n_threads : params.cpuparams_batch.n_threads;
  922. cparams.logits_all = params.logits_all;
  923. cparams.embeddings = params.embedding;
  924. cparams.rope_scaling_type = params.rope_scaling_type;
  925. cparams.rope_freq_base = params.rope_freq_base;
  926. cparams.rope_freq_scale = params.rope_freq_scale;
  927. cparams.yarn_ext_factor = params.yarn_ext_factor;
  928. cparams.yarn_attn_factor = params.yarn_attn_factor;
  929. cparams.yarn_beta_fast = params.yarn_beta_fast;
  930. cparams.yarn_beta_slow = params.yarn_beta_slow;
  931. cparams.yarn_orig_ctx = params.yarn_orig_ctx;
  932. cparams.pooling_type = params.pooling_type;
  933. cparams.attention_type = params.attention_type;
  934. cparams.defrag_thold = params.defrag_thold;
  935. cparams.cb_eval = params.cb_eval;
  936. cparams.cb_eval_user_data = params.cb_eval_user_data;
  937. cparams.offload_kqv = !params.no_kv_offload;
  938. cparams.flash_attn = params.flash_attn;
  939. cparams.no_perf = params.no_perf;
  940. if (params.reranking) {
  941. cparams.embeddings = true;
  942. cparams.pooling_type = LLAMA_POOLING_TYPE_RANK;
  943. }
  944. cparams.type_k = params.cache_type_k;
  945. cparams.type_v = params.cache_type_v;
  946. return cparams;
  947. }
  948. struct ggml_threadpool_params ggml_threadpool_params_from_cpu_params(const cpu_params & params) {
  949. struct ggml_threadpool_params tpp;
  950. ggml_threadpool_params_init(&tpp, params.n_threads); // setup the defaults
  951. if (params.mask_valid) {
  952. std::memcpy(&tpp.cpumask, &params.cpumask, GGML_MAX_N_THREADS);
  953. }
  954. tpp.prio = params.priority;
  955. tpp.poll = params.poll;
  956. tpp.strict_cpu = params.strict_cpu;
  957. return tpp;
  958. }
  959. #ifdef LLAMA_USE_CURL
  960. #define CURL_MAX_RETRY 3
  961. #define CURL_RETRY_DELAY_SECONDS 2
  962. static bool curl_perform_with_retry(const std::string& url, CURL* curl, int max_attempts, int retry_delay_seconds) {
  963. int remaining_attempts = max_attempts;
  964. while (remaining_attempts > 0) {
  965. LOG_INF("%s: Trying to download from %s (attempt %d of %d)...\n", __func__ , url.c_str(), max_attempts - remaining_attempts + 1, max_attempts);
  966. CURLcode res = curl_easy_perform(curl);
  967. if (res == CURLE_OK) {
  968. return true;
  969. }
  970. int exponential_backoff_delay = std::pow(retry_delay_seconds, max_attempts - remaining_attempts) * 1000;
  971. LOG_WRN("%s: curl_easy_perform() failed: %s, retrying after %d milliseconds...\n", __func__, curl_easy_strerror(res), exponential_backoff_delay);
  972. remaining_attempts--;
  973. std::this_thread::sleep_for(std::chrono::milliseconds(exponential_backoff_delay));
  974. }
  975. LOG_ERR("%s: curl_easy_perform() failed after %d attempts\n", __func__, max_attempts);
  976. return false;
  977. }
  978. static bool common_download_file(const std::string & url, const std::string & path, const std::string & hf_token) {
  979. // Initialize libcurl
  980. std::unique_ptr<CURL, decltype(&curl_easy_cleanup)> curl(curl_easy_init(), &curl_easy_cleanup);
  981. if (!curl) {
  982. LOG_ERR("%s: error initializing libcurl\n", __func__);
  983. return false;
  984. }
  985. bool force_download = false;
  986. // Set the URL, allow to follow http redirection
  987. curl_easy_setopt(curl.get(), CURLOPT_URL, url.c_str());
  988. curl_easy_setopt(curl.get(), CURLOPT_FOLLOWLOCATION, 1L);
  989. // Check if hf-token or bearer-token was specified
  990. if (!hf_token.empty()) {
  991. std::string auth_header = "Authorization: Bearer ";
  992. auth_header += hf_token.c_str();
  993. struct curl_slist *http_headers = NULL;
  994. http_headers = curl_slist_append(http_headers, auth_header.c_str());
  995. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, http_headers);
  996. }
  997. #if defined(_WIN32)
  998. // CURLSSLOPT_NATIVE_CA tells libcurl to use standard certificate store of
  999. // operating system. Currently implemented under MS-Windows.
  1000. curl_easy_setopt(curl.get(), CURLOPT_SSL_OPTIONS, CURLSSLOPT_NATIVE_CA);
  1001. #endif
  1002. // Check if the file already exists locally
  1003. struct stat model_file_info;
  1004. auto file_exists = (stat(path.c_str(), &model_file_info) == 0);
  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. bool common_chat_verify_template(const std::string & tmpl) {
  1397. llama_chat_message chat[] = {{"user", "test"}};
  1398. int res = llama_chat_apply_template(nullptr, tmpl.c_str(), chat, 1, true, nullptr, 0);
  1399. return res >= 0;
  1400. }
  1401. std::string common_chat_apply_template(const struct llama_model * model,
  1402. const std::string & tmpl,
  1403. const std::vector<common_chat_msg> & msgs,
  1404. bool add_ass) {
  1405. int alloc_size = 0;
  1406. bool fallback = false; // indicate if we must fallback to default chatml
  1407. std::vector<llama_chat_message> chat;
  1408. for (auto & msg : msgs) {
  1409. chat.push_back({msg.role.c_str(), msg.content.c_str()});
  1410. alloc_size += (msg.role.size() + msg.content.size()) * 1.25;
  1411. }
  1412. const char * ptr_tmpl = tmpl.empty() ? nullptr : tmpl.c_str();
  1413. std::vector<char> buf(alloc_size);
  1414. // run the first time to get the total output length
  1415. int32_t res = llama_chat_apply_template(model, ptr_tmpl, chat.data(), chat.size(), add_ass, buf.data(), buf.size());
  1416. // error: chat template is not supported
  1417. if (res < 0) {
  1418. if (ptr_tmpl != nullptr) {
  1419. // if the custom "tmpl" is not supported, we throw an error
  1420. // this is a bit redundant (for good), since we're not sure if user validated the custom template with llama_chat_verify_template()
  1421. throw std::runtime_error("this custom template is not supported");
  1422. } else {
  1423. // If the built-in template is not supported, we default to chatml
  1424. res = llama_chat_apply_template(nullptr, "chatml", chat.data(), chat.size(), add_ass, buf.data(), buf.size());
  1425. fallback = true;
  1426. }
  1427. }
  1428. // if it turns out that our buffer is too small, we resize it
  1429. if ((size_t) res > buf.size()) {
  1430. buf.resize(res);
  1431. res = llama_chat_apply_template(
  1432. fallback ? nullptr : model,
  1433. fallback ? "chatml" : ptr_tmpl,
  1434. chat.data(), chat.size(), add_ass, buf.data(), buf.size());
  1435. }
  1436. std::string formatted_chat(buf.data(), res);
  1437. return formatted_chat;
  1438. }
  1439. std::string common_chat_format_single(const struct llama_model * model,
  1440. const std::string & tmpl,
  1441. const std::vector<common_chat_msg> & past_msg,
  1442. const common_chat_msg & new_msg,
  1443. bool add_ass) {
  1444. std::ostringstream ss;
  1445. auto fmt_past_msg = past_msg.empty() ? "" : common_chat_apply_template(model, tmpl, past_msg, false);
  1446. std::vector<common_chat_msg> chat_new(past_msg);
  1447. // if the past_msg ends with a newline, we must preserve it in the formatted version
  1448. if (add_ass && !fmt_past_msg.empty() && fmt_past_msg.back() == '\n') {
  1449. ss << "\n";
  1450. };
  1451. // format chat with new_msg
  1452. chat_new.push_back(new_msg);
  1453. auto fmt_new_msg = common_chat_apply_template(model, tmpl, chat_new, add_ass);
  1454. // get the diff part
  1455. ss << fmt_new_msg.substr(fmt_past_msg.size(), fmt_new_msg.size() - fmt_past_msg.size());
  1456. return ss.str();
  1457. }
  1458. std::string common_chat_format_example(const struct llama_model * model,
  1459. const std::string & tmpl) {
  1460. std::vector<common_chat_msg> msgs = {
  1461. {"system", "You are a helpful assistant"},
  1462. {"user", "Hello"},
  1463. {"assistant", "Hi there"},
  1464. {"user", "How are you?"},
  1465. };
  1466. return common_chat_apply_template(model, tmpl, msgs, true);
  1467. }
  1468. //
  1469. // KV cache utils
  1470. //
  1471. void common_kv_cache_dump_view(const llama_kv_cache_view & view, int row_size) {
  1472. static const char slot_chars[] = ".123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+";
  1473. 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",
  1474. view.n_cells, view.n_seq_max, view.used_cells, view.token_count, view.max_contiguous, view.max_contiguous_idx);
  1475. llama_kv_cache_view_cell * c_curr = view.cells;
  1476. llama_seq_id * cs_curr = view.cells_sequences;
  1477. for (int i = 0; i < view.n_cells; i++, c_curr++, cs_curr += view.n_seq_max) {
  1478. if (i % row_size == 0) {
  1479. printf("\n%5d: ", i);
  1480. }
  1481. int seq_count = 0;
  1482. for (int j = 0; j < view.n_seq_max; j++) {
  1483. if (cs_curr[j] >= 0) { seq_count++; }
  1484. }
  1485. putchar(slot_chars[std::min(sizeof(slot_chars) - 2, size_t(seq_count))]);
  1486. }
  1487. printf("\n=== Done dumping\n");
  1488. }
  1489. void common_kv_cache_dump_view_seqs(const llama_kv_cache_view & view, int row_size) {
  1490. static const char slot_chars[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  1491. 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",
  1492. view.n_cells, view.n_seq_max, view.used_cells, view.token_count, view.max_contiguous, view.max_contiguous_idx);
  1493. std::unordered_map<llama_seq_id, size_t> seqs;
  1494. llama_kv_cache_view_cell * c_curr = view.cells;
  1495. llama_seq_id * cs_curr = view.cells_sequences;
  1496. for (int i = 0; i < view.n_cells; i++, c_curr++, cs_curr += view.n_seq_max) {
  1497. for (int j = 0; j < view.n_seq_max; j++) {
  1498. if (cs_curr[j] < 0) { continue; }
  1499. if (seqs.find(cs_curr[j]) == seqs.end()) {
  1500. if (seqs.size() + 1 >= sizeof(slot_chars)) { break; }
  1501. const size_t sz = seqs.size();
  1502. seqs[cs_curr[j]] = sz;
  1503. }
  1504. }
  1505. if (seqs.size() + 1 >= sizeof(slot_chars)) { break; }
  1506. }
  1507. printf("=== Sequence legend: ");
  1508. for (const auto & it : seqs) {
  1509. printf("%zu=%d, ", it.second, it.first);
  1510. }
  1511. printf("'+'=other sequence ids");
  1512. c_curr = view.cells;
  1513. cs_curr = view.cells_sequences;
  1514. for (int i = 0; i < view.n_cells; i++, c_curr++, cs_curr += view.n_seq_max) {
  1515. if (i % row_size == 0) {
  1516. printf("\n%5d: ", i);
  1517. }
  1518. for (int j = 0; j < view.n_seq_max; j++) {
  1519. if (cs_curr[j] >= 0) {
  1520. const auto & it = seqs.find(cs_curr[j]);
  1521. putchar(it != seqs.end() ? int(slot_chars[it->second]) : '+');
  1522. } else {
  1523. putchar('.');
  1524. }
  1525. }
  1526. putchar(' ');
  1527. }
  1528. printf("\n=== Done dumping\n");
  1529. }
  1530. //
  1531. // Embedding utils
  1532. //
  1533. void common_embd_normalize(const float * inp, float * out, int n, int embd_norm) {
  1534. double sum = 0.0;
  1535. switch (embd_norm) {
  1536. case -1: // no normalisation
  1537. sum = 1.0;
  1538. break;
  1539. case 0: // max absolute
  1540. for (int i = 0; i < n; i++) {
  1541. if (sum < std::abs(inp[i])) sum = std::abs(inp[i]);
  1542. }
  1543. sum /= 32760.0; // make an int16 range
  1544. break;
  1545. case 2: // euclidean
  1546. for (int i = 0; i < n; i++) {
  1547. sum += inp[i] * inp[i];
  1548. }
  1549. sum = std::sqrt(sum);
  1550. break;
  1551. default: // p-norm (euclidean is p-norm p=2)
  1552. for (int i = 0; i < n; i++) {
  1553. sum += std::pow(std::abs(inp[i]), embd_norm);
  1554. }
  1555. sum = std::pow(sum, 1.0 / embd_norm);
  1556. break;
  1557. }
  1558. const float norm = sum > 0.0 ? 1.0 / sum : 0.0f;
  1559. for (int i = 0; i < n; i++) {
  1560. out[i] = inp[i] * norm;
  1561. }
  1562. }
  1563. float common_embd_similarity_cos(const float * embd1, const float * embd2, int n){
  1564. double sum = 0.0;
  1565. double sum1 = 0.0;
  1566. double sum2 = 0.0;
  1567. for (int i = 0; i < n; i++) {
  1568. sum += embd1[i] * embd2[i];
  1569. sum1 += embd1[i] * embd1[i];
  1570. sum2 += embd2[i] * embd2[i];
  1571. }
  1572. // Handle the case where one or both vectors are zero vectors
  1573. if (sum1 == 0.0 || sum2 == 0.0) {
  1574. if (sum1 == 0.0 && sum2 == 0.0) {
  1575. return 1.0f; // two zero vectors are similar
  1576. }
  1577. return 0.0f;
  1578. }
  1579. return sum / (sqrt(sum1) * sqrt(sum2));
  1580. }
  1581. //
  1582. // Control vector utils
  1583. //
  1584. static common_control_vector_data common_control_vector_load_one(const common_control_vector_load_info & load_info) {
  1585. common_control_vector_data result = { -1, {} };
  1586. ggml_context * ctx = nullptr;
  1587. struct gguf_init_params meta_gguf_params = {
  1588. /* .no_alloc = */ false,
  1589. /* .ctx = */ &ctx,
  1590. };
  1591. struct gguf_context * ctx_gguf = gguf_init_from_file(load_info.fname.c_str(), meta_gguf_params);
  1592. if (!ctx_gguf) {
  1593. LOG_ERR("%s: failed to load control vector file from %s\n", __func__, load_info.fname.c_str());
  1594. return result;
  1595. }
  1596. int32_t n_tensors = gguf_get_n_tensors(ctx_gguf);
  1597. if (n_tensors == 0) {
  1598. LOG_WRN("%s: no direction tensors found in %s\n", __func__, load_info.fname.c_str());
  1599. }
  1600. for (int i = 0; i < n_tensors; i++) {
  1601. std::string name = gguf_get_tensor_name(ctx_gguf, i);
  1602. int layer_idx = -1;
  1603. // split on '.'
  1604. size_t dotpos = name.find('.');
  1605. if (dotpos != std::string::npos && name.substr(0, dotpos) == "direction") {
  1606. try {
  1607. layer_idx = std::stoi(name.substr(dotpos + 1));
  1608. } catch (...) {
  1609. layer_idx = -1;
  1610. }
  1611. }
  1612. if (layer_idx < 0) {
  1613. LOG_ERR("%s: invalid/unparsable direction tensor layer index in %s\n", __func__, load_info.fname.c_str());
  1614. result.n_embd = -1;
  1615. break;
  1616. } else if (layer_idx == 0) {
  1617. LOG_ERR("%s: invalid (zero) direction tensor layer index in %s\n", __func__, load_info.fname.c_str());
  1618. result.n_embd = -1;
  1619. break;
  1620. }
  1621. struct ggml_tensor * tensor = ggml_get_tensor(ctx, name.c_str());
  1622. if (tensor->type != GGML_TYPE_F32) {
  1623. LOG_ERR("%s: invalid (non-F32) direction tensor type in %s\n", __func__, load_info.fname.c_str());
  1624. result.n_embd = -1;
  1625. break;
  1626. }
  1627. if (ggml_n_dims(tensor) != 1) {
  1628. LOG_ERR("%s: invalid (non-1D) direction tensor shape in %s\n", __func__, load_info.fname.c_str());
  1629. result.n_embd = -1;
  1630. break;
  1631. }
  1632. if (result.n_embd == -1) {
  1633. result.n_embd = ggml_nelements(tensor);
  1634. } else if (ggml_nelements(tensor) != result.n_embd) {
  1635. LOG_ERR("%s: direction tensor in %s does not match previous dimensions\n", __func__, load_info.fname.c_str());
  1636. result.n_embd = -1;
  1637. break;
  1638. }
  1639. // extend if necessary - do not store data for layer 0 (it's not used)
  1640. result.data.resize(std::max(result.data.size(), static_cast<size_t>(result.n_embd * layer_idx)), 0.0f);
  1641. const float * src = (const float *) tensor->data;
  1642. float * dst = result.data.data() + result.n_embd * (layer_idx - 1); // layer 1 at [0]
  1643. for (int j = 0; j < result.n_embd; j++) {
  1644. dst[j] += src[j] * load_info.strength; // allows multiple directions for same layer in same file
  1645. }
  1646. }
  1647. if (result.n_embd == -1) {
  1648. LOG_WRN("%s: skipping %s due to invalid direction tensors\n", __func__, load_info.fname.c_str());
  1649. result.data.clear();
  1650. }
  1651. gguf_free(ctx_gguf);
  1652. ggml_free(ctx);
  1653. return result;
  1654. }
  1655. common_control_vector_data common_control_vector_load(const std::vector<common_control_vector_load_info> & load_infos) {
  1656. common_control_vector_data result = { -1, {} };
  1657. for (const auto & info : load_infos) {
  1658. auto cur = common_control_vector_load_one(info);
  1659. if (cur.n_embd == -1) {
  1660. result.n_embd = -1;
  1661. break;
  1662. }
  1663. if (result.n_embd != -1 && result.n_embd != cur.n_embd) {
  1664. LOG_ERR("%s: control vectors in %s does not match previous dimensions\n", __func__, info.fname.c_str());
  1665. result.n_embd = -1;
  1666. break;
  1667. }
  1668. if (result.n_embd == -1) {
  1669. result = std::move(cur);
  1670. } else {
  1671. result.data.resize(std::max(result.data.size(), cur.data.size()), 0.0f); // extend if necessary
  1672. for (size_t i = 0; i < cur.data.size(); i++) {
  1673. result.data[i] += cur.data[i];
  1674. }
  1675. }
  1676. }
  1677. if (result.n_embd == -1) {
  1678. LOG_ERR("%s: no valid control vector files passed\n", __func__);
  1679. result.data.clear();
  1680. }
  1681. return result;
  1682. }