common.cpp 52 KB

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