1
0

common.cpp 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584
  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. std::string regex_escape(const std::string & s) {
  382. static const std::regex special_chars("[.^$|()*+?\\[\\]{}\\\\]");
  383. return std::regex_replace(s, special_chars, "\\$0");
  384. }
  385. std::string string_join(const std::vector<std::string> & values, const std::string & separator) {
  386. std::ostringstream result;
  387. for (size_t i = 0; i < values.size(); ++i) {
  388. if (i > 0) {
  389. result << separator;
  390. }
  391. result << values[i];
  392. }
  393. return result.str();
  394. }
  395. std::vector<std::string> string_split(const std::string & str, const std::string & delimiter) {
  396. std::vector<std::string> parts;
  397. size_t start = 0;
  398. size_t end = str.find(delimiter);
  399. while (end != std::string::npos) {
  400. parts.push_back(str.substr(start, end - start));
  401. start = end + delimiter.length();
  402. end = str.find(delimiter, start);
  403. }
  404. parts.push_back(str.substr(start));
  405. return parts;
  406. }
  407. std::string string_repeat(const std::string & str, size_t n) {
  408. if (n == 0) {
  409. return "";
  410. }
  411. std::string result;
  412. result.reserve(str.length() * n);
  413. for (size_t i = 0; i < n; ++i) {
  414. result += str;
  415. }
  416. return result;
  417. }
  418. std::string string_from(bool value) {
  419. return value ? "true" : "false";
  420. }
  421. std::string string_from(const std::vector<int> & values) {
  422. std::stringstream buf;
  423. buf << "[ ";
  424. bool first = true;
  425. for (auto e : values) {
  426. if (first) {
  427. first = false;
  428. } else {
  429. buf << ", ";
  430. }
  431. buf << std::to_string(e);
  432. }
  433. buf << " ]";
  434. return buf.str();
  435. }
  436. std::string string_from(const struct llama_context * ctx, const std::vector<llama_token> & tokens) {
  437. std::stringstream buf;
  438. buf << "[ ";
  439. bool first = true;
  440. for (const auto & token : tokens) {
  441. if (!first) {
  442. buf << ", ";
  443. } else {
  444. first = false;
  445. }
  446. auto detokenized = common_token_to_piece(ctx, token);
  447. detokenized.erase(
  448. std::remove_if(
  449. detokenized.begin(),
  450. detokenized.end(),
  451. [](const unsigned char c) { return !std::isprint(c); }),
  452. detokenized.end());
  453. buf << "'" << detokenized << "'"
  454. << ":" << std::to_string(token);
  455. }
  456. buf << " ]";
  457. return buf.str();
  458. }
  459. std::string string_from(const struct llama_context * ctx, const struct llama_batch & batch) {
  460. std::stringstream buf;
  461. buf << "[ ";
  462. bool first = true;
  463. for (int i = 0; i < batch.n_tokens; ++i) {
  464. if (!first) {
  465. buf << ", ";
  466. } else {
  467. first = false;
  468. }
  469. auto detokenized = common_token_to_piece(ctx, batch.token[i]);
  470. detokenized.erase(
  471. std::remove_if(
  472. detokenized.begin(),
  473. detokenized.end(),
  474. [](const unsigned char c) { return !std::isprint(c); }),
  475. detokenized.end());
  476. buf << "\n" << std::to_string(i)
  477. << ", token '" << detokenized << "'"
  478. << ", pos " << std::to_string(batch.pos[i])
  479. << ", n_seq_id " << std::to_string(batch.n_seq_id[i])
  480. << ", seq_id " << std::to_string(batch.seq_id[i][0])
  481. << ", logits " << std::to_string(batch.logits[i]);
  482. }
  483. buf << " ]";
  484. return buf.str();
  485. }
  486. void string_process_escapes(std::string & input) {
  487. std::size_t input_len = input.length();
  488. std::size_t output_idx = 0;
  489. for (std::size_t input_idx = 0; input_idx < input_len; ++input_idx) {
  490. if (input[input_idx] == '\\' && input_idx + 1 < input_len) {
  491. switch (input[++input_idx]) {
  492. case 'n': input[output_idx++] = '\n'; break;
  493. case 'r': input[output_idx++] = '\r'; break;
  494. case 't': input[output_idx++] = '\t'; break;
  495. case '\'': input[output_idx++] = '\''; break;
  496. case '\"': input[output_idx++] = '\"'; break;
  497. case '\\': input[output_idx++] = '\\'; break;
  498. case 'x':
  499. // Handle \x12, etc
  500. if (input_idx + 2 < input_len) {
  501. const char x[3] = { input[input_idx + 1], input[input_idx + 2], 0 };
  502. char *err_p = nullptr;
  503. const long val = std::strtol(x, &err_p, 16);
  504. if (err_p == x + 2) {
  505. input_idx += 2;
  506. input[output_idx++] = char(val);
  507. break;
  508. }
  509. }
  510. // fall through
  511. default: input[output_idx++] = '\\';
  512. input[output_idx++] = input[input_idx]; break;
  513. }
  514. } else {
  515. input[output_idx++] = input[input_idx];
  516. }
  517. }
  518. input.resize(output_idx);
  519. }
  520. bool string_parse_kv_override(const char * data, std::vector<llama_model_kv_override> & overrides) {
  521. const char * sep = strchr(data, '=');
  522. if (sep == nullptr || sep - data >= 128) {
  523. LOG_ERR("%s: malformed KV override '%s'\n", __func__, data);
  524. return false;
  525. }
  526. llama_model_kv_override kvo;
  527. std::strncpy(kvo.key, data, sep - data);
  528. kvo.key[sep - data] = 0;
  529. sep++;
  530. if (strncmp(sep, "int:", 4) == 0) {
  531. sep += 4;
  532. kvo.tag = LLAMA_KV_OVERRIDE_TYPE_INT;
  533. kvo.val_i64 = std::atol(sep);
  534. } else if (strncmp(sep, "float:", 6) == 0) {
  535. sep += 6;
  536. kvo.tag = LLAMA_KV_OVERRIDE_TYPE_FLOAT;
  537. kvo.val_f64 = std::atof(sep);
  538. } else if (strncmp(sep, "bool:", 5) == 0) {
  539. sep += 5;
  540. kvo.tag = LLAMA_KV_OVERRIDE_TYPE_BOOL;
  541. if (std::strcmp(sep, "true") == 0) {
  542. kvo.val_bool = true;
  543. } else if (std::strcmp(sep, "false") == 0) {
  544. kvo.val_bool = false;
  545. } else {
  546. LOG_ERR("%s: invalid boolean value for KV override '%s'\n", __func__, data);
  547. return false;
  548. }
  549. } else if (strncmp(sep, "str:", 4) == 0) {
  550. sep += 4;
  551. kvo.tag = LLAMA_KV_OVERRIDE_TYPE_STR;
  552. if (strlen(sep) > 127) {
  553. LOG_ERR("%s: malformed KV override '%s', value cannot exceed 127 chars\n", __func__, data);
  554. return false;
  555. }
  556. strncpy(kvo.val_str, sep, 127);
  557. kvo.val_str[127] = '\0';
  558. } else {
  559. LOG_ERR("%s: invalid type for KV override '%s'\n", __func__, data);
  560. return false;
  561. }
  562. overrides.emplace_back(std::move(kvo));
  563. return true;
  564. }
  565. //
  566. // Filesystem utils
  567. //
  568. // Validate if a filename is safe to use
  569. // To validate a full path, split the path by the OS-specific path separator, and validate each part with this function
  570. bool fs_validate_filename(const std::string & filename) {
  571. if (!filename.length()) {
  572. // Empty filename invalid
  573. return false;
  574. }
  575. if (filename.length() > 255) {
  576. // Limit at common largest possible filename on Linux filesystems
  577. // to avoid unnecessary further validation
  578. // (On systems with smaller limits it will be caught by the OS)
  579. return false;
  580. }
  581. std::u32string filename_utf32;
  582. try {
  583. #if defined(__clang__)
  584. // disable C++17 deprecation warning for std::codecvt_utf8
  585. # pragma clang diagnostic push
  586. # pragma clang diagnostic ignored "-Wdeprecated-declarations"
  587. #endif
  588. std::wstring_convert<std::codecvt_utf8<char32_t>, char32_t> converter;
  589. #if defined(__clang__)
  590. # pragma clang diagnostic pop
  591. #endif
  592. filename_utf32 = converter.from_bytes(filename);
  593. // If the reverse conversion mismatches, it means overlong UTF-8 sequences were used,
  594. // or invalid encodings were encountered. Reject such attempts
  595. std::string filename_reencoded = converter.to_bytes(filename_utf32);
  596. if (filename_reencoded != filename) {
  597. return false;
  598. }
  599. } catch (const std::exception &) {
  600. return false;
  601. }
  602. // Check for forbidden codepoints:
  603. // - Control characters
  604. // - Unicode equivalents of illegal characters
  605. // - UTF-16 surrogate pairs
  606. // - UTF-8 replacement character
  607. // - Byte order mark (BOM)
  608. // - Illegal characters: / \ : * ? " < > |
  609. for (char32_t c : filename_utf32) {
  610. if (c <= 0x1F // Control characters (C0)
  611. || c == 0x7F // Control characters (DEL)
  612. || (c >= 0x80 && c <= 0x9F) // Control characters (C1)
  613. || c == 0xFF0E // Fullwidth Full Stop (period equivalent)
  614. || c == 0x2215 // Division Slash (forward slash equivalent)
  615. || c == 0x2216 // Set Minus (backslash equivalent)
  616. || (c >= 0xD800 && c <= 0xDFFF) // UTF-16 surrogate pairs
  617. || c == 0xFFFD // Replacement Character (UTF-8)
  618. || c == 0xFEFF // Byte Order Mark (BOM)
  619. || c == '/' || c == '\\' || c == ':' || c == '*' // Illegal characters
  620. || c == '?' || c == '"' || c == '<' || c == '>' || c == '|') {
  621. return false;
  622. }
  623. }
  624. // Reject any leading or trailing ' ', or any trailing '.', these are stripped on Windows and will cause a different filename
  625. // Unicode and other whitespace is not affected, only 0x20 space
  626. if (filename.front() == ' ' || filename.back() == ' ' || filename.back() == '.') {
  627. return false;
  628. }
  629. // Reject any ".." (currently stricter than necessary, it should be fine to just check for == ".." instead)
  630. if (filename.find("..") != std::string::npos) {
  631. return false;
  632. }
  633. // Reject "."
  634. if (filename == ".") {
  635. return false;
  636. }
  637. return true;
  638. }
  639. // returns true if successful, false otherwise
  640. bool fs_create_directory_with_parents(const std::string & path) {
  641. #ifdef _WIN32
  642. std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;
  643. std::wstring wpath = converter.from_bytes(path);
  644. // if the path already exists, check whether it's a directory
  645. const DWORD attributes = GetFileAttributesW(wpath.c_str());
  646. if ((attributes != INVALID_FILE_ATTRIBUTES) && (attributes & FILE_ATTRIBUTE_DIRECTORY)) {
  647. return true;
  648. }
  649. size_t pos_slash = 0;
  650. // process path from front to back, procedurally creating directories
  651. while ((pos_slash = path.find('\\', pos_slash)) != std::string::npos) {
  652. const std::wstring subpath = wpath.substr(0, pos_slash);
  653. const wchar_t * test = subpath.c_str();
  654. const bool success = CreateDirectoryW(test, NULL);
  655. if (!success) {
  656. const DWORD error = GetLastError();
  657. // if the path already exists, ensure that it's a directory
  658. if (error == ERROR_ALREADY_EXISTS) {
  659. const DWORD attributes = GetFileAttributesW(subpath.c_str());
  660. if (attributes == INVALID_FILE_ATTRIBUTES || !(attributes & FILE_ATTRIBUTE_DIRECTORY)) {
  661. return false;
  662. }
  663. } else {
  664. return false;
  665. }
  666. }
  667. pos_slash += 1;
  668. }
  669. return true;
  670. #else
  671. // if the path already exists, check whether it's a directory
  672. struct stat info;
  673. if (stat(path.c_str(), &info) == 0) {
  674. return S_ISDIR(info.st_mode);
  675. }
  676. size_t pos_slash = 1; // skip leading slashes for directory creation
  677. // process path from front to back, procedurally creating directories
  678. while ((pos_slash = path.find('/', pos_slash)) != std::string::npos) {
  679. const std::string subpath = path.substr(0, pos_slash);
  680. struct stat info;
  681. // if the path already exists, ensure that it's a directory
  682. if (stat(subpath.c_str(), &info) == 0) {
  683. if (!S_ISDIR(info.st_mode)) {
  684. return false;
  685. }
  686. } else {
  687. // create parent directories
  688. const int ret = mkdir(subpath.c_str(), 0755);
  689. if (ret != 0) {
  690. return false;
  691. }
  692. }
  693. pos_slash += 1;
  694. }
  695. return true;
  696. #endif // _WIN32
  697. }
  698. std::string fs_get_cache_directory() {
  699. std::string cache_directory = "";
  700. auto ensure_trailing_slash = [](std::string p) {
  701. // Make sure to add trailing slash
  702. if (p.back() != DIRECTORY_SEPARATOR) {
  703. p += DIRECTORY_SEPARATOR;
  704. }
  705. return p;
  706. };
  707. if (getenv("LLAMA_CACHE")) {
  708. cache_directory = std::getenv("LLAMA_CACHE");
  709. } else {
  710. #if defined(__linux__) || defined(__FreeBSD__) || defined(_AIX)
  711. if (std::getenv("XDG_CACHE_HOME")) {
  712. cache_directory = std::getenv("XDG_CACHE_HOME");
  713. } else {
  714. cache_directory = std::getenv("HOME") + std::string("/.cache/");
  715. }
  716. #elif defined(__APPLE__)
  717. cache_directory = std::getenv("HOME") + std::string("/Library/Caches/");
  718. #elif defined(_WIN32)
  719. cache_directory = std::getenv("LOCALAPPDATA");
  720. #else
  721. # error Unknown architecture
  722. #endif
  723. cache_directory = ensure_trailing_slash(cache_directory);
  724. cache_directory += "llama.cpp";
  725. }
  726. return ensure_trailing_slash(cache_directory);
  727. }
  728. std::string fs_get_cache_file(const std::string & filename) {
  729. GGML_ASSERT(filename.find(DIRECTORY_SEPARATOR) == std::string::npos);
  730. std::string cache_directory = fs_get_cache_directory();
  731. const bool success = fs_create_directory_with_parents(cache_directory);
  732. if (!success) {
  733. throw std::runtime_error("failed to create cache directory: " + cache_directory);
  734. }
  735. return cache_directory + filename;
  736. }
  737. //
  738. // Model utils
  739. //
  740. struct common_init_result common_init_from_params(common_params & params) {
  741. common_init_result iparams;
  742. auto mparams = common_model_params_to_llama(params);
  743. llama_model * model = llama_model_load_from_file(params.model.path.c_str(), mparams);
  744. if (model == NULL) {
  745. LOG_ERR("%s: failed to load model '%s'\n", __func__, params.model.path.c_str());
  746. return iparams;
  747. }
  748. const llama_vocab * vocab = llama_model_get_vocab(model);
  749. if (params.reranking) {
  750. bool ok = true;
  751. if (llama_vocab_bos(vocab) == LLAMA_TOKEN_NULL) {
  752. LOG_WRN("%s: warning: vocab does not have a BOS token, reranking will not work\n", __func__);
  753. ok = false;
  754. }
  755. if (llama_vocab_eos(vocab) == LLAMA_TOKEN_NULL) {
  756. LOG_WRN("%s: warning: vocab does not have an EOS token, reranking will not work\n", __func__);
  757. ok = false;
  758. }
  759. if (llama_vocab_sep(vocab) == LLAMA_TOKEN_NULL) {
  760. LOG_WRN("%s: warning: vocab does not have a SEP token, reranking will not work\n", __func__);
  761. ok = false;
  762. }
  763. if (!ok) {
  764. llama_model_free(model);
  765. return iparams;
  766. }
  767. }
  768. auto cparams = common_context_params_to_llama(params);
  769. llama_context * lctx = llama_init_from_model(model, cparams);
  770. if (lctx == NULL) {
  771. LOG_ERR("%s: failed to create context with model '%s'\n", __func__, params.model.path.c_str());
  772. llama_model_free(model);
  773. return iparams;
  774. }
  775. if (params.ctx_shift && !llama_kv_self_can_shift(lctx)) {
  776. LOG_WRN("%s: KV cache shifting is not supported for this context, disabling KV cache shifting\n", __func__);
  777. params.ctx_shift = false;
  778. }
  779. if (!params.control_vectors.empty()) {
  780. if (params.control_vector_layer_start <= 0) params.control_vector_layer_start = 1;
  781. if (params.control_vector_layer_end <= 0) params.control_vector_layer_end = llama_model_n_layer(model);
  782. const auto cvec = common_control_vector_load(params.control_vectors);
  783. if (cvec.n_embd == -1) {
  784. llama_free(lctx);
  785. llama_model_free(model);
  786. return iparams;
  787. }
  788. int err = llama_apply_adapter_cvec(
  789. lctx,
  790. cvec.data.data(),
  791. cvec.data.size(),
  792. cvec.n_embd,
  793. params.control_vector_layer_start,
  794. params.control_vector_layer_end);
  795. if (err) {
  796. llama_free(lctx);
  797. llama_model_free(model);
  798. return iparams;
  799. }
  800. }
  801. // load and optionally apply lora adapters
  802. for (auto & la : params.lora_adapters) {
  803. llama_adapter_lora_ptr lora;
  804. lora.reset(llama_adapter_lora_init(model, la.path.c_str()));
  805. if (lora == nullptr) {
  806. LOG_ERR("%s: failed to apply lora adapter '%s'\n", __func__, la.path.c_str());
  807. llama_free(lctx);
  808. llama_model_free(model);
  809. return iparams;
  810. }
  811. la.ptr = lora.get();
  812. iparams.lora.emplace_back(std::move(lora)); // copy to list of loaded adapters
  813. }
  814. if (!params.lora_init_without_apply) {
  815. common_set_adapter_lora(lctx, params.lora_adapters);
  816. }
  817. if (params.sampling.ignore_eos && llama_vocab_eos(vocab) == LLAMA_TOKEN_NULL) {
  818. LOG_WRN("%s: warning: vocab does not have an EOS token, ignoring --ignore-eos\n", __func__);
  819. params.sampling.ignore_eos = false;
  820. }
  821. if (params.sampling.ignore_eos) {
  822. for (llama_token i = 0; i < llama_vocab_n_tokens(vocab); i++) {
  823. if (llama_vocab_is_eog(vocab, i)) {
  824. LOG_INF("%s: added %s logit bias = %f\n", __func__, common_token_to_piece(lctx, i).c_str(), -INFINITY);
  825. params.sampling.logit_bias.push_back({i, -INFINITY});
  826. }
  827. }
  828. }
  829. if (params.sampling.penalty_last_n == -1) {
  830. LOG_INF("%s: setting penalty_last_n to ctx_size = %d\n", __func__, llama_n_ctx(lctx));
  831. params.sampling.penalty_last_n = llama_n_ctx(lctx);
  832. }
  833. if (params.sampling.dry_penalty_last_n == -1) {
  834. LOG_INF("%s: setting dry_penalty_last_n to ctx_size = %d\n", __func__, llama_n_ctx(lctx));
  835. params.sampling.dry_penalty_last_n = llama_n_ctx(lctx);
  836. }
  837. if (params.warmup) {
  838. LOG_WRN("%s: warming up the model with an empty run - please wait ... (--no-warmup to disable)\n", __func__);
  839. llama_set_warmup(lctx, true);
  840. std::vector<llama_token> tmp;
  841. llama_token bos = llama_vocab_bos(vocab);
  842. llama_token eos = llama_vocab_eos(vocab);
  843. // some models (e.g. T5) don't have a BOS token
  844. if (bos != LLAMA_TOKEN_NULL) {
  845. tmp.push_back(bos);
  846. }
  847. if (eos != LLAMA_TOKEN_NULL) {
  848. tmp.push_back(eos);
  849. }
  850. if (tmp.empty()) {
  851. tmp.push_back(0);
  852. }
  853. if (llama_model_has_encoder(model)) {
  854. llama_encode(lctx, llama_batch_get_one(tmp.data(), tmp.size()));
  855. llama_token decoder_start_token_id = llama_model_decoder_start_token(model);
  856. if (decoder_start_token_id == LLAMA_TOKEN_NULL) {
  857. decoder_start_token_id = bos;
  858. }
  859. tmp.clear();
  860. tmp.push_back(decoder_start_token_id);
  861. }
  862. if (llama_model_has_decoder(model)) {
  863. llama_decode(lctx, llama_batch_get_one(tmp.data(), std::min(tmp.size(), (size_t) params.n_batch)));
  864. }
  865. llama_kv_self_clear(lctx);
  866. llama_synchronize(lctx);
  867. llama_perf_context_reset(lctx);
  868. llama_set_warmup(lctx, false);
  869. }
  870. iparams.model.reset(model);
  871. iparams.context.reset(lctx);
  872. return iparams;
  873. }
  874. std::string get_model_endpoint() {
  875. const char * model_endpoint_env = getenv("MODEL_ENDPOINT");
  876. // We still respect the use of environment-variable "HF_ENDPOINT" for backward-compatibility.
  877. const char * hf_endpoint_env = getenv("HF_ENDPOINT");
  878. const char * endpoint_env = model_endpoint_env ? model_endpoint_env : hf_endpoint_env;
  879. std::string model_endpoint = "https://huggingface.co/";
  880. if (endpoint_env) {
  881. model_endpoint = endpoint_env;
  882. if (model_endpoint.back() != '/') model_endpoint += '/';
  883. }
  884. return model_endpoint;
  885. }
  886. void common_set_adapter_lora(struct llama_context * ctx, std::vector<common_adapter_lora_info> & lora) {
  887. llama_clear_adapter_lora(ctx);
  888. for (auto & la : lora) {
  889. if (la.scale != 0.0f) {
  890. llama_set_adapter_lora(ctx, la.ptr, la.scale);
  891. }
  892. }
  893. }
  894. struct llama_model_params common_model_params_to_llama(common_params & params) {
  895. auto mparams = llama_model_default_params();
  896. if (!params.devices.empty()) {
  897. mparams.devices = params.devices.data();
  898. }
  899. if (params.n_gpu_layers != -1) {
  900. mparams.n_gpu_layers = params.n_gpu_layers;
  901. }
  902. mparams.main_gpu = params.main_gpu;
  903. mparams.split_mode = params.split_mode;
  904. mparams.tensor_split = params.tensor_split;
  905. mparams.use_mmap = params.use_mmap;
  906. mparams.use_mlock = params.use_mlock;
  907. mparams.check_tensors = params.check_tensors;
  908. if (params.kv_overrides.empty()) {
  909. mparams.kv_overrides = NULL;
  910. } else {
  911. GGML_ASSERT(params.kv_overrides.back().key[0] == 0 && "KV overrides not terminated with empty key");
  912. mparams.kv_overrides = params.kv_overrides.data();
  913. }
  914. if (params.tensor_buft_overrides.empty()) {
  915. mparams.tensor_buft_overrides = NULL;
  916. } else {
  917. GGML_ASSERT(params.tensor_buft_overrides.back().pattern == nullptr && "Tensor buffer overrides not terminated with empty pattern");
  918. mparams.tensor_buft_overrides = params.tensor_buft_overrides.data();
  919. }
  920. return mparams;
  921. }
  922. struct llama_context_params common_context_params_to_llama(const common_params & params) {
  923. auto cparams = llama_context_default_params();
  924. cparams.n_ctx = params.n_ctx;
  925. cparams.n_seq_max = params.n_parallel;
  926. cparams.n_batch = params.n_batch;
  927. cparams.n_ubatch = params.n_ubatch;
  928. cparams.n_threads = params.cpuparams.n_threads;
  929. cparams.n_threads_batch = params.cpuparams_batch.n_threads == -1 ?
  930. params.cpuparams.n_threads : params.cpuparams_batch.n_threads;
  931. cparams.embeddings = params.embedding;
  932. cparams.rope_scaling_type = params.rope_scaling_type;
  933. cparams.rope_freq_base = params.rope_freq_base;
  934. cparams.rope_freq_scale = params.rope_freq_scale;
  935. cparams.yarn_ext_factor = params.yarn_ext_factor;
  936. cparams.yarn_attn_factor = params.yarn_attn_factor;
  937. cparams.yarn_beta_fast = params.yarn_beta_fast;
  938. cparams.yarn_beta_slow = params.yarn_beta_slow;
  939. cparams.yarn_orig_ctx = params.yarn_orig_ctx;
  940. cparams.pooling_type = params.pooling_type;
  941. cparams.attention_type = params.attention_type;
  942. cparams.defrag_thold = params.defrag_thold;
  943. cparams.cb_eval = params.cb_eval;
  944. cparams.cb_eval_user_data = params.cb_eval_user_data;
  945. cparams.offload_kqv = !params.no_kv_offload;
  946. cparams.flash_attn = params.flash_attn;
  947. cparams.no_perf = params.no_perf;
  948. cparams.op_offload = !params.no_op_offload;
  949. if (params.reranking) {
  950. cparams.embeddings = true;
  951. cparams.pooling_type = LLAMA_POOLING_TYPE_RANK;
  952. }
  953. cparams.type_k = params.cache_type_k;
  954. cparams.type_v = params.cache_type_v;
  955. return cparams;
  956. }
  957. struct ggml_threadpool_params ggml_threadpool_params_from_cpu_params(const cpu_params & params) {
  958. struct ggml_threadpool_params tpp;
  959. ggml_threadpool_params_init(&tpp, params.n_threads); // setup the defaults
  960. if (params.mask_valid) {
  961. std::memcpy(&tpp.cpumask, &params.cpumask, GGML_MAX_N_THREADS);
  962. }
  963. tpp.prio = params.priority;
  964. tpp.poll = params.poll;
  965. tpp.strict_cpu = params.strict_cpu;
  966. return tpp;
  967. }
  968. //
  969. // Batch utils
  970. //
  971. void common_batch_clear(struct llama_batch & batch) {
  972. batch.n_tokens = 0;
  973. }
  974. void common_batch_add(
  975. struct llama_batch & batch,
  976. llama_token id,
  977. llama_pos pos,
  978. const std::vector<llama_seq_id> & seq_ids,
  979. bool logits) {
  980. GGML_ASSERT(batch.seq_id[batch.n_tokens] && "llama_batch size exceeded");
  981. batch.token [batch.n_tokens] = id;
  982. batch.pos [batch.n_tokens] = pos;
  983. batch.n_seq_id[batch.n_tokens] = seq_ids.size();
  984. for (size_t i = 0; i < seq_ids.size(); ++i) {
  985. batch.seq_id[batch.n_tokens][i] = seq_ids[i];
  986. }
  987. batch.logits [batch.n_tokens] = logits;
  988. batch.n_tokens++;
  989. }
  990. //
  991. // Token utils
  992. //
  993. size_t common_lcp(const llama_tokens & a, const llama_tokens & b) {
  994. size_t i;
  995. for (i = 0; i < a.size() && i < b.size() && a[i] == b[i]; i++) {}
  996. return i;
  997. }
  998. size_t common_lcs(const llama_tokens & a, const llama_tokens & b) {
  999. // check for empty sequences
  1000. if (a.empty() || b.empty()) {
  1001. return 0;
  1002. }
  1003. // get the lengths of the input sequences
  1004. size_t a_len = a.size();
  1005. size_t b_len = b.size();
  1006. // initialize the maximum length of the longest common subsequence (LCS)
  1007. size_t max_length = 0;
  1008. // use two rows instead of a 2D matrix to optimize space
  1009. std::vector<size_t> prev_row(b_len + 1, 0);
  1010. std::vector<size_t> curr_row(b_len + 1, 0);
  1011. // iterate through the elements of a
  1012. for (size_t i = 1; i <= a_len; i++) {
  1013. // iterate through the elements of b
  1014. for (size_t j = 1; j <= b_len; j++) {
  1015. // if elements at the current positions match
  1016. if (a[i - 1] == b[j - 1]) {
  1017. // if it's the first element of either sequences, set LCS length to 1
  1018. if (i == 1 || j == 1) {
  1019. curr_row[j] = 1;
  1020. } else {
  1021. // increment LCS length by 1 compared to the previous element
  1022. curr_row[j] = prev_row[j - 1] + 1;
  1023. }
  1024. // update max_length if necessary
  1025. if (curr_row[j] > max_length) {
  1026. max_length = curr_row[j];
  1027. }
  1028. } else {
  1029. // reset LCS length if elements don't match
  1030. curr_row[j] = 0;
  1031. }
  1032. }
  1033. // update the previous row for the next iteration
  1034. prev_row = curr_row;
  1035. }
  1036. // return the maximum length of the LCS
  1037. return max_length;
  1038. }
  1039. //
  1040. // Vocab utils
  1041. //
  1042. std::vector<llama_token> common_tokenize(
  1043. const struct llama_context * ctx,
  1044. const std::string & text,
  1045. bool add_special,
  1046. bool parse_special) {
  1047. const llama_model * model = llama_get_model(ctx);
  1048. const llama_vocab * vocab = llama_model_get_vocab(model);
  1049. return common_tokenize(vocab, text, add_special, parse_special);
  1050. }
  1051. std::vector<llama_token> common_tokenize(
  1052. const struct llama_vocab * vocab,
  1053. const std::string & text,
  1054. bool add_special,
  1055. bool parse_special) {
  1056. // upper limit for the number of tokens
  1057. int n_tokens = text.length() + 2 * add_special;
  1058. std::vector<llama_token> result(n_tokens);
  1059. n_tokens = llama_tokenize(vocab, text.data(), text.length(), result.data(), result.size(), add_special, parse_special);
  1060. if (n_tokens < 0) {
  1061. result.resize(-n_tokens);
  1062. int check = llama_tokenize(vocab, text.data(), text.length(), result.data(), result.size(), add_special, parse_special);
  1063. GGML_ASSERT(check == -n_tokens);
  1064. } else {
  1065. result.resize(n_tokens);
  1066. }
  1067. return result;
  1068. }
  1069. std::string common_token_to_piece(const struct llama_context * ctx, llama_token token, bool special) {
  1070. const llama_model * model = llama_get_model(ctx);
  1071. const llama_vocab * vocab = llama_model_get_vocab(model);
  1072. return common_token_to_piece(vocab, token, special);
  1073. }
  1074. std::string common_token_to_piece(const struct llama_vocab * vocab, llama_token token, bool special) {
  1075. std::string piece;
  1076. piece.resize(piece.capacity()); // using string internal cache, 15 bytes + '\n'
  1077. const int n_chars = llama_token_to_piece(vocab, token, &piece[0], piece.size(), 0, special);
  1078. if (n_chars < 0) {
  1079. piece.resize(-n_chars);
  1080. int check = llama_token_to_piece(vocab, token, &piece[0], piece.size(), 0, special);
  1081. GGML_ASSERT(check == -n_chars);
  1082. }
  1083. else {
  1084. piece.resize(n_chars);
  1085. }
  1086. return piece;
  1087. }
  1088. std::string common_detokenize(const struct llama_context * ctx, const std::vector<llama_token> & tokens, bool special) {
  1089. const llama_model * model = llama_get_model(ctx);
  1090. const llama_vocab * vocab = llama_model_get_vocab(model);
  1091. return common_detokenize(vocab, tokens, special);
  1092. }
  1093. std::string common_detokenize(const struct llama_vocab * vocab, const std::vector<llama_token> & tokens, bool special) {
  1094. std::string text;
  1095. text.resize(std::max(text.capacity(), tokens.size()));
  1096. int32_t n_chars = llama_detokenize(vocab, tokens.data(), (int32_t)tokens.size(), &text[0], (int32_t)text.size(), false, special);
  1097. if (n_chars < 0) {
  1098. text.resize(-n_chars);
  1099. n_chars = llama_detokenize(vocab, tokens.data(), (int32_t)tokens.size(), &text[0], (int32_t)text.size(), false, special);
  1100. GGML_ASSERT(n_chars <= (int32_t)text.size()); // whitespace trimming is performed after per-token detokenization
  1101. }
  1102. text.resize(n_chars);
  1103. // NOTE: the original tokenizer decodes bytes after collecting the pieces.
  1104. return text;
  1105. }
  1106. //
  1107. // KV cache utils
  1108. //
  1109. void common_kv_cache_dump_view(const llama_kv_cache_view & view, int row_size) {
  1110. static const char slot_chars[] = ".123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+";
  1111. 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",
  1112. view.n_cells, view.n_seq_max, view.used_cells, view.token_count, view.max_contiguous, view.max_contiguous_idx);
  1113. llama_kv_cache_view_cell * c_curr = view.cells;
  1114. llama_seq_id * cs_curr = view.cells_sequences;
  1115. for (int i = 0; i < view.n_cells; i++, c_curr++, cs_curr += view.n_seq_max) {
  1116. if (i % row_size == 0) {
  1117. printf("\n%5d: ", i);
  1118. }
  1119. int seq_count = 0;
  1120. for (int j = 0; j < view.n_seq_max; j++) {
  1121. if (cs_curr[j] >= 0) { seq_count++; }
  1122. }
  1123. putchar(slot_chars[std::min(sizeof(slot_chars) - 2, size_t(seq_count))]);
  1124. }
  1125. printf("\n=== Done dumping\n");
  1126. }
  1127. void common_kv_cache_dump_view_seqs(const llama_kv_cache_view & view, int row_size) {
  1128. static const char slot_chars[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  1129. 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",
  1130. view.n_cells, view.n_seq_max, view.used_cells, view.token_count, view.max_contiguous, view.max_contiguous_idx);
  1131. std::unordered_map<llama_seq_id, size_t> seqs;
  1132. llama_kv_cache_view_cell * c_curr = view.cells;
  1133. llama_seq_id * cs_curr = view.cells_sequences;
  1134. for (int i = 0; i < view.n_cells; i++, c_curr++, cs_curr += view.n_seq_max) {
  1135. for (int j = 0; j < view.n_seq_max; j++) {
  1136. if (cs_curr[j] < 0) { continue; }
  1137. if (seqs.find(cs_curr[j]) == seqs.end()) {
  1138. if (seqs.size() + 1 >= sizeof(slot_chars)) { break; }
  1139. const size_t sz = seqs.size();
  1140. seqs[cs_curr[j]] = sz;
  1141. }
  1142. }
  1143. if (seqs.size() + 1 >= sizeof(slot_chars)) { break; }
  1144. }
  1145. printf("=== Sequence legend: ");
  1146. for (const auto & it : seqs) {
  1147. printf("%zu=%d, ", it.second, it.first);
  1148. }
  1149. printf("'+'=other sequence ids");
  1150. c_curr = view.cells;
  1151. cs_curr = view.cells_sequences;
  1152. for (int i = 0; i < view.n_cells; i++, c_curr++, cs_curr += view.n_seq_max) {
  1153. if (i % row_size == 0) {
  1154. printf("\n%5d: ", i);
  1155. }
  1156. for (int j = 0; j < view.n_seq_max; j++) {
  1157. if (cs_curr[j] >= 0) {
  1158. const auto & it = seqs.find(cs_curr[j]);
  1159. putchar(it != seqs.end() ? int(slot_chars[it->second]) : '+');
  1160. } else {
  1161. putchar('.');
  1162. }
  1163. }
  1164. putchar(' ');
  1165. }
  1166. printf("\n=== Done dumping\n");
  1167. }
  1168. //
  1169. // Embedding utils
  1170. //
  1171. void common_embd_normalize(const float * inp, float * out, int n, int embd_norm) {
  1172. double sum = 0.0;
  1173. switch (embd_norm) {
  1174. case -1: // no normalisation
  1175. sum = 1.0;
  1176. break;
  1177. case 0: // max absolute
  1178. for (int i = 0; i < n; i++) {
  1179. if (sum < std::abs(inp[i])) {
  1180. sum = std::abs(inp[i]);
  1181. }
  1182. }
  1183. sum /= 32760.0; // make an int16 range
  1184. break;
  1185. case 2: // euclidean
  1186. for (int i = 0; i < n; i++) {
  1187. sum += inp[i] * inp[i];
  1188. }
  1189. sum = std::sqrt(sum);
  1190. break;
  1191. default: // p-norm (euclidean is p-norm p=2)
  1192. for (int i = 0; i < n; i++) {
  1193. sum += std::pow(std::abs(inp[i]), embd_norm);
  1194. }
  1195. sum = std::pow(sum, 1.0 / embd_norm);
  1196. break;
  1197. }
  1198. const float norm = sum > 0.0 ? 1.0 / sum : 0.0f;
  1199. for (int i = 0; i < n; i++) {
  1200. out[i] = inp[i] * norm;
  1201. }
  1202. }
  1203. float common_embd_similarity_cos(const float * embd1, const float * embd2, int n){
  1204. double sum = 0.0;
  1205. double sum1 = 0.0;
  1206. double sum2 = 0.0;
  1207. for (int i = 0; i < n; i++) {
  1208. sum += embd1[i] * embd2[i];
  1209. sum1 += embd1[i] * embd1[i];
  1210. sum2 += embd2[i] * embd2[i];
  1211. }
  1212. // Handle the case where one or both vectors are zero vectors
  1213. if (sum1 == 0.0 || sum2 == 0.0) {
  1214. if (sum1 == 0.0 && sum2 == 0.0) {
  1215. return 1.0f; // two zero vectors are similar
  1216. }
  1217. return 0.0f;
  1218. }
  1219. return sum / (sqrt(sum1) * sqrt(sum2));
  1220. }
  1221. //
  1222. // Control vector utils
  1223. //
  1224. static common_control_vector_data common_control_vector_load_one(const common_control_vector_load_info & load_info) {
  1225. common_control_vector_data result = { -1, {} };
  1226. ggml_context * ctx = nullptr;
  1227. struct gguf_init_params meta_gguf_params = {
  1228. /* .no_alloc = */ false,
  1229. /* .ctx = */ &ctx,
  1230. };
  1231. struct gguf_context * ctx_gguf = gguf_init_from_file(load_info.fname.c_str(), meta_gguf_params);
  1232. if (!ctx_gguf) {
  1233. LOG_ERR("%s: failed to load control vector file from %s\n", __func__, load_info.fname.c_str());
  1234. return result;
  1235. }
  1236. int32_t n_tensors = gguf_get_n_tensors(ctx_gguf);
  1237. if (n_tensors == 0) {
  1238. LOG_WRN("%s: no direction tensors found in %s\n", __func__, load_info.fname.c_str());
  1239. }
  1240. for (int i = 0; i < n_tensors; i++) {
  1241. std::string name = gguf_get_tensor_name(ctx_gguf, i);
  1242. int layer_idx = -1;
  1243. // split on '.'
  1244. size_t dotpos = name.find('.');
  1245. if (dotpos != std::string::npos && name.substr(0, dotpos) == "direction") {
  1246. try {
  1247. layer_idx = std::stoi(name.substr(dotpos + 1));
  1248. } catch (...) {
  1249. layer_idx = -1;
  1250. }
  1251. }
  1252. if (layer_idx < 0) {
  1253. LOG_ERR("%s: invalid/unparsable direction tensor layer index in %s\n", __func__, load_info.fname.c_str());
  1254. result.n_embd = -1;
  1255. break;
  1256. } else if (layer_idx == 0) {
  1257. LOG_ERR("%s: invalid (zero) direction tensor layer index in %s\n", __func__, load_info.fname.c_str());
  1258. result.n_embd = -1;
  1259. break;
  1260. }
  1261. struct ggml_tensor * tensor = ggml_get_tensor(ctx, name.c_str());
  1262. if (tensor->type != GGML_TYPE_F32) {
  1263. LOG_ERR("%s: invalid (non-F32) direction tensor type in %s\n", __func__, load_info.fname.c_str());
  1264. result.n_embd = -1;
  1265. break;
  1266. }
  1267. if (ggml_n_dims(tensor) != 1) {
  1268. LOG_ERR("%s: invalid (non-1D) direction tensor shape in %s\n", __func__, load_info.fname.c_str());
  1269. result.n_embd = -1;
  1270. break;
  1271. }
  1272. if (result.n_embd == -1) {
  1273. result.n_embd = ggml_nelements(tensor);
  1274. } else if (ggml_nelements(tensor) != result.n_embd) {
  1275. LOG_ERR("%s: direction tensor in %s does not match previous dimensions\n", __func__, load_info.fname.c_str());
  1276. result.n_embd = -1;
  1277. break;
  1278. }
  1279. // extend if necessary - do not store data for layer 0 (it's not used)
  1280. result.data.resize(std::max(result.data.size(), static_cast<size_t>(result.n_embd * layer_idx)), 0.0f);
  1281. const float * src = (const float *) tensor->data;
  1282. float * dst = result.data.data() + result.n_embd * (layer_idx - 1); // layer 1 at [0]
  1283. for (int j = 0; j < result.n_embd; j++) {
  1284. dst[j] += src[j] * load_info.strength; // allows multiple directions for same layer in same file
  1285. }
  1286. }
  1287. if (result.n_embd == -1) {
  1288. LOG_WRN("%s: skipping %s due to invalid direction tensors\n", __func__, load_info.fname.c_str());
  1289. result.data.clear();
  1290. }
  1291. gguf_free(ctx_gguf);
  1292. ggml_free(ctx);
  1293. return result;
  1294. }
  1295. common_control_vector_data common_control_vector_load(const std::vector<common_control_vector_load_info> & load_infos) {
  1296. common_control_vector_data result = { -1, {} };
  1297. for (const auto & info : load_infos) {
  1298. auto cur = common_control_vector_load_one(info);
  1299. if (cur.n_embd == -1) {
  1300. result.n_embd = -1;
  1301. break;
  1302. }
  1303. if (result.n_embd != -1 && result.n_embd != cur.n_embd) {
  1304. LOG_ERR("%s: control vectors in %s does not match previous dimensions\n", __func__, info.fname.c_str());
  1305. result.n_embd = -1;
  1306. break;
  1307. }
  1308. if (result.n_embd == -1) {
  1309. result = std::move(cur);
  1310. } else {
  1311. result.data.resize(std::max(result.data.size(), cur.data.size()), 0.0f); // extend if necessary
  1312. for (size_t i = 0; i < cur.data.size(); i++) {
  1313. result.data[i] += cur.data[i];
  1314. }
  1315. }
  1316. }
  1317. if (result.n_embd == -1) {
  1318. LOG_ERR("%s: no valid control vector files passed\n", __func__);
  1319. result.data.clear();
  1320. }
  1321. return result;
  1322. }
  1323. ggml_opt_dataset_t common_opt_dataset_init(struct llama_context * ctx, const std::vector<llama_token> & tokens, int64_t stride) {
  1324. const int64_t ne_datapoint = llama_n_ctx(ctx);
  1325. const int64_t ndata = (tokens.size() - ne_datapoint - 1) / stride;
  1326. ggml_opt_dataset_t result = ggml_opt_dataset_init(
  1327. GGML_TYPE_I32, GGML_TYPE_I32, ne_datapoint, ne_datapoint, ndata, /*ndata_shard =*/ 1);
  1328. llama_token * data = (llama_token *) ggml_opt_dataset_data(result)->data;
  1329. llama_token * labels = (llama_token *) ggml_opt_dataset_labels(result)->data;
  1330. for (int64_t idata = 0; idata < ndata; ++idata) {
  1331. memcpy(data + idata*ne_datapoint, tokens.data() + idata*stride + 0, ne_datapoint*sizeof(llama_token));
  1332. memcpy(labels + idata*ne_datapoint, tokens.data() + idata*stride + 1, ne_datapoint*sizeof(llama_token));
  1333. }
  1334. return result;
  1335. }