common.cpp 50 KB

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