common.cpp 75 KB

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