1
0

common.cpp 71 KB

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