common.cpp 66 KB

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