common.cpp 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721
  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. #include "llama.h"
  9. #include "sampling.h"
  10. #include <algorithm>
  11. #include <cinttypes>
  12. #include <climits>
  13. #include <cmath>
  14. #include <codecvt>
  15. #include <chrono>
  16. #include <cstdarg>
  17. #include <cstring>
  18. #include <ctime>
  19. #include <filesystem>
  20. #include <fstream>
  21. #include <iostream>
  22. #include <iterator>
  23. #include <regex>
  24. #include <sstream>
  25. #include <string>
  26. #include <thread>
  27. #include <unordered_set>
  28. #include <vector>
  29. #if defined(__APPLE__) && defined(__MACH__)
  30. #include <sys/types.h>
  31. #include <sys/sysctl.h>
  32. #endif
  33. #if defined(_WIN32)
  34. #define WIN32_LEAN_AND_MEAN
  35. #ifndef NOMINMAX
  36. # define NOMINMAX
  37. #endif
  38. #include <locale>
  39. #include <windows.h>
  40. #include <string.h>
  41. #include <fcntl.h>
  42. #include <io.h>
  43. #else
  44. #include <sys/ioctl.h>
  45. #include <sys/stat.h>
  46. #include <unistd.h>
  47. #endif
  48. #if defined(__linux__)
  49. #include <sys/types.h>
  50. #include <pwd.h>
  51. #endif
  52. #if defined(_MSC_VER)
  53. #pragma warning(disable: 4244 4267) // possible loss of data
  54. #endif
  55. common_time_meas::common_time_meas(int64_t & t_acc, bool disable) : t_start_us(disable ? -1 : ggml_time_us()), t_acc(t_acc) {}
  56. common_time_meas::~common_time_meas() {
  57. if (t_start_us >= 0) {
  58. t_acc += ggml_time_us() - t_start_us;
  59. }
  60. }
  61. //
  62. // CPU utils
  63. //
  64. int32_t cpu_get_num_physical_cores() {
  65. #ifdef __linux__
  66. // enumerate the set of thread siblings, num entries is num cores
  67. std::unordered_set<std::string> siblings;
  68. for (uint32_t cpu=0; cpu < UINT32_MAX; ++cpu) {
  69. std::ifstream thread_siblings("/sys/devices/system/cpu/cpu"
  70. + std::to_string(cpu) + "/topology/thread_siblings");
  71. if (!thread_siblings.is_open()) {
  72. break; // no more cpus
  73. }
  74. std::string line;
  75. if (std::getline(thread_siblings, line)) {
  76. siblings.insert(line);
  77. }
  78. }
  79. if (!siblings.empty()) {
  80. return static_cast<int32_t>(siblings.size());
  81. }
  82. #elif defined(__APPLE__) && defined(__MACH__)
  83. int32_t num_physical_cores;
  84. size_t len = sizeof(num_physical_cores);
  85. int result = sysctlbyname("hw.perflevel0.physicalcpu", &num_physical_cores, &len, NULL, 0);
  86. if (result == 0) {
  87. return num_physical_cores;
  88. }
  89. result = sysctlbyname("hw.physicalcpu", &num_physical_cores, &len, NULL, 0);
  90. if (result == 0) {
  91. return num_physical_cores;
  92. }
  93. #elif defined(_WIN32) && (_WIN32_WINNT >= 0x0601) && !defined(__MINGW64__) // windows 7 and later
  94. // TODO: windows + arm64 + mingw64
  95. unsigned int n_threads_win = std::thread::hardware_concurrency();
  96. unsigned int default_threads = n_threads_win > 0 ? (n_threads_win <= 4 ? n_threads_win : n_threads_win / 2) : 4;
  97. DWORD buffer_size = 0;
  98. if (!GetLogicalProcessorInformationEx(RelationProcessorCore, nullptr, &buffer_size)) {
  99. if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
  100. return default_threads;
  101. }
  102. }
  103. std::vector<char> buffer(buffer_size);
  104. if (!GetLogicalProcessorInformationEx(RelationProcessorCore, reinterpret_cast<PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX>(buffer.data()), &buffer_size)) {
  105. return default_threads;
  106. }
  107. int32_t num_physical_cores = 0;
  108. PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX info = reinterpret_cast<PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX>(buffer.data());
  109. while (buffer_size > 0) {
  110. if (info->Relationship == RelationProcessorCore) {
  111. num_physical_cores += info->Processor.GroupCount;
  112. }
  113. buffer_size -= info->Size;
  114. info = reinterpret_cast<PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX>(reinterpret_cast<char*>(info) + info->Size);
  115. }
  116. return num_physical_cores > 0 ? num_physical_cores : default_threads;
  117. #endif
  118. unsigned int n_threads = std::thread::hardware_concurrency();
  119. return n_threads > 0 ? (n_threads <= 4 ? n_threads : n_threads / 2) : 4;
  120. }
  121. #if defined(__x86_64__) && defined(__linux__) && !defined(__ANDROID__)
  122. #include <pthread.h>
  123. static void cpuid(unsigned leaf, unsigned subleaf,
  124. unsigned *eax, unsigned *ebx, unsigned *ecx, unsigned *edx) {
  125. __asm__("movq\t%%rbx,%%rsi\n\t"
  126. "cpuid\n\t"
  127. "xchgq\t%%rbx,%%rsi"
  128. : "=a"(*eax), "=S"(*ebx), "=c"(*ecx), "=d"(*edx)
  129. : "0"(leaf), "2"(subleaf));
  130. }
  131. static int pin_cpu(int cpu) {
  132. cpu_set_t mask;
  133. CPU_ZERO(&mask);
  134. CPU_SET(cpu, &mask);
  135. return pthread_setaffinity_np(pthread_self(), sizeof(mask), &mask);
  136. }
  137. static bool is_hybrid_cpu(void) {
  138. unsigned eax, ebx, ecx, edx;
  139. cpuid(7, 0, &eax, &ebx, &ecx, &edx);
  140. return !!(edx & (1u << 15));
  141. }
  142. static bool is_running_on_efficiency_core(void) {
  143. unsigned eax, ebx, ecx, edx;
  144. cpuid(0x1a, 0, &eax, &ebx, &ecx, &edx);
  145. int intel_atom = 0x20;
  146. int core_type = (eax & 0xff000000u) >> 24;
  147. return core_type == intel_atom;
  148. }
  149. static int cpu_count_math_cpus(int n_cpu) {
  150. int result = 0;
  151. for (int cpu = 0; cpu < n_cpu; ++cpu) {
  152. if (pin_cpu(cpu)) {
  153. return -1;
  154. }
  155. if (is_running_on_efficiency_core()) {
  156. continue; // efficiency cores harm lockstep threading
  157. }
  158. ++cpu; // hyperthreading isn't useful for linear algebra
  159. ++result;
  160. }
  161. return result;
  162. }
  163. #endif // __x86_64__ && __linux__
  164. /**
  165. * Returns number of CPUs on system that are useful for math.
  166. */
  167. int32_t cpu_get_num_math() {
  168. #if defined(__x86_64__) && defined(__linux__) && !defined(__ANDROID__)
  169. int n_cpu = sysconf(_SC_NPROCESSORS_ONLN);
  170. if (n_cpu < 1) {
  171. return cpu_get_num_physical_cores();
  172. }
  173. if (is_hybrid_cpu()) {
  174. cpu_set_t affinity;
  175. if (!pthread_getaffinity_np(pthread_self(), sizeof(affinity), &affinity)) {
  176. int result = cpu_count_math_cpus(n_cpu);
  177. pthread_setaffinity_np(pthread_self(), sizeof(affinity), &affinity);
  178. if (result > 0) {
  179. return result;
  180. }
  181. }
  182. }
  183. #endif
  184. return cpu_get_num_physical_cores();
  185. }
  186. // Helper for setting process priority
  187. #if defined(_WIN32)
  188. bool set_process_priority(enum ggml_sched_priority prio) {
  189. if (prio == GGML_SCHED_PRIO_NORMAL) {
  190. return true;
  191. }
  192. DWORD p = NORMAL_PRIORITY_CLASS;
  193. switch (prio) {
  194. case GGML_SCHED_PRIO_LOW: p = BELOW_NORMAL_PRIORITY_CLASS; break;
  195. case GGML_SCHED_PRIO_NORMAL: p = NORMAL_PRIORITY_CLASS; break;
  196. case GGML_SCHED_PRIO_MEDIUM: p = ABOVE_NORMAL_PRIORITY_CLASS; break;
  197. case GGML_SCHED_PRIO_HIGH: p = HIGH_PRIORITY_CLASS; break;
  198. case GGML_SCHED_PRIO_REALTIME: p = REALTIME_PRIORITY_CLASS; break;
  199. }
  200. if (!SetPriorityClass(GetCurrentProcess(), p)) {
  201. LOG_WRN("failed to set process priority class %d : (%d)\n", prio, (int) GetLastError());
  202. return false;
  203. }
  204. return true;
  205. }
  206. #else // MacOS and POSIX
  207. #include <sys/types.h>
  208. #include <sys/resource.h>
  209. bool set_process_priority(enum ggml_sched_priority prio) {
  210. if (prio == GGML_SCHED_PRIO_NORMAL) {
  211. return true;
  212. }
  213. int p = 0;
  214. switch (prio) {
  215. case GGML_SCHED_PRIO_LOW: p = 5; break;
  216. case GGML_SCHED_PRIO_NORMAL: p = 0; break;
  217. case GGML_SCHED_PRIO_MEDIUM: p = -5; break;
  218. case GGML_SCHED_PRIO_HIGH: p = -10; break;
  219. case GGML_SCHED_PRIO_REALTIME: p = -20; break;
  220. }
  221. if (!setpriority(PRIO_PROCESS, 0, p)) {
  222. LOG_WRN("failed to set process priority %d : %s (%d)\n", prio, strerror(errno), errno);
  223. return false;
  224. }
  225. return true;
  226. }
  227. #endif
  228. //
  229. // CLI argument parsing
  230. //
  231. void postprocess_cpu_params(cpu_params& cpuparams, const cpu_params* role_model) {
  232. int32_t n_set = 0;
  233. if (cpuparams.n_threads < 0) {
  234. // Assuming everything about cpuparams is invalid
  235. if (role_model != nullptr) {
  236. cpuparams = *role_model;
  237. } else {
  238. cpuparams.n_threads = cpu_get_num_math();
  239. }
  240. }
  241. for (int32_t i = 0; i < GGML_MAX_N_THREADS; i++) {
  242. if (cpuparams.cpumask[i]) {
  243. n_set++;
  244. }
  245. }
  246. if (n_set && n_set < cpuparams.n_threads) {
  247. // Not enough set bits, may experience performance issues.
  248. LOG_WRN("Not enough set bits in CPU mask (%d) to satisfy requested thread count: %d\n", n_set, cpuparams.n_threads);
  249. }
  250. }
  251. bool parse_cpu_range(const std::string & range, bool (&boolmask)[GGML_MAX_N_THREADS]) {
  252. size_t dash_loc = range.find('-');
  253. if (dash_loc == std::string::npos) {
  254. LOG_ERR("Format of CPU range is invalid! Expected [<start>]-[<end>].\n");
  255. return false;
  256. }
  257. size_t start_i;
  258. size_t end_i;
  259. if (dash_loc == 0) {
  260. start_i = 0;
  261. } else {
  262. start_i = std::stoull(range.substr(0, dash_loc));
  263. if (start_i >= GGML_MAX_N_THREADS) {
  264. LOG_ERR("Start index out of bounds!\n");
  265. return false;
  266. }
  267. }
  268. if (dash_loc == range.length() - 1) {
  269. end_i = GGML_MAX_N_THREADS - 1;
  270. } else {
  271. end_i = std::stoull(range.substr(dash_loc + 1));
  272. if (end_i >= GGML_MAX_N_THREADS) {
  273. LOG_ERR("End index out of bounds!\n");
  274. return false;
  275. }
  276. }
  277. for (size_t i = start_i; i <= end_i; i++) {
  278. boolmask[i] = true;
  279. }
  280. return true;
  281. }
  282. bool parse_cpu_mask(const std::string & mask, bool (&boolmask)[GGML_MAX_N_THREADS]) {
  283. // Discard potential 0x prefix
  284. size_t start_i = 0;
  285. if (mask.length() >= 2 && mask.substr(0, 2) == "0x") {
  286. start_i = 2;
  287. }
  288. size_t num_digits = mask.length() - start_i;
  289. if (num_digits > 128) num_digits = 128;
  290. size_t end_i = num_digits + start_i;
  291. for (size_t i = start_i, n = (num_digits*4 - 1); i < end_i; i++, n-=4) {
  292. char c = mask.at(i);
  293. int8_t id = c;
  294. if ((c >= '0' && c <= '9')) {
  295. id -= '0';
  296. } else if (c >= 'a' && c <= 'f') {
  297. id -= 'a' - 10;
  298. } else if (c >= 'A' && c <= 'F') {
  299. id -= 'A' - 10;
  300. } else {
  301. LOG_ERR("Invalid hex character '%c' at position %d\n", c, int32_t(i));
  302. return false;
  303. }
  304. boolmask[ n ] = boolmask[ n ] || ((id & 8) != 0);
  305. boolmask[n - 1] = boolmask[n - 1] || ((id & 4) != 0);
  306. boolmask[n - 2] = boolmask[n - 2] || ((id & 2) != 0);
  307. boolmask[n - 3] = boolmask[n - 3] || ((id & 1) != 0);
  308. }
  309. return true;
  310. }
  311. void common_init() {
  312. llama_log_set(common_log_default_callback, NULL);
  313. #ifdef NDEBUG
  314. const char * build_type = "";
  315. #else
  316. const char * build_type = " (debug)";
  317. #endif
  318. LOG_INF("build: %d (%s) with %s for %s%s\n", LLAMA_BUILD_NUMBER, LLAMA_COMMIT, LLAMA_COMPILER, LLAMA_BUILD_TARGET, build_type);
  319. }
  320. std::string common_params_get_system_info(const common_params & params) {
  321. std::ostringstream os;
  322. os << "system_info: n_threads = " << params.cpuparams.n_threads;
  323. if (params.cpuparams_batch.n_threads != -1) {
  324. os << " (n_threads_batch = " << params.cpuparams_batch.n_threads << ")";
  325. }
  326. #if defined(_WIN32) && (_WIN32_WINNT >= 0x0601) && !defined(__MINGW64__) // windows 7 and later
  327. // TODO: windows + arm64 + mingw64
  328. DWORD logicalProcessorCount = GetActiveProcessorCount(ALL_PROCESSOR_GROUPS);
  329. os << " / " << logicalProcessorCount << " | " << llama_print_system_info();
  330. #else
  331. os << " / " << std::thread::hardware_concurrency() << " | " << llama_print_system_info();
  332. #endif
  333. return os.str();
  334. }
  335. //
  336. // String utils
  337. //
  338. std::string string_format(const char * fmt, ...) {
  339. va_list ap;
  340. va_list ap2;
  341. va_start(ap, fmt);
  342. va_copy(ap2, ap);
  343. int size = vsnprintf(NULL, 0, fmt, ap);
  344. GGML_ASSERT(size >= 0 && size < INT_MAX); // NOLINT
  345. std::vector<char> buf(size + 1);
  346. int size2 = vsnprintf(buf.data(), size + 1, fmt, ap2);
  347. GGML_ASSERT(size2 == size);
  348. va_end(ap2);
  349. va_end(ap);
  350. return std::string(buf.data(), size);
  351. }
  352. std::string string_strip(const std::string & str) {
  353. size_t start = 0;
  354. size_t end = str.size();
  355. while (start < end && std::isspace(str[start])) {
  356. start++;
  357. }
  358. while (end > start && std::isspace(str[end - 1])) {
  359. end--;
  360. }
  361. return str.substr(start, end - start);
  362. }
  363. std::string string_get_sortable_timestamp() {
  364. using clock = std::chrono::system_clock;
  365. const clock::time_point current_time = clock::now();
  366. const time_t as_time_t = clock::to_time_t(current_time);
  367. char timestamp_no_ns[100];
  368. std::strftime(timestamp_no_ns, 100, "%Y_%m_%d-%H_%M_%S", std::localtime(&as_time_t));
  369. const int64_t ns = std::chrono::duration_cast<std::chrono::nanoseconds>(
  370. current_time.time_since_epoch() % 1000000000).count();
  371. char timestamp_ns[11];
  372. snprintf(timestamp_ns, 11, "%09" PRId64, ns);
  373. return std::string(timestamp_no_ns) + "." + std::string(timestamp_ns);
  374. }
  375. void string_replace_all(std::string & s, const std::string & search, const std::string & replace) {
  376. if (search.empty()) {
  377. return;
  378. }
  379. std::string builder;
  380. builder.reserve(s.length());
  381. size_t pos = 0;
  382. size_t last_pos = 0;
  383. while ((pos = s.find(search, last_pos)) != std::string::npos) {
  384. builder.append(s, last_pos, pos - last_pos);
  385. builder.append(replace);
  386. last_pos = pos + search.length();
  387. }
  388. builder.append(s, last_pos, std::string::npos);
  389. s = std::move(builder);
  390. }
  391. bool string_ends_with(const std::string_view & str, const std::string_view & suffix) {
  392. return str.size() >= suffix.size() && str.compare(str.size()-suffix.size(), suffix.size(), suffix) == 0;
  393. }
  394. bool string_remove_suffix(std::string & str, const std::string_view & suffix) {
  395. bool has_suffix = string_ends_with(str, suffix);
  396. if (has_suffix) {
  397. str = str.substr(0, str.size() - suffix.size());
  398. }
  399. return has_suffix;
  400. }
  401. size_t string_find_partial_stop(const std::string_view & str, const std::string_view & stop) {
  402. if (!str.empty() && !stop.empty()) {
  403. const char text_last_char = str.back();
  404. for (int64_t char_index = stop.size() - 1; char_index >= 0; char_index--) {
  405. if (stop[char_index] == text_last_char) {
  406. const auto current_partial = stop.substr(0, char_index + 1);
  407. if (string_ends_with(str, current_partial)) {
  408. return str.size() - char_index - 1;
  409. }
  410. }
  411. }
  412. }
  413. return std::string::npos;
  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, "\\$&");
  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. buf << "'" << detokenized << "'"
  482. << ":" << std::to_string(token);
  483. }
  484. buf << " ]";
  485. return buf.str();
  486. }
  487. std::string string_from(const struct llama_context * ctx, const struct llama_batch & batch) {
  488. std::stringstream buf;
  489. buf << "[ ";
  490. bool first = true;
  491. for (int i = 0; i < batch.n_tokens; ++i) {
  492. if (!first) {
  493. buf << ", ";
  494. } else {
  495. first = false;
  496. }
  497. auto detokenized = common_token_to_piece(ctx, batch.token[i]);
  498. buf << "\n" << std::to_string(i)
  499. << ", token '" << detokenized << "'"
  500. << ", pos " << std::to_string(batch.pos[i])
  501. << ", n_seq_id " << std::to_string(batch.n_seq_id[i])
  502. << ", seq_id " << std::to_string(batch.seq_id[i][0])
  503. << ", logits " << std::to_string(batch.logits[i]);
  504. }
  505. buf << " ]";
  506. return buf.str();
  507. }
  508. void string_process_escapes(std::string & input) {
  509. std::size_t input_len = input.length();
  510. std::size_t output_idx = 0;
  511. for (std::size_t input_idx = 0; input_idx < input_len; ++input_idx) {
  512. if (input[input_idx] == '\\' && input_idx + 1 < input_len) {
  513. switch (input[++input_idx]) {
  514. case 'n': input[output_idx++] = '\n'; break;
  515. case 'r': input[output_idx++] = '\r'; break;
  516. case 't': input[output_idx++] = '\t'; break;
  517. case '\'': input[output_idx++] = '\''; break;
  518. case '\"': input[output_idx++] = '\"'; break;
  519. case '\\': input[output_idx++] = '\\'; break;
  520. case 'x':
  521. // Handle \x12, etc
  522. if (input_idx + 2 < input_len) {
  523. const char x[3] = { input[input_idx + 1], input[input_idx + 2], 0 };
  524. char *err_p = nullptr;
  525. const long val = std::strtol(x, &err_p, 16);
  526. if (err_p == x + 2) {
  527. input_idx += 2;
  528. input[output_idx++] = char(val);
  529. break;
  530. }
  531. }
  532. // fall through
  533. default: input[output_idx++] = '\\';
  534. input[output_idx++] = input[input_idx]; break;
  535. }
  536. } else {
  537. input[output_idx++] = input[input_idx];
  538. }
  539. }
  540. input.resize(output_idx);
  541. }
  542. bool string_parse_kv_override(const char * data, std::vector<llama_model_kv_override> & overrides) {
  543. const char * sep = strchr(data, '=');
  544. if (sep == nullptr || sep - data >= 128) {
  545. LOG_ERR("%s: malformed KV override '%s'\n", __func__, data);
  546. return false;
  547. }
  548. llama_model_kv_override kvo;
  549. std::strncpy(kvo.key, data, sep - data);
  550. kvo.key[sep - data] = 0;
  551. sep++;
  552. if (strncmp(sep, "int:", 4) == 0) {
  553. sep += 4;
  554. kvo.tag = LLAMA_KV_OVERRIDE_TYPE_INT;
  555. kvo.val_i64 = std::atol(sep);
  556. } else if (strncmp(sep, "float:", 6) == 0) {
  557. sep += 6;
  558. kvo.tag = LLAMA_KV_OVERRIDE_TYPE_FLOAT;
  559. kvo.val_f64 = std::atof(sep);
  560. } else if (strncmp(sep, "bool:", 5) == 0) {
  561. sep += 5;
  562. kvo.tag = LLAMA_KV_OVERRIDE_TYPE_BOOL;
  563. if (std::strcmp(sep, "true") == 0) {
  564. kvo.val_bool = true;
  565. } else if (std::strcmp(sep, "false") == 0) {
  566. kvo.val_bool = false;
  567. } else {
  568. LOG_ERR("%s: invalid boolean value for KV override '%s'\n", __func__, data);
  569. return false;
  570. }
  571. } else if (strncmp(sep, "str:", 4) == 0) {
  572. sep += 4;
  573. kvo.tag = LLAMA_KV_OVERRIDE_TYPE_STR;
  574. if (strlen(sep) > 127) {
  575. LOG_ERR("%s: malformed KV override '%s', value cannot exceed 127 chars\n", __func__, data);
  576. return false;
  577. }
  578. strncpy(kvo.val_str, sep, 127);
  579. kvo.val_str[127] = '\0';
  580. } else {
  581. LOG_ERR("%s: invalid type for KV override '%s'\n", __func__, data);
  582. return false;
  583. }
  584. overrides.emplace_back(std::move(kvo));
  585. return true;
  586. }
  587. //
  588. // Filesystem utils
  589. //
  590. // Validate if a filename is safe to use
  591. // To validate a full path, split the path by the OS-specific path separator, and validate each part with this function
  592. bool fs_validate_filename(const std::string & filename) {
  593. if (!filename.length()) {
  594. // Empty filename invalid
  595. return false;
  596. }
  597. if (filename.length() > 255) {
  598. // Limit at common largest possible filename on Linux filesystems
  599. // to avoid unnecessary further validation
  600. // (On systems with smaller limits it will be caught by the OS)
  601. return false;
  602. }
  603. std::u32string filename_utf32;
  604. try {
  605. #if defined(__clang__)
  606. // disable C++17 deprecation warning for std::codecvt_utf8
  607. # pragma clang diagnostic push
  608. # pragma clang diagnostic ignored "-Wdeprecated-declarations"
  609. #elif defined(__GNUC__)
  610. # pragma GCC diagnostic push
  611. # pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  612. #endif
  613. std::wstring_convert<std::codecvt_utf8<char32_t>, char32_t> converter;
  614. #if defined(__clang__)
  615. # pragma clang diagnostic pop
  616. #elif defined(__GNUC__)
  617. # pragma GCC diagnostic pop
  618. #endif
  619. filename_utf32 = converter.from_bytes(filename);
  620. // If the reverse conversion mismatches, it means overlong UTF-8 sequences were used,
  621. // or invalid encodings were encountered. Reject such attempts
  622. std::string filename_reencoded = converter.to_bytes(filename_utf32);
  623. if (filename_reencoded != filename) {
  624. return false;
  625. }
  626. } catch (const std::exception &) {
  627. return false;
  628. }
  629. // Check for forbidden codepoints:
  630. // - Control characters
  631. // - Unicode equivalents of illegal characters
  632. // - UTF-16 surrogate pairs
  633. // - UTF-8 replacement character
  634. // - Byte order mark (BOM)
  635. // - Illegal characters: / \ : * ? " < > |
  636. for (char32_t c : filename_utf32) {
  637. if (c <= 0x1F // Control characters (C0)
  638. || c == 0x7F // Control characters (DEL)
  639. || (c >= 0x80 && c <= 0x9F) // Control characters (C1)
  640. || c == 0xFF0E // Fullwidth Full Stop (period equivalent)
  641. || c == 0x2215 // Division Slash (forward slash equivalent)
  642. || c == 0x2216 // Set Minus (backslash equivalent)
  643. || (c >= 0xD800 && c <= 0xDFFF) // UTF-16 surrogate pairs
  644. || c == 0xFFFD // Replacement Character (UTF-8)
  645. || c == 0xFEFF // Byte Order Mark (BOM)
  646. || c == '/' || c == '\\' || c == ':' || c == '*' // Illegal characters
  647. || c == '?' || c == '"' || c == '<' || c == '>' || c == '|') {
  648. return false;
  649. }
  650. }
  651. // Reject any leading or trailing ' ', or any trailing '.', these are stripped on Windows and will cause a different filename
  652. // Unicode and other whitespace is not affected, only 0x20 space
  653. if (filename.front() == ' ' || filename.back() == ' ' || filename.back() == '.') {
  654. return false;
  655. }
  656. // Reject any ".." (currently stricter than necessary, it should be fine to just check for == ".." instead)
  657. if (filename.find("..") != std::string::npos) {
  658. return false;
  659. }
  660. // Reject "."
  661. if (filename == ".") {
  662. return false;
  663. }
  664. return true;
  665. }
  666. #include <iostream>
  667. // returns true if successful, false otherwise
  668. bool fs_create_directory_with_parents(const std::string & path) {
  669. #ifdef _WIN32
  670. std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;
  671. std::wstring wpath = converter.from_bytes(path);
  672. // if the path already exists, check whether it's a directory
  673. const DWORD attributes = GetFileAttributesW(wpath.c_str());
  674. if ((attributes != INVALID_FILE_ATTRIBUTES) && (attributes & FILE_ATTRIBUTE_DIRECTORY)) {
  675. return true;
  676. }
  677. size_t pos_slash = 0;
  678. // process path from front to back, procedurally creating directories
  679. while ((pos_slash = path.find('\\', pos_slash)) != std::string::npos) {
  680. const std::wstring subpath = wpath.substr(0, pos_slash);
  681. pos_slash += 1;
  682. // skip the drive letter, in some systems it can return an access denied error
  683. if (subpath.length() == 2 && subpath[1] == ':') {
  684. continue;
  685. }
  686. const bool success = CreateDirectoryW(subpath.c_str(), NULL);
  687. if (!success) {
  688. const DWORD error = GetLastError();
  689. // if the path already exists, ensure that it's a directory
  690. if (error == ERROR_ALREADY_EXISTS) {
  691. const DWORD attributes = GetFileAttributesW(subpath.c_str());
  692. if (attributes == INVALID_FILE_ATTRIBUTES || !(attributes & FILE_ATTRIBUTE_DIRECTORY)) {
  693. return false;
  694. }
  695. } else {
  696. return false;
  697. }
  698. }
  699. }
  700. return true;
  701. #else
  702. // if the path already exists, check whether it's a directory
  703. struct stat info;
  704. if (stat(path.c_str(), &info) == 0) {
  705. return S_ISDIR(info.st_mode);
  706. }
  707. size_t pos_slash = 1; // skip leading slashes for directory creation
  708. // process path from front to back, procedurally creating directories
  709. while ((pos_slash = path.find('/', pos_slash)) != std::string::npos) {
  710. const std::string subpath = path.substr(0, pos_slash);
  711. struct stat info;
  712. // if the path already exists, ensure that it's a directory
  713. if (stat(subpath.c_str(), &info) == 0) {
  714. if (!S_ISDIR(info.st_mode)) {
  715. return false;
  716. }
  717. } else {
  718. // create parent directories
  719. const int ret = mkdir(subpath.c_str(), 0755);
  720. if (ret != 0) {
  721. return false;
  722. }
  723. }
  724. pos_slash += 1;
  725. }
  726. return true;
  727. #endif // _WIN32
  728. }
  729. std::string fs_get_cache_directory() {
  730. std::string cache_directory = "";
  731. auto ensure_trailing_slash = [](std::string p) {
  732. // Make sure to add trailing slash
  733. if (p.back() != DIRECTORY_SEPARATOR) {
  734. p += DIRECTORY_SEPARATOR;
  735. }
  736. return p;
  737. };
  738. if (getenv("LLAMA_CACHE")) {
  739. cache_directory = std::getenv("LLAMA_CACHE");
  740. } else {
  741. #if defined(__linux__) || defined(__FreeBSD__) || defined(_AIX) || defined(__OpenBSD__)
  742. if (std::getenv("XDG_CACHE_HOME")) {
  743. cache_directory = std::getenv("XDG_CACHE_HOME");
  744. } else if (std::getenv("HOME")) {
  745. cache_directory = std::getenv("HOME") + std::string("/.cache/");
  746. } else {
  747. #if defined(__linux__)
  748. /* no $HOME is defined, fallback to getpwuid */
  749. struct passwd *pw = getpwuid(getuid());
  750. if ((!pw) || (!pw->pw_dir)) {
  751. throw std::runtime_error("Failed to find $HOME directory");
  752. }
  753. cache_directory = std::string(pw->pw_dir) + std::string("/.cache/");
  754. #else /* defined(__linux__) */
  755. throw std::runtime_error("Failed to find $HOME directory");
  756. #endif /* defined(__linux__) */
  757. }
  758. #elif defined(__APPLE__)
  759. cache_directory = std::getenv("HOME") + std::string("/Library/Caches/");
  760. #elif defined(_WIN32)
  761. cache_directory = std::getenv("LOCALAPPDATA");
  762. #else
  763. # error Unknown architecture
  764. #endif
  765. cache_directory = ensure_trailing_slash(cache_directory);
  766. cache_directory += "llama.cpp";
  767. }
  768. return ensure_trailing_slash(cache_directory);
  769. }
  770. std::string fs_get_cache_file(const std::string & filename) {
  771. GGML_ASSERT(filename.find(DIRECTORY_SEPARATOR) == std::string::npos);
  772. std::string cache_directory = fs_get_cache_directory();
  773. const bool success = fs_create_directory_with_parents(cache_directory);
  774. if (!success) {
  775. throw std::runtime_error("failed to create cache directory: " + cache_directory);
  776. }
  777. return cache_directory + filename;
  778. }
  779. std::vector<common_file_info> fs_list_files(const std::string & path) {
  780. std::vector<common_file_info> files;
  781. if (path.empty()) return files;
  782. std::filesystem::path dir(path);
  783. if (!std::filesystem::exists(dir) || !std::filesystem::is_directory(dir)) {
  784. return files;
  785. }
  786. for (const auto & entry : std::filesystem::directory_iterator(dir)) {
  787. try {
  788. // Only include regular files (skip directories)
  789. const auto & p = entry.path();
  790. if (std::filesystem::is_regular_file(p)) {
  791. common_file_info info;
  792. info.path = p.string();
  793. info.name = p.filename().string();
  794. try {
  795. info.size = static_cast<size_t>(std::filesystem::file_size(p));
  796. } catch (const std::filesystem::filesystem_error &) {
  797. info.size = 0;
  798. }
  799. files.push_back(std::move(info));
  800. }
  801. } catch (const std::filesystem::filesystem_error &) {
  802. // skip entries we cannot inspect
  803. continue;
  804. }
  805. }
  806. return files;
  807. }
  808. //
  809. // Model utils
  810. //
  811. static inline void common_init_sampler_from_model(
  812. const llama_model * model,
  813. common_params_sampling & sparams) {
  814. const uint64_t config = sparams.user_sampling_config;
  815. auto get_int32 = [&](const char * key, int32_t & dst, uint64_t user_config) {
  816. if (config & user_config) return;
  817. char buf[64] = {0};
  818. if (llama_model_meta_val_str(model, key, buf, sizeof(buf)) > 0) {
  819. char * end = nullptr;
  820. int32_t v = strtol(buf, &end, 10);
  821. if (end && end != buf) dst = v;
  822. }
  823. };
  824. auto get_float = [&](const char * key, float & dst, uint64_t user_config) {
  825. if (config & user_config) return;
  826. char buf[128] = {0};
  827. if (llama_model_meta_val_str(model, key, buf, sizeof(buf)) > 0) {
  828. char * end = nullptr;
  829. float v = strtof(buf, &end);
  830. if (end && end != buf) dst = v;
  831. }
  832. };
  833. // Sampling sequence
  834. if (!(config & common_params_sampling_config::COMMON_PARAMS_SAMPLING_CONFIG_SAMPLERS)) {
  835. char buf[512] = {0};
  836. if (llama_model_meta_val_str(model, llama_model_meta_key_str(LLAMA_MODEL_META_KEY_SAMPLING_SEQUENCE), buf, sizeof(buf)) > 0) {
  837. const std::vector<std::string> sampler_names = string_split<std::string>(std::string(buf), ';');
  838. if (!sampler_names.empty()) {
  839. sparams.samplers = common_sampler_types_from_names(sampler_names, true);
  840. }
  841. }
  842. }
  843. get_int32(llama_model_meta_key_str(LLAMA_MODEL_META_KEY_SAMPLING_TOP_K), sparams.top_k, common_params_sampling_config::COMMON_PARAMS_SAMPLING_CONFIG_TOP_K);
  844. get_float(llama_model_meta_key_str(LLAMA_MODEL_META_KEY_SAMPLING_TOP_P), sparams.top_p, common_params_sampling_config::COMMON_PARAMS_SAMPLING_CONFIG_TOP_P);
  845. get_float(llama_model_meta_key_str(LLAMA_MODEL_META_KEY_SAMPLING_MIN_P), sparams.min_p, common_params_sampling_config::COMMON_PARAMS_SAMPLING_CONFIG_MIN_P);
  846. get_float(llama_model_meta_key_str(LLAMA_MODEL_META_KEY_SAMPLING_XTC_PROBABILITY), sparams.xtc_probability, common_params_sampling_config::COMMON_PARAMS_SAMPLING_CONFIG_XTC_PROBABILITY);
  847. get_float(llama_model_meta_key_str(LLAMA_MODEL_META_KEY_SAMPLING_XTC_THRESHOLD), sparams.xtc_threshold, common_params_sampling_config::COMMON_PARAMS_SAMPLING_CONFIG_XTC_THRESHOLD);
  848. get_float(llama_model_meta_key_str(LLAMA_MODEL_META_KEY_SAMPLING_TEMP), sparams.temp, common_params_sampling_config::COMMON_PARAMS_SAMPLING_CONFIG_TEMP);
  849. get_int32(llama_model_meta_key_str(LLAMA_MODEL_META_KEY_SAMPLING_PENALTY_LAST_N), sparams.penalty_last_n, common_params_sampling_config::COMMON_PARAMS_SAMPLING_CONFIG_PENALTY_LAST_N);
  850. get_float(llama_model_meta_key_str(LLAMA_MODEL_META_KEY_SAMPLING_PENALTY_REPEAT), sparams.penalty_repeat, common_params_sampling_config::COMMON_PARAMS_SAMPLING_CONFIG_PENALTY_REPEAT);
  851. get_int32(llama_model_meta_key_str(LLAMA_MODEL_META_KEY_SAMPLING_MIROSTAT), sparams.mirostat, common_params_sampling_config::COMMON_PARAMS_SAMPLING_CONFIG_MIROSTAT);
  852. get_float(llama_model_meta_key_str(LLAMA_MODEL_META_KEY_SAMPLING_MIROSTAT_TAU), sparams.mirostat_tau, common_params_sampling_config::COMMON_PARAMS_SAMPLING_CONFIG_MIROSTAT_TAU);
  853. get_float(llama_model_meta_key_str(LLAMA_MODEL_META_KEY_SAMPLING_MIROSTAT_ETA), sparams.mirostat_eta, common_params_sampling_config::COMMON_PARAMS_SAMPLING_CONFIG_MIROSTAT_ETA);
  854. }
  855. struct common_init_result common_init_from_params(common_params & params) {
  856. common_init_result iparams;
  857. auto mparams = common_model_params_to_llama(params);
  858. llama_model * model = llama_model_load_from_file(params.model.path.c_str(), mparams);
  859. if (model == NULL) {
  860. LOG_ERR("%s: failed to load model '%s', try reducing --n-gpu-layers if you're running out of VRAM\n",
  861. __func__, params.model.path.c_str());
  862. return iparams;
  863. }
  864. common_init_sampler_from_model(model, params.sampling);
  865. const llama_vocab * vocab = llama_model_get_vocab(model);
  866. auto cparams = common_context_params_to_llama(params);
  867. llama_context * lctx = llama_init_from_model(model, cparams);
  868. if (lctx == NULL) {
  869. LOG_ERR("%s: failed to create context with model '%s', try reducing --n-gpu-layers if you're running out of VRAM\n",
  870. __func__, params.model.path.c_str());
  871. llama_model_free(model);
  872. return iparams;
  873. }
  874. if (params.ctx_shift && !llama_memory_can_shift(llama_get_memory(lctx))) {
  875. LOG_WRN("%s: KV cache shifting is not supported for this context, disabling KV cache shifting\n", __func__);
  876. params.ctx_shift = false;
  877. }
  878. if (!params.control_vectors.empty()) {
  879. if (params.control_vector_layer_start <= 0) params.control_vector_layer_start = 1;
  880. if (params.control_vector_layer_end <= 0) params.control_vector_layer_end = llama_model_n_layer(model);
  881. const auto cvec = common_control_vector_load(params.control_vectors);
  882. if (cvec.n_embd == -1) {
  883. llama_free(lctx);
  884. llama_model_free(model);
  885. return iparams;
  886. }
  887. int err = llama_apply_adapter_cvec(
  888. lctx,
  889. cvec.data.data(),
  890. cvec.data.size(),
  891. cvec.n_embd,
  892. params.control_vector_layer_start,
  893. params.control_vector_layer_end);
  894. if (err) {
  895. llama_free(lctx);
  896. llama_model_free(model);
  897. return iparams;
  898. }
  899. }
  900. if (llama_pooling_type(lctx) == LLAMA_POOLING_TYPE_RANK) {
  901. bool ok = true;
  902. if (llama_vocab_bos(vocab) == LLAMA_TOKEN_NULL) {
  903. LOG_WRN("%s: warning: vocab does not have a BOS token, reranking will not work\n", __func__);
  904. ok = false;
  905. }
  906. bool has_eos = llama_vocab_eos(vocab) != LLAMA_TOKEN_NULL;
  907. bool has_sep = llama_vocab_sep(vocab) != LLAMA_TOKEN_NULL;
  908. bool has_rerank_prompt = llama_model_chat_template(model, "rerank") != NULL;
  909. if (!has_eos && !has_sep && !has_rerank_prompt) {
  910. LOG_WRN("%s: warning: vocab does not have an EOS token, SEP token, or rerank prompt. Reranking will not work\n", __func__);
  911. ok = false;
  912. } else if (!has_eos) {
  913. LOG_WRN("%s: warning: vocab does not have an EOS token, using SEP token as fallback\n", __func__);
  914. }
  915. if (!ok) {
  916. llama_free(lctx);
  917. llama_model_free(model);
  918. return iparams;
  919. }
  920. }
  921. // load and optionally apply lora adapters
  922. for (auto & la : params.lora_adapters) {
  923. llama_adapter_lora_ptr lora;
  924. lora.reset(llama_adapter_lora_init(model, la.path.c_str()));
  925. if (lora == nullptr) {
  926. LOG_ERR("%s: failed to apply lora adapter '%s'\n", __func__, la.path.c_str());
  927. llama_free(lctx);
  928. llama_model_free(model);
  929. return iparams;
  930. }
  931. char buf[1024];
  932. la.ptr = lora.get();
  933. llama_adapter_meta_val_str(la.ptr, "adapter.lora.task_name", buf, sizeof(buf));
  934. la.task_name = buf;
  935. llama_adapter_meta_val_str(la.ptr, "adapter.lora.prompt_prefix", buf, sizeof(buf));
  936. la.prompt_prefix = buf;
  937. iparams.lora.emplace_back(std::move(lora)); // copy to list of loaded adapters
  938. }
  939. if (!params.lora_init_without_apply) {
  940. common_set_adapter_lora(lctx, params.lora_adapters);
  941. }
  942. if (params.sampling.ignore_eos && llama_vocab_eos(vocab) == LLAMA_TOKEN_NULL) {
  943. LOG_WRN("%s: warning: vocab does not have an EOS token, ignoring --ignore-eos\n", __func__);
  944. params.sampling.ignore_eos = false;
  945. }
  946. // initialize once
  947. for (llama_token i = 0; i < llama_vocab_n_tokens(vocab); i++) {
  948. if (llama_vocab_is_eog(vocab, i)) {
  949. LOG_INF("%s: added %s logit bias = %f\n", __func__, common_token_to_piece(lctx, i).c_str(), -INFINITY);
  950. params.sampling.logit_bias_eog.push_back({i, -INFINITY});
  951. }
  952. }
  953. if (params.sampling.ignore_eos) {
  954. // add EOG biases to the active set of logit biases
  955. params.sampling.logit_bias.insert(
  956. params.sampling.logit_bias.end(),
  957. params.sampling.logit_bias_eog.begin(), params.sampling.logit_bias_eog.end());
  958. }
  959. if (params.sampling.penalty_last_n == -1) {
  960. LOG_INF("%s: setting penalty_last_n to ctx_size = %d\n", __func__, llama_n_ctx(lctx));
  961. params.sampling.penalty_last_n = llama_n_ctx(lctx);
  962. }
  963. if (params.sampling.dry_penalty_last_n == -1) {
  964. LOG_INF("%s: setting dry_penalty_last_n to ctx_size = %d\n", __func__, llama_n_ctx(lctx));
  965. params.sampling.dry_penalty_last_n = llama_n_ctx(lctx);
  966. }
  967. if (params.warmup) {
  968. LOG_WRN("%s: warming up the model with an empty run - please wait ... (--no-warmup to disable)\n", __func__);
  969. llama_set_warmup(lctx, true);
  970. std::vector<llama_token> tmp;
  971. llama_token bos = llama_vocab_bos(vocab);
  972. llama_token eos = llama_vocab_eos(vocab);
  973. // some models (e.g. T5) don't have a BOS token
  974. if (bos != LLAMA_TOKEN_NULL) {
  975. tmp.push_back(bos);
  976. }
  977. if (eos != LLAMA_TOKEN_NULL) {
  978. tmp.push_back(eos);
  979. }
  980. if (tmp.empty()) {
  981. tmp.push_back(0);
  982. }
  983. if (llama_model_has_encoder(model)) {
  984. llama_encode(lctx, llama_batch_get_one(tmp.data(), tmp.size()));
  985. llama_token decoder_start_token_id = llama_model_decoder_start_token(model);
  986. if (decoder_start_token_id == LLAMA_TOKEN_NULL) {
  987. decoder_start_token_id = bos;
  988. }
  989. tmp.clear();
  990. tmp.push_back(decoder_start_token_id);
  991. }
  992. if (llama_model_has_decoder(model)) {
  993. llama_decode(lctx, llama_batch_get_one(tmp.data(), std::min(tmp.size(), (size_t) params.n_batch)));
  994. }
  995. llama_memory_clear(llama_get_memory(lctx), true);
  996. llama_synchronize(lctx);
  997. llama_perf_context_reset(lctx);
  998. llama_set_warmup(lctx, false);
  999. }
  1000. iparams.model.reset(model);
  1001. iparams.context.reset(lctx);
  1002. return iparams;
  1003. }
  1004. std::string get_model_endpoint() {
  1005. const char * model_endpoint_env = getenv("MODEL_ENDPOINT");
  1006. // We still respect the use of environment-variable "HF_ENDPOINT" for backward-compatibility.
  1007. const char * hf_endpoint_env = getenv("HF_ENDPOINT");
  1008. const char * endpoint_env = model_endpoint_env ? model_endpoint_env : hf_endpoint_env;
  1009. std::string model_endpoint = "https://huggingface.co/";
  1010. if (endpoint_env) {
  1011. model_endpoint = endpoint_env;
  1012. if (model_endpoint.back() != '/') model_endpoint += '/';
  1013. }
  1014. return model_endpoint;
  1015. }
  1016. void common_set_adapter_lora(struct llama_context * ctx, std::vector<common_adapter_lora_info> & lora) {
  1017. llama_clear_adapter_lora(ctx);
  1018. for (auto & la : lora) {
  1019. if (la.scale != 0.0f) {
  1020. llama_set_adapter_lora(ctx, la.ptr, la.scale);
  1021. }
  1022. }
  1023. }
  1024. struct llama_model_params common_model_params_to_llama(common_params & params) {
  1025. auto mparams = llama_model_default_params();
  1026. if (!params.devices.empty()) {
  1027. mparams.devices = params.devices.data();
  1028. }
  1029. if (params.n_gpu_layers != -1) {
  1030. mparams.n_gpu_layers = params.n_gpu_layers;
  1031. }
  1032. mparams.main_gpu = params.main_gpu;
  1033. mparams.split_mode = params.split_mode;
  1034. mparams.tensor_split = params.tensor_split;
  1035. mparams.use_mmap = params.use_mmap;
  1036. mparams.use_mlock = params.use_mlock;
  1037. mparams.check_tensors = params.check_tensors;
  1038. mparams.use_extra_bufts = !params.no_extra_bufts;
  1039. mparams.no_host = params.no_host;
  1040. if (params.kv_overrides.empty()) {
  1041. mparams.kv_overrides = NULL;
  1042. } else {
  1043. GGML_ASSERT(params.kv_overrides.back().key[0] == 0 && "KV overrides not terminated with empty key");
  1044. mparams.kv_overrides = params.kv_overrides.data();
  1045. }
  1046. if (params.tensor_buft_overrides.empty()) {
  1047. mparams.tensor_buft_overrides = NULL;
  1048. } else {
  1049. GGML_ASSERT(params.tensor_buft_overrides.back().pattern == nullptr && "Tensor buffer overrides not terminated with empty pattern");
  1050. mparams.tensor_buft_overrides = params.tensor_buft_overrides.data();
  1051. }
  1052. mparams.progress_callback = params.load_progress_callback;
  1053. mparams.progress_callback_user_data = params.load_progress_callback_user_data;
  1054. return mparams;
  1055. }
  1056. struct llama_context_params common_context_params_to_llama(const common_params & params) {
  1057. auto cparams = llama_context_default_params();
  1058. cparams.n_ctx = params.n_ctx;
  1059. cparams.n_seq_max = params.n_parallel;
  1060. cparams.n_batch = params.n_batch;
  1061. cparams.n_ubatch = params.n_ubatch;
  1062. cparams.n_threads = params.cpuparams.n_threads;
  1063. cparams.n_threads_batch = params.cpuparams_batch.n_threads == -1 ?
  1064. params.cpuparams.n_threads : params.cpuparams_batch.n_threads;
  1065. cparams.embeddings = params.embedding;
  1066. cparams.rope_scaling_type = params.rope_scaling_type;
  1067. cparams.rope_freq_base = params.rope_freq_base;
  1068. cparams.rope_freq_scale = params.rope_freq_scale;
  1069. cparams.yarn_ext_factor = params.yarn_ext_factor;
  1070. cparams.yarn_attn_factor = params.yarn_attn_factor;
  1071. cparams.yarn_beta_fast = params.yarn_beta_fast;
  1072. cparams.yarn_beta_slow = params.yarn_beta_slow;
  1073. cparams.yarn_orig_ctx = params.yarn_orig_ctx;
  1074. cparams.pooling_type = params.pooling_type;
  1075. cparams.attention_type = params.attention_type;
  1076. cparams.flash_attn_type = params.flash_attn_type;
  1077. cparams.cb_eval = params.cb_eval;
  1078. cparams.cb_eval_user_data = params.cb_eval_user_data;
  1079. cparams.offload_kqv = !params.no_kv_offload;
  1080. cparams.no_perf = params.no_perf;
  1081. cparams.op_offload = !params.no_op_offload;
  1082. cparams.swa_full = params.swa_full;
  1083. cparams.kv_unified = params.kv_unified;
  1084. cparams.type_k = params.cache_type_k;
  1085. cparams.type_v = params.cache_type_v;
  1086. return cparams;
  1087. }
  1088. struct ggml_threadpool_params ggml_threadpool_params_from_cpu_params(const cpu_params & params) {
  1089. struct ggml_threadpool_params tpp;
  1090. ggml_threadpool_params_init(&tpp, params.n_threads); // setup the defaults
  1091. if (params.mask_valid) {
  1092. std::memcpy(&tpp.cpumask, &params.cpumask, GGML_MAX_N_THREADS);
  1093. }
  1094. tpp.prio = params.priority;
  1095. tpp.poll = params.poll;
  1096. tpp.strict_cpu = params.strict_cpu;
  1097. return tpp;
  1098. }
  1099. //
  1100. // Batch utils
  1101. //
  1102. void common_batch_clear(struct llama_batch & batch) {
  1103. batch.n_tokens = 0;
  1104. }
  1105. void common_batch_add(
  1106. struct llama_batch & batch,
  1107. llama_token id,
  1108. llama_pos pos,
  1109. const std::vector<llama_seq_id> & seq_ids,
  1110. bool logits) {
  1111. GGML_ASSERT(batch.seq_id[batch.n_tokens] && "llama_batch size exceeded");
  1112. batch.token [batch.n_tokens] = id;
  1113. batch.pos [batch.n_tokens] = pos;
  1114. batch.n_seq_id[batch.n_tokens] = seq_ids.size();
  1115. for (size_t i = 0; i < seq_ids.size(); ++i) {
  1116. batch.seq_id[batch.n_tokens][i] = seq_ids[i];
  1117. }
  1118. batch.logits [batch.n_tokens] = logits;
  1119. batch.n_tokens++;
  1120. }
  1121. //
  1122. // Token utils
  1123. //
  1124. size_t common_lcp(const llama_tokens & a, const llama_tokens & b) {
  1125. size_t i;
  1126. for (i = 0; i < a.size() && i < b.size() && a[i] == b[i]; i++) {}
  1127. return i;
  1128. }
  1129. size_t common_lcs(const llama_tokens & a, const llama_tokens & b) {
  1130. // check for empty sequences
  1131. if (a.empty() || b.empty()) {
  1132. return 0;
  1133. }
  1134. // get the lengths of the input sequences
  1135. size_t a_len = a.size();
  1136. size_t b_len = b.size();
  1137. // initialize the maximum length of the longest common subsequence (LCS)
  1138. size_t max_length = 0;
  1139. // use two rows instead of a 2D matrix to optimize space
  1140. std::vector<size_t> prev_row(b_len + 1, 0);
  1141. std::vector<size_t> curr_row(b_len + 1, 0);
  1142. // iterate through the elements of a
  1143. for (size_t i = 1; i <= a_len; i++) {
  1144. // iterate through the elements of b
  1145. for (size_t j = 1; j <= b_len; j++) {
  1146. // if elements at the current positions match
  1147. if (a[i - 1] == b[j - 1]) {
  1148. // if it's the first element of either sequences, set LCS length to 1
  1149. if (i == 1 || j == 1) {
  1150. curr_row[j] = 1;
  1151. } else {
  1152. // increment LCS length by 1 compared to the previous element
  1153. curr_row[j] = prev_row[j - 1] + 1;
  1154. }
  1155. // update max_length if necessary
  1156. if (curr_row[j] > max_length) {
  1157. max_length = curr_row[j];
  1158. }
  1159. } else {
  1160. // reset LCS length if elements don't match
  1161. curr_row[j] = 0;
  1162. }
  1163. }
  1164. // update the previous row for the next iteration
  1165. prev_row = curr_row;
  1166. }
  1167. // return the maximum length of the LCS
  1168. return max_length;
  1169. }
  1170. //
  1171. // Vocab utils
  1172. //
  1173. std::vector<llama_token> common_tokenize(
  1174. const struct llama_context * ctx,
  1175. const std::string & text,
  1176. bool add_special,
  1177. bool parse_special) {
  1178. const llama_model * model = llama_get_model(ctx);
  1179. const llama_vocab * vocab = llama_model_get_vocab(model);
  1180. return common_tokenize(vocab, text, add_special, parse_special);
  1181. }
  1182. std::vector<llama_token> common_tokenize(
  1183. const struct llama_vocab * vocab,
  1184. const std::string & text,
  1185. bool add_special,
  1186. bool parse_special) {
  1187. // upper limit for the number of tokens
  1188. int n_tokens = text.length() + 2 * add_special;
  1189. std::vector<llama_token> result(n_tokens);
  1190. n_tokens = llama_tokenize(vocab, text.data(), text.length(), result.data(), result.size(), add_special, parse_special);
  1191. if (n_tokens == std::numeric_limits<int32_t>::min()) {
  1192. throw std::runtime_error("Tokenization failed: input text too large, tokenization result exceeds int32_t limit");
  1193. }
  1194. if (n_tokens < 0) {
  1195. result.resize(-n_tokens);
  1196. int check = llama_tokenize(vocab, text.data(), text.length(), result.data(), result.size(), add_special, parse_special);
  1197. GGML_ASSERT(check == -n_tokens);
  1198. } else {
  1199. result.resize(n_tokens);
  1200. }
  1201. return result;
  1202. }
  1203. std::string common_token_to_piece(const struct llama_context * ctx, llama_token token, bool special) {
  1204. const llama_model * model = llama_get_model(ctx);
  1205. const llama_vocab * vocab = llama_model_get_vocab(model);
  1206. return common_token_to_piece(vocab, token, special);
  1207. }
  1208. std::string common_token_to_piece(const struct llama_vocab * vocab, llama_token token, bool special) {
  1209. std::string piece;
  1210. piece.resize(piece.capacity()); // using string internal cache, 15 bytes + '\n'
  1211. const int n_chars = llama_token_to_piece(vocab, token, &piece[0], piece.size(), 0, special);
  1212. if (n_chars < 0) {
  1213. piece.resize(-n_chars);
  1214. int check = llama_token_to_piece(vocab, token, &piece[0], piece.size(), 0, special);
  1215. GGML_ASSERT(check == -n_chars);
  1216. }
  1217. else {
  1218. piece.resize(n_chars);
  1219. }
  1220. return piece;
  1221. }
  1222. std::string common_detokenize(const struct llama_context * ctx, const std::vector<llama_token> & tokens, bool special) {
  1223. const llama_model * model = llama_get_model(ctx);
  1224. const llama_vocab * vocab = llama_model_get_vocab(model);
  1225. return common_detokenize(vocab, tokens, special);
  1226. }
  1227. std::string common_detokenize(const struct llama_vocab * vocab, const std::vector<llama_token> & tokens, bool special) {
  1228. std::string text;
  1229. text.resize(std::max(text.capacity(), tokens.size()));
  1230. int32_t n_chars = llama_detokenize(vocab, tokens.data(), (int32_t)tokens.size(), &text[0], (int32_t)text.size(), false, special);
  1231. if (n_chars < 0) {
  1232. text.resize(-n_chars);
  1233. n_chars = llama_detokenize(vocab, tokens.data(), (int32_t)tokens.size(), &text[0], (int32_t)text.size(), false, special);
  1234. GGML_ASSERT(n_chars <= (int32_t)text.size()); // whitespace trimming is performed after per-token detokenization
  1235. }
  1236. text.resize(n_chars);
  1237. // NOTE: the original tokenizer decodes bytes after collecting the pieces.
  1238. return text;
  1239. }
  1240. //
  1241. // Embedding utils
  1242. //
  1243. void common_embd_normalize(const float * inp, float * out, int n, int embd_norm) {
  1244. double sum = 0.0;
  1245. switch (embd_norm) {
  1246. case -1: // no normalisation
  1247. sum = 1.0;
  1248. break;
  1249. case 0: // max absolute
  1250. for (int i = 0; i < n; i++) {
  1251. if (sum < std::abs(inp[i])) {
  1252. sum = std::abs(inp[i]);
  1253. }
  1254. }
  1255. sum /= 32760.0; // make an int16 range
  1256. break;
  1257. case 2: // euclidean
  1258. for (int i = 0; i < n; i++) {
  1259. sum += inp[i] * inp[i];
  1260. }
  1261. sum = std::sqrt(sum);
  1262. break;
  1263. default: // p-norm (euclidean is p-norm p=2)
  1264. for (int i = 0; i < n; i++) {
  1265. sum += std::pow(std::abs(inp[i]), embd_norm);
  1266. }
  1267. sum = std::pow(sum, 1.0 / embd_norm);
  1268. break;
  1269. }
  1270. const float norm = sum > 0.0 ? 1.0 / sum : 0.0f;
  1271. for (int i = 0; i < n; i++) {
  1272. out[i] = inp[i] * norm;
  1273. }
  1274. }
  1275. float common_embd_similarity_cos(const float * embd1, const float * embd2, int n){
  1276. double sum = 0.0;
  1277. double sum1 = 0.0;
  1278. double sum2 = 0.0;
  1279. for (int i = 0; i < n; i++) {
  1280. sum += embd1[i] * embd2[i];
  1281. sum1 += embd1[i] * embd1[i];
  1282. sum2 += embd2[i] * embd2[i];
  1283. }
  1284. // Handle the case where one or both vectors are zero vectors
  1285. if (sum1 == 0.0 || sum2 == 0.0) {
  1286. if (sum1 == 0.0 && sum2 == 0.0) {
  1287. return 1.0f; // two zero vectors are similar
  1288. }
  1289. return 0.0f;
  1290. }
  1291. return sum / (sqrt(sum1) * sqrt(sum2));
  1292. }
  1293. //
  1294. // Control vector utils
  1295. //
  1296. static common_control_vector_data common_control_vector_load_one(const common_control_vector_load_info & load_info) {
  1297. common_control_vector_data result = { -1, {} };
  1298. ggml_context * ctx = nullptr;
  1299. struct gguf_init_params meta_gguf_params = {
  1300. /* .no_alloc = */ false,
  1301. /* .ctx = */ &ctx,
  1302. };
  1303. struct gguf_context * ctx_gguf = gguf_init_from_file(load_info.fname.c_str(), meta_gguf_params);
  1304. if (!ctx_gguf) {
  1305. LOG_ERR("%s: failed to load control vector file from %s\n", __func__, load_info.fname.c_str());
  1306. return result;
  1307. }
  1308. int32_t n_tensors = gguf_get_n_tensors(ctx_gguf);
  1309. if (n_tensors == 0) {
  1310. LOG_WRN("%s: no direction tensors found in %s\n", __func__, load_info.fname.c_str());
  1311. }
  1312. for (int i = 0; i < n_tensors; i++) {
  1313. std::string name = gguf_get_tensor_name(ctx_gguf, i);
  1314. int layer_idx = -1;
  1315. // split on '.'
  1316. size_t dotpos = name.find('.');
  1317. if (dotpos != std::string::npos && name.substr(0, dotpos) == "direction") {
  1318. try {
  1319. layer_idx = std::stoi(name.substr(dotpos + 1));
  1320. } catch (...) {
  1321. layer_idx = -1;
  1322. }
  1323. }
  1324. if (layer_idx < 0) {
  1325. LOG_ERR("%s: invalid/unparsable direction tensor layer index in %s\n", __func__, load_info.fname.c_str());
  1326. result.n_embd = -1;
  1327. break;
  1328. } else if (layer_idx == 0) {
  1329. LOG_ERR("%s: invalid (zero) direction tensor layer index in %s\n", __func__, load_info.fname.c_str());
  1330. result.n_embd = -1;
  1331. break;
  1332. }
  1333. struct ggml_tensor * tensor = ggml_get_tensor(ctx, name.c_str());
  1334. if (tensor->type != GGML_TYPE_F32) {
  1335. LOG_ERR("%s: invalid (non-F32) direction tensor type in %s\n", __func__, load_info.fname.c_str());
  1336. result.n_embd = -1;
  1337. break;
  1338. }
  1339. if (ggml_n_dims(tensor) != 1) {
  1340. LOG_ERR("%s: invalid (non-1D) direction tensor shape in %s\n", __func__, load_info.fname.c_str());
  1341. result.n_embd = -1;
  1342. break;
  1343. }
  1344. if (result.n_embd == -1) {
  1345. result.n_embd = ggml_nelements(tensor);
  1346. } else if (ggml_nelements(tensor) != result.n_embd) {
  1347. LOG_ERR("%s: direction tensor in %s does not match previous dimensions\n", __func__, load_info.fname.c_str());
  1348. result.n_embd = -1;
  1349. break;
  1350. }
  1351. // extend if necessary - do not store data for layer 0 (it's not used)
  1352. result.data.resize(std::max(result.data.size(), static_cast<size_t>(result.n_embd * layer_idx)), 0.0f);
  1353. const float * src = (const float *) tensor->data;
  1354. float * dst = result.data.data() + result.n_embd * (layer_idx - 1); // layer 1 at [0]
  1355. for (int j = 0; j < result.n_embd; j++) {
  1356. dst[j] += src[j] * load_info.strength; // allows multiple directions for same layer in same file
  1357. }
  1358. }
  1359. if (result.n_embd == -1) {
  1360. LOG_WRN("%s: skipping %s due to invalid direction tensors\n", __func__, load_info.fname.c_str());
  1361. result.data.clear();
  1362. }
  1363. gguf_free(ctx_gguf);
  1364. ggml_free(ctx);
  1365. return result;
  1366. }
  1367. common_control_vector_data common_control_vector_load(const std::vector<common_control_vector_load_info> & load_infos) {
  1368. common_control_vector_data result = { -1, {} };
  1369. for (const auto & info : load_infos) {
  1370. auto cur = common_control_vector_load_one(info);
  1371. if (cur.n_embd == -1) {
  1372. result.n_embd = -1;
  1373. break;
  1374. }
  1375. if (result.n_embd != -1 && result.n_embd != cur.n_embd) {
  1376. LOG_ERR("%s: control vectors in %s does not match previous dimensions\n", __func__, info.fname.c_str());
  1377. result.n_embd = -1;
  1378. break;
  1379. }
  1380. if (result.n_embd == -1) {
  1381. result = std::move(cur);
  1382. } else {
  1383. result.data.resize(std::max(result.data.size(), cur.data.size()), 0.0f); // extend if necessary
  1384. for (size_t i = 0; i < cur.data.size(); i++) {
  1385. result.data[i] += cur.data[i];
  1386. }
  1387. }
  1388. }
  1389. if (result.n_embd == -1) {
  1390. LOG_ERR("%s: no valid control vector files passed\n", __func__);
  1391. result.data.clear();
  1392. }
  1393. return result;
  1394. }
  1395. ggml_opt_dataset_t common_opt_dataset_init(struct llama_context * ctx, const std::vector<llama_token> & tokens, int64_t stride) {
  1396. const int64_t ne_datapoint = llama_n_ctx(ctx);
  1397. const int64_t ndata = (tokens.size() - ne_datapoint - 1) / stride;
  1398. ggml_opt_dataset_t result = ggml_opt_dataset_init(
  1399. GGML_TYPE_I32, GGML_TYPE_I32, ne_datapoint, ne_datapoint, ndata, /*ndata_shard =*/ 1);
  1400. llama_token * data = (llama_token *) ggml_opt_dataset_data(result)->data;
  1401. llama_token * labels = (llama_token *) ggml_opt_dataset_labels(result)->data;
  1402. for (int64_t idata = 0; idata < ndata; ++idata) {
  1403. memcpy(data + idata*ne_datapoint, tokens.data() + idata*stride + 0, ne_datapoint*sizeof(llama_token));
  1404. memcpy(labels + idata*ne_datapoint, tokens.data() + idata*stride + 1, ne_datapoint*sizeof(llama_token));
  1405. }
  1406. return result;
  1407. }
  1408. ggml_opt_optimizer_params common_opt_lr_pars(void * userdata) {
  1409. ggml_opt_optimizer_params result = ggml_opt_get_default_optimizer_params(nullptr);
  1410. const lr_opt & d = *(lr_opt *) userdata;
  1411. result.adamw.alpha = result.sgd.alpha = d.get_lr(d.epoch);
  1412. result.sgd.wd = result.adamw.wd = d.wd;
  1413. return result;
  1414. }
  1415. // TODO make all command line args case-insensitive
  1416. static inline bool eq_case_insensitive(char const* a, char const* b) {
  1417. return !
  1418. #if defined(_MSC_VER)
  1419. _stricmp
  1420. #else
  1421. strcasecmp
  1422. #endif // defined(_MSC_VER)
  1423. (a, b);
  1424. }
  1425. enum ggml_opt_optimizer_type common_opt_get_optimizer(const char * n) {
  1426. if (eq_case_insensitive("adamw", n)) {
  1427. return GGML_OPT_OPTIMIZER_TYPE_ADAMW;
  1428. }
  1429. if (eq_case_insensitive("sgd", n)) {
  1430. return GGML_OPT_OPTIMIZER_TYPE_SGD;
  1431. }
  1432. return GGML_OPT_OPTIMIZER_TYPE_COUNT;
  1433. }
  1434. // TODO simplify to use just log and exp
  1435. static float const k_log_2 = std::log(2.f);
  1436. void lr_opt::init() {
  1437. if (lr_min > 0 && lr_min < lr0) {
  1438. float nhalf = std::log(lr0 / lr_min) / k_log_2;
  1439. float e = epochs;
  1440. if (decay_epochs > 0 && decay_epochs < e) {
  1441. e = decay_epochs;
  1442. } else {
  1443. decay_epochs = e;
  1444. }
  1445. scale_epoch = nhalf / e;
  1446. }
  1447. }
  1448. float lr_opt::get_lr(float epoch) const {
  1449. float r = lr_min <= 0 ? lr0 :
  1450. epoch >= decay_epochs ? lr_min :
  1451. lr0 * std::pow(0.5f, epoch * scale_epoch);
  1452. LOG_INF("epoch %.2g lr=%.2g\n", epoch, r);
  1453. return r;
  1454. }