1
0

common.cpp 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784
  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, bool allow_subdirs) {
  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 == '*' // Illegal characters
  647. || c == '?' || c == '"' || c == '<' || c == '>' || c == '|') {
  648. return false;
  649. }
  650. if (!allow_subdirs && (c == '/' || c == '\\')) {
  651. // Subdirectories not allowed, reject path separators
  652. return false;
  653. }
  654. }
  655. // Reject any leading or trailing ' ', or any trailing '.', these are stripped on Windows and will cause a different filename
  656. // Unicode and other whitespace is not affected, only 0x20 space
  657. if (filename.front() == ' ' || filename.back() == ' ' || filename.back() == '.') {
  658. return false;
  659. }
  660. // Reject any ".." (currently stricter than necessary, it should be fine to just check for == ".." instead)
  661. if (filename.find("..") != std::string::npos) {
  662. return false;
  663. }
  664. // Reject "."
  665. if (filename == ".") {
  666. return false;
  667. }
  668. return true;
  669. }
  670. #include <iostream>
  671. #ifdef _WIN32
  672. static std::wstring utf8_to_wstring(const std::string & str) {
  673. if (str.empty()) {
  674. return std::wstring();
  675. }
  676. int size = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), (int)str.size(), NULL, 0);
  677. if (size <= 0) {
  678. return std::wstring();
  679. }
  680. std::wstring wstr(size, 0);
  681. MultiByteToWideChar(CP_UTF8, 0, str.c_str(), (int)str.size(), &wstr[0], size);
  682. return wstr;
  683. }
  684. #endif
  685. // returns true if successful, false otherwise
  686. bool fs_create_directory_with_parents(const std::string & path) {
  687. #ifdef _WIN32
  688. std::wstring wpath = utf8_to_wstring(path);
  689. // if the path already exists, check whether it's a directory
  690. const DWORD attributes = GetFileAttributesW(wpath.c_str());
  691. if ((attributes != INVALID_FILE_ATTRIBUTES) && (attributes & FILE_ATTRIBUTE_DIRECTORY)) {
  692. return true;
  693. }
  694. size_t pos_slash = 0;
  695. // process path from front to back, procedurally creating directories
  696. while ((pos_slash = path.find('\\', pos_slash)) != std::string::npos) {
  697. const std::wstring subpath = wpath.substr(0, pos_slash);
  698. pos_slash += 1;
  699. // skip the drive letter, in some systems it can return an access denied error
  700. if (subpath.length() == 2 && subpath[1] == ':') {
  701. continue;
  702. }
  703. const bool success = CreateDirectoryW(subpath.c_str(), NULL);
  704. if (!success) {
  705. const DWORD error = GetLastError();
  706. // if the path already exists, ensure that it's a directory
  707. if (error == ERROR_ALREADY_EXISTS) {
  708. const DWORD attributes = GetFileAttributesW(subpath.c_str());
  709. if (attributes == INVALID_FILE_ATTRIBUTES || !(attributes & FILE_ATTRIBUTE_DIRECTORY)) {
  710. return false;
  711. }
  712. } else {
  713. return false;
  714. }
  715. }
  716. }
  717. return true;
  718. #else
  719. // if the path already exists, check whether it's a directory
  720. struct stat info;
  721. if (stat(path.c_str(), &info) == 0) {
  722. return S_ISDIR(info.st_mode);
  723. }
  724. size_t pos_slash = 1; // skip leading slashes for directory creation
  725. // process path from front to back, procedurally creating directories
  726. while ((pos_slash = path.find('/', pos_slash)) != std::string::npos) {
  727. const std::string subpath = path.substr(0, pos_slash);
  728. struct stat info;
  729. // if the path already exists, ensure that it's a directory
  730. if (stat(subpath.c_str(), &info) == 0) {
  731. if (!S_ISDIR(info.st_mode)) {
  732. return false;
  733. }
  734. } else {
  735. // create parent directories
  736. const int ret = mkdir(subpath.c_str(), 0755);
  737. if (ret != 0) {
  738. return false;
  739. }
  740. }
  741. pos_slash += 1;
  742. }
  743. return true;
  744. #endif // _WIN32
  745. }
  746. bool fs_is_directory(const std::string & path) {
  747. std::filesystem::path dir(path);
  748. return std::filesystem::exists(dir) && std::filesystem::is_directory(dir);
  749. }
  750. std::string fs_get_cache_directory() {
  751. std::string cache_directory = "";
  752. auto ensure_trailing_slash = [](std::string p) {
  753. // Make sure to add trailing slash
  754. if (p.back() != DIRECTORY_SEPARATOR) {
  755. p += DIRECTORY_SEPARATOR;
  756. }
  757. return p;
  758. };
  759. if (getenv("LLAMA_CACHE")) {
  760. cache_directory = std::getenv("LLAMA_CACHE");
  761. } else {
  762. #if defined(__linux__) || defined(__FreeBSD__) || defined(_AIX) || defined(__OpenBSD__)
  763. if (std::getenv("XDG_CACHE_HOME")) {
  764. cache_directory = std::getenv("XDG_CACHE_HOME");
  765. } else if (std::getenv("HOME")) {
  766. cache_directory = std::getenv("HOME") + std::string("/.cache/");
  767. } else {
  768. #if defined(__linux__)
  769. /* no $HOME is defined, fallback to getpwuid */
  770. struct passwd *pw = getpwuid(getuid());
  771. if ((!pw) || (!pw->pw_dir)) {
  772. throw std::runtime_error("Failed to find $HOME directory");
  773. }
  774. cache_directory = std::string(pw->pw_dir) + std::string("/.cache/");
  775. #else /* defined(__linux__) */
  776. throw std::runtime_error("Failed to find $HOME directory");
  777. #endif /* defined(__linux__) */
  778. }
  779. #elif defined(__APPLE__)
  780. cache_directory = std::getenv("HOME") + std::string("/Library/Caches/");
  781. #elif defined(_WIN32)
  782. cache_directory = std::getenv("LOCALAPPDATA");
  783. #elif defined(__EMSCRIPTEN__)
  784. GGML_ABORT("not implemented on this platform");
  785. #else
  786. # error Unknown architecture
  787. #endif
  788. cache_directory = ensure_trailing_slash(cache_directory);
  789. cache_directory += "llama.cpp";
  790. }
  791. return ensure_trailing_slash(cache_directory);
  792. }
  793. std::string fs_get_cache_file(const std::string & filename) {
  794. GGML_ASSERT(filename.find(DIRECTORY_SEPARATOR) == std::string::npos);
  795. std::string cache_directory = fs_get_cache_directory();
  796. const bool success = fs_create_directory_with_parents(cache_directory);
  797. if (!success) {
  798. throw std::runtime_error("failed to create cache directory: " + cache_directory);
  799. }
  800. return cache_directory + filename;
  801. }
  802. std::vector<common_file_info> fs_list(const std::string & path, bool include_directories) {
  803. std::vector<common_file_info> files;
  804. if (path.empty()) return files;
  805. std::filesystem::path dir(path);
  806. if (!std::filesystem::exists(dir) || !std::filesystem::is_directory(dir)) {
  807. return files;
  808. }
  809. for (const auto & entry : std::filesystem::directory_iterator(dir)) {
  810. try {
  811. // Only include regular files (skip directories)
  812. const auto & p = entry.path();
  813. if (std::filesystem::is_regular_file(p)) {
  814. common_file_info info;
  815. info.path = p.string();
  816. info.name = p.filename().string();
  817. info.is_dir = false;
  818. try {
  819. info.size = static_cast<size_t>(std::filesystem::file_size(p));
  820. } catch (const std::filesystem::filesystem_error &) {
  821. info.size = 0;
  822. }
  823. files.push_back(std::move(info));
  824. } else if (include_directories && std::filesystem::is_directory(p)) {
  825. common_file_info info;
  826. info.path = p.string();
  827. info.name = p.filename().string();
  828. info.size = 0; // Directories have no size
  829. info.is_dir = true;
  830. files.push_back(std::move(info));
  831. }
  832. } catch (const std::filesystem::filesystem_error &) {
  833. // skip entries we cannot inspect
  834. continue;
  835. }
  836. }
  837. return files;
  838. }
  839. //
  840. // TTY utils
  841. //
  842. bool tty_can_use_colors() {
  843. // Check NO_COLOR environment variable (https://no-color.org/)
  844. if (const char * no_color = std::getenv("NO_COLOR")) {
  845. if (no_color[0] != '\0') {
  846. return false;
  847. }
  848. }
  849. // Check TERM environment variable
  850. if (const char * term = std::getenv("TERM")) {
  851. if (std::strcmp(term, "dumb") == 0) {
  852. return false;
  853. }
  854. }
  855. // Check if stdout and stderr are connected to a terminal
  856. // We check both because log messages can go to either
  857. bool stdout_is_tty = isatty(fileno(stdout));
  858. bool stderr_is_tty = isatty(fileno(stderr));
  859. return stdout_is_tty || stderr_is_tty;
  860. }
  861. //
  862. // Model utils
  863. //
  864. static inline void common_init_sampler_from_model(
  865. const llama_model * model,
  866. common_params_sampling & sparams) {
  867. const uint64_t config = sparams.user_sampling_config;
  868. auto get_int32 = [&](const char * key, int32_t & dst, uint64_t user_config) {
  869. if (config & user_config) return;
  870. char buf[64] = {0};
  871. if (llama_model_meta_val_str(model, key, buf, sizeof(buf)) > 0) {
  872. char * end = nullptr;
  873. int32_t v = strtol(buf, &end, 10);
  874. if (end && end != buf) dst = v;
  875. }
  876. };
  877. auto get_float = [&](const char * key, float & dst, uint64_t user_config) {
  878. if (config & user_config) return;
  879. char buf[128] = {0};
  880. if (llama_model_meta_val_str(model, key, buf, sizeof(buf)) > 0) {
  881. char * end = nullptr;
  882. float v = strtof(buf, &end);
  883. if (end && end != buf) dst = v;
  884. }
  885. };
  886. // Sampling sequence
  887. if (!(config & common_params_sampling_config::COMMON_PARAMS_SAMPLING_CONFIG_SAMPLERS)) {
  888. char buf[512] = {0};
  889. if (llama_model_meta_val_str(model, llama_model_meta_key_str(LLAMA_MODEL_META_KEY_SAMPLING_SEQUENCE), buf, sizeof(buf)) > 0) {
  890. const std::vector<std::string> sampler_names = string_split<std::string>(std::string(buf), ';');
  891. if (!sampler_names.empty()) {
  892. sparams.samplers = common_sampler_types_from_names(sampler_names, true);
  893. }
  894. }
  895. }
  896. 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);
  897. 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);
  898. 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);
  899. 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);
  900. 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);
  901. get_float(llama_model_meta_key_str(LLAMA_MODEL_META_KEY_SAMPLING_TEMP), sparams.temp, common_params_sampling_config::COMMON_PARAMS_SAMPLING_CONFIG_TEMP);
  902. 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);
  903. 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);
  904. get_int32(llama_model_meta_key_str(LLAMA_MODEL_META_KEY_SAMPLING_MIROSTAT), sparams.mirostat, common_params_sampling_config::COMMON_PARAMS_SAMPLING_CONFIG_MIROSTAT);
  905. 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);
  906. 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);
  907. }
  908. struct common_init_result common_init_from_params(common_params & params) {
  909. common_init_result iparams;
  910. auto mparams = common_model_params_to_llama(params);
  911. llama_model * model = llama_model_load_from_file(params.model.path.c_str(), mparams);
  912. if (model == NULL) {
  913. LOG_ERR("%s: failed to load model '%s', try reducing --n-gpu-layers if you're running out of VRAM\n",
  914. __func__, params.model.path.c_str());
  915. return iparams;
  916. }
  917. common_init_sampler_from_model(model, params.sampling);
  918. const llama_vocab * vocab = llama_model_get_vocab(model);
  919. auto cparams = common_context_params_to_llama(params);
  920. llama_context * lctx = llama_init_from_model(model, cparams);
  921. if (lctx == NULL) {
  922. LOG_ERR("%s: failed to create context with model '%s', try reducing --n-gpu-layers if you're running out of VRAM\n",
  923. __func__, params.model.path.c_str());
  924. llama_model_free(model);
  925. return iparams;
  926. }
  927. if (params.ctx_shift && !llama_memory_can_shift(llama_get_memory(lctx))) {
  928. LOG_WRN("%s: KV cache shifting is not supported for this context, disabling KV cache shifting\n", __func__);
  929. params.ctx_shift = false;
  930. }
  931. if (!params.control_vectors.empty()) {
  932. if (params.control_vector_layer_start <= 0) params.control_vector_layer_start = 1;
  933. if (params.control_vector_layer_end <= 0) params.control_vector_layer_end = llama_model_n_layer(model);
  934. const auto cvec = common_control_vector_load(params.control_vectors);
  935. if (cvec.n_embd == -1) {
  936. llama_free(lctx);
  937. llama_model_free(model);
  938. return iparams;
  939. }
  940. int err = llama_apply_adapter_cvec(
  941. lctx,
  942. cvec.data.data(),
  943. cvec.data.size(),
  944. cvec.n_embd,
  945. params.control_vector_layer_start,
  946. params.control_vector_layer_end);
  947. if (err) {
  948. llama_free(lctx);
  949. llama_model_free(model);
  950. return iparams;
  951. }
  952. }
  953. if (llama_pooling_type(lctx) == LLAMA_POOLING_TYPE_RANK) {
  954. bool ok = true;
  955. if (llama_vocab_bos(vocab) == LLAMA_TOKEN_NULL) {
  956. LOG_WRN("%s: warning: vocab does not have a BOS token, reranking will not work\n", __func__);
  957. ok = false;
  958. }
  959. bool has_eos = llama_vocab_eos(vocab) != LLAMA_TOKEN_NULL;
  960. bool has_sep = llama_vocab_sep(vocab) != LLAMA_TOKEN_NULL;
  961. bool has_rerank_prompt = llama_model_chat_template(model, "rerank") != NULL;
  962. if (!has_eos && !has_sep && !has_rerank_prompt) {
  963. LOG_WRN("%s: warning: vocab does not have an EOS token, SEP token, or rerank prompt. Reranking will not work\n", __func__);
  964. ok = false;
  965. } else if (!has_eos) {
  966. LOG_WRN("%s: warning: vocab does not have an EOS token, using SEP token as fallback\n", __func__);
  967. }
  968. if (!ok) {
  969. llama_free(lctx);
  970. llama_model_free(model);
  971. return iparams;
  972. }
  973. }
  974. // load and optionally apply lora adapters
  975. for (auto & la : params.lora_adapters) {
  976. llama_adapter_lora_ptr lora;
  977. lora.reset(llama_adapter_lora_init(model, la.path.c_str()));
  978. if (lora == nullptr) {
  979. LOG_ERR("%s: failed to apply lora adapter '%s'\n", __func__, la.path.c_str());
  980. llama_free(lctx);
  981. llama_model_free(model);
  982. return iparams;
  983. }
  984. char buf[1024];
  985. la.ptr = lora.get();
  986. llama_adapter_meta_val_str(la.ptr, "adapter.lora.task_name", buf, sizeof(buf));
  987. la.task_name = buf;
  988. llama_adapter_meta_val_str(la.ptr, "adapter.lora.prompt_prefix", buf, sizeof(buf));
  989. la.prompt_prefix = buf;
  990. iparams.lora.emplace_back(std::move(lora)); // copy to list of loaded adapters
  991. }
  992. if (!params.lora_init_without_apply) {
  993. common_set_adapter_lora(lctx, params.lora_adapters);
  994. }
  995. if (params.sampling.ignore_eos && llama_vocab_eos(vocab) == LLAMA_TOKEN_NULL) {
  996. LOG_WRN("%s: warning: vocab does not have an EOS token, ignoring --ignore-eos\n", __func__);
  997. params.sampling.ignore_eos = false;
  998. }
  999. // initialize once
  1000. for (llama_token i = 0; i < llama_vocab_n_tokens(vocab); i++) {
  1001. if (llama_vocab_is_eog(vocab, i)) {
  1002. LOG_INF("%s: added %s logit bias = %f\n", __func__, common_token_to_piece(lctx, i).c_str(), -INFINITY);
  1003. params.sampling.logit_bias_eog.push_back({i, -INFINITY});
  1004. }
  1005. }
  1006. if (params.sampling.ignore_eos) {
  1007. // add EOG biases to the active set of logit biases
  1008. params.sampling.logit_bias.insert(
  1009. params.sampling.logit_bias.end(),
  1010. params.sampling.logit_bias_eog.begin(), params.sampling.logit_bias_eog.end());
  1011. }
  1012. if (params.sampling.penalty_last_n == -1) {
  1013. LOG_INF("%s: setting penalty_last_n to ctx_size = %d\n", __func__, llama_n_ctx(lctx));
  1014. params.sampling.penalty_last_n = llama_n_ctx(lctx);
  1015. }
  1016. if (params.sampling.dry_penalty_last_n == -1) {
  1017. LOG_INF("%s: setting dry_penalty_last_n to ctx_size = %d\n", __func__, llama_n_ctx(lctx));
  1018. params.sampling.dry_penalty_last_n = llama_n_ctx(lctx);
  1019. }
  1020. if (params.warmup) {
  1021. LOG_WRN("%s: warming up the model with an empty run - please wait ... (--no-warmup to disable)\n", __func__);
  1022. llama_set_warmup(lctx, true);
  1023. std::vector<llama_token> tmp;
  1024. llama_token bos = llama_vocab_bos(vocab);
  1025. llama_token eos = llama_vocab_eos(vocab);
  1026. // some models (e.g. T5) don't have a BOS token
  1027. if (bos != LLAMA_TOKEN_NULL) {
  1028. tmp.push_back(bos);
  1029. }
  1030. if (eos != LLAMA_TOKEN_NULL) {
  1031. tmp.push_back(eos);
  1032. }
  1033. if (tmp.empty()) {
  1034. tmp.push_back(0);
  1035. }
  1036. if (llama_model_has_encoder(model)) {
  1037. llama_encode(lctx, llama_batch_get_one(tmp.data(), tmp.size()));
  1038. llama_token decoder_start_token_id = llama_model_decoder_start_token(model);
  1039. if (decoder_start_token_id == LLAMA_TOKEN_NULL) {
  1040. decoder_start_token_id = bos;
  1041. }
  1042. tmp.clear();
  1043. tmp.push_back(decoder_start_token_id);
  1044. }
  1045. if (llama_model_has_decoder(model)) {
  1046. llama_decode(lctx, llama_batch_get_one(tmp.data(), std::min(tmp.size(), (size_t) params.n_batch)));
  1047. }
  1048. llama_memory_clear(llama_get_memory(lctx), true);
  1049. llama_synchronize(lctx);
  1050. llama_perf_context_reset(lctx);
  1051. llama_set_warmup(lctx, false);
  1052. }
  1053. iparams.model.reset(model);
  1054. iparams.context.reset(lctx);
  1055. return iparams;
  1056. }
  1057. std::string get_model_endpoint() {
  1058. const char * model_endpoint_env = getenv("MODEL_ENDPOINT");
  1059. // We still respect the use of environment-variable "HF_ENDPOINT" for backward-compatibility.
  1060. const char * hf_endpoint_env = getenv("HF_ENDPOINT");
  1061. const char * endpoint_env = model_endpoint_env ? model_endpoint_env : hf_endpoint_env;
  1062. std::string model_endpoint = "https://huggingface.co/";
  1063. if (endpoint_env) {
  1064. model_endpoint = endpoint_env;
  1065. if (model_endpoint.back() != '/') model_endpoint += '/';
  1066. }
  1067. return model_endpoint;
  1068. }
  1069. void common_set_adapter_lora(struct llama_context * ctx, std::vector<common_adapter_lora_info> & lora) {
  1070. llama_clear_adapter_lora(ctx);
  1071. for (auto & la : lora) {
  1072. if (la.scale != 0.0f) {
  1073. llama_set_adapter_lora(ctx, la.ptr, la.scale);
  1074. }
  1075. }
  1076. }
  1077. struct llama_model_params common_model_params_to_llama(common_params & params) {
  1078. auto mparams = llama_model_default_params();
  1079. if (!params.devices.empty()) {
  1080. mparams.devices = params.devices.data();
  1081. }
  1082. if (params.n_gpu_layers != -1) {
  1083. mparams.n_gpu_layers = params.n_gpu_layers;
  1084. }
  1085. mparams.main_gpu = params.main_gpu;
  1086. mparams.split_mode = params.split_mode;
  1087. mparams.tensor_split = params.tensor_split;
  1088. mparams.use_mmap = params.use_mmap;
  1089. mparams.use_mlock = params.use_mlock;
  1090. mparams.check_tensors = params.check_tensors;
  1091. mparams.use_extra_bufts = !params.no_extra_bufts;
  1092. mparams.no_host = params.no_host;
  1093. if (params.kv_overrides.empty()) {
  1094. mparams.kv_overrides = NULL;
  1095. } else {
  1096. GGML_ASSERT(params.kv_overrides.back().key[0] == 0 && "KV overrides not terminated with empty key");
  1097. mparams.kv_overrides = params.kv_overrides.data();
  1098. }
  1099. if (params.tensor_buft_overrides.empty()) {
  1100. mparams.tensor_buft_overrides = NULL;
  1101. } else {
  1102. GGML_ASSERT(params.tensor_buft_overrides.back().pattern == nullptr && "Tensor buffer overrides not terminated with empty pattern");
  1103. mparams.tensor_buft_overrides = params.tensor_buft_overrides.data();
  1104. }
  1105. mparams.progress_callback = params.load_progress_callback;
  1106. mparams.progress_callback_user_data = params.load_progress_callback_user_data;
  1107. return mparams;
  1108. }
  1109. struct llama_context_params common_context_params_to_llama(const common_params & params) {
  1110. auto cparams = llama_context_default_params();
  1111. cparams.n_ctx = params.n_ctx;
  1112. cparams.n_seq_max = params.n_parallel;
  1113. cparams.n_batch = params.n_batch;
  1114. cparams.n_ubatch = params.n_ubatch;
  1115. cparams.n_threads = params.cpuparams.n_threads;
  1116. cparams.n_threads_batch = params.cpuparams_batch.n_threads == -1 ?
  1117. params.cpuparams.n_threads : params.cpuparams_batch.n_threads;
  1118. cparams.embeddings = params.embedding;
  1119. cparams.rope_scaling_type = params.rope_scaling_type;
  1120. cparams.rope_freq_base = params.rope_freq_base;
  1121. cparams.rope_freq_scale = params.rope_freq_scale;
  1122. cparams.yarn_ext_factor = params.yarn_ext_factor;
  1123. cparams.yarn_attn_factor = params.yarn_attn_factor;
  1124. cparams.yarn_beta_fast = params.yarn_beta_fast;
  1125. cparams.yarn_beta_slow = params.yarn_beta_slow;
  1126. cparams.yarn_orig_ctx = params.yarn_orig_ctx;
  1127. cparams.pooling_type = params.pooling_type;
  1128. cparams.attention_type = params.attention_type;
  1129. cparams.flash_attn_type = params.flash_attn_type;
  1130. cparams.cb_eval = params.cb_eval;
  1131. cparams.cb_eval_user_data = params.cb_eval_user_data;
  1132. cparams.offload_kqv = !params.no_kv_offload;
  1133. cparams.no_perf = params.no_perf;
  1134. cparams.op_offload = !params.no_op_offload;
  1135. cparams.swa_full = params.swa_full;
  1136. cparams.kv_unified = params.kv_unified;
  1137. cparams.type_k = params.cache_type_k;
  1138. cparams.type_v = params.cache_type_v;
  1139. return cparams;
  1140. }
  1141. struct ggml_threadpool_params ggml_threadpool_params_from_cpu_params(const cpu_params & params) {
  1142. struct ggml_threadpool_params tpp;
  1143. ggml_threadpool_params_init(&tpp, params.n_threads); // setup the defaults
  1144. if (params.mask_valid) {
  1145. std::memcpy(&tpp.cpumask, &params.cpumask, GGML_MAX_N_THREADS);
  1146. }
  1147. tpp.prio = params.priority;
  1148. tpp.poll = params.poll;
  1149. tpp.strict_cpu = params.strict_cpu;
  1150. return tpp;
  1151. }
  1152. //
  1153. // Batch utils
  1154. //
  1155. void common_batch_clear(struct llama_batch & batch) {
  1156. batch.n_tokens = 0;
  1157. }
  1158. void common_batch_add(
  1159. struct llama_batch & batch,
  1160. llama_token id,
  1161. llama_pos pos,
  1162. const std::vector<llama_seq_id> & seq_ids,
  1163. bool logits) {
  1164. GGML_ASSERT(batch.seq_id[batch.n_tokens] && "llama_batch size exceeded");
  1165. batch.token [batch.n_tokens] = id;
  1166. batch.pos [batch.n_tokens] = pos;
  1167. batch.n_seq_id[batch.n_tokens] = seq_ids.size();
  1168. for (size_t i = 0; i < seq_ids.size(); ++i) {
  1169. batch.seq_id[batch.n_tokens][i] = seq_ids[i];
  1170. }
  1171. batch.logits [batch.n_tokens] = logits;
  1172. batch.n_tokens++;
  1173. }
  1174. //
  1175. // Token utils
  1176. //
  1177. size_t common_lcp(const llama_tokens & a, const llama_tokens & b) {
  1178. size_t i;
  1179. for (i = 0; i < a.size() && i < b.size() && a[i] == b[i]; i++) {}
  1180. return i;
  1181. }
  1182. size_t common_lcs(const llama_tokens & a, const llama_tokens & b) {
  1183. // check for empty sequences
  1184. if (a.empty() || b.empty()) {
  1185. return 0;
  1186. }
  1187. // get the lengths of the input sequences
  1188. size_t a_len = a.size();
  1189. size_t b_len = b.size();
  1190. // initialize the maximum length of the longest common subsequence (LCS)
  1191. size_t max_length = 0;
  1192. // use two rows instead of a 2D matrix to optimize space
  1193. std::vector<size_t> prev_row(b_len + 1, 0);
  1194. std::vector<size_t> curr_row(b_len + 1, 0);
  1195. // iterate through the elements of a
  1196. for (size_t i = 1; i <= a_len; i++) {
  1197. // iterate through the elements of b
  1198. for (size_t j = 1; j <= b_len; j++) {
  1199. // if elements at the current positions match
  1200. if (a[i - 1] == b[j - 1]) {
  1201. // if it's the first element of either sequences, set LCS length to 1
  1202. if (i == 1 || j == 1) {
  1203. curr_row[j] = 1;
  1204. } else {
  1205. // increment LCS length by 1 compared to the previous element
  1206. curr_row[j] = prev_row[j - 1] + 1;
  1207. }
  1208. // update max_length if necessary
  1209. if (curr_row[j] > max_length) {
  1210. max_length = curr_row[j];
  1211. }
  1212. } else {
  1213. // reset LCS length if elements don't match
  1214. curr_row[j] = 0;
  1215. }
  1216. }
  1217. // update the previous row for the next iteration
  1218. prev_row = curr_row;
  1219. }
  1220. // return the maximum length of the LCS
  1221. return max_length;
  1222. }
  1223. //
  1224. // Vocab utils
  1225. //
  1226. std::vector<llama_token> common_tokenize(
  1227. const struct llama_context * ctx,
  1228. const std::string & text,
  1229. bool add_special,
  1230. bool parse_special) {
  1231. const llama_model * model = llama_get_model(ctx);
  1232. const llama_vocab * vocab = llama_model_get_vocab(model);
  1233. return common_tokenize(vocab, text, add_special, parse_special);
  1234. }
  1235. std::vector<llama_token> common_tokenize(
  1236. const struct llama_vocab * vocab,
  1237. const std::string & text,
  1238. bool add_special,
  1239. bool parse_special) {
  1240. // upper limit for the number of tokens
  1241. int n_tokens = text.length() + 2 * add_special;
  1242. std::vector<llama_token> result(n_tokens);
  1243. n_tokens = llama_tokenize(vocab, text.data(), text.length(), result.data(), result.size(), add_special, parse_special);
  1244. if (n_tokens == std::numeric_limits<int32_t>::min()) {
  1245. throw std::runtime_error("Tokenization failed: input text too large, tokenization result exceeds int32_t limit");
  1246. }
  1247. if (n_tokens < 0) {
  1248. result.resize(-n_tokens);
  1249. int check = llama_tokenize(vocab, text.data(), text.length(), result.data(), result.size(), add_special, parse_special);
  1250. GGML_ASSERT(check == -n_tokens);
  1251. } else {
  1252. result.resize(n_tokens);
  1253. }
  1254. return result;
  1255. }
  1256. std::string common_token_to_piece(const struct llama_context * ctx, llama_token token, bool special) {
  1257. const llama_model * model = llama_get_model(ctx);
  1258. const llama_vocab * vocab = llama_model_get_vocab(model);
  1259. return common_token_to_piece(vocab, token, special);
  1260. }
  1261. std::string common_token_to_piece(const struct llama_vocab * vocab, llama_token token, bool special) {
  1262. std::string piece;
  1263. piece.resize(piece.capacity()); // using string internal cache, 15 bytes + '\n'
  1264. const int n_chars = llama_token_to_piece(vocab, token, &piece[0], piece.size(), 0, special);
  1265. if (n_chars < 0) {
  1266. piece.resize(-n_chars);
  1267. int check = llama_token_to_piece(vocab, token, &piece[0], piece.size(), 0, special);
  1268. GGML_ASSERT(check == -n_chars);
  1269. }
  1270. else {
  1271. piece.resize(n_chars);
  1272. }
  1273. return piece;
  1274. }
  1275. std::string common_detokenize(const struct llama_context * ctx, const std::vector<llama_token> & tokens, bool special) {
  1276. const llama_model * model = llama_get_model(ctx);
  1277. const llama_vocab * vocab = llama_model_get_vocab(model);
  1278. return common_detokenize(vocab, tokens, special);
  1279. }
  1280. std::string common_detokenize(const struct llama_vocab * vocab, const std::vector<llama_token> & tokens, bool special) {
  1281. std::string text;
  1282. text.resize(std::max(text.capacity(), tokens.size()));
  1283. int32_t n_chars = llama_detokenize(vocab, tokens.data(), (int32_t)tokens.size(), &text[0], (int32_t)text.size(), false, special);
  1284. if (n_chars < 0) {
  1285. text.resize(-n_chars);
  1286. n_chars = llama_detokenize(vocab, tokens.data(), (int32_t)tokens.size(), &text[0], (int32_t)text.size(), false, special);
  1287. GGML_ASSERT(n_chars <= (int32_t)text.size()); // whitespace trimming is performed after per-token detokenization
  1288. }
  1289. text.resize(n_chars);
  1290. // NOTE: the original tokenizer decodes bytes after collecting the pieces.
  1291. return text;
  1292. }
  1293. //
  1294. // Embedding utils
  1295. //
  1296. void common_embd_normalize(const float * inp, float * out, int n, int embd_norm) {
  1297. double sum = 0.0;
  1298. switch (embd_norm) {
  1299. case -1: // no normalisation
  1300. sum = 1.0;
  1301. break;
  1302. case 0: // max absolute
  1303. for (int i = 0; i < n; i++) {
  1304. if (sum < std::abs(inp[i])) {
  1305. sum = std::abs(inp[i]);
  1306. }
  1307. }
  1308. sum /= 32760.0; // make an int16 range
  1309. break;
  1310. case 2: // euclidean
  1311. for (int i = 0; i < n; i++) {
  1312. sum += inp[i] * inp[i];
  1313. }
  1314. sum = std::sqrt(sum);
  1315. break;
  1316. default: // p-norm (euclidean is p-norm p=2)
  1317. for (int i = 0; i < n; i++) {
  1318. sum += std::pow(std::abs(inp[i]), embd_norm);
  1319. }
  1320. sum = std::pow(sum, 1.0 / embd_norm);
  1321. break;
  1322. }
  1323. const float norm = sum > 0.0 ? 1.0 / sum : 0.0f;
  1324. for (int i = 0; i < n; i++) {
  1325. out[i] = inp[i] * norm;
  1326. }
  1327. }
  1328. float common_embd_similarity_cos(const float * embd1, const float * embd2, int n){
  1329. double sum = 0.0;
  1330. double sum1 = 0.0;
  1331. double sum2 = 0.0;
  1332. for (int i = 0; i < n; i++) {
  1333. sum += embd1[i] * embd2[i];
  1334. sum1 += embd1[i] * embd1[i];
  1335. sum2 += embd2[i] * embd2[i];
  1336. }
  1337. // Handle the case where one or both vectors are zero vectors
  1338. if (sum1 == 0.0 || sum2 == 0.0) {
  1339. if (sum1 == 0.0 && sum2 == 0.0) {
  1340. return 1.0f; // two zero vectors are similar
  1341. }
  1342. return 0.0f;
  1343. }
  1344. return sum / (sqrt(sum1) * sqrt(sum2));
  1345. }
  1346. //
  1347. // Control vector utils
  1348. //
  1349. static common_control_vector_data common_control_vector_load_one(const common_control_vector_load_info & load_info) {
  1350. common_control_vector_data result = { -1, {} };
  1351. ggml_context * ctx = nullptr;
  1352. struct gguf_init_params meta_gguf_params = {
  1353. /* .no_alloc = */ false,
  1354. /* .ctx = */ &ctx,
  1355. };
  1356. struct gguf_context * ctx_gguf = gguf_init_from_file(load_info.fname.c_str(), meta_gguf_params);
  1357. if (!ctx_gguf) {
  1358. LOG_ERR("%s: failed to load control vector file from %s\n", __func__, load_info.fname.c_str());
  1359. return result;
  1360. }
  1361. int32_t n_tensors = gguf_get_n_tensors(ctx_gguf);
  1362. if (n_tensors == 0) {
  1363. LOG_WRN("%s: no direction tensors found in %s\n", __func__, load_info.fname.c_str());
  1364. }
  1365. for (int i = 0; i < n_tensors; i++) {
  1366. std::string name = gguf_get_tensor_name(ctx_gguf, i);
  1367. int layer_idx = -1;
  1368. // split on '.'
  1369. size_t dotpos = name.find('.');
  1370. if (dotpos != std::string::npos && name.substr(0, dotpos) == "direction") {
  1371. try {
  1372. layer_idx = std::stoi(name.substr(dotpos + 1));
  1373. } catch (...) {
  1374. layer_idx = -1;
  1375. }
  1376. }
  1377. if (layer_idx < 0) {
  1378. LOG_ERR("%s: invalid/unparsable direction tensor layer index in %s\n", __func__, load_info.fname.c_str());
  1379. result.n_embd = -1;
  1380. break;
  1381. } else if (layer_idx == 0) {
  1382. LOG_ERR("%s: invalid (zero) direction tensor layer index in %s\n", __func__, load_info.fname.c_str());
  1383. result.n_embd = -1;
  1384. break;
  1385. }
  1386. struct ggml_tensor * tensor = ggml_get_tensor(ctx, name.c_str());
  1387. if (tensor->type != GGML_TYPE_F32) {
  1388. LOG_ERR("%s: invalid (non-F32) direction tensor type in %s\n", __func__, load_info.fname.c_str());
  1389. result.n_embd = -1;
  1390. break;
  1391. }
  1392. if (ggml_n_dims(tensor) != 1) {
  1393. LOG_ERR("%s: invalid (non-1D) direction tensor shape in %s\n", __func__, load_info.fname.c_str());
  1394. result.n_embd = -1;
  1395. break;
  1396. }
  1397. if (result.n_embd == -1) {
  1398. result.n_embd = ggml_nelements(tensor);
  1399. } else if (ggml_nelements(tensor) != result.n_embd) {
  1400. LOG_ERR("%s: direction tensor in %s does not match previous dimensions\n", __func__, load_info.fname.c_str());
  1401. result.n_embd = -1;
  1402. break;
  1403. }
  1404. // extend if necessary - do not store data for layer 0 (it's not used)
  1405. result.data.resize(std::max(result.data.size(), static_cast<size_t>(result.n_embd * layer_idx)), 0.0f);
  1406. const float * src = (const float *) tensor->data;
  1407. float * dst = result.data.data() + result.n_embd * (layer_idx - 1); // layer 1 at [0]
  1408. for (int j = 0; j < result.n_embd; j++) {
  1409. dst[j] += src[j] * load_info.strength; // allows multiple directions for same layer in same file
  1410. }
  1411. }
  1412. if (result.n_embd == -1) {
  1413. LOG_WRN("%s: skipping %s due to invalid direction tensors\n", __func__, load_info.fname.c_str());
  1414. result.data.clear();
  1415. }
  1416. gguf_free(ctx_gguf);
  1417. ggml_free(ctx);
  1418. return result;
  1419. }
  1420. common_control_vector_data common_control_vector_load(const std::vector<common_control_vector_load_info> & load_infos) {
  1421. common_control_vector_data result = { -1, {} };
  1422. for (const auto & info : load_infos) {
  1423. auto cur = common_control_vector_load_one(info);
  1424. if (cur.n_embd == -1) {
  1425. result.n_embd = -1;
  1426. break;
  1427. }
  1428. if (result.n_embd != -1 && result.n_embd != cur.n_embd) {
  1429. LOG_ERR("%s: control vectors in %s does not match previous dimensions\n", __func__, info.fname.c_str());
  1430. result.n_embd = -1;
  1431. break;
  1432. }
  1433. if (result.n_embd == -1) {
  1434. result = std::move(cur);
  1435. } else {
  1436. result.data.resize(std::max(result.data.size(), cur.data.size()), 0.0f); // extend if necessary
  1437. for (size_t i = 0; i < cur.data.size(); i++) {
  1438. result.data[i] += cur.data[i];
  1439. }
  1440. }
  1441. }
  1442. if (result.n_embd == -1) {
  1443. LOG_ERR("%s: no valid control vector files passed\n", __func__);
  1444. result.data.clear();
  1445. }
  1446. return result;
  1447. }
  1448. ggml_opt_dataset_t common_opt_dataset_init(struct llama_context * ctx, const std::vector<llama_token> & tokens, int64_t stride) {
  1449. const int64_t ne_datapoint = llama_n_ctx(ctx);
  1450. const int64_t ndata = (tokens.size() - ne_datapoint - 1) / stride;
  1451. ggml_opt_dataset_t result = ggml_opt_dataset_init(
  1452. GGML_TYPE_I32, GGML_TYPE_I32, ne_datapoint, ne_datapoint, ndata, /*ndata_shard =*/ 1);
  1453. llama_token * data = (llama_token *) ggml_opt_dataset_data(result)->data;
  1454. llama_token * labels = (llama_token *) ggml_opt_dataset_labels(result)->data;
  1455. for (int64_t idata = 0; idata < ndata; ++idata) {
  1456. memcpy(data + idata*ne_datapoint, tokens.data() + idata*stride + 0, ne_datapoint*sizeof(llama_token));
  1457. memcpy(labels + idata*ne_datapoint, tokens.data() + idata*stride + 1, ne_datapoint*sizeof(llama_token));
  1458. }
  1459. return result;
  1460. }
  1461. ggml_opt_optimizer_params common_opt_lr_pars(void * userdata) {
  1462. ggml_opt_optimizer_params result = ggml_opt_get_default_optimizer_params(nullptr);
  1463. const lr_opt & d = *(lr_opt *) userdata;
  1464. result.adamw.alpha = result.sgd.alpha = d.get_lr(d.epoch);
  1465. result.sgd.wd = result.adamw.wd = d.wd;
  1466. return result;
  1467. }
  1468. // TODO make all command line args case-insensitive
  1469. static inline bool eq_case_insensitive(char const* a, char const* b) {
  1470. return !
  1471. #if defined(_MSC_VER)
  1472. _stricmp
  1473. #else
  1474. strcasecmp
  1475. #endif // defined(_MSC_VER)
  1476. (a, b);
  1477. }
  1478. enum ggml_opt_optimizer_type common_opt_get_optimizer(const char * n) {
  1479. if (eq_case_insensitive("adamw", n)) {
  1480. return GGML_OPT_OPTIMIZER_TYPE_ADAMW;
  1481. }
  1482. if (eq_case_insensitive("sgd", n)) {
  1483. return GGML_OPT_OPTIMIZER_TYPE_SGD;
  1484. }
  1485. return GGML_OPT_OPTIMIZER_TYPE_COUNT;
  1486. }
  1487. // TODO simplify to use just log and exp
  1488. static float const k_log_2 = std::log(2.f);
  1489. void lr_opt::init() {
  1490. if (lr_min > 0 && lr_min < lr0) {
  1491. float nhalf = std::log(lr0 / lr_min) / k_log_2;
  1492. float e = epochs;
  1493. if (decay_epochs > 0 && decay_epochs < e) {
  1494. e = decay_epochs;
  1495. } else {
  1496. decay_epochs = e;
  1497. }
  1498. scale_epoch = nhalf / e;
  1499. }
  1500. }
  1501. float lr_opt::get_lr(float epoch) const {
  1502. float r = lr_min <= 0 ? lr0 :
  1503. epoch >= decay_epochs ? lr_min :
  1504. lr0 * std::pow(0.5f, epoch * scale_epoch);
  1505. LOG_INF("epoch %.2g lr=%.2g\n", epoch, r);
  1506. return r;
  1507. }