1
0

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. }
  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, params.hf_file, params.model, params.hf_token, mparams);
  716. } else if (!params.model_url.empty()) {
  717. model = common_load_model_from_url(params.model_url, params.model, params.hf_token, 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(common_params & params) {
  842. auto mparams = llama_model_default_params();
  843. if (!params.devices.empty()) {
  844. mparams.devices = params.devices.data();
  845. }
  846. if (params.n_gpu_layers != -1) {
  847. mparams.n_gpu_layers = params.n_gpu_layers;
  848. }
  849. mparams.rpc_servers = params.rpc_servers.c_str();
  850. mparams.main_gpu = params.main_gpu;
  851. mparams.split_mode = params.split_mode;
  852. mparams.tensor_split = params.tensor_split;
  853. mparams.use_mmap = params.use_mmap;
  854. mparams.use_mlock = params.use_mlock;
  855. mparams.check_tensors = params.check_tensors;
  856. if (params.kv_overrides.empty()) {
  857. mparams.kv_overrides = NULL;
  858. } else {
  859. GGML_ASSERT(params.kv_overrides.back().key[0] == 0 && "KV overrides not terminated with empty key");
  860. mparams.kv_overrides = params.kv_overrides.data();
  861. }
  862. return mparams;
  863. }
  864. static ggml_type kv_cache_type_from_str(const std::string & s) {
  865. if (s == "f32") {
  866. return GGML_TYPE_F32;
  867. }
  868. if (s == "f16") {
  869. return GGML_TYPE_F16;
  870. }
  871. if (s == "bf16") {
  872. return GGML_TYPE_BF16;
  873. }
  874. if (s == "q8_0") {
  875. return GGML_TYPE_Q8_0;
  876. }
  877. if (s == "q4_0") {
  878. return GGML_TYPE_Q4_0;
  879. }
  880. if (s == "q4_1") {
  881. return GGML_TYPE_Q4_1;
  882. }
  883. if (s == "iq4_nl") {
  884. return GGML_TYPE_IQ4_NL;
  885. }
  886. if (s == "q5_0") {
  887. return GGML_TYPE_Q5_0;
  888. }
  889. if (s == "q5_1") {
  890. return GGML_TYPE_Q5_1;
  891. }
  892. throw std::runtime_error("Unsupported cache type: " + s);
  893. }
  894. struct llama_context_params common_context_params_to_llama(const common_params & params) {
  895. auto cparams = llama_context_default_params();
  896. cparams.n_ctx = params.n_ctx;
  897. cparams.n_seq_max = params.n_parallel;
  898. cparams.n_batch = params.n_batch;
  899. cparams.n_ubatch = params.n_ubatch;
  900. cparams.n_threads = params.cpuparams.n_threads;
  901. cparams.n_threads_batch = params.cpuparams_batch.n_threads == -1 ?
  902. params.cpuparams.n_threads : params.cpuparams_batch.n_threads;
  903. cparams.logits_all = params.logits_all;
  904. cparams.embeddings = params.embedding;
  905. cparams.rope_scaling_type = params.rope_scaling_type;
  906. cparams.rope_freq_base = params.rope_freq_base;
  907. cparams.rope_freq_scale = params.rope_freq_scale;
  908. cparams.yarn_ext_factor = params.yarn_ext_factor;
  909. cparams.yarn_attn_factor = params.yarn_attn_factor;
  910. cparams.yarn_beta_fast = params.yarn_beta_fast;
  911. cparams.yarn_beta_slow = params.yarn_beta_slow;
  912. cparams.yarn_orig_ctx = params.yarn_orig_ctx;
  913. cparams.pooling_type = params.pooling_type;
  914. cparams.attention_type = params.attention_type;
  915. cparams.defrag_thold = params.defrag_thold;
  916. cparams.cb_eval = params.cb_eval;
  917. cparams.cb_eval_user_data = params.cb_eval_user_data;
  918. cparams.offload_kqv = !params.no_kv_offload;
  919. cparams.flash_attn = params.flash_attn;
  920. cparams.no_perf = params.no_perf;
  921. if (params.reranking) {
  922. cparams.embeddings = true;
  923. cparams.pooling_type = LLAMA_POOLING_TYPE_RANK;
  924. }
  925. cparams.type_k = kv_cache_type_from_str(params.cache_type_k);
  926. cparams.type_v = kv_cache_type_from_str(params.cache_type_v);
  927. return cparams;
  928. }
  929. struct ggml_threadpool_params ggml_threadpool_params_from_cpu_params(const cpu_params & params) {
  930. struct ggml_threadpool_params tpp;
  931. ggml_threadpool_params_init(&tpp, params.n_threads); // setup the defaults
  932. if (params.mask_valid) {
  933. std::memcpy(&tpp.cpumask, &params.cpumask, GGML_MAX_N_THREADS);
  934. }
  935. tpp.prio = params.priority;
  936. tpp.poll = params.poll;
  937. tpp.strict_cpu = params.strict_cpu;
  938. return tpp;
  939. }
  940. #ifdef LLAMA_USE_CURL
  941. #define CURL_MAX_RETRY 3
  942. #define CURL_RETRY_DELAY_SECONDS 2
  943. static bool starts_with(const std::string & str, const std::string & prefix) {
  944. // While we wait for C++20's std::string::starts_with...
  945. return str.rfind(prefix, 0) == 0;
  946. }
  947. static bool curl_perform_with_retry(const std::string& url, CURL* curl, int max_attempts, int retry_delay_seconds) {
  948. int remaining_attempts = max_attempts;
  949. while (remaining_attempts > 0) {
  950. LOG_INF("%s: Trying to download from %s (attempt %d of %d)...\n", __func__ , url.c_str(), max_attempts - remaining_attempts + 1, max_attempts);
  951. CURLcode res = curl_easy_perform(curl);
  952. if (res == CURLE_OK) {
  953. return true;
  954. }
  955. int exponential_backoff_delay = std::pow(retry_delay_seconds, max_attempts - remaining_attempts) * 1000;
  956. LOG_WRN("%s: curl_easy_perform() failed: %s, retrying after %d milliseconds...\n", __func__, curl_easy_strerror(res), exponential_backoff_delay);
  957. remaining_attempts--;
  958. std::this_thread::sleep_for(std::chrono::milliseconds(exponential_backoff_delay));
  959. }
  960. LOG_ERR("%s: curl_easy_perform() failed after %d attempts\n", __func__, max_attempts);
  961. return false;
  962. }
  963. static bool common_download_file(const std::string & url, const std::string & path, const std::string & hf_token) {
  964. // Initialize libcurl
  965. std::unique_ptr<CURL, decltype(&curl_easy_cleanup)> curl(curl_easy_init(), &curl_easy_cleanup);
  966. if (!curl) {
  967. LOG_ERR("%s: error initializing libcurl\n", __func__);
  968. return false;
  969. }
  970. bool force_download = false;
  971. // Set the URL, allow to follow http redirection
  972. curl_easy_setopt(curl.get(), CURLOPT_URL, url.c_str());
  973. curl_easy_setopt(curl.get(), CURLOPT_FOLLOWLOCATION, 1L);
  974. // Check if hf-token or bearer-token was specified
  975. if (!hf_token.empty()) {
  976. std::string auth_header = "Authorization: Bearer ";
  977. auth_header += hf_token.c_str();
  978. struct curl_slist *http_headers = NULL;
  979. http_headers = curl_slist_append(http_headers, auth_header.c_str());
  980. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, http_headers);
  981. }
  982. #if defined(_WIN32)
  983. // CURLSSLOPT_NATIVE_CA tells libcurl to use standard certificate store of
  984. // operating system. Currently implemented under MS-Windows.
  985. curl_easy_setopt(curl.get(), CURLOPT_SSL_OPTIONS, CURLSSLOPT_NATIVE_CA);
  986. #endif
  987. // Check if the file already exists locally
  988. struct stat model_file_info;
  989. auto file_exists = (stat(path.c_str(), &model_file_info) == 0);
  990. // If the file exists, check its JSON metadata companion file.
  991. std::string metadata_path = path + ".json";
  992. nlohmann::json metadata;
  993. std::string etag;
  994. std::string last_modified;
  995. if (file_exists) {
  996. // Try and read the JSON metadata file (note: stream autoclosed upon exiting this block).
  997. std::ifstream metadata_in(metadata_path);
  998. if (metadata_in.good()) {
  999. try {
  1000. metadata_in >> metadata;
  1001. LOG_INF("%s: previous metadata file found %s: %s\n", __func__, metadata_path.c_str(), metadata.dump().c_str());
  1002. if (metadata.contains("url") && metadata.at("url").is_string()) {
  1003. auto previous_url = metadata.at("url").get<std::string>();
  1004. if (previous_url != url) {
  1005. LOG_ERR("%s: Model URL mismatch: %s != %s\n", __func__, url.c_str(), previous_url.c_str());
  1006. return false;
  1007. }
  1008. }
  1009. if (metadata.contains("etag") && metadata.at("etag").is_string()) {
  1010. etag = metadata.at("etag");
  1011. }
  1012. if (metadata.contains("lastModified") && metadata.at("lastModified").is_string()) {
  1013. last_modified = metadata.at("lastModified");
  1014. }
  1015. } catch (const nlohmann::json::exception & e) {
  1016. LOG_ERR("%s: error reading metadata file %s: %s\n", __func__, metadata_path.c_str(), e.what());
  1017. return false;
  1018. }
  1019. }
  1020. } else {
  1021. LOG_INF("%s: no previous model file found %s\n", __func__, path.c_str());
  1022. }
  1023. // Send a HEAD request to retrieve the etag and last-modified headers
  1024. struct common_load_model_from_url_headers {
  1025. std::string etag;
  1026. std::string last_modified;
  1027. };
  1028. common_load_model_from_url_headers headers;
  1029. {
  1030. typedef size_t(*CURLOPT_HEADERFUNCTION_PTR)(char *, size_t, size_t, void *);
  1031. auto header_callback = [](char * buffer, size_t /*size*/, size_t n_items, void * userdata) -> size_t {
  1032. common_load_model_from_url_headers *headers = (common_load_model_from_url_headers *) userdata;
  1033. static std::regex header_regex("([^:]+): (.*)\r\n");
  1034. static std::regex etag_regex("ETag", std::regex_constants::icase);
  1035. static std::regex last_modified_regex("Last-Modified", std::regex_constants::icase);
  1036. std::string header(buffer, n_items);
  1037. std::smatch match;
  1038. if (std::regex_match(header, match, header_regex)) {
  1039. const std::string & key = match[1];
  1040. const std::string & value = match[2];
  1041. if (std::regex_match(key, match, etag_regex)) {
  1042. headers->etag = value;
  1043. } else if (std::regex_match(key, match, last_modified_regex)) {
  1044. headers->last_modified = value;
  1045. }
  1046. }
  1047. return n_items;
  1048. };
  1049. curl_easy_setopt(curl.get(), CURLOPT_NOBODY, 1L); // will trigger the HEAD verb
  1050. curl_easy_setopt(curl.get(), CURLOPT_NOPROGRESS, 1L); // hide head request progress
  1051. curl_easy_setopt(curl.get(), CURLOPT_HEADERFUNCTION, static_cast<CURLOPT_HEADERFUNCTION_PTR>(header_callback));
  1052. curl_easy_setopt(curl.get(), CURLOPT_HEADERDATA, &headers);
  1053. bool was_perform_successful = curl_perform_with_retry(url, curl.get(), CURL_MAX_RETRY, CURL_RETRY_DELAY_SECONDS);
  1054. if (!was_perform_successful) {
  1055. return false;
  1056. }
  1057. long http_code = 0;
  1058. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &http_code);
  1059. if (http_code != 200) {
  1060. // HEAD not supported, we don't know if the file has changed
  1061. // force trigger downloading
  1062. force_download = true;
  1063. LOG_ERR("%s: HEAD invalid http status code received: %ld\n", __func__, http_code);
  1064. }
  1065. }
  1066. bool should_download = !file_exists || force_download;
  1067. if (!should_download) {
  1068. if (!etag.empty() && etag != headers.etag) {
  1069. LOG_WRN("%s: ETag header is different (%s != %s): triggering a new download\n", __func__, etag.c_str(), headers.etag.c_str());
  1070. should_download = true;
  1071. } else if (!last_modified.empty() && last_modified != headers.last_modified) {
  1072. 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());
  1073. should_download = true;
  1074. }
  1075. }
  1076. if (should_download) {
  1077. std::string path_temporary = path + ".downloadInProgress";
  1078. if (file_exists) {
  1079. LOG_WRN("%s: deleting previous downloaded file: %s\n", __func__, path.c_str());
  1080. if (remove(path.c_str()) != 0) {
  1081. LOG_ERR("%s: unable to delete file: %s\n", __func__, path.c_str());
  1082. return false;
  1083. }
  1084. }
  1085. // Set the output file
  1086. struct FILE_deleter {
  1087. void operator()(FILE * f) const {
  1088. fclose(f);
  1089. }
  1090. };
  1091. std::unique_ptr<FILE, FILE_deleter> outfile(fopen(path_temporary.c_str(), "wb"));
  1092. if (!outfile) {
  1093. LOG_ERR("%s: error opening local file for writing: %s\n", __func__, path.c_str());
  1094. return false;
  1095. }
  1096. typedef size_t(*CURLOPT_WRITEFUNCTION_PTR)(void * data, size_t size, size_t nmemb, void * fd);
  1097. auto write_callback = [](void * data, size_t size, size_t nmemb, void * fd) -> size_t {
  1098. return fwrite(data, size, nmemb, (FILE *)fd);
  1099. };
  1100. curl_easy_setopt(curl.get(), CURLOPT_NOBODY, 0L);
  1101. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, static_cast<CURLOPT_WRITEFUNCTION_PTR>(write_callback));
  1102. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, outfile.get());
  1103. // display download progress
  1104. curl_easy_setopt(curl.get(), CURLOPT_NOPROGRESS, 0L);
  1105. // helper function to hide password in URL
  1106. auto llama_download_hide_password_in_url = [](const std::string & url) -> std::string {
  1107. std::size_t protocol_pos = url.find("://");
  1108. if (protocol_pos == std::string::npos) {
  1109. return url; // Malformed URL
  1110. }
  1111. std::size_t at_pos = url.find('@', protocol_pos + 3);
  1112. if (at_pos == std::string::npos) {
  1113. return url; // No password in URL
  1114. }
  1115. return url.substr(0, protocol_pos + 3) + "********" + url.substr(at_pos);
  1116. };
  1117. // start the download
  1118. LOG_INF("%s: trying to download model from %s to %s (server_etag:%s, server_last_modified:%s)...\n", __func__,
  1119. llama_download_hide_password_in_url(url).c_str(), path.c_str(), headers.etag.c_str(), headers.last_modified.c_str());
  1120. bool was_perform_successful = curl_perform_with_retry(url, curl.get(), CURL_MAX_RETRY, CURL_RETRY_DELAY_SECONDS);
  1121. if (!was_perform_successful) {
  1122. return false;
  1123. }
  1124. long http_code = 0;
  1125. curl_easy_getinfo (curl.get(), CURLINFO_RESPONSE_CODE, &http_code);
  1126. if (http_code < 200 || http_code >= 400) {
  1127. LOG_ERR("%s: invalid http status code received: %ld\n", __func__, http_code);
  1128. return false;
  1129. }
  1130. // Causes file to be closed explicitly here before we rename it.
  1131. outfile.reset();
  1132. // Write the updated JSON metadata file.
  1133. metadata.update({
  1134. {"url", url},
  1135. {"etag", headers.etag},
  1136. {"lastModified", headers.last_modified}
  1137. });
  1138. std::ofstream(metadata_path) << metadata.dump(4);
  1139. LOG_INF("%s: file metadata saved: %s\n", __func__, metadata_path.c_str());
  1140. if (rename(path_temporary.c_str(), path.c_str()) != 0) {
  1141. LOG_ERR("%s: unable to rename file: %s to %s\n", __func__, path_temporary.c_str(), path.c_str());
  1142. return false;
  1143. }
  1144. }
  1145. return true;
  1146. }
  1147. struct llama_model * common_load_model_from_url(
  1148. const std::string & model_url,
  1149. const std::string & local_path,
  1150. const std::string & hf_token,
  1151. const struct llama_model_params & params) {
  1152. // Basic validation of the model_url
  1153. if (model_url.empty()) {
  1154. LOG_ERR("%s: invalid model_url\n", __func__);
  1155. return NULL;
  1156. }
  1157. if (!common_download_file(model_url, local_path, hf_token)) {
  1158. return NULL;
  1159. }
  1160. // check for additional GGUFs split to download
  1161. int n_split = 0;
  1162. {
  1163. struct gguf_init_params gguf_params = {
  1164. /*.no_alloc = */ true,
  1165. /*.ctx = */ NULL,
  1166. };
  1167. auto * ctx_gguf = gguf_init_from_file(local_path.c_str(), gguf_params);
  1168. if (!ctx_gguf) {
  1169. LOG_ERR("\n%s: failed to load input GGUF from %s\n", __func__, local_path.c_str());
  1170. return NULL;
  1171. }
  1172. auto key_n_split = gguf_find_key(ctx_gguf, LLM_KV_SPLIT_COUNT);
  1173. if (key_n_split >= 0) {
  1174. n_split = gguf_get_val_u16(ctx_gguf, key_n_split);
  1175. }
  1176. gguf_free(ctx_gguf);
  1177. }
  1178. if (n_split > 1) {
  1179. char split_prefix[PATH_MAX] = {0};
  1180. char split_url_prefix[LLAMA_CURL_MAX_URL_LENGTH] = {0};
  1181. // Verify the first split file format
  1182. // and extract split URL and PATH prefixes
  1183. {
  1184. if (!llama_split_prefix(split_prefix, sizeof(split_prefix), local_path.c_str(), 0, n_split)) {
  1185. LOG_ERR("\n%s: unexpected model file name: %s n_split=%d\n", __func__, local_path.c_str(), n_split);
  1186. return NULL;
  1187. }
  1188. if (!llama_split_prefix(split_url_prefix, sizeof(split_url_prefix), model_url.c_str(), 0, n_split)) {
  1189. LOG_ERR("\n%s: unexpected model url: %s n_split=%d\n", __func__, model_url.c_str(), n_split);
  1190. return NULL;
  1191. }
  1192. }
  1193. // Prepare download in parallel
  1194. std::vector<std::future<bool>> futures_download;
  1195. for (int idx = 1; idx < n_split; idx++) {
  1196. futures_download.push_back(std::async(std::launch::async, [&split_prefix, &split_url_prefix, &n_split, hf_token](int download_idx) -> bool {
  1197. char split_path[PATH_MAX] = {0};
  1198. llama_split_path(split_path, sizeof(split_path), split_prefix, download_idx, n_split);
  1199. char split_url[LLAMA_CURL_MAX_URL_LENGTH] = {0};
  1200. llama_split_path(split_url, sizeof(split_url), split_url_prefix, download_idx, n_split);
  1201. return common_download_file(split_url, split_path, hf_token);
  1202. }, idx));
  1203. }
  1204. // Wait for all downloads to complete
  1205. for (auto & f : futures_download) {
  1206. if (!f.get()) {
  1207. return NULL;
  1208. }
  1209. }
  1210. }
  1211. return llama_load_model_from_file(local_path.c_str(), params);
  1212. }
  1213. struct llama_model * common_load_model_from_hf(
  1214. const std::string & repo,
  1215. const std::string & remote_path,
  1216. const std::string & local_path,
  1217. const std::string & hf_token,
  1218. const struct llama_model_params & params) {
  1219. // construct hugging face model url:
  1220. //
  1221. // --repo ggml-org/models --file tinyllama-1.1b/ggml-model-f16.gguf
  1222. // https://huggingface.co/ggml-org/models/resolve/main/tinyllama-1.1b/ggml-model-f16.gguf
  1223. //
  1224. // --repo TheBloke/Mixtral-8x7B-v0.1-GGUF --file mixtral-8x7b-v0.1.Q4_K_M.gguf
  1225. // https://huggingface.co/TheBloke/Mixtral-8x7B-v0.1-GGUF/resolve/main/mixtral-8x7b-v0.1.Q4_K_M.gguf
  1226. //
  1227. std::string model_url = "https://huggingface.co/";
  1228. model_url += repo;
  1229. model_url += "/resolve/main/";
  1230. model_url += remote_path;
  1231. return common_load_model_from_url(model_url, local_path, hf_token, params);
  1232. }
  1233. #else
  1234. struct llama_model * common_load_model_from_url(
  1235. const std::string & /*model_url*/,
  1236. const std::string & /*local_path*/,
  1237. const std::string & /*hf_token*/,
  1238. const struct llama_model_params & /*params*/) {
  1239. LOG_WRN("%s: llama.cpp built without libcurl, downloading from an url not supported.\n", __func__);
  1240. return nullptr;
  1241. }
  1242. struct llama_model * common_load_model_from_hf(
  1243. const std::string & /*repo*/,
  1244. const std::string & /*remote_path*/,
  1245. const std::string & /*local_path*/,
  1246. const std::string & /*hf_token*/,
  1247. const struct llama_model_params & /*params*/) {
  1248. LOG_WRN("%s: llama.cpp built without libcurl, downloading from Hugging Face not supported.\n", __func__);
  1249. return nullptr;
  1250. }
  1251. #endif // LLAMA_USE_CURL
  1252. //
  1253. // Batch utils
  1254. //
  1255. void common_batch_clear(struct llama_batch & batch) {
  1256. batch.n_tokens = 0;
  1257. }
  1258. void common_batch_add(
  1259. struct llama_batch & batch,
  1260. llama_token id,
  1261. llama_pos pos,
  1262. const std::vector<llama_seq_id> & seq_ids,
  1263. bool logits) {
  1264. GGML_ASSERT(batch.seq_id[batch.n_tokens] && "llama_batch size exceeded");
  1265. batch.token [batch.n_tokens] = id;
  1266. batch.pos [batch.n_tokens] = pos;
  1267. batch.n_seq_id[batch.n_tokens] = seq_ids.size();
  1268. for (size_t i = 0; i < seq_ids.size(); ++i) {
  1269. batch.seq_id[batch.n_tokens][i] = seq_ids[i];
  1270. }
  1271. batch.logits [batch.n_tokens] = logits;
  1272. batch.n_tokens++;
  1273. }
  1274. //
  1275. // Token utils
  1276. //
  1277. size_t common_lcp(const llama_tokens & a, const llama_tokens & b) {
  1278. size_t i;
  1279. for (i = 0; i < a.size() && i < b.size() && a[i] == b[i]; i++) {}
  1280. return i;
  1281. }
  1282. size_t common_lcs(const llama_tokens & a, const llama_tokens & b) {
  1283. // check for empty sequences
  1284. if (a.empty() || b.empty()) {
  1285. return 0;
  1286. }
  1287. // get the lengths of the input sequences
  1288. size_t a_len = a.size();
  1289. size_t b_len = b.size();
  1290. // initialize the maximum length of the longest common subsequence (LCS)
  1291. size_t max_length = 0;
  1292. // use two rows instead of a 2D matrix to optimize space
  1293. std::vector<size_t> prev_row(b_len + 1, 0);
  1294. std::vector<size_t> curr_row(b_len + 1, 0);
  1295. // iterate through the elements of a
  1296. for (size_t i = 1; i <= a_len; i++) {
  1297. // iterate through the elements of b
  1298. for (size_t j = 1; j <= b_len; j++) {
  1299. // if elements at the current positions match
  1300. if (a[i - 1] == b[j - 1]) {
  1301. // if it's the first element of either sequences, set LCS length to 1
  1302. if (i == 1 || j == 1) {
  1303. curr_row[j] = 1;
  1304. } else {
  1305. // increment LCS length by 1 compared to the previous element
  1306. curr_row[j] = prev_row[j - 1] + 1;
  1307. }
  1308. // update max_length if necessary
  1309. if (curr_row[j] > max_length) {
  1310. max_length = curr_row[j];
  1311. }
  1312. } else {
  1313. // reset LCS length if elements don't match
  1314. curr_row[j] = 0;
  1315. }
  1316. }
  1317. // update the previous row for the next iteration
  1318. prev_row = curr_row;
  1319. }
  1320. // return the maximum length of the LCS
  1321. return max_length;
  1322. }
  1323. //
  1324. // Vocab utils
  1325. //
  1326. std::vector<llama_token> common_tokenize(
  1327. const struct llama_context * ctx,
  1328. const std::string & text,
  1329. bool add_special,
  1330. bool parse_special) {
  1331. return common_tokenize(llama_get_model(ctx), text, add_special, parse_special);
  1332. }
  1333. std::vector<llama_token> common_tokenize(
  1334. const struct llama_model * model,
  1335. const std::string & text,
  1336. bool add_special,
  1337. bool parse_special) {
  1338. // upper limit for the number of tokens
  1339. int n_tokens = text.length() + 2 * add_special;
  1340. std::vector<llama_token> result(n_tokens);
  1341. n_tokens = llama_tokenize(model, text.data(), text.length(), result.data(), result.size(), add_special, parse_special);
  1342. if (n_tokens < 0) {
  1343. result.resize(-n_tokens);
  1344. int check = llama_tokenize(model, text.data(), text.length(), result.data(), result.size(), add_special, parse_special);
  1345. GGML_ASSERT(check == -n_tokens);
  1346. } else {
  1347. result.resize(n_tokens);
  1348. }
  1349. return result;
  1350. }
  1351. std::string common_token_to_piece(const struct llama_context * ctx, llama_token token, bool special) {
  1352. std::string piece;
  1353. piece.resize(piece.capacity()); // using string internal cache, 15 bytes + '\n'
  1354. const int n_chars = llama_token_to_piece(llama_get_model(ctx), token, &piece[0], piece.size(), 0, special);
  1355. if (n_chars < 0) {
  1356. piece.resize(-n_chars);
  1357. int check = llama_token_to_piece(llama_get_model(ctx), token, &piece[0], piece.size(), 0, special);
  1358. GGML_ASSERT(check == -n_chars);
  1359. }
  1360. else {
  1361. piece.resize(n_chars);
  1362. }
  1363. return piece;
  1364. }
  1365. std::string common_detokenize(llama_context * ctx, const std::vector<llama_token> & tokens, bool special) {
  1366. std::string text;
  1367. text.resize(std::max(text.capacity(), tokens.size()));
  1368. int32_t n_chars = llama_detokenize(llama_get_model(ctx), tokens.data(), (int32_t)tokens.size(), &text[0], (int32_t)text.size(), false, special);
  1369. if (n_chars < 0) {
  1370. text.resize(-n_chars);
  1371. n_chars = llama_detokenize(llama_get_model(ctx), tokens.data(), (int32_t)tokens.size(), &text[0], (int32_t)text.size(), false, special);
  1372. GGML_ASSERT(n_chars <= (int32_t)text.size()); // whitespace trimming is performed after per-token detokenization
  1373. }
  1374. text.resize(n_chars);
  1375. // NOTE: the original tokenizer decodes bytes after collecting the pieces.
  1376. return text;
  1377. }
  1378. //
  1379. // Chat template utils
  1380. //
  1381. bool common_chat_verify_template(const std::string & tmpl) {
  1382. llama_chat_message chat[] = {{"user", "test"}};
  1383. int res = llama_chat_apply_template(nullptr, tmpl.c_str(), chat, 1, true, nullptr, 0);
  1384. return res >= 0;
  1385. }
  1386. std::string common_chat_apply_template(const struct llama_model * model,
  1387. const std::string & tmpl,
  1388. const std::vector<common_chat_msg> & msgs,
  1389. bool add_ass) {
  1390. int alloc_size = 0;
  1391. bool fallback = false; // indicate if we must fallback to default chatml
  1392. std::vector<llama_chat_message> chat;
  1393. for (auto & msg : msgs) {
  1394. chat.push_back({msg.role.c_str(), msg.content.c_str()});
  1395. alloc_size += (msg.role.size() + msg.content.size()) * 1.25;
  1396. }
  1397. const char * ptr_tmpl = tmpl.empty() ? nullptr : tmpl.c_str();
  1398. std::vector<char> buf(alloc_size);
  1399. // run the first time to get the total output length
  1400. int32_t res = llama_chat_apply_template(model, ptr_tmpl, chat.data(), chat.size(), add_ass, buf.data(), buf.size());
  1401. // error: chat template is not supported
  1402. if (res < 0) {
  1403. if (ptr_tmpl != nullptr) {
  1404. // if the custom "tmpl" is not supported, we throw an error
  1405. // this is a bit redundant (for good), since we're not sure if user validated the custom template with llama_chat_verify_template()
  1406. throw std::runtime_error("this custom template is not supported");
  1407. } else {
  1408. // If the built-in template is not supported, we default to chatml
  1409. res = llama_chat_apply_template(nullptr, "chatml", chat.data(), chat.size(), add_ass, buf.data(), buf.size());
  1410. fallback = true;
  1411. }
  1412. }
  1413. // if it turns out that our buffer is too small, we resize it
  1414. if ((size_t) res > buf.size()) {
  1415. buf.resize(res);
  1416. res = llama_chat_apply_template(
  1417. fallback ? nullptr : model,
  1418. fallback ? "chatml" : ptr_tmpl,
  1419. chat.data(), chat.size(), add_ass, buf.data(), buf.size());
  1420. }
  1421. std::string formatted_chat(buf.data(), res);
  1422. return formatted_chat;
  1423. }
  1424. std::string common_chat_format_single(const struct llama_model * model,
  1425. const std::string & tmpl,
  1426. const std::vector<common_chat_msg> & past_msg,
  1427. const common_chat_msg & new_msg,
  1428. bool add_ass) {
  1429. std::ostringstream ss;
  1430. auto fmt_past_msg = past_msg.empty() ? "" : common_chat_apply_template(model, tmpl, past_msg, false);
  1431. std::vector<common_chat_msg> chat_new(past_msg);
  1432. // if the past_msg ends with a newline, we must preserve it in the formatted version
  1433. if (add_ass && !fmt_past_msg.empty() && fmt_past_msg.back() == '\n') {
  1434. ss << "\n";
  1435. };
  1436. // format chat with new_msg
  1437. chat_new.push_back(new_msg);
  1438. auto fmt_new_msg = common_chat_apply_template(model, tmpl, chat_new, add_ass);
  1439. // get the diff part
  1440. ss << fmt_new_msg.substr(fmt_past_msg.size(), fmt_new_msg.size() - fmt_past_msg.size());
  1441. return ss.str();
  1442. }
  1443. std::string common_chat_format_example(const struct llama_model * model,
  1444. const std::string & tmpl) {
  1445. std::vector<common_chat_msg> msgs = {
  1446. {"system", "You are a helpful assistant"},
  1447. {"user", "Hello"},
  1448. {"assistant", "Hi there"},
  1449. {"user", "How are you?"},
  1450. };
  1451. return common_chat_apply_template(model, tmpl, msgs, true);
  1452. }
  1453. //
  1454. // KV cache utils
  1455. //
  1456. void common_kv_cache_dump_view(const llama_kv_cache_view & view, int row_size) {
  1457. static const char slot_chars[] = ".123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+";
  1458. 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",
  1459. view.n_cells, view.n_seq_max, view.used_cells, view.token_count, view.max_contiguous, view.max_contiguous_idx);
  1460. llama_kv_cache_view_cell * c_curr = view.cells;
  1461. llama_seq_id * cs_curr = view.cells_sequences;
  1462. for (int i = 0; i < view.n_cells; i++, c_curr++, cs_curr += view.n_seq_max) {
  1463. if (i % row_size == 0) {
  1464. printf("\n%5d: ", i);
  1465. }
  1466. int seq_count = 0;
  1467. for (int j = 0; j < view.n_seq_max; j++) {
  1468. if (cs_curr[j] >= 0) { seq_count++; }
  1469. }
  1470. putchar(slot_chars[std::min(sizeof(slot_chars) - 2, size_t(seq_count))]);
  1471. }
  1472. printf("\n=== Done dumping\n");
  1473. }
  1474. void common_kv_cache_dump_view_seqs(const llama_kv_cache_view & view, int row_size) {
  1475. static const char slot_chars[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  1476. 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",
  1477. view.n_cells, view.n_seq_max, view.used_cells, view.token_count, view.max_contiguous, view.max_contiguous_idx);
  1478. std::unordered_map<llama_seq_id, size_t> seqs;
  1479. llama_kv_cache_view_cell * c_curr = view.cells;
  1480. llama_seq_id * cs_curr = view.cells_sequences;
  1481. for (int i = 0; i < view.n_cells; i++, c_curr++, cs_curr += view.n_seq_max) {
  1482. for (int j = 0; j < view.n_seq_max; j++) {
  1483. if (cs_curr[j] < 0) { continue; }
  1484. if (seqs.find(cs_curr[j]) == seqs.end()) {
  1485. if (seqs.size() + 1 >= sizeof(slot_chars)) { break; }
  1486. const size_t sz = seqs.size();
  1487. seqs[cs_curr[j]] = sz;
  1488. }
  1489. }
  1490. if (seqs.size() + 1 >= sizeof(slot_chars)) { break; }
  1491. }
  1492. printf("=== Sequence legend: ");
  1493. for (const auto & it : seqs) {
  1494. printf("%zu=%d, ", it.second, it.first);
  1495. }
  1496. printf("'+'=other sequence ids");
  1497. c_curr = view.cells;
  1498. cs_curr = view.cells_sequences;
  1499. for (int i = 0; i < view.n_cells; i++, c_curr++, cs_curr += view.n_seq_max) {
  1500. if (i % row_size == 0) {
  1501. printf("\n%5d: ", i);
  1502. }
  1503. for (int j = 0; j < view.n_seq_max; j++) {
  1504. if (cs_curr[j] >= 0) {
  1505. const auto & it = seqs.find(cs_curr[j]);
  1506. putchar(it != seqs.end() ? int(slot_chars[it->second]) : '+');
  1507. } else {
  1508. putchar('.');
  1509. }
  1510. }
  1511. putchar(' ');
  1512. }
  1513. printf("\n=== Done dumping\n");
  1514. }
  1515. //
  1516. // Embedding utils
  1517. //
  1518. void common_embd_normalize(const float * inp, float * out, int n, int embd_norm) {
  1519. double sum = 0.0;
  1520. switch (embd_norm) {
  1521. case -1: // no normalisation
  1522. sum = 1.0;
  1523. break;
  1524. case 0: // max absolute
  1525. for (int i = 0; i < n; i++) {
  1526. if (sum < std::abs(inp[i])) sum = std::abs(inp[i]);
  1527. }
  1528. sum /= 32760.0; // make an int16 range
  1529. break;
  1530. case 2: // euclidean
  1531. for (int i = 0; i < n; i++) {
  1532. sum += inp[i] * inp[i];
  1533. }
  1534. sum = std::sqrt(sum);
  1535. break;
  1536. default: // p-norm (euclidean is p-norm p=2)
  1537. for (int i = 0; i < n; i++) {
  1538. sum += std::pow(std::abs(inp[i]), embd_norm);
  1539. }
  1540. sum = std::pow(sum, 1.0 / embd_norm);
  1541. break;
  1542. }
  1543. const float norm = sum > 0.0 ? 1.0 / sum : 0.0f;
  1544. for (int i = 0; i < n; i++) {
  1545. out[i] = inp[i] * norm;
  1546. }
  1547. }
  1548. float common_embd_similarity_cos(const float * embd1, const float * embd2, int n){
  1549. double sum = 0.0;
  1550. double sum1 = 0.0;
  1551. double sum2 = 0.0;
  1552. for (int i = 0; i < n; i++) {
  1553. sum += embd1[i] * embd2[i];
  1554. sum1 += embd1[i] * embd1[i];
  1555. sum2 += embd2[i] * embd2[i];
  1556. }
  1557. // Handle the case where one or both vectors are zero vectors
  1558. if (sum1 == 0.0 || sum2 == 0.0) {
  1559. if (sum1 == 0.0 && sum2 == 0.0) {
  1560. return 1.0f; // two zero vectors are similar
  1561. }
  1562. return 0.0f;
  1563. }
  1564. return sum / (sqrt(sum1) * sqrt(sum2));
  1565. }
  1566. //
  1567. // Control vector utils
  1568. //
  1569. static common_control_vector_data common_control_vector_load_one(const common_control_vector_load_info & load_info) {
  1570. common_control_vector_data result = { -1, {} };
  1571. ggml_context * ctx = nullptr;
  1572. struct gguf_init_params meta_gguf_params = {
  1573. /* .no_alloc = */ false,
  1574. /* .ctx = */ &ctx,
  1575. };
  1576. struct gguf_context * ctx_gguf = gguf_init_from_file(load_info.fname.c_str(), meta_gguf_params);
  1577. if (!ctx_gguf) {
  1578. LOG_ERR("%s: failed to load control vector file from %s\n", __func__, load_info.fname.c_str());
  1579. return result;
  1580. }
  1581. int32_t n_tensors = gguf_get_n_tensors(ctx_gguf);
  1582. if (n_tensors == 0) {
  1583. LOG_WRN("%s: no direction tensors found in %s\n", __func__, load_info.fname.c_str());
  1584. }
  1585. for (int i = 0; i < n_tensors; i++) {
  1586. std::string name = gguf_get_tensor_name(ctx_gguf, i);
  1587. int layer_idx = -1;
  1588. // split on '.'
  1589. size_t dotpos = name.find('.');
  1590. if (dotpos != std::string::npos && name.substr(0, dotpos) == "direction") {
  1591. try {
  1592. layer_idx = std::stoi(name.substr(dotpos + 1));
  1593. } catch (...) {
  1594. layer_idx = -1;
  1595. }
  1596. }
  1597. if (layer_idx < 0) {
  1598. LOG_ERR("%s: invalid/unparsable direction tensor layer index in %s\n", __func__, load_info.fname.c_str());
  1599. result.n_embd = -1;
  1600. break;
  1601. } else if (layer_idx == 0) {
  1602. LOG_ERR("%s: invalid (zero) direction tensor layer index in %s\n", __func__, load_info.fname.c_str());
  1603. result.n_embd = -1;
  1604. break;
  1605. }
  1606. struct ggml_tensor * tensor = ggml_get_tensor(ctx, name.c_str());
  1607. if (tensor->type != GGML_TYPE_F32) {
  1608. LOG_ERR("%s: invalid (non-F32) direction tensor type in %s\n", __func__, load_info.fname.c_str());
  1609. result.n_embd = -1;
  1610. break;
  1611. }
  1612. if (ggml_n_dims(tensor) != 1) {
  1613. LOG_ERR("%s: invalid (non-1D) direction tensor shape in %s\n", __func__, load_info.fname.c_str());
  1614. result.n_embd = -1;
  1615. break;
  1616. }
  1617. if (result.n_embd == -1) {
  1618. result.n_embd = ggml_nelements(tensor);
  1619. } else if (ggml_nelements(tensor) != result.n_embd) {
  1620. LOG_ERR("%s: direction tensor in %s does not match previous dimensions\n", __func__, load_info.fname.c_str());
  1621. result.n_embd = -1;
  1622. break;
  1623. }
  1624. // extend if necessary - do not store data for layer 0 (it's not used)
  1625. result.data.resize(std::max(result.data.size(), static_cast<size_t>(result.n_embd * layer_idx)), 0.0f);
  1626. const float * src = (const float *) tensor->data;
  1627. float * dst = result.data.data() + result.n_embd * (layer_idx - 1); // layer 1 at [0]
  1628. for (int j = 0; j < result.n_embd; j++) {
  1629. dst[j] += src[j] * load_info.strength; // allows multiple directions for same layer in same file
  1630. }
  1631. }
  1632. if (result.n_embd == -1) {
  1633. LOG_WRN("%s: skipping %s due to invalid direction tensors\n", __func__, load_info.fname.c_str());
  1634. result.data.clear();
  1635. }
  1636. gguf_free(ctx_gguf);
  1637. ggml_free(ctx);
  1638. return result;
  1639. }
  1640. common_control_vector_data common_control_vector_load(const std::vector<common_control_vector_load_info> & load_infos) {
  1641. common_control_vector_data result = { -1, {} };
  1642. for (const auto & info : load_infos) {
  1643. auto cur = common_control_vector_load_one(info);
  1644. if (cur.n_embd == -1) {
  1645. result.n_embd = -1;
  1646. break;
  1647. }
  1648. if (result.n_embd != -1 && result.n_embd != cur.n_embd) {
  1649. LOG_ERR("%s: control vectors in %s does not match previous dimensions\n", __func__, info.fname.c_str());
  1650. result.n_embd = -1;
  1651. break;
  1652. }
  1653. if (result.n_embd == -1) {
  1654. result = std::move(cur);
  1655. } else {
  1656. result.data.resize(std::max(result.data.size(), cur.data.size()), 0.0f); // extend if necessary
  1657. for (size_t i = 0; i < cur.data.size(); i++) {
  1658. result.data[i] += cur.data[i];
  1659. }
  1660. }
  1661. }
  1662. if (result.n_embd == -1) {
  1663. LOG_ERR("%s: no valid control vector files passed\n", __func__);
  1664. result.data.clear();
  1665. }
  1666. return result;
  1667. }