common.cpp 49 KB

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