common.cpp 74 KB

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