common.cpp 71 KB

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