common.cpp 74 KB

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