common.cpp 68 KB

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