common.cpp 75 KB

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