common.cpp 66 KB

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