1
0

common.cpp 58 KB

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