common.cpp 50 KB

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