common.cpp 69 KB

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