common.cpp 72 KB

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