common.cpp 67 KB

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