common.cpp 52 KB

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