common.cpp 52 KB

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