1
0

common.cpp 113 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003
  1. #include "common.h"
  2. // Change JSON_ASSERT from assert() to GGML_ASSERT:
  3. #define JSON_ASSERT GGML_ASSERT
  4. #include "json.hpp"
  5. #include "json-schema-to-grammar.h"
  6. #include "llama.h"
  7. #include <algorithm>
  8. #include <cassert>
  9. #include <cmath>
  10. #include <cstring>
  11. #include <ctime>
  12. #include <fstream>
  13. #include <iterator>
  14. #include <iostream>
  15. #include <regex>
  16. #include <sstream>
  17. #include <string>
  18. #include <unordered_map>
  19. #include <unordered_set>
  20. #include <vector>
  21. #include <cinttypes>
  22. #include <codecvt>
  23. #if defined(__APPLE__) && defined(__MACH__)
  24. #include <sys/types.h>
  25. #include <sys/sysctl.h>
  26. #endif
  27. #if defined(_WIN32)
  28. #define WIN32_LEAN_AND_MEAN
  29. #ifndef NOMINMAX
  30. # define NOMINMAX
  31. #endif
  32. #include <locale>
  33. #include <windows.h>
  34. #include <fcntl.h>
  35. #include <io.h>
  36. #else
  37. #include <sys/ioctl.h>
  38. #include <sys/stat.h>
  39. #include <unistd.h>
  40. #endif
  41. #if defined(LLAMA_USE_CURL)
  42. #include <curl/curl.h>
  43. #include <curl/easy.h>
  44. #include <thread>
  45. #include <future>
  46. #endif
  47. #if defined(_MSC_VER)
  48. #pragma warning(disable: 4244 4267) // possible loss of data
  49. #endif
  50. #if (defined(GGML_USE_CUDA) || defined(GGML_USE_SYCL))
  51. #define GGML_USE_CUDA_SYCL
  52. #endif
  53. #if (defined(GGML_USE_CUDA) || defined(GGML_USE_SYCL)) || defined(GGML_USE_VULKAN)
  54. #define GGML_USE_CUDA_SYCL_VULKAN
  55. #endif
  56. #if defined(LLAMA_USE_CURL)
  57. #ifdef __linux__
  58. #include <linux/limits.h>
  59. #elif defined(_WIN32)
  60. #define PATH_MAX MAX_PATH
  61. #else
  62. #include <sys/syslimits.h>
  63. #endif
  64. #define LLAMA_CURL_MAX_URL_LENGTH 2084 // Maximum URL Length in Chrome: 2083
  65. #endif // LLAMA_USE_CURL
  66. using json = nlohmann::ordered_json;
  67. int32_t get_num_physical_cores() {
  68. #ifdef __linux__
  69. // enumerate the set of thread siblings, num entries is num cores
  70. std::unordered_set<std::string> siblings;
  71. for (uint32_t cpu=0; cpu < UINT32_MAX; ++cpu) {
  72. std::ifstream thread_siblings("/sys/devices/system/cpu/cpu"
  73. + std::to_string(cpu) + "/topology/thread_siblings");
  74. if (!thread_siblings.is_open()) {
  75. break; // no more cpus
  76. }
  77. std::string line;
  78. if (std::getline(thread_siblings, line)) {
  79. siblings.insert(line);
  80. }
  81. }
  82. if (!siblings.empty()) {
  83. return static_cast<int32_t>(siblings.size());
  84. }
  85. #elif defined(__APPLE__) && defined(__MACH__)
  86. int32_t num_physical_cores;
  87. size_t len = sizeof(num_physical_cores);
  88. int result = sysctlbyname("hw.perflevel0.physicalcpu", &num_physical_cores, &len, NULL, 0);
  89. if (result == 0) {
  90. return num_physical_cores;
  91. }
  92. result = sysctlbyname("hw.physicalcpu", &num_physical_cores, &len, NULL, 0);
  93. if (result == 0) {
  94. return num_physical_cores;
  95. }
  96. #elif defined(_WIN32)
  97. //TODO: Implement
  98. #endif
  99. unsigned int n_threads = std::thread::hardware_concurrency();
  100. return n_threads > 0 ? (n_threads <= 4 ? n_threads : n_threads / 2) : 4;
  101. }
  102. #if defined(__x86_64__) && defined(__linux__) && !defined(__ANDROID__)
  103. #include <pthread.h>
  104. static void cpuid(unsigned leaf, unsigned subleaf,
  105. unsigned *eax, unsigned *ebx, unsigned *ecx, unsigned *edx) {
  106. __asm__("movq\t%%rbx,%%rsi\n\t"
  107. "cpuid\n\t"
  108. "xchgq\t%%rbx,%%rsi"
  109. : "=a"(*eax), "=S"(*ebx), "=c"(*ecx), "=d"(*edx)
  110. : "0"(leaf), "2"(subleaf));
  111. }
  112. static int pin_cpu(int cpu) {
  113. cpu_set_t mask;
  114. CPU_ZERO(&mask);
  115. CPU_SET(cpu, &mask);
  116. return pthread_setaffinity_np(pthread_self(), sizeof(mask), &mask);
  117. }
  118. static bool is_hybrid_cpu(void) {
  119. unsigned eax, ebx, ecx, edx;
  120. cpuid(7, 0, &eax, &ebx, &ecx, &edx);
  121. return !!(edx & (1u << 15));
  122. }
  123. static bool is_running_on_efficiency_core(void) {
  124. unsigned eax, ebx, ecx, edx;
  125. cpuid(0x1a, 0, &eax, &ebx, &ecx, &edx);
  126. int intel_atom = 0x20;
  127. int core_type = (eax & 0xff000000u) >> 24;
  128. return core_type == intel_atom;
  129. }
  130. static int count_math_cpus(int cpu_count) {
  131. int result = 0;
  132. for (int cpu = 0; cpu < cpu_count; ++cpu) {
  133. if (pin_cpu(cpu)) {
  134. return -1;
  135. }
  136. if (is_running_on_efficiency_core()) {
  137. continue; // efficiency cores harm lockstep threading
  138. }
  139. ++cpu; // hyperthreading isn't useful for linear algebra
  140. ++result;
  141. }
  142. return result;
  143. }
  144. #endif // __x86_64__ && __linux__
  145. /**
  146. * Returns number of CPUs on system that are useful for math.
  147. */
  148. int get_math_cpu_count() {
  149. #if defined(__x86_64__) && defined(__linux__) && !defined(__ANDROID__)
  150. int cpu_count = sysconf(_SC_NPROCESSORS_ONLN);
  151. if (cpu_count < 1) {
  152. return get_num_physical_cores();
  153. }
  154. if (is_hybrid_cpu()) {
  155. cpu_set_t affinity;
  156. if (!pthread_getaffinity_np(pthread_self(), sizeof(affinity), &affinity)) {
  157. int result = count_math_cpus(cpu_count);
  158. pthread_setaffinity_np(pthread_self(), sizeof(affinity), &affinity);
  159. if (result > 0) {
  160. return result;
  161. }
  162. }
  163. }
  164. #endif
  165. return get_num_physical_cores();
  166. }
  167. void process_escapes(std::string & input) {
  168. std::size_t input_len = input.length();
  169. std::size_t output_idx = 0;
  170. for (std::size_t input_idx = 0; input_idx < input_len; ++input_idx) {
  171. if (input[input_idx] == '\\' && input_idx + 1 < input_len) {
  172. switch (input[++input_idx]) {
  173. case 'n': input[output_idx++] = '\n'; break;
  174. case 'r': input[output_idx++] = '\r'; break;
  175. case 't': input[output_idx++] = '\t'; break;
  176. case '\'': input[output_idx++] = '\''; break;
  177. case '\"': input[output_idx++] = '\"'; break;
  178. case '\\': input[output_idx++] = '\\'; break;
  179. case 'x':
  180. // Handle \x12, etc
  181. if (input_idx + 2 < input_len) {
  182. const char x[3] = { input[input_idx + 1], input[input_idx + 2], 0 };
  183. char *err_p = nullptr;
  184. const long val = std::strtol(x, &err_p, 16);
  185. if (err_p == x + 2) {
  186. input_idx += 2;
  187. input[output_idx++] = char(val);
  188. break;
  189. }
  190. }
  191. // fall through
  192. default: input[output_idx++] = '\\';
  193. input[output_idx++] = input[input_idx]; break;
  194. }
  195. } else {
  196. input[output_idx++] = input[input_idx];
  197. }
  198. }
  199. input.resize(output_idx);
  200. }
  201. bool gpt_params_parse(int argc, char ** argv, gpt_params & params) {
  202. bool result = true;
  203. try {
  204. if (!gpt_params_parse_ex(argc, argv, params)) {
  205. gpt_print_usage(argc, argv, gpt_params());
  206. exit(0);
  207. }
  208. }
  209. catch (const std::invalid_argument & ex) {
  210. fprintf(stderr, "%s\n", ex.what());
  211. gpt_print_usage(argc, argv, gpt_params());
  212. exit(1);
  213. }
  214. return result;
  215. }
  216. bool parse_kv_override(const char * data, std::vector<llama_model_kv_override> & overrides) {
  217. const char * sep = strchr(data, '=');
  218. if (sep == nullptr || sep - data >= 128) {
  219. fprintf(stderr, "%s: malformed KV override '%s'\n", __func__, data);
  220. return false;
  221. }
  222. llama_model_kv_override kvo;
  223. std::strncpy(kvo.key, data, sep - data);
  224. kvo.key[sep - data] = 0;
  225. sep++;
  226. if (strncmp(sep, "int:", 4) == 0) {
  227. sep += 4;
  228. kvo.tag = LLAMA_KV_OVERRIDE_TYPE_INT;
  229. kvo.val_i64 = std::atol(sep);
  230. } else if (strncmp(sep, "float:", 6) == 0) {
  231. sep += 6;
  232. kvo.tag = LLAMA_KV_OVERRIDE_TYPE_FLOAT;
  233. kvo.val_f64 = std::atof(sep);
  234. } else if (strncmp(sep, "bool:", 5) == 0) {
  235. sep += 5;
  236. kvo.tag = LLAMA_KV_OVERRIDE_TYPE_BOOL;
  237. if (std::strcmp(sep, "true") == 0) {
  238. kvo.val_bool = true;
  239. } else if (std::strcmp(sep, "false") == 0) {
  240. kvo.val_bool = false;
  241. } else {
  242. fprintf(stderr, "%s: invalid boolean value for KV override '%s'\n", __func__, data);
  243. return false;
  244. }
  245. } else if (strncmp(sep, "str:", 4) == 0) {
  246. sep += 4;
  247. kvo.tag = LLAMA_KV_OVERRIDE_TYPE_STR;
  248. if (strlen(sep) > 127) {
  249. fprintf(stderr, "%s: malformed KV override '%s', value cannot exceed 127 chars\n", __func__, data);
  250. return false;
  251. }
  252. strncpy(kvo.val_str, sep, 127);
  253. kvo.val_str[127] = '\0';
  254. } else {
  255. fprintf(stderr, "%s: invalid type for KV override '%s'\n", __func__, data);
  256. return false;
  257. }
  258. overrides.emplace_back(std::move(kvo));
  259. return true;
  260. }
  261. bool gpt_params_find_arg(int argc, char ** argv, const std::string & arg, gpt_params & params, int & i, bool & invalid_param) {
  262. llama_sampling_params & sparams = params.sparams;
  263. if (arg == "-s" || arg == "--seed") {
  264. if (++i >= argc) {
  265. invalid_param = true;
  266. return true;
  267. }
  268. // This is temporary, in the future the samplign state will be moved fully to llama_sampling_context.
  269. params.seed = std::stoul(argv[i]);
  270. sparams.seed = std::stoul(argv[i]);
  271. return true;
  272. }
  273. if (arg == "-t" || arg == "--threads") {
  274. if (++i >= argc) {
  275. invalid_param = true;
  276. return true;
  277. }
  278. params.n_threads = std::stoi(argv[i]);
  279. if (params.n_threads <= 0) {
  280. params.n_threads = std::thread::hardware_concurrency();
  281. }
  282. return true;
  283. }
  284. if (arg == "-tb" || arg == "--threads-batch") {
  285. if (++i >= argc) {
  286. invalid_param = true;
  287. return true;
  288. }
  289. params.n_threads_batch = std::stoi(argv[i]);
  290. if (params.n_threads_batch <= 0) {
  291. params.n_threads_batch = std::thread::hardware_concurrency();
  292. }
  293. return true;
  294. }
  295. if (arg == "-td" || arg == "--threads-draft") {
  296. if (++i >= argc) {
  297. invalid_param = true;
  298. return true;
  299. }
  300. params.n_threads_draft = std::stoi(argv[i]);
  301. if (params.n_threads_draft <= 0) {
  302. params.n_threads_draft = std::thread::hardware_concurrency();
  303. }
  304. return true;
  305. }
  306. if (arg == "-tbd" || arg == "--threads-batch-draft") {
  307. if (++i >= argc) {
  308. invalid_param = true;
  309. return true;
  310. }
  311. params.n_threads_batch_draft = std::stoi(argv[i]);
  312. if (params.n_threads_batch_draft <= 0) {
  313. params.n_threads_batch_draft = std::thread::hardware_concurrency();
  314. }
  315. return true;
  316. }
  317. if (arg == "-p" || arg == "--prompt") {
  318. if (++i >= argc) {
  319. invalid_param = true;
  320. return true;
  321. }
  322. params.prompt = argv[i];
  323. return true;
  324. }
  325. if (arg == "-e" || arg == "--escape") {
  326. params.escape = true;
  327. return true;
  328. }
  329. if (arg == "--prompt-cache") {
  330. if (++i >= argc) {
  331. invalid_param = true;
  332. return true;
  333. }
  334. params.path_prompt_cache = argv[i];
  335. return true;
  336. }
  337. if (arg == "--prompt-cache-all") {
  338. params.prompt_cache_all = true;
  339. return true;
  340. }
  341. if (arg == "--prompt-cache-ro") {
  342. params.prompt_cache_ro = true;
  343. return true;
  344. }
  345. if (arg == "-bf" || arg == "--binary-file") {
  346. if (++i >= argc) {
  347. invalid_param = true;
  348. return true;
  349. }
  350. std::ifstream file(argv[i], std::ios::binary);
  351. if (!file) {
  352. fprintf(stderr, "error: failed to open file '%s'\n", argv[i]);
  353. invalid_param = true;
  354. return true;
  355. }
  356. // store the external file name in params
  357. params.prompt_file = argv[i];
  358. std::ostringstream ss;
  359. ss << file.rdbuf();
  360. params.prompt = ss.str();
  361. fprintf(stderr, "Read %zu bytes from binary file %s\n", params.prompt.size(), argv[i]);
  362. return true;
  363. }
  364. if (arg == "-f" || arg == "--file") {
  365. if (++i >= argc) {
  366. invalid_param = true;
  367. return true;
  368. }
  369. std::ifstream file(argv[i]);
  370. if (!file) {
  371. fprintf(stderr, "error: failed to open file '%s'\n", argv[i]);
  372. invalid_param = true;
  373. return true;
  374. }
  375. // store the external file name in params
  376. params.prompt_file = argv[i];
  377. std::copy(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>(), back_inserter(params.prompt));
  378. if (!params.prompt.empty() && params.prompt.back() == '\n') {
  379. params.prompt.pop_back();
  380. }
  381. return true;
  382. }
  383. if (arg == "-n" || arg == "--n-predict") {
  384. if (++i >= argc) {
  385. invalid_param = true;
  386. return true;
  387. }
  388. params.n_predict = std::stoi(argv[i]);
  389. return true;
  390. }
  391. if (arg == "--top-k") {
  392. if (++i >= argc) {
  393. invalid_param = true;
  394. return true;
  395. }
  396. sparams.top_k = std::stoi(argv[i]);
  397. return true;
  398. }
  399. if (arg == "-c" || arg == "--ctx-size") {
  400. if (++i >= argc) {
  401. invalid_param = true;
  402. return true;
  403. }
  404. params.n_ctx = std::stoi(argv[i]);
  405. return true;
  406. }
  407. if (arg == "--grp-attn-n" || arg == "-gan") {
  408. if (++i >= argc) {
  409. invalid_param = true;
  410. return true;
  411. }
  412. params.grp_attn_n = std::stoi(argv[i]);
  413. return true;
  414. }
  415. if (arg == "--grp-attn-w" || arg == "-gaw") {
  416. if (++i >= argc) {
  417. invalid_param = true;
  418. return true;
  419. }
  420. params.grp_attn_w = std::stoi(argv[i]);
  421. return true;
  422. }
  423. if (arg == "--rope-freq-base") {
  424. if (++i >= argc) {
  425. invalid_param = true;
  426. return true;
  427. }
  428. params.rope_freq_base = std::stof(argv[i]);
  429. return true;
  430. }
  431. if (arg == "--rope-freq-scale") {
  432. if (++i >= argc) {
  433. invalid_param = true;
  434. return true;
  435. }
  436. params.rope_freq_scale = std::stof(argv[i]);
  437. return true;
  438. }
  439. if (arg == "--rope-scaling") {
  440. if (++i >= argc) {
  441. invalid_param = true;
  442. return true;
  443. }
  444. std::string value(argv[i]);
  445. /**/ if (value == "none") { params.rope_scaling_type = LLAMA_ROPE_SCALING_TYPE_NONE; }
  446. else if (value == "linear") { params.rope_scaling_type = LLAMA_ROPE_SCALING_TYPE_LINEAR; }
  447. else if (value == "yarn") { params.rope_scaling_type = LLAMA_ROPE_SCALING_TYPE_YARN; }
  448. else { invalid_param = true; }
  449. return true;
  450. }
  451. if (arg == "--rope-scale") {
  452. if (++i >= argc) {
  453. invalid_param = true;
  454. return true;
  455. }
  456. params.rope_freq_scale = 1.0f / std::stof(argv[i]);
  457. return true;
  458. }
  459. if (arg == "--yarn-orig-ctx") {
  460. if (++i >= argc) {
  461. invalid_param = true;
  462. return true;
  463. }
  464. params.yarn_orig_ctx = std::stoi(argv[i]);
  465. return true;
  466. }
  467. if (arg == "--yarn-ext-factor") {
  468. if (++i >= argc) {
  469. invalid_param = true;
  470. return true;
  471. }
  472. params.yarn_ext_factor = std::stof(argv[i]);
  473. return true;
  474. }
  475. if (arg == "--yarn-attn-factor") {
  476. if (++i >= argc) {
  477. invalid_param = true;
  478. return true;
  479. }
  480. params.yarn_attn_factor = std::stof(argv[i]);
  481. return true;
  482. }
  483. if (arg == "--yarn-beta-fast") {
  484. if (++i >= argc) {
  485. invalid_param = true;
  486. return true;
  487. }
  488. params.yarn_beta_fast = std::stof(argv[i]);
  489. return true;
  490. }
  491. if (arg == "--yarn-beta-slow") {
  492. if (++i >= argc) {
  493. invalid_param = true;
  494. return true;
  495. }
  496. params.yarn_beta_slow = std::stof(argv[i]);
  497. return true;
  498. }
  499. if (arg == "--pooling") {
  500. if (++i >= argc) {
  501. invalid_param = true;
  502. return true;
  503. }
  504. std::string value(argv[i]);
  505. /**/ if (value == "none") { params.pooling_type = LLAMA_POOLING_TYPE_NONE; }
  506. else if (value == "mean") { params.pooling_type = LLAMA_POOLING_TYPE_MEAN; }
  507. else if (value == "cls") { params.pooling_type = LLAMA_POOLING_TYPE_CLS; }
  508. else { invalid_param = true; }
  509. return true;
  510. }
  511. if (arg == "--defrag-thold" || arg == "-dt") {
  512. if (++i >= argc) {
  513. invalid_param = true;
  514. return true;
  515. }
  516. params.defrag_thold = std::stof(argv[i]);
  517. return true;
  518. }
  519. if (arg == "--samplers") {
  520. if (++i >= argc) {
  521. invalid_param = true;
  522. return true;
  523. }
  524. const auto sampler_names = string_split(argv[i], ';');
  525. sparams.samplers_sequence = sampler_types_from_names(sampler_names, true);
  526. return true;
  527. }
  528. if (arg == "--sampling-seq") {
  529. if (++i >= argc) {
  530. invalid_param = true;
  531. return true;
  532. }
  533. sparams.samplers_sequence = sampler_types_from_chars(argv[i]);
  534. return true;
  535. }
  536. if (arg == "--top-p") {
  537. if (++i >= argc) {
  538. invalid_param = true;
  539. return true;
  540. }
  541. sparams.top_p = std::stof(argv[i]);
  542. return true;
  543. }
  544. if (arg == "--min-p") {
  545. if (++i >= argc) {
  546. invalid_param = true;
  547. return true;
  548. }
  549. sparams.min_p = std::stof(argv[i]);
  550. return true;
  551. }
  552. if (arg == "--temp") {
  553. if (++i >= argc) {
  554. invalid_param = true;
  555. return true;
  556. }
  557. sparams.temp = std::stof(argv[i]);
  558. sparams.temp = std::max(sparams.temp, 0.0f);
  559. return true;
  560. }
  561. if (arg == "--tfs") {
  562. if (++i >= argc) {
  563. invalid_param = true;
  564. return true;
  565. }
  566. sparams.tfs_z = std::stof(argv[i]);
  567. return true;
  568. }
  569. if (arg == "--typical") {
  570. if (++i >= argc) {
  571. invalid_param = true;
  572. return true;
  573. }
  574. sparams.typical_p = std::stof(argv[i]);
  575. return true;
  576. }
  577. if (arg == "--repeat-last-n") {
  578. if (++i >= argc) {
  579. invalid_param = true;
  580. return true;
  581. }
  582. sparams.penalty_last_n = std::stoi(argv[i]);
  583. sparams.n_prev = std::max(sparams.n_prev, sparams.penalty_last_n);
  584. return true;
  585. }
  586. if (arg == "--repeat-penalty") {
  587. if (++i >= argc) {
  588. invalid_param = true;
  589. return true;
  590. }
  591. sparams.penalty_repeat = std::stof(argv[i]);
  592. return true;
  593. }
  594. if (arg == "--frequency-penalty") {
  595. if (++i >= argc) {
  596. invalid_param = true;
  597. return true;
  598. }
  599. sparams.penalty_freq = std::stof(argv[i]);
  600. return true;
  601. }
  602. if (arg == "--presence-penalty") {
  603. if (++i >= argc) {
  604. invalid_param = true;
  605. return true;
  606. }
  607. sparams.penalty_present = std::stof(argv[i]);
  608. return true;
  609. }
  610. if (arg == "--dynatemp-range") {
  611. if (++i >= argc) {
  612. invalid_param = true;
  613. return true;
  614. }
  615. sparams.dynatemp_range = std::stof(argv[i]);
  616. return true;
  617. }
  618. if (arg == "--dynatemp-exp") {
  619. if (++i >= argc) {
  620. invalid_param = true;
  621. return true;
  622. }
  623. sparams.dynatemp_exponent = std::stof(argv[i]);
  624. return true;
  625. }
  626. if (arg == "--mirostat") {
  627. if (++i >= argc) {
  628. invalid_param = true;
  629. return true;
  630. }
  631. sparams.mirostat = std::stoi(argv[i]);
  632. return true;
  633. }
  634. if (arg == "--mirostat-lr") {
  635. if (++i >= argc) {
  636. invalid_param = true;
  637. return true;
  638. }
  639. sparams.mirostat_eta = std::stof(argv[i]);
  640. return true;
  641. }
  642. if (arg == "--mirostat-ent") {
  643. if (++i >= argc) {
  644. invalid_param = true;
  645. return true;
  646. }
  647. sparams.mirostat_tau = std::stof(argv[i]);
  648. return true;
  649. }
  650. if (arg == "--cfg-negative-prompt") {
  651. if (++i >= argc) {
  652. invalid_param = true;
  653. return true;
  654. }
  655. sparams.cfg_negative_prompt = argv[i];
  656. return true;
  657. }
  658. if (arg == "--cfg-negative-prompt-file") {
  659. if (++i >= argc) {
  660. invalid_param = true;
  661. return true;
  662. }
  663. std::ifstream file(argv[i]);
  664. if (!file) {
  665. fprintf(stderr, "error: failed to open file '%s'\n", argv[i]);
  666. invalid_param = true;
  667. return true;
  668. }
  669. std::copy(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>(), back_inserter(sparams.cfg_negative_prompt));
  670. if (!sparams.cfg_negative_prompt.empty() && sparams.cfg_negative_prompt.back() == '\n') {
  671. sparams.cfg_negative_prompt.pop_back();
  672. }
  673. return true;
  674. }
  675. if (arg == "--cfg-scale") {
  676. if (++i >= argc) {
  677. invalid_param = true;
  678. return true;
  679. }
  680. sparams.cfg_scale = std::stof(argv[i]);
  681. return true;
  682. }
  683. if (arg == "-b" || arg == "--batch-size") {
  684. if (++i >= argc) {
  685. invalid_param = true;
  686. return true;
  687. }
  688. params.n_batch = std::stoi(argv[i]);
  689. return true;
  690. }
  691. if (arg == "-ub" || arg == "--ubatch-size") {
  692. if (++i >= argc) {
  693. invalid_param = true;
  694. return true;
  695. }
  696. params.n_ubatch = std::stoi(argv[i]);
  697. return true;
  698. }
  699. if (arg == "--keep") {
  700. if (++i >= argc) {
  701. invalid_param = true;
  702. return true;
  703. }
  704. params.n_keep = std::stoi(argv[i]);
  705. return true;
  706. }
  707. if (arg == "--draft") {
  708. if (++i >= argc) {
  709. invalid_param = true;
  710. return true;
  711. }
  712. params.n_draft = std::stoi(argv[i]);
  713. return true;
  714. }
  715. if (arg == "--chunks") {
  716. if (++i >= argc) {
  717. invalid_param = true;
  718. return true;
  719. }
  720. params.n_chunks = std::stoi(argv[i]);
  721. return true;
  722. }
  723. if (arg == "-np" || arg == "--parallel") {
  724. if (++i >= argc) {
  725. invalid_param = true;
  726. return true;
  727. }
  728. params.n_parallel = std::stoi(argv[i]);
  729. return true;
  730. }
  731. if (arg == "-ns" || arg == "--sequences") {
  732. if (++i >= argc) {
  733. invalid_param = true;
  734. return true;
  735. }
  736. params.n_sequences = std::stoi(argv[i]);
  737. return true;
  738. }
  739. if (arg == "--p-split" || arg == "-ps") {
  740. if (++i >= argc) {
  741. invalid_param = true;
  742. return true;
  743. }
  744. params.p_split = std::stof(argv[i]);
  745. return true;
  746. }
  747. if (arg == "-m" || arg == "--model") {
  748. if (++i >= argc) {
  749. invalid_param = true;
  750. return true;
  751. }
  752. params.model = argv[i];
  753. return true;
  754. }
  755. if (arg == "-md" || arg == "--model-draft") {
  756. if (++i >= argc) {
  757. invalid_param = true;
  758. return true;
  759. }
  760. params.model_draft = argv[i];
  761. return true;
  762. }
  763. if (arg == "-a" || arg == "--alias") {
  764. if (++i >= argc) {
  765. invalid_param = true;
  766. return true;
  767. }
  768. params.model_alias = argv[i];
  769. return true;
  770. }
  771. if (arg == "-mu" || arg == "--model-url") {
  772. if (++i >= argc) {
  773. invalid_param = true;
  774. return true;
  775. }
  776. params.model_url = argv[i];
  777. return true;
  778. }
  779. if (arg == "-hfr" || arg == "--hf-repo") {
  780. if (++i >= argc) {
  781. invalid_param = true;
  782. return true;
  783. }
  784. params.hf_repo = argv[i];
  785. return true;
  786. }
  787. if (arg == "-hff" || arg == "--hf-file") {
  788. if (++i >= argc) {
  789. invalid_param = true;
  790. return true;
  791. }
  792. params.hf_file = argv[i];
  793. return true;
  794. }
  795. if (arg == "--lora") {
  796. if (++i >= argc) {
  797. invalid_param = true;
  798. return true;
  799. }
  800. params.lora_adapter.emplace_back(argv[i], 1.0f);
  801. params.use_mmap = false;
  802. return true;
  803. }
  804. if (arg == "--lora-scaled") {
  805. if (++i >= argc) {
  806. invalid_param = true;
  807. return true;
  808. }
  809. const char* lora_adapter = argv[i];
  810. if (++i >= argc) {
  811. invalid_param = true;
  812. return true;
  813. }
  814. params.lora_adapter.emplace_back(lora_adapter, std::stof(argv[i]));
  815. params.use_mmap = false;
  816. return true;
  817. }
  818. if (arg == "--lora-base") {
  819. if (++i >= argc) {
  820. invalid_param = true;
  821. return true;
  822. }
  823. params.lora_base = argv[i];
  824. return true;
  825. }
  826. if (arg == "--control-vector") {
  827. if (++i >= argc) {
  828. invalid_param = true;
  829. return true;
  830. }
  831. params.control_vectors.push_back({ 1.0f, argv[i], });
  832. return true;
  833. }
  834. if (arg == "--control-vector-scaled") {
  835. if (++i >= argc) {
  836. invalid_param = true;
  837. return true;
  838. }
  839. const char* fname = argv[i];
  840. if (++i >= argc) {
  841. invalid_param = true;
  842. return true;
  843. }
  844. params.control_vectors.push_back({ std::stof(argv[i]), fname, });
  845. return true;
  846. }
  847. if (arg == "--control-vector-layer-range") {
  848. if (++i >= argc) {
  849. invalid_param = true;
  850. return true;
  851. }
  852. params.control_vector_layer_start = std::stoi(argv[i]);
  853. if (++i >= argc) {
  854. invalid_param = true;
  855. return true;
  856. }
  857. params.control_vector_layer_end = std::stoi(argv[i]);
  858. return true;
  859. }
  860. if (arg == "--mmproj") {
  861. if (++i >= argc) {
  862. invalid_param = true;
  863. return true;
  864. }
  865. params.mmproj = argv[i];
  866. return true;
  867. }
  868. if (arg == "--image") {
  869. if (++i >= argc) {
  870. invalid_param = true;
  871. return true;
  872. }
  873. params.image.emplace_back(argv[i]);
  874. return true;
  875. }
  876. if (arg == "-i" || arg == "--interactive") {
  877. params.interactive = true;
  878. return true;
  879. }
  880. if (arg == "--interactive-specials") {
  881. params.interactive_specials = true;
  882. return true;
  883. }
  884. if (arg == "--embedding") {
  885. params.embedding = true;
  886. return true;
  887. }
  888. if (arg == "--interactive-first") {
  889. params.interactive_first = true;
  890. return true;
  891. }
  892. if (arg == "-ins" || arg == "--instruct") {
  893. params.instruct = true;
  894. return true;
  895. }
  896. if (arg == "-cnv" || arg == "--conversation") {
  897. params.conversation = true;
  898. return true;
  899. }
  900. if (arg == "-cml" || arg == "--chatml") {
  901. params.chatml = true;
  902. return true;
  903. }
  904. if (arg == "--infill") {
  905. params.infill = true;
  906. return true;
  907. }
  908. if (arg == "-dkvc" || arg == "--dump-kv-cache") {
  909. params.dump_kv_cache = true;
  910. return true;
  911. }
  912. if (arg == "-nkvo" || arg == "--no-kv-offload") {
  913. params.no_kv_offload = true;
  914. return true;
  915. }
  916. if (arg == "-ctk" || arg == "--cache-type-k") {
  917. params.cache_type_k = argv[++i];
  918. return true;
  919. }
  920. if (arg == "-ctv" || arg == "--cache-type-v") {
  921. params.cache_type_v = argv[++i];
  922. return true;
  923. }
  924. if (arg == "--multiline-input") {
  925. params.multiline_input = true;
  926. return true;
  927. }
  928. if (arg == "--simple-io") {
  929. params.simple_io = true;
  930. return true;
  931. }
  932. if (arg == "-cb" || arg == "--cont-batching") {
  933. params.cont_batching = true;
  934. return true;
  935. }
  936. if (arg == "-fa" || arg == "--flash-attn") {
  937. params.flash_attn = true;
  938. return true;
  939. }
  940. if (arg == "--color") {
  941. params.use_color = true;
  942. return true;
  943. }
  944. if (arg == "--mlock") {
  945. params.use_mlock = true;
  946. return true;
  947. }
  948. if (arg == "--gpu-layers" || arg == "-ngl" || arg == "--n-gpu-layers") {
  949. if (++i >= argc) {
  950. invalid_param = true;
  951. return true;
  952. }
  953. params.n_gpu_layers = std::stoi(argv[i]);
  954. if (!llama_supports_gpu_offload()) {
  955. fprintf(stderr, "warning: not compiled with GPU offload support, --n-gpu-layers option will be ignored\n");
  956. fprintf(stderr, "warning: see main README.md for information on enabling GPU BLAS support\n");
  957. }
  958. return true;
  959. }
  960. if (arg == "--gpu-layers-draft" || arg == "-ngld" || arg == "--n-gpu-layers-draft") {
  961. if (++i >= argc) {
  962. invalid_param = true;
  963. return true;
  964. }
  965. params.n_gpu_layers_draft = std::stoi(argv[i]);
  966. if (!llama_supports_gpu_offload()) {
  967. fprintf(stderr, "warning: not compiled with GPU offload support, --n-gpu-layers-draft option will be ignored\n");
  968. fprintf(stderr, "warning: see main README.md for information on enabling GPU BLAS support\n");
  969. }
  970. return true;
  971. }
  972. if (arg == "--main-gpu" || arg == "-mg") {
  973. if (++i >= argc) {
  974. invalid_param = true;
  975. return true;
  976. }
  977. params.main_gpu = std::stoi(argv[i]);
  978. #ifndef GGML_USE_CUDA_SYCL
  979. fprintf(stderr, "warning: llama.cpp was compiled without CUDA/SYCL. Setting the main GPU has no effect.\n");
  980. #endif // GGML_USE_CUDA_SYCL
  981. return true;
  982. }
  983. if (arg == "--split-mode" || arg == "-sm") {
  984. if (++i >= argc) {
  985. invalid_param = true;
  986. return true;
  987. }
  988. std::string arg_next = argv[i];
  989. if (arg_next == "none") {
  990. params.split_mode = LLAMA_SPLIT_MODE_NONE;
  991. }
  992. else if (arg_next == "layer") {
  993. params.split_mode = LLAMA_SPLIT_MODE_LAYER;
  994. }
  995. else if (arg_next == "row") {
  996. #ifdef GGML_USE_SYCL
  997. fprintf(stderr, "warning: The split mode value:[row] is not supported by llama.cpp with SYCL. It's developing.\nExit!\n");
  998. exit(1);
  999. #endif // GGML_USE_SYCL
  1000. params.split_mode = LLAMA_SPLIT_MODE_ROW;
  1001. }
  1002. else {
  1003. invalid_param = true;
  1004. return true;
  1005. }
  1006. #ifndef GGML_USE_CUDA_SYCL
  1007. fprintf(stderr, "warning: llama.cpp was compiled without CUDA/SYCL. Setting the split mode has no effect.\n");
  1008. #endif // GGML_USE_CUDA_SYCL
  1009. return true;
  1010. }
  1011. if (arg == "--tensor-split" || arg == "-ts") {
  1012. if (++i >= argc) {
  1013. invalid_param = true;
  1014. return true;
  1015. }
  1016. std::string arg_next = argv[i];
  1017. // split string by , and /
  1018. const std::regex regex{ R"([,/]+)" };
  1019. std::sregex_token_iterator it{ arg_next.begin(), arg_next.end(), regex, -1 };
  1020. std::vector<std::string> split_arg{ it, {} };
  1021. if (split_arg.size() >= llama_max_devices()) {
  1022. invalid_param = true;
  1023. return true;
  1024. }
  1025. for (size_t i = 0; i < llama_max_devices(); ++i) {
  1026. if (i < split_arg.size()) {
  1027. params.tensor_split[i] = std::stof(split_arg[i]);
  1028. }
  1029. else {
  1030. params.tensor_split[i] = 0.0f;
  1031. }
  1032. }
  1033. #ifndef GGML_USE_CUDA_SYCL_VULKAN
  1034. fprintf(stderr, "warning: llama.cpp was compiled without CUDA/SYCL/Vulkan. Setting a tensor split has no effect.\n");
  1035. #endif // GGML_USE_CUDA_SYCL_VULKAN
  1036. return true;
  1037. }
  1038. if (arg == "--no-mmap") {
  1039. params.use_mmap = false;
  1040. return true;
  1041. }
  1042. if (arg == "--numa") {
  1043. if (++i >= argc) {
  1044. invalid_param = true;
  1045. return true;
  1046. }
  1047. std::string value(argv[i]);
  1048. /**/ if (value == "distribute" || value == "") { params.numa = GGML_NUMA_STRATEGY_DISTRIBUTE; }
  1049. else if (value == "isolate") { params.numa = GGML_NUMA_STRATEGY_ISOLATE; }
  1050. else if (value == "numactl") { params.numa = GGML_NUMA_STRATEGY_NUMACTL; }
  1051. else { invalid_param = true; }
  1052. return true;
  1053. }
  1054. if (arg == "--verbose-prompt") {
  1055. params.verbose_prompt = true;
  1056. return true;
  1057. }
  1058. if (arg == "--no-display-prompt") {
  1059. params.display_prompt = false;
  1060. return true;
  1061. }
  1062. if (arg == "-r" || arg == "--reverse-prompt") {
  1063. if (++i >= argc) {
  1064. invalid_param = true;
  1065. return true;
  1066. }
  1067. params.antiprompt.emplace_back(argv[i]);
  1068. return true;
  1069. }
  1070. if (arg == "-ld" || arg == "--logdir") {
  1071. if (++i >= argc) {
  1072. invalid_param = true;
  1073. return true;
  1074. }
  1075. params.logdir = argv[i];
  1076. if (params.logdir.back() != DIRECTORY_SEPARATOR) {
  1077. params.logdir += DIRECTORY_SEPARATOR;
  1078. }
  1079. return true;
  1080. }
  1081. if (arg == "-lcs" || arg == "--lookup-cache-static") {
  1082. if (++i >= argc) {
  1083. invalid_param = true;
  1084. return true;
  1085. }
  1086. params.lookup_cache_static = argv[i];
  1087. return true;
  1088. }
  1089. if (arg == "-lcd" || arg == "--lookup-cache-dynamic") {
  1090. if (++i >= argc) {
  1091. invalid_param = true;
  1092. return true;
  1093. }
  1094. params.lookup_cache_dynamic = argv[i];
  1095. return true;
  1096. }
  1097. if (arg == "--save-all-logits" || arg == "--kl-divergence-base") {
  1098. if (++i >= argc) {
  1099. invalid_param = true;
  1100. return true;
  1101. }
  1102. params.logits_file = argv[i];
  1103. return true;
  1104. }
  1105. if (arg == "--perplexity" || arg == "--all-logits") {
  1106. params.logits_all = true;
  1107. return true;
  1108. }
  1109. if (arg == "--ppl-stride") {
  1110. if (++i >= argc) {
  1111. invalid_param = true;
  1112. return true;
  1113. }
  1114. params.ppl_stride = std::stoi(argv[i]);
  1115. return true;
  1116. }
  1117. if (arg == "-ptc" || arg == "--print-token-count") {
  1118. if (++i >= argc) {
  1119. invalid_param = true;
  1120. return true;
  1121. }
  1122. params.n_print = std::stoi(argv[i]);
  1123. return true;
  1124. }
  1125. if (arg == "--check-tensors") {
  1126. params.check_tensors = true;
  1127. return true;
  1128. }
  1129. if (arg == "--ppl-output-type") {
  1130. if (++i >= argc) {
  1131. invalid_param = true;
  1132. return true;
  1133. }
  1134. params.ppl_output_type = std::stoi(argv[i]);
  1135. return true;
  1136. }
  1137. if (arg == "--hellaswag") {
  1138. params.hellaswag = true;
  1139. return true;
  1140. }
  1141. if (arg == "--hellaswag-tasks") {
  1142. if (++i >= argc) {
  1143. invalid_param = true;
  1144. return true;
  1145. }
  1146. params.hellaswag_tasks = std::stoi(argv[i]);
  1147. return true;
  1148. }
  1149. if (arg == "--winogrande") {
  1150. params.winogrande = true;
  1151. return true;
  1152. }
  1153. if (arg == "--winogrande-tasks") {
  1154. if (++i >= argc) {
  1155. invalid_param = true;
  1156. return true;
  1157. }
  1158. params.winogrande_tasks = std::stoi(argv[i]);
  1159. return true;
  1160. }
  1161. if (arg == "--multiple-choice") {
  1162. params.multiple_choice = true;
  1163. return true;
  1164. }
  1165. if (arg == "--multiple-choice-tasks") {
  1166. if (++i >= argc) {
  1167. invalid_param = true;
  1168. return true;
  1169. }
  1170. params.multiple_choice_tasks = std::stoi(argv[i]);
  1171. return true;
  1172. }
  1173. if (arg == "--kl-divergence") {
  1174. params.kl_divergence = true;
  1175. return true;
  1176. }
  1177. if (arg == "--ignore-eos") {
  1178. params.ignore_eos = true;
  1179. return true;
  1180. }
  1181. if (arg == "--penalize-nl") {
  1182. sparams.penalize_nl = true;
  1183. return true;
  1184. }
  1185. if (arg == "-l" || arg == "--logit-bias") {
  1186. if (++i >= argc) {
  1187. invalid_param = true;
  1188. return true;
  1189. }
  1190. std::stringstream ss(argv[i]);
  1191. llama_token key;
  1192. char sign;
  1193. std::string value_str;
  1194. try {
  1195. if (ss >> key && ss >> sign && std::getline(ss, value_str) && (sign == '+' || sign == '-')) {
  1196. sparams.logit_bias[key] = std::stof(value_str) * ((sign == '-') ? -1.0f : 1.0f);
  1197. }
  1198. else {
  1199. throw std::exception();
  1200. }
  1201. }
  1202. catch (const std::exception&) {
  1203. invalid_param = true;
  1204. return true;
  1205. }
  1206. return true;
  1207. }
  1208. if (arg == "-h" || arg == "--help") {
  1209. gpt_print_usage(argc, argv, gpt_params());
  1210. exit(0);
  1211. }
  1212. if (arg == "--version") {
  1213. fprintf(stderr, "version: %d (%s)\n", LLAMA_BUILD_NUMBER, LLAMA_COMMIT);
  1214. fprintf(stderr, "built with %s for %s\n", LLAMA_COMPILER, LLAMA_BUILD_TARGET);
  1215. exit(0);
  1216. }
  1217. if (arg == "--random-prompt") {
  1218. params.random_prompt = true;
  1219. return true;
  1220. }
  1221. if (arg == "--in-prefix-bos") {
  1222. params.input_prefix_bos = true;
  1223. return true;
  1224. }
  1225. if (arg == "--in-prefix") {
  1226. if (++i >= argc) {
  1227. invalid_param = true;
  1228. return true;
  1229. }
  1230. params.input_prefix = argv[i];
  1231. return true;
  1232. }
  1233. if (arg == "--in-suffix") {
  1234. if (++i >= argc) {
  1235. invalid_param = true;
  1236. return true;
  1237. }
  1238. params.input_suffix = argv[i];
  1239. return true;
  1240. }
  1241. if (arg == "--grammar") {
  1242. if (++i >= argc) {
  1243. invalid_param = true;
  1244. return true;
  1245. }
  1246. sparams.grammar = argv[i];
  1247. return true;
  1248. }
  1249. if (arg == "--grammar-file") {
  1250. if (++i >= argc) {
  1251. invalid_param = true;
  1252. return true;
  1253. }
  1254. std::ifstream file(argv[i]);
  1255. if (!file) {
  1256. fprintf(stderr, "error: failed to open file '%s'\n", argv[i]);
  1257. invalid_param = true;
  1258. return true;
  1259. }
  1260. std::copy(
  1261. std::istreambuf_iterator<char>(file),
  1262. std::istreambuf_iterator<char>(),
  1263. std::back_inserter(sparams.grammar)
  1264. );
  1265. return true;
  1266. }
  1267. if (arg == "-j" || arg == "--json-schema") {
  1268. if (++i >= argc) {
  1269. invalid_param = true;
  1270. return true;
  1271. }
  1272. sparams.grammar = json_schema_to_grammar(json::parse(argv[i]));
  1273. return true;
  1274. }
  1275. if (arg == "--override-kv") {
  1276. if (++i >= argc) {
  1277. invalid_param = true;
  1278. return true;
  1279. }
  1280. if (!parse_kv_override(argv[i], params.kv_overrides)) {
  1281. fprintf(stderr, "error: Invalid type for KV override: %s\n", argv[i]);
  1282. invalid_param = true;
  1283. return true;
  1284. }
  1285. return true;
  1286. }
  1287. #ifndef LOG_DISABLE_LOGS
  1288. // Parse args for logging parameters
  1289. if (log_param_single_parse(argv[i])) {
  1290. // Do nothing, log_param_single_parse automatically does it's thing
  1291. // and returns if a match was found and parsed.
  1292. return true;
  1293. }
  1294. if (log_param_pair_parse( /*check_but_dont_parse*/ true, argv[i])) {
  1295. // We have a matching known parameter requiring an argument,
  1296. // now we need to check if there is anything after this argv
  1297. // and flag invalid_param or parse it.
  1298. if (++i >= argc) {
  1299. invalid_param = true;
  1300. return true;
  1301. }
  1302. if (!log_param_pair_parse( /*check_but_dont_parse*/ false, argv[i - 1], argv[i])) {
  1303. invalid_param = true;
  1304. return true;
  1305. }
  1306. return true;
  1307. }
  1308. // End of Parse args for logging parameters
  1309. #endif // LOG_DISABLE_LOGS
  1310. return false;
  1311. }
  1312. void gpt_params_handle_model_default(gpt_params & params) {
  1313. if (!params.hf_repo.empty()) {
  1314. // short-hand to avoid specifying --hf-file -> default it to --model
  1315. if (params.hf_file.empty()) {
  1316. if (params.model.empty()) {
  1317. throw std::invalid_argument("error: --hf-repo requires either --hf-file or --model\n");
  1318. }
  1319. params.hf_file = params.model;
  1320. } else if (params.model.empty()) {
  1321. params.model = "models/" + string_split(params.hf_file, '/').back();
  1322. }
  1323. } else if (!params.model_url.empty()) {
  1324. if (params.model.empty()) {
  1325. auto f = string_split(params.model_url, '#').front();
  1326. f = string_split(f, '?').front();
  1327. f = string_split(f, '/').back();
  1328. params.model = "models/" + f;
  1329. }
  1330. } else if (params.model.empty()) {
  1331. params.model = DEFAULT_MODEL_PATH;
  1332. }
  1333. }
  1334. bool gpt_params_parse_ex(int argc, char ** argv, gpt_params & params) {
  1335. bool invalid_param = false;
  1336. std::string arg;
  1337. const std::string arg_prefix = "--";
  1338. llama_sampling_params & sparams = params.sparams;
  1339. for (int i = 1; i < argc; i++) {
  1340. arg = argv[i];
  1341. if (arg.compare(0, arg_prefix.size(), arg_prefix) == 0) {
  1342. std::replace(arg.begin(), arg.end(), '_', '-');
  1343. }
  1344. if (!gpt_params_find_arg(argc, argv, arg, params, i, invalid_param)) {
  1345. throw std::invalid_argument("error: unknown argument: " + arg);
  1346. }
  1347. }
  1348. if (invalid_param) {
  1349. throw std::invalid_argument("error: invalid parameter for argument: " + arg);
  1350. }
  1351. if (params.prompt_cache_all &&
  1352. (params.interactive || params.interactive_first ||
  1353. params.instruct)) {
  1354. throw std::invalid_argument("error: --prompt-cache-all not supported in interactive mode yet\n");
  1355. }
  1356. gpt_params_handle_model_default(params);
  1357. if (params.escape) {
  1358. process_escapes(params.prompt);
  1359. process_escapes(params.input_prefix);
  1360. process_escapes(params.input_suffix);
  1361. process_escapes(sparams.cfg_negative_prompt);
  1362. for (auto & antiprompt : params.antiprompt) {
  1363. process_escapes(antiprompt);
  1364. }
  1365. }
  1366. if (!params.kv_overrides.empty()) {
  1367. params.kv_overrides.emplace_back();
  1368. params.kv_overrides.back().key[0] = 0;
  1369. }
  1370. return true;
  1371. }
  1372. void gpt_print_usage(int /*argc*/, char ** argv, const gpt_params & params) {
  1373. const llama_sampling_params & sparams = params.sparams;
  1374. std::string sampler_type_chars;
  1375. std::string sampler_type_names;
  1376. for (const auto sampler_type : sparams.samplers_sequence) {
  1377. sampler_type_chars += static_cast<char>(sampler_type);
  1378. sampler_type_names += sampler_type_to_name_string(sampler_type) + ";";
  1379. }
  1380. sampler_type_names.pop_back();
  1381. printf("\n");
  1382. printf("usage: %s [options]\n", argv[0]);
  1383. printf("\n");
  1384. printf("options:\n");
  1385. printf(" -h, --help show this help message and exit\n");
  1386. printf(" --version show version and build info\n");
  1387. printf(" -i, --interactive run in interactive mode\n");
  1388. printf(" --interactive-specials allow special tokens in user text, in interactive mode\n");
  1389. printf(" --interactive-first run in interactive mode and wait for input right away\n");
  1390. printf(" -cnv, --conversation run in conversation mode (does not print special tokens and suffix/prefix)\n");
  1391. printf(" -ins, --instruct run in instruction mode (use with Alpaca models)\n");
  1392. printf(" -cml, --chatml run in chatml mode (use with ChatML-compatible models)\n");
  1393. printf(" --multiline-input allows you to write or paste multiple lines without ending each in '\\'\n");
  1394. printf(" -r PROMPT, --reverse-prompt PROMPT\n");
  1395. printf(" halt generation at PROMPT, return control in interactive mode\n");
  1396. printf(" (can be specified more than once for multiple prompts).\n");
  1397. printf(" --color colorise output to distinguish prompt and user input from generations\n");
  1398. printf(" -s SEED, --seed SEED RNG seed (default: -1, use random seed for < 0)\n");
  1399. printf(" -t N, --threads N number of threads to use during generation (default: %d)\n", params.n_threads);
  1400. printf(" -tb N, --threads-batch N\n");
  1401. printf(" number of threads to use during batch and prompt processing (default: same as --threads)\n");
  1402. printf(" -td N, --threads-draft N");
  1403. printf(" number of threads to use during generation (default: same as --threads)\n");
  1404. printf(" -tbd N, --threads-batch-draft N\n");
  1405. printf(" number of threads to use during batch and prompt processing (default: same as --threads-draft)\n");
  1406. printf(" -p PROMPT, --prompt PROMPT\n");
  1407. printf(" prompt to start generation with (default: empty)\n");
  1408. printf(" -e, --escape process prompt escapes sequences (\\n, \\r, \\t, \\', \\\", \\\\)\n");
  1409. printf(" --prompt-cache FNAME file to cache prompt state for faster startup (default: none)\n");
  1410. printf(" --prompt-cache-all if specified, saves user input and generations to cache as well.\n");
  1411. printf(" not supported with --interactive or other interactive options\n");
  1412. printf(" --prompt-cache-ro if specified, uses the prompt cache but does not update it.\n");
  1413. printf(" --random-prompt start with a randomized prompt.\n");
  1414. printf(" --in-prefix-bos prefix BOS to user inputs, preceding the `--in-prefix` string\n");
  1415. printf(" --in-prefix STRING string to prefix user inputs with (default: empty)\n");
  1416. printf(" --in-suffix STRING string to suffix after user inputs with (default: empty)\n");
  1417. printf(" -f FNAME, --file FNAME\n");
  1418. printf(" prompt file to start generation.\n");
  1419. printf(" -bf FNAME, --binary-file FNAME\n");
  1420. printf(" binary file containing multiple choice tasks.\n");
  1421. printf(" -n N, --n-predict N number of tokens to predict (default: %d, -1 = infinity, -2 = until context filled)\n", params.n_predict);
  1422. printf(" -c N, --ctx-size N size of the prompt context (default: %d, 0 = loaded from model)\n", params.n_ctx);
  1423. printf(" -b N, --batch-size N logical maximum batch size (default: %d)\n", params.n_batch);
  1424. printf(" -ub N, --ubatch-size N\n");
  1425. printf(" physical maximum batch size (default: %d)\n", params.n_ubatch);
  1426. printf(" --samplers samplers that will be used for generation in the order, separated by \';\'\n");
  1427. printf(" (default: %s)\n", sampler_type_names.c_str());
  1428. printf(" --sampling-seq simplified sequence for samplers that will be used (default: %s)\n", sampler_type_chars.c_str());
  1429. printf(" --top-k N top-k sampling (default: %d, 0 = disabled)\n", sparams.top_k);
  1430. printf(" --top-p N top-p sampling (default: %.1f, 1.0 = disabled)\n", (double)sparams.top_p);
  1431. printf(" --min-p N min-p sampling (default: %.1f, 0.0 = disabled)\n", (double)sparams.min_p);
  1432. printf(" --tfs N tail free sampling, parameter z (default: %.1f, 1.0 = disabled)\n", (double)sparams.tfs_z);
  1433. printf(" --typical N locally typical sampling, parameter p (default: %.1f, 1.0 = disabled)\n", (double)sparams.typical_p);
  1434. printf(" --repeat-last-n N last n tokens to consider for penalize (default: %d, 0 = disabled, -1 = ctx_size)\n", sparams.penalty_last_n);
  1435. printf(" --repeat-penalty N penalize repeat sequence of tokens (default: %.1f, 1.0 = disabled)\n", (double)sparams.penalty_repeat);
  1436. printf(" --presence-penalty N repeat alpha presence penalty (default: %.1f, 0.0 = disabled)\n", (double)sparams.penalty_present);
  1437. printf(" --frequency-penalty N repeat alpha frequency penalty (default: %.1f, 0.0 = disabled)\n", (double)sparams.penalty_freq);
  1438. printf(" --dynatemp-range N dynamic temperature range (default: %.1f, 0.0 = disabled)\n", (double)sparams.dynatemp_range);
  1439. printf(" --dynatemp-exp N dynamic temperature exponent (default: %.1f)\n", (double)sparams.dynatemp_exponent);
  1440. printf(" --mirostat N use Mirostat sampling.\n");
  1441. printf(" Top K, Nucleus, Tail Free and Locally Typical samplers are ignored if used.\n");
  1442. printf(" (default: %d, 0 = disabled, 1 = Mirostat, 2 = Mirostat 2.0)\n", sparams.mirostat);
  1443. printf(" --mirostat-lr N Mirostat learning rate, parameter eta (default: %.1f)\n", (double)sparams.mirostat_eta);
  1444. printf(" --mirostat-ent N Mirostat target entropy, parameter tau (default: %.1f)\n", (double)sparams.mirostat_tau);
  1445. printf(" -l TOKEN_ID(+/-)BIAS, --logit-bias TOKEN_ID(+/-)BIAS\n");
  1446. printf(" modifies the likelihood of token appearing in the completion,\n");
  1447. printf(" i.e. `--logit-bias 15043+1` to increase likelihood of token ' Hello',\n");
  1448. printf(" or `--logit-bias 15043-1` to decrease likelihood of token ' Hello'\n");
  1449. printf(" --grammar GRAMMAR BNF-like grammar to constrain generations (see samples in grammars/ dir)\n");
  1450. printf(" --grammar-file FNAME file to read grammar from\n");
  1451. printf(" -j SCHEMA, --json-schema SCHEMA\n");
  1452. printf(" JSON schema to constrain generations (https://json-schema.org/), e.g. `{}` for any JSON object.\n");
  1453. printf(" For schemas w/ external $refs, use --grammar + example/json_schema_to_grammar.py instead\n");
  1454. printf(" --cfg-negative-prompt PROMPT\n");
  1455. printf(" negative prompt to use for guidance. (default: empty)\n");
  1456. printf(" --cfg-negative-prompt-file FNAME\n");
  1457. printf(" negative prompt file to use for guidance. (default: empty)\n");
  1458. printf(" --cfg-scale N strength of guidance (default: %f, 1.0 = disable)\n", sparams.cfg_scale);
  1459. printf(" --rope-scaling {none,linear,yarn}\n");
  1460. printf(" RoPE frequency scaling method, defaults to linear unless specified by the model\n");
  1461. printf(" --rope-scale N RoPE context scaling factor, expands context by a factor of N\n");
  1462. printf(" --rope-freq-base N RoPE base frequency, used by NTK-aware scaling (default: loaded from model)\n");
  1463. printf(" --rope-freq-scale N RoPE frequency scaling factor, expands context by a factor of 1/N\n");
  1464. printf(" --yarn-orig-ctx N YaRN: original context size of model (default: 0 = model training context size)\n");
  1465. printf(" --yarn-ext-factor N YaRN: extrapolation mix factor (default: 1.0, 0.0 = full interpolation)\n");
  1466. printf(" --yarn-attn-factor N YaRN: scale sqrt(t) or attention magnitude (default: 1.0)\n");
  1467. printf(" --yarn-beta-slow N YaRN: high correction dim or alpha (default: %.1f)\n", params.yarn_beta_slow);
  1468. printf(" --yarn-beta-fast N YaRN: low correction dim or beta (default: %.1f)\n", params.yarn_beta_fast);
  1469. printf(" --pooling {none,mean,cls}\n");
  1470. printf(" pooling type for embeddings, use model default if unspecified\n");
  1471. printf(" -dt N, --defrag-thold N\n");
  1472. printf(" KV cache defragmentation threshold (default: %.1f, < 0 - disabled)\n", params.defrag_thold);
  1473. printf(" --ignore-eos ignore end of stream token and continue generating (implies --logit-bias 2-inf)\n");
  1474. printf(" --penalize-nl penalize newline tokens\n");
  1475. printf(" --temp N temperature (default: %.1f)\n", (double)sparams.temp);
  1476. printf(" --all-logits return logits for all tokens in the batch (default: disabled)\n");
  1477. printf(" --hellaswag compute HellaSwag score over random tasks from datafile supplied with -f\n");
  1478. printf(" --hellaswag-tasks N number of tasks to use when computing the HellaSwag score (default: %zu)\n", params.hellaswag_tasks);
  1479. printf(" --winogrande compute Winogrande score over random tasks from datafile supplied with -f\n");
  1480. printf(" --winogrande-tasks N number of tasks to use when computing the Winogrande score (default: %zu)\n", params.winogrande_tasks);
  1481. printf(" --multiple-choice compute multiple choice score over random tasks from datafile supplied with -f\n");
  1482. printf(" --multiple-choice-tasks N number of tasks to use when computing the multiple choice score (default: %zu)\n", params.winogrande_tasks);
  1483. printf(" --kl-divergence computes KL-divergence to logits provided via --kl-divergence-base\n");
  1484. printf(" --keep N number of tokens to keep from the initial prompt (default: %d, -1 = all)\n", params.n_keep);
  1485. printf(" --draft N number of tokens to draft for speculative decoding (default: %d)\n", params.n_draft);
  1486. printf(" --chunks N max number of chunks to process (default: %d, -1 = all)\n", params.n_chunks);
  1487. printf(" -np N, --parallel N number of parallel sequences to decode (default: %d)\n", params.n_parallel);
  1488. printf(" -ns N, --sequences N number of sequences to decode (default: %d)\n", params.n_sequences);
  1489. printf(" -ps N, --p-split N speculative decoding split probability (default: %.1f)\n", (double)params.p_split);
  1490. printf(" -cb, --cont-batching enable continuous batching (a.k.a dynamic batching) (default: disabled)\n");
  1491. printf(" -fa, --flash-attn enable Flash Attention (default: %s)\n", params.flash_attn ? "enabled" : "disabled");
  1492. printf(" --mmproj MMPROJ_FILE path to a multimodal projector file for LLaVA. see examples/llava/README.md\n");
  1493. printf(" --image IMAGE_FILE path to an image file. use with multimodal models. Specify multiple times for batching\n");
  1494. if (llama_supports_mlock()) {
  1495. printf(" --mlock force system to keep model in RAM rather than swapping or compressing\n");
  1496. }
  1497. if (llama_supports_mmap()) {
  1498. printf(" --no-mmap do not memory-map model (slower load but may reduce pageouts if not using mlock)\n");
  1499. }
  1500. printf(" --numa TYPE attempt optimizations that help on some NUMA systems\n");
  1501. printf(" - distribute: spread execution evenly over all nodes\n");
  1502. printf(" - isolate: only spawn threads on CPUs on the node that execution started on\n");
  1503. printf(" - numactl: use the CPU map provided by numactl\n");
  1504. printf(" if run without this previously, it is recommended to drop the system page cache before using this\n");
  1505. printf(" see https://github.com/ggerganov/llama.cpp/issues/1437\n");
  1506. if (llama_supports_gpu_offload()) {
  1507. printf(" -ngl N, --n-gpu-layers N\n");
  1508. printf(" number of layers to store in VRAM\n");
  1509. printf(" -ngld N, --n-gpu-layers-draft N\n");
  1510. printf(" number of layers to store in VRAM for the draft model\n");
  1511. printf(" -sm SPLIT_MODE, --split-mode SPLIT_MODE\n");
  1512. printf(" how to split the model across multiple GPUs, one of:\n");
  1513. printf(" - none: use one GPU only\n");
  1514. printf(" - layer (default): split layers and KV across GPUs\n");
  1515. printf(" - row: split rows across GPUs\n");
  1516. printf(" -ts SPLIT, --tensor-split SPLIT\n");
  1517. printf(" fraction of the model to offload to each GPU, comma-separated list of proportions, e.g. 3,1\n");
  1518. printf(" -mg i, --main-gpu i the GPU to use for the model (with split-mode = none),\n");
  1519. printf(" or for intermediate results and KV (with split-mode = row) (default: %d)\n", params.main_gpu);
  1520. }
  1521. printf(" --verbose-prompt print a verbose prompt before generation (default: %s)\n", params.verbose_prompt ? "true" : "false");
  1522. printf(" --no-display-prompt don't print prompt at generation (default: %s)\n", !params.display_prompt ? "true" : "false");
  1523. printf(" -gan N, --grp-attn-n N\n");
  1524. printf(" group-attention factor (default: %d)\n", params.grp_attn_n);
  1525. printf(" -gaw N, --grp-attn-w N\n");
  1526. printf(" group-attention width (default: %.1f)\n", (double)params.grp_attn_w);
  1527. printf(" -dkvc, --dump-kv-cache\n");
  1528. printf(" verbose print of the KV cache\n");
  1529. printf(" -nkvo, --no-kv-offload\n");
  1530. printf(" disable KV offload\n");
  1531. printf(" -ctk TYPE, --cache-type-k TYPE\n");
  1532. printf(" KV cache data type for K (default: %s)\n", params.cache_type_k.c_str());
  1533. printf(" -ctv TYPE, --cache-type-v TYPE\n");
  1534. printf(" KV cache data type for V (default: %s)\n", params.cache_type_v.c_str());
  1535. printf(" --simple-io use basic IO for better compatibility in subprocesses and limited consoles\n");
  1536. printf(" --lora FNAME apply LoRA adapter (implies --no-mmap)\n");
  1537. printf(" --lora-scaled FNAME S apply LoRA adapter with user defined scaling S (implies --no-mmap)\n");
  1538. printf(" --lora-base FNAME optional model to use as a base for the layers modified by the LoRA adapter\n");
  1539. printf(" --control-vector FNAME\n");
  1540. printf(" add a control vector\n");
  1541. printf(" --control-vector-scaled FNAME S\n");
  1542. printf(" add a control vector with user defined scaling S\n");
  1543. printf(" --control-vector-layer-range START END\n");
  1544. printf(" layer range to apply the control vector(s) to, start and end inclusive\n");
  1545. printf(" -m FNAME, --model FNAME\n");
  1546. printf(" model path (default: models/$filename with filename from --hf-file or --model-url if set, otherwise %s)\n", DEFAULT_MODEL_PATH);
  1547. printf(" -md FNAME, --model-draft FNAME\n");
  1548. printf(" draft model for speculative decoding (default: unused)\n");
  1549. printf(" -mu MODEL_URL, --model-url MODEL_URL\n");
  1550. printf(" model download url (default: unused)\n");
  1551. printf(" -hfr REPO, --hf-repo REPO\n");
  1552. printf(" Hugging Face model repository (default: unused)\n");
  1553. printf(" -hff FILE, --hf-file FILE\n");
  1554. printf(" Hugging Face model file (default: unused)\n");
  1555. printf(" -ld LOGDIR, --logdir LOGDIR\n");
  1556. printf(" path under which to save YAML logs (no logging if unset)\n");
  1557. printf(" -lcs FNAME, --lookup-cache-static FNAME\n");
  1558. printf(" path to static lookup cache to use for lookup decoding (not updated by generation)\n");
  1559. printf(" -lcd FNAME, --lookup-cache-dynamic FNAME\n");
  1560. printf(" path to dynamic lookup cache to use for lookup decoding (updated by generation)\n");
  1561. printf(" --override-kv KEY=TYPE:VALUE\n");
  1562. printf(" advanced option to override model metadata by key. may be specified multiple times.\n");
  1563. printf(" types: int, float, bool, str. example: --override-kv tokenizer.ggml.add_bos_token=bool:false\n");
  1564. printf(" -ptc N, --print-token-count N\n");
  1565. printf(" print token count every N tokens (default: %d)\n", params.n_print);
  1566. printf(" --check-tensors check model tensor data for invalid values\n");
  1567. printf("\n");
  1568. #ifndef LOG_DISABLE_LOGS
  1569. log_print_usage();
  1570. #endif // LOG_DISABLE_LOGS
  1571. }
  1572. std::string get_system_info(const gpt_params & params) {
  1573. std::ostringstream os;
  1574. os << "system_info: n_threads = " << params.n_threads;
  1575. if (params.n_threads_batch != -1) {
  1576. os << " (n_threads_batch = " << params.n_threads_batch << ")";
  1577. }
  1578. os << " / " << std::thread::hardware_concurrency() << " | " << llama_print_system_info();
  1579. return os.str();
  1580. }
  1581. std::string gpt_random_prompt(std::mt19937 & rng) {
  1582. const int r = rng() % 10;
  1583. switch (r) {
  1584. case 0: return "So";
  1585. case 1: return "Once upon a time";
  1586. case 2: return "When";
  1587. case 3: return "The";
  1588. case 4: return "After";
  1589. case 5: return "If";
  1590. case 6: return "import";
  1591. case 7: return "He";
  1592. case 8: return "She";
  1593. case 9: return "They";
  1594. }
  1595. GGML_UNREACHABLE();
  1596. }
  1597. // Validate if a filename is safe to use
  1598. // To validate a full path, split the path by the OS-specific path separator, and validate each part with this function
  1599. bool validate_file_name(const std::string & filename) {
  1600. if (!filename.length()) {
  1601. // Empty filename invalid
  1602. return false;
  1603. }
  1604. if (filename.length() > 255) {
  1605. // Limit at common largest possible filename on Linux filesystems
  1606. // to avoid unnecessary further validation
  1607. // (On systems with smaller limits it will be caught by the OS)
  1608. return false;
  1609. }
  1610. std::u32string filename_utf32;
  1611. try {
  1612. std::wstring_convert<std::codecvt_utf8<char32_t>, char32_t> converter;
  1613. filename_utf32 = converter.from_bytes(filename);
  1614. // If the reverse conversion mismatches, it means overlong UTF-8 sequences were used,
  1615. // or invalid encodings were encountered. Reject such attempts
  1616. std::string filename_reencoded = converter.to_bytes(filename_utf32);
  1617. if (filename_reencoded != filename) {
  1618. return false;
  1619. }
  1620. } catch (const std::exception &) {
  1621. return false;
  1622. }
  1623. // Check for forbidden codepoints:
  1624. // - Control characters
  1625. // - Unicode equivalents of illegal characters
  1626. // - UTF-16 surrogate pairs
  1627. // - UTF-8 replacement character
  1628. // - Byte order mark (BOM)
  1629. // - Illegal characters: / \ : * ? " < > |
  1630. for (char32_t c : filename_utf32) {
  1631. if (c <= 0x1F // Control characters (C0)
  1632. || c == 0x7F // Control characters (DEL)
  1633. || (c >= 0x80 && c <= 0x9F) // Control characters (C1)
  1634. || c == 0xFF0E // Fullwidth Full Stop (period equivalent)
  1635. || c == 0x2215 // Division Slash (forward slash equivalent)
  1636. || c == 0x2216 // Set Minus (backslash equivalent)
  1637. || (c >= 0xD800 && c <= 0xDFFF) // UTF-16 surrogate pairs
  1638. || c == 0xFFFD // Replacement Character (UTF-8)
  1639. || c == 0xFEFF // Byte Order Mark (BOM)
  1640. || c == '/' || c == '\\' || c == ':' || c == '*' // Illegal characters
  1641. || c == '?' || c == '"' || c == '<' || c == '>' || c == '|') {
  1642. return false;
  1643. }
  1644. }
  1645. // Reject any leading or trailing ' ', or any trailing '.', these are stripped on Windows and will cause a different filename
  1646. // Unicode and other whitespace is not affected, only 0x20 space
  1647. if (filename.front() == ' ' || filename.back() == ' ' || filename.back() == '.') {
  1648. return false;
  1649. }
  1650. // Reject any ".." (currently stricter than necessary, it should be fine to just check for == ".." instead)
  1651. if (filename.find("..") != std::string::npos) {
  1652. return false;
  1653. }
  1654. // Reject "."
  1655. if (filename == ".") {
  1656. return false;
  1657. }
  1658. return true;
  1659. }
  1660. //
  1661. // String utils
  1662. //
  1663. std::vector<std::string> string_split(std::string input, char separator) {
  1664. std::vector<std::string> parts;
  1665. size_t separator_pos = input.find(separator);
  1666. while (separator_pos != std::string::npos) {
  1667. std::string part = input.substr(0, separator_pos);
  1668. parts.emplace_back(part);
  1669. input = input.substr(separator_pos + 1);
  1670. separator_pos = input.find(separator);
  1671. }
  1672. parts.emplace_back(input);
  1673. return parts;
  1674. }
  1675. std::string string_strip(const std::string & str) {
  1676. size_t start = 0;
  1677. size_t end = str.size();
  1678. while (start < end && std::isspace(str[start])) {
  1679. start++;
  1680. }
  1681. while (end > start && std::isspace(str[end - 1])) {
  1682. end--;
  1683. }
  1684. return str.substr(start, end - start);
  1685. }
  1686. std::vector<llama_sampler_type> sampler_types_from_names(const std::vector<std::string> & names, bool allow_alt_names) {
  1687. std::unordered_map<std::string, llama_sampler_type> sampler_canonical_name_map {
  1688. {"top_k", llama_sampler_type::TOP_K},
  1689. {"top_p", llama_sampler_type::TOP_P},
  1690. {"typical_p", llama_sampler_type::TYPICAL_P},
  1691. {"min_p", llama_sampler_type::MIN_P},
  1692. {"tfs_z", llama_sampler_type::TFS_Z},
  1693. {"temperature", llama_sampler_type::TEMPERATURE}
  1694. };
  1695. // since samplers names are written multiple ways
  1696. // make it ready for both system names and input names
  1697. std::unordered_map<std::string, llama_sampler_type> sampler_alt_name_map {
  1698. {"top-k", llama_sampler_type::TOP_K},
  1699. {"top-p", llama_sampler_type::TOP_P},
  1700. {"nucleus", llama_sampler_type::TOP_P},
  1701. {"typical-p", llama_sampler_type::TYPICAL_P},
  1702. {"typical", llama_sampler_type::TYPICAL_P},
  1703. {"min-p", llama_sampler_type::MIN_P},
  1704. {"tfs-z", llama_sampler_type::TFS_Z},
  1705. {"tfs", llama_sampler_type::TFS_Z},
  1706. {"temp", llama_sampler_type::TEMPERATURE}
  1707. };
  1708. std::vector<llama_sampler_type> sampler_types;
  1709. sampler_types.reserve(names.size());
  1710. for (const auto & name : names)
  1711. {
  1712. auto sampler_item = sampler_canonical_name_map.find(name);
  1713. if (sampler_item != sampler_canonical_name_map.end())
  1714. {
  1715. sampler_types.push_back(sampler_item->second);
  1716. }
  1717. else
  1718. {
  1719. if (allow_alt_names)
  1720. {
  1721. sampler_item = sampler_alt_name_map.find(name);
  1722. if (sampler_item != sampler_alt_name_map.end())
  1723. {
  1724. sampler_types.push_back(sampler_item->second);
  1725. }
  1726. }
  1727. }
  1728. }
  1729. return sampler_types;
  1730. }
  1731. std::vector<llama_sampler_type> sampler_types_from_chars(const std::string & names_string) {
  1732. std::unordered_map<char, llama_sampler_type> sampler_name_map {
  1733. {'k', llama_sampler_type::TOP_K},
  1734. {'p', llama_sampler_type::TOP_P},
  1735. {'y', llama_sampler_type::TYPICAL_P},
  1736. {'m', llama_sampler_type::MIN_P},
  1737. {'f', llama_sampler_type::TFS_Z},
  1738. {'t', llama_sampler_type::TEMPERATURE}
  1739. };
  1740. std::vector<llama_sampler_type> sampler_types;
  1741. sampler_types.reserve(names_string.size());
  1742. for (const auto & c : names_string) {
  1743. const auto sampler_item = sampler_name_map.find(c);
  1744. if (sampler_item != sampler_name_map.end()) {
  1745. sampler_types.push_back(sampler_item->second);
  1746. }
  1747. }
  1748. return sampler_types;
  1749. }
  1750. std::string sampler_type_to_name_string(llama_sampler_type sampler_type) {
  1751. switch (sampler_type) {
  1752. case llama_sampler_type::TOP_K: return "top_k";
  1753. case llama_sampler_type::TFS_Z: return "tfs_z";
  1754. case llama_sampler_type::TYPICAL_P: return "typical_p";
  1755. case llama_sampler_type::TOP_P: return "top_p";
  1756. case llama_sampler_type::MIN_P: return "min_p";
  1757. case llama_sampler_type::TEMPERATURE: return "temperature";
  1758. default : return "";
  1759. }
  1760. }
  1761. //
  1762. // Model utils
  1763. //
  1764. struct llama_model_params llama_model_params_from_gpt_params(const gpt_params & params) {
  1765. auto mparams = llama_model_default_params();
  1766. if (params.n_gpu_layers != -1) {
  1767. mparams.n_gpu_layers = params.n_gpu_layers;
  1768. }
  1769. mparams.main_gpu = params.main_gpu;
  1770. mparams.split_mode = params.split_mode;
  1771. mparams.tensor_split = params.tensor_split;
  1772. mparams.use_mmap = params.use_mmap;
  1773. mparams.use_mlock = params.use_mlock;
  1774. mparams.check_tensors = params.check_tensors;
  1775. if (params.kv_overrides.empty()) {
  1776. mparams.kv_overrides = NULL;
  1777. } else {
  1778. GGML_ASSERT(params.kv_overrides.back().key[0] == 0 && "KV overrides not terminated with empty key");
  1779. mparams.kv_overrides = params.kv_overrides.data();
  1780. }
  1781. return mparams;
  1782. }
  1783. static ggml_type kv_cache_type_from_str(const std::string & s) {
  1784. if (s == "f32") {
  1785. return GGML_TYPE_F32;
  1786. }
  1787. if (s == "f16") {
  1788. return GGML_TYPE_F16;
  1789. }
  1790. if (s == "q8_0") {
  1791. return GGML_TYPE_Q8_0;
  1792. }
  1793. if (s == "q4_0") {
  1794. return GGML_TYPE_Q4_0;
  1795. }
  1796. if (s == "q4_1") {
  1797. return GGML_TYPE_Q4_1;
  1798. }
  1799. if (s == "iq4_nl") {
  1800. return GGML_TYPE_IQ4_NL;
  1801. }
  1802. if (s == "q5_0") {
  1803. return GGML_TYPE_Q5_0;
  1804. }
  1805. if (s == "q5_1") {
  1806. return GGML_TYPE_Q5_1;
  1807. }
  1808. throw std::runtime_error("Invalid cache type: " + s);
  1809. }
  1810. struct llama_context_params llama_context_params_from_gpt_params(const gpt_params & params) {
  1811. auto cparams = llama_context_default_params();
  1812. cparams.n_ctx = params.n_ctx;
  1813. cparams.n_seq_max = params.n_parallel;
  1814. cparams.n_batch = params.n_batch;
  1815. cparams.n_ubatch = params.n_ubatch;
  1816. cparams.n_threads = params.n_threads;
  1817. cparams.n_threads_batch = params.n_threads_batch == -1 ? params.n_threads : params.n_threads_batch;
  1818. cparams.seed = params.seed;
  1819. cparams.logits_all = params.logits_all;
  1820. cparams.embeddings = params.embedding;
  1821. cparams.rope_scaling_type = params.rope_scaling_type;
  1822. cparams.rope_freq_base = params.rope_freq_base;
  1823. cparams.rope_freq_scale = params.rope_freq_scale;
  1824. cparams.yarn_ext_factor = params.yarn_ext_factor;
  1825. cparams.yarn_attn_factor = params.yarn_attn_factor;
  1826. cparams.yarn_beta_fast = params.yarn_beta_fast;
  1827. cparams.yarn_beta_slow = params.yarn_beta_slow;
  1828. cparams.yarn_orig_ctx = params.yarn_orig_ctx;
  1829. cparams.pooling_type = params.pooling_type;
  1830. cparams.defrag_thold = params.defrag_thold;
  1831. cparams.cb_eval = params.cb_eval;
  1832. cparams.cb_eval_user_data = params.cb_eval_user_data;
  1833. cparams.offload_kqv = !params.no_kv_offload;
  1834. cparams.flash_attn = params.flash_attn;
  1835. cparams.type_k = kv_cache_type_from_str(params.cache_type_k);
  1836. cparams.type_v = kv_cache_type_from_str(params.cache_type_v);
  1837. return cparams;
  1838. }
  1839. void llama_batch_clear(struct llama_batch & batch) {
  1840. batch.n_tokens = 0;
  1841. }
  1842. void llama_batch_add(
  1843. struct llama_batch & batch,
  1844. llama_token id,
  1845. llama_pos pos,
  1846. const std::vector<llama_seq_id> & seq_ids,
  1847. bool logits) {
  1848. batch.token [batch.n_tokens] = id;
  1849. batch.pos [batch.n_tokens] = pos;
  1850. batch.n_seq_id[batch.n_tokens] = seq_ids.size();
  1851. for (size_t i = 0; i < seq_ids.size(); ++i) {
  1852. batch.seq_id[batch.n_tokens][i] = seq_ids[i];
  1853. }
  1854. batch.logits [batch.n_tokens] = logits;
  1855. batch.n_tokens++;
  1856. }
  1857. #ifdef LLAMA_USE_CURL
  1858. static bool starts_with(const std::string & str, const std::string & prefix) {
  1859. // While we wait for C++20's std::string::starts_with...
  1860. return str.rfind(prefix, 0) == 0;
  1861. }
  1862. static bool llama_download_file(const std::string & url, const std::string & path) {
  1863. // Initialize libcurl
  1864. std::unique_ptr<CURL, decltype(&curl_easy_cleanup)> curl(curl_easy_init(), &curl_easy_cleanup);
  1865. if (!curl) {
  1866. fprintf(stderr, "%s: error initializing libcurl\n", __func__);
  1867. return false;
  1868. }
  1869. bool force_download = false;
  1870. // Set the URL, allow to follow http redirection
  1871. curl_easy_setopt(curl.get(), CURLOPT_URL, url.c_str());
  1872. curl_easy_setopt(curl.get(), CURLOPT_FOLLOWLOCATION, 1L);
  1873. #if defined(_WIN32)
  1874. // CURLSSLOPT_NATIVE_CA tells libcurl to use standard certificate store of
  1875. // operating system. Currently implemented under MS-Windows.
  1876. curl_easy_setopt(curl.get(), CURLOPT_SSL_OPTIONS, CURLSSLOPT_NATIVE_CA);
  1877. #endif
  1878. // Check if the file already exists locally
  1879. struct stat model_file_info;
  1880. auto file_exists = (stat(path.c_str(), &model_file_info) == 0);
  1881. // If the file exists, check its JSON metadata companion file.
  1882. std::string metadata_path = path + ".json";
  1883. nlohmann::json metadata;
  1884. std::string etag;
  1885. std::string last_modified;
  1886. if (file_exists) {
  1887. // Try and read the JSON metadata file (note: stream autoclosed upon exiting this block).
  1888. std::ifstream metadata_in(metadata_path);
  1889. if (metadata_in.good()) {
  1890. try {
  1891. metadata_in >> metadata;
  1892. fprintf(stderr, "%s: previous metadata file found %s: %s\n", __func__, metadata_path.c_str(), metadata.dump().c_str());
  1893. if (metadata.contains("url") && metadata.at("url").is_string()) {
  1894. auto previous_url = metadata.at("url").get<std::string>();
  1895. if (previous_url != url) {
  1896. fprintf(stderr, "%s: Model URL mismatch: %s != %s\n", __func__, url.c_str(), previous_url.c_str());
  1897. return false;
  1898. }
  1899. }
  1900. if (metadata.contains("etag") && metadata.at("etag").is_string()) {
  1901. etag = metadata.at("etag");
  1902. }
  1903. if (metadata.contains("lastModified") && metadata.at("lastModified").is_string()) {
  1904. last_modified = metadata.at("lastModified");
  1905. }
  1906. } catch (const nlohmann::json::exception & e) {
  1907. fprintf(stderr, "%s: error reading metadata file %s: %s\n", __func__, metadata_path.c_str(), e.what());
  1908. return false;
  1909. }
  1910. }
  1911. } else {
  1912. fprintf(stderr, "%s: no previous model file found %s\n", __func__, path.c_str());
  1913. }
  1914. // Send a HEAD request to retrieve the etag and last-modified headers
  1915. struct llama_load_model_from_url_headers {
  1916. std::string etag;
  1917. std::string last_modified;
  1918. };
  1919. llama_load_model_from_url_headers headers;
  1920. {
  1921. typedef size_t(*CURLOPT_HEADERFUNCTION_PTR)(char *, size_t, size_t, void *);
  1922. auto header_callback = [](char * buffer, size_t /*size*/, size_t n_items, void * userdata) -> size_t {
  1923. llama_load_model_from_url_headers *headers = (llama_load_model_from_url_headers *) userdata;
  1924. static std::regex header_regex("([^:]+): (.*)\r\n");
  1925. static std::regex etag_regex("ETag", std::regex_constants::icase);
  1926. static std::regex last_modified_regex("Last-Modified", std::regex_constants::icase);
  1927. std::string header(buffer, n_items);
  1928. std::smatch match;
  1929. if (std::regex_match(header, match, header_regex)) {
  1930. const std::string & key = match[1];
  1931. const std::string & value = match[2];
  1932. if (std::regex_match(key, match, etag_regex)) {
  1933. headers->etag = value;
  1934. } else if (std::regex_match(key, match, last_modified_regex)) {
  1935. headers->last_modified = value;
  1936. }
  1937. }
  1938. return n_items;
  1939. };
  1940. curl_easy_setopt(curl.get(), CURLOPT_NOBODY, 1L); // will trigger the HEAD verb
  1941. curl_easy_setopt(curl.get(), CURLOPT_NOPROGRESS, 1L); // hide head request progress
  1942. curl_easy_setopt(curl.get(), CURLOPT_HEADERFUNCTION, static_cast<CURLOPT_HEADERFUNCTION_PTR>(header_callback));
  1943. curl_easy_setopt(curl.get(), CURLOPT_HEADERDATA, &headers);
  1944. CURLcode res = curl_easy_perform(curl.get());
  1945. if (res != CURLE_OK) {
  1946. fprintf(stderr, "%s: curl_easy_perform() failed: %s\n", __func__, curl_easy_strerror(res));
  1947. return false;
  1948. }
  1949. long http_code = 0;
  1950. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &http_code);
  1951. if (http_code != 200) {
  1952. // HEAD not supported, we don't know if the file has changed
  1953. // force trigger downloading
  1954. force_download = true;
  1955. fprintf(stderr, "%s: HEAD invalid http status code received: %ld\n", __func__, http_code);
  1956. }
  1957. }
  1958. bool should_download = !file_exists || force_download;
  1959. if (!should_download) {
  1960. if (!etag.empty() && etag != headers.etag) {
  1961. fprintf(stderr, "%s: ETag header is different (%s != %s): triggering a new download\n", __func__, etag.c_str(), headers.etag.c_str());
  1962. should_download = true;
  1963. } else if (!last_modified.empty() && last_modified != headers.last_modified) {
  1964. fprintf(stderr, "%s: Last-Modified header is different (%s != %s): triggering a new download\n", __func__, last_modified.c_str(), headers.last_modified.c_str());
  1965. should_download = true;
  1966. }
  1967. }
  1968. if (should_download) {
  1969. std::string path_temporary = path + ".downloadInProgress";
  1970. if (file_exists) {
  1971. fprintf(stderr, "%s: deleting previous downloaded file: %s\n", __func__, path.c_str());
  1972. if (remove(path.c_str()) != 0) {
  1973. fprintf(stderr, "%s: unable to delete file: %s\n", __func__, path.c_str());
  1974. return false;
  1975. }
  1976. }
  1977. // Set the output file
  1978. std::unique_ptr<FILE, decltype(&fclose)> outfile(fopen(path_temporary.c_str(), "wb"), fclose);
  1979. if (!outfile) {
  1980. fprintf(stderr, "%s: error opening local file for writing: %s\n", __func__, path.c_str());
  1981. return false;
  1982. }
  1983. typedef size_t(*CURLOPT_WRITEFUNCTION_PTR)(void * data, size_t size, size_t nmemb, void * fd);
  1984. auto write_callback = [](void * data, size_t size, size_t nmemb, void * fd) -> size_t {
  1985. return fwrite(data, size, nmemb, (FILE *)fd);
  1986. };
  1987. curl_easy_setopt(curl.get(), CURLOPT_NOBODY, 0L);
  1988. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, static_cast<CURLOPT_WRITEFUNCTION_PTR>(write_callback));
  1989. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, outfile.get());
  1990. // display download progress
  1991. curl_easy_setopt(curl.get(), CURLOPT_NOPROGRESS, 0L);
  1992. // helper function to hide password in URL
  1993. auto llama_download_hide_password_in_url = [](const std::string & url) -> std::string {
  1994. std::size_t protocol_pos = url.find("://");
  1995. if (protocol_pos == std::string::npos) {
  1996. return url; // Malformed URL
  1997. }
  1998. std::size_t at_pos = url.find('@', protocol_pos + 3);
  1999. if (at_pos == std::string::npos) {
  2000. return url; // No password in URL
  2001. }
  2002. return url.substr(0, protocol_pos + 3) + "********" + url.substr(at_pos);
  2003. };
  2004. // start the download
  2005. fprintf(stderr, "%s: downloading from %s to %s (server_etag:%s, server_last_modified:%s)...\n", __func__,
  2006. llama_download_hide_password_in_url(url).c_str(), path.c_str(), headers.etag.c_str(), headers.last_modified.c_str());
  2007. auto res = curl_easy_perform(curl.get());
  2008. if (res != CURLE_OK) {
  2009. fprintf(stderr, "%s: curl_easy_perform() failed: %s\n", __func__, curl_easy_strerror(res));
  2010. return false;
  2011. }
  2012. long http_code = 0;
  2013. curl_easy_getinfo (curl.get(), CURLINFO_RESPONSE_CODE, &http_code);
  2014. if (http_code < 200 || http_code >= 400) {
  2015. fprintf(stderr, "%s: invalid http status code received: %ld\n", __func__, http_code);
  2016. return false;
  2017. }
  2018. // Causes file to be closed explicitly here before we rename it.
  2019. outfile.reset();
  2020. // Write the updated JSON metadata file.
  2021. metadata.update({
  2022. {"url", url},
  2023. {"etag", headers.etag},
  2024. {"lastModified", headers.last_modified}
  2025. });
  2026. std::ofstream(metadata_path) << metadata.dump(4);
  2027. fprintf(stderr, "%s: file metadata saved: %s\n", __func__, metadata_path.c_str());
  2028. if (rename(path_temporary.c_str(), path.c_str()) != 0) {
  2029. fprintf(stderr, "%s: unable to rename file: %s to %s\n", __func__, path_temporary.c_str(), path.c_str());
  2030. return false;
  2031. }
  2032. }
  2033. return true;
  2034. }
  2035. struct llama_model * llama_load_model_from_url(
  2036. const char * model_url,
  2037. const char * path_model,
  2038. const struct llama_model_params & params) {
  2039. // Basic validation of the model_url
  2040. if (!model_url || strlen(model_url) == 0) {
  2041. fprintf(stderr, "%s: invalid model_url\n", __func__);
  2042. return NULL;
  2043. }
  2044. if (!llama_download_file(model_url, path_model)) {
  2045. return NULL;
  2046. }
  2047. // check for additional GGUFs split to download
  2048. int n_split = 0;
  2049. {
  2050. struct gguf_init_params gguf_params = {
  2051. /*.no_alloc = */ true,
  2052. /*.ctx = */ NULL,
  2053. };
  2054. auto * ctx_gguf = gguf_init_from_file(path_model, gguf_params);
  2055. if (!ctx_gguf) {
  2056. fprintf(stderr, "\n%s: failed to load input GGUF from %s\n", __func__, path_model);
  2057. return NULL;
  2058. }
  2059. auto key_n_split = gguf_find_key(ctx_gguf, LLM_KV_SPLIT_COUNT);
  2060. if (key_n_split >= 0) {
  2061. n_split = gguf_get_val_u16(ctx_gguf, key_n_split);
  2062. }
  2063. gguf_free(ctx_gguf);
  2064. }
  2065. if (n_split > 1) {
  2066. char split_prefix[PATH_MAX] = {0};
  2067. char split_url_prefix[LLAMA_CURL_MAX_URL_LENGTH] = {0};
  2068. // Verify the first split file format
  2069. // and extract split URL and PATH prefixes
  2070. {
  2071. if (!llama_split_prefix(split_prefix, sizeof(split_prefix), path_model, 0, n_split)) {
  2072. fprintf(stderr, "\n%s: unexpected model file name: %s"
  2073. " n_split=%d\n", __func__, path_model, n_split);
  2074. return NULL;
  2075. }
  2076. if (!llama_split_prefix(split_url_prefix, sizeof(split_url_prefix), model_url, 0, n_split)) {
  2077. fprintf(stderr, "\n%s: unexpected model url: %s"
  2078. " n_split=%d\n", __func__, model_url, n_split);
  2079. return NULL;
  2080. }
  2081. }
  2082. // Prepare download in parallel
  2083. std::vector<std::future<bool>> futures_download;
  2084. for (int idx = 1; idx < n_split; idx++) {
  2085. futures_download.push_back(std::async(std::launch::async, [&split_prefix, &split_url_prefix, &n_split](int download_idx) -> bool {
  2086. char split_path[PATH_MAX] = {0};
  2087. llama_split_path(split_path, sizeof(split_path), split_prefix, download_idx, n_split);
  2088. char split_url[LLAMA_CURL_MAX_URL_LENGTH] = {0};
  2089. llama_split_path(split_url, sizeof(split_url), split_url_prefix, download_idx, n_split);
  2090. return llama_download_file(split_url, split_path);
  2091. }, idx));
  2092. }
  2093. // Wait for all downloads to complete
  2094. for (auto & f : futures_download) {
  2095. if (!f.get()) {
  2096. return NULL;
  2097. }
  2098. }
  2099. }
  2100. return llama_load_model_from_file(path_model, params);
  2101. }
  2102. struct llama_model * llama_load_model_from_hf(
  2103. const char * repo,
  2104. const char * model,
  2105. const char * path_model,
  2106. const struct llama_model_params & params) {
  2107. // construct hugging face model url:
  2108. //
  2109. // --repo ggml-org/models --file tinyllama-1.1b/ggml-model-f16.gguf
  2110. // https://huggingface.co/ggml-org/models/resolve/main/tinyllama-1.1b/ggml-model-f16.gguf
  2111. //
  2112. // --repo TheBloke/Mixtral-8x7B-v0.1-GGUF --file mixtral-8x7b-v0.1.Q4_K_M.gguf
  2113. // https://huggingface.co/TheBloke/Mixtral-8x7B-v0.1-GGUF/resolve/main/mixtral-8x7b-v0.1.Q4_K_M.gguf
  2114. //
  2115. std::string model_url = "https://huggingface.co/";
  2116. model_url += repo;
  2117. model_url += "/resolve/main/";
  2118. model_url += model;
  2119. return llama_load_model_from_url(model_url.c_str(), path_model, params);
  2120. }
  2121. #else
  2122. struct llama_model * llama_load_model_from_url(
  2123. const char * /*model_url*/,
  2124. const char * /*path_model*/,
  2125. const struct llama_model_params & /*params*/) {
  2126. fprintf(stderr, "%s: llama.cpp built without libcurl, downloading from an url not supported.\n", __func__);
  2127. return nullptr;
  2128. }
  2129. struct llama_model * llama_load_model_from_hf(
  2130. const char * /*repo*/,
  2131. const char * /*model*/,
  2132. const char * /*path_model*/,
  2133. const struct llama_model_params & /*params*/) {
  2134. fprintf(stderr, "%s: llama.cpp built without libcurl, downloading from Hugging Face not supported.\n", __func__);
  2135. return nullptr;
  2136. }
  2137. #endif // LLAMA_USE_CURL
  2138. std::tuple<struct llama_model *, struct llama_context *> llama_init_from_gpt_params(gpt_params & params) {
  2139. auto mparams = llama_model_params_from_gpt_params(params);
  2140. llama_model * model = nullptr;
  2141. if (!params.hf_repo.empty() && !params.hf_file.empty()) {
  2142. model = llama_load_model_from_hf(params.hf_repo.c_str(), params.hf_file.c_str(), params.model.c_str(), mparams);
  2143. } else if (!params.model_url.empty()) {
  2144. model = llama_load_model_from_url(params.model_url.c_str(), params.model.c_str(), mparams);
  2145. } else {
  2146. model = llama_load_model_from_file(params.model.c_str(), mparams);
  2147. }
  2148. if (model == NULL) {
  2149. fprintf(stderr, "%s: error: failed to load model '%s'\n", __func__, params.model.c_str());
  2150. return std::make_tuple(nullptr, nullptr);
  2151. }
  2152. auto cparams = llama_context_params_from_gpt_params(params);
  2153. llama_context * lctx = llama_new_context_with_model(model, cparams);
  2154. if (lctx == NULL) {
  2155. fprintf(stderr, "%s: error: failed to create context with model '%s'\n", __func__, params.model.c_str());
  2156. llama_free_model(model);
  2157. return std::make_tuple(nullptr, nullptr);
  2158. }
  2159. if (!params.control_vectors.empty()) {
  2160. if (params.control_vector_layer_start <= 0) params.control_vector_layer_start = 1;
  2161. if (params.control_vector_layer_end <= 0) params.control_vector_layer_end = llama_n_layer(model);
  2162. const auto cvec = llama_control_vector_load(params.control_vectors);
  2163. if (cvec.n_embd == -1) {
  2164. llama_free(lctx);
  2165. llama_free_model(model);
  2166. return std::make_tuple(nullptr, nullptr);
  2167. }
  2168. int err = llama_control_vector_apply(lctx,
  2169. cvec.data.data(),
  2170. cvec.data.size(),
  2171. cvec.n_embd,
  2172. params.control_vector_layer_start,
  2173. params.control_vector_layer_end);
  2174. if (err) {
  2175. llama_free(lctx);
  2176. llama_free_model(model);
  2177. return std::make_tuple(nullptr, nullptr);
  2178. }
  2179. }
  2180. for (unsigned int i = 0; i < params.lora_adapter.size(); ++i) {
  2181. const std::string & lora_adapter = std::get<0>(params.lora_adapter[i]);
  2182. float lora_scale = std::get<1>(params.lora_adapter[i]);
  2183. int err = llama_model_apply_lora_from_file(model,
  2184. lora_adapter.c_str(),
  2185. lora_scale,
  2186. ((i > 0) || params.lora_base.empty())
  2187. ? NULL
  2188. : params.lora_base.c_str(),
  2189. params.n_threads);
  2190. if (err != 0) {
  2191. fprintf(stderr, "%s: error: failed to apply lora adapter\n", __func__);
  2192. llama_free(lctx);
  2193. llama_free_model(model);
  2194. return std::make_tuple(nullptr, nullptr);
  2195. }
  2196. }
  2197. if (params.ignore_eos) {
  2198. params.sparams.logit_bias[llama_token_eos(model)] = -INFINITY;
  2199. }
  2200. if (params.warmup) {
  2201. LOG("warming up the model with an empty run\n");
  2202. std::vector<llama_token> tmp = { llama_token_bos(model), llama_token_eos(model), };
  2203. llama_decode(lctx, llama_batch_get_one(tmp.data(), std::min(tmp.size(), (size_t) params.n_batch), 0, 0));
  2204. llama_kv_cache_clear(lctx);
  2205. llama_synchronize(lctx);
  2206. llama_reset_timings(lctx);
  2207. }
  2208. return std::make_tuple(model, lctx);
  2209. }
  2210. //
  2211. // Vocab utils
  2212. //
  2213. std::vector<llama_token> llama_tokenize(
  2214. const struct llama_context * ctx,
  2215. const std::string & text,
  2216. bool add_special,
  2217. bool parse_special) {
  2218. return llama_tokenize(llama_get_model(ctx), text, add_special, parse_special);
  2219. }
  2220. std::vector<llama_token> llama_tokenize(
  2221. const struct llama_model * model,
  2222. const std::string & text,
  2223. bool add_special,
  2224. bool parse_special) {
  2225. // upper limit for the number of tokens
  2226. int n_tokens = text.length() + 2 * add_special;
  2227. std::vector<llama_token> result(n_tokens);
  2228. n_tokens = llama_tokenize(model, text.data(), text.length(), result.data(), result.size(), add_special, parse_special);
  2229. if (n_tokens < 0) {
  2230. result.resize(-n_tokens);
  2231. int check = llama_tokenize(model, text.data(), text.length(), result.data(), result.size(), add_special, parse_special);
  2232. GGML_ASSERT(check == -n_tokens);
  2233. } else {
  2234. result.resize(n_tokens);
  2235. }
  2236. return result;
  2237. }
  2238. std::string llama_token_to_piece(const struct llama_context * ctx, llama_token token, bool special) {
  2239. std::vector<char> result(8, 0);
  2240. const int n_tokens = llama_token_to_piece(llama_get_model(ctx), token, result.data(), result.size(), special);
  2241. if (n_tokens < 0) {
  2242. result.resize(-n_tokens);
  2243. int check = llama_token_to_piece(llama_get_model(ctx), token, result.data(), result.size(), special);
  2244. GGML_ASSERT(check == -n_tokens);
  2245. } else {
  2246. result.resize(n_tokens);
  2247. }
  2248. return std::string(result.data(), result.size());
  2249. }
  2250. std::string llama_detokenize_spm(llama_context * ctx, const std::vector<llama_token> & tokens) {
  2251. const llama_token bos_id = llama_token_bos(llama_get_model(ctx));
  2252. std::string piece;
  2253. std::string result;
  2254. for (size_t i = 0; i < tokens.size(); ++i) {
  2255. piece = llama_token_to_piece(ctx, tokens[i]);
  2256. // remove the leading space of the first non-BOS token
  2257. if (((tokens[0] == bos_id && i == 1) || (tokens[0] != bos_id && i == 0)) && piece[0] == ' ') {
  2258. piece = piece.substr(1);
  2259. }
  2260. result += piece;
  2261. }
  2262. return result;
  2263. }
  2264. std::string llama_detokenize_bpe(llama_context * ctx, const std::vector<llama_token> & tokens) {
  2265. std::string piece;
  2266. std::string result;
  2267. for (size_t i = 0; i < tokens.size(); ++i) {
  2268. piece = llama_token_to_piece(ctx, tokens[i]);
  2269. result += piece;
  2270. }
  2271. // NOTE: the original tokenizer decodes bytes after collecting the pieces.
  2272. return result;
  2273. }
  2274. bool llama_should_add_bos_token(const llama_model * model) {
  2275. const int add_bos = llama_add_bos_token(model);
  2276. return add_bos != -1 ? bool(add_bos) : (llama_vocab_type(model) == LLAMA_VOCAB_TYPE_SPM);
  2277. }
  2278. //
  2279. // YAML utils
  2280. //
  2281. // returns true if successful, false otherwise
  2282. bool create_directory_with_parents(const std::string & path) {
  2283. #ifdef _WIN32
  2284. std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;
  2285. std::wstring wpath = converter.from_bytes(path);
  2286. // if the path already exists, check whether it's a directory
  2287. const DWORD attributes = GetFileAttributesW(wpath.c_str());
  2288. if ((attributes != INVALID_FILE_ATTRIBUTES) && (attributes & FILE_ATTRIBUTE_DIRECTORY)) {
  2289. return true;
  2290. }
  2291. size_t pos_slash = 0;
  2292. // process path from front to back, procedurally creating directories
  2293. while ((pos_slash = path.find('\\', pos_slash)) != std::string::npos) {
  2294. const std::wstring subpath = wpath.substr(0, pos_slash);
  2295. const wchar_t * test = subpath.c_str();
  2296. const bool success = CreateDirectoryW(test, NULL);
  2297. if (!success) {
  2298. const DWORD error = GetLastError();
  2299. // if the path already exists, ensure that it's a directory
  2300. if (error == ERROR_ALREADY_EXISTS) {
  2301. const DWORD attributes = GetFileAttributesW(subpath.c_str());
  2302. if (attributes == INVALID_FILE_ATTRIBUTES || !(attributes & FILE_ATTRIBUTE_DIRECTORY)) {
  2303. return false;
  2304. }
  2305. } else {
  2306. return false;
  2307. }
  2308. }
  2309. pos_slash += 1;
  2310. }
  2311. return true;
  2312. #else
  2313. // if the path already exists, check whether it's a directory
  2314. struct stat info;
  2315. if (stat(path.c_str(), &info) == 0) {
  2316. return S_ISDIR(info.st_mode);
  2317. }
  2318. size_t pos_slash = 1; // skip leading slashes for directory creation
  2319. // process path from front to back, procedurally creating directories
  2320. while ((pos_slash = path.find('/', pos_slash)) != std::string::npos) {
  2321. const std::string subpath = path.substr(0, pos_slash);
  2322. struct stat info;
  2323. // if the path already exists, ensure that it's a directory
  2324. if (stat(subpath.c_str(), &info) == 0) {
  2325. if (!S_ISDIR(info.st_mode)) {
  2326. return false;
  2327. }
  2328. } else {
  2329. // create parent directories
  2330. const int ret = mkdir(subpath.c_str(), 0755);
  2331. if (ret != 0) {
  2332. return false;
  2333. }
  2334. }
  2335. pos_slash += 1;
  2336. }
  2337. return true;
  2338. #endif // _WIN32
  2339. }
  2340. void dump_vector_float_yaml(FILE * stream, const char * prop_name, const std::vector<float> & data) {
  2341. if (data.empty()) {
  2342. fprintf(stream, "%s:\n", prop_name);
  2343. return;
  2344. }
  2345. fprintf(stream, "%s: [", prop_name);
  2346. for (size_t i = 0; i < data.size() - 1; ++i) {
  2347. fprintf(stream, "%e, ", data[i]);
  2348. }
  2349. fprintf(stream, "%e]\n", data.back());
  2350. }
  2351. void dump_vector_int_yaml(FILE * stream, const char * prop_name, const std::vector<int> & data) {
  2352. if (data.empty()) {
  2353. fprintf(stream, "%s:\n", prop_name);
  2354. return;
  2355. }
  2356. fprintf(stream, "%s: [", prop_name);
  2357. for (size_t i = 0; i < data.size() - 1; ++i) {
  2358. fprintf(stream, "%d, ", data[i]);
  2359. }
  2360. fprintf(stream, "%d]\n", data.back());
  2361. }
  2362. void dump_string_yaml_multiline(FILE * stream, const char * prop_name, const char * data) {
  2363. std::string data_str(data == NULL ? "" : data);
  2364. if (data_str.empty()) {
  2365. fprintf(stream, "%s:\n", prop_name);
  2366. return;
  2367. }
  2368. size_t pos_start = 0;
  2369. size_t pos_found = 0;
  2370. if (!data_str.empty() && (std::isspace(data_str[0]) || std::isspace(data_str.back()))) {
  2371. data_str = std::regex_replace(data_str, std::regex("\n"), "\\n");
  2372. data_str = std::regex_replace(data_str, std::regex("\""), "\\\"");
  2373. data_str = std::regex_replace(data_str, std::regex(R"(\\[^n"])"), R"(\$&)");
  2374. data_str = "\"" + data_str + "\"";
  2375. fprintf(stream, "%s: %s\n", prop_name, data_str.c_str());
  2376. return;
  2377. }
  2378. if (data_str.find('\n') == std::string::npos) {
  2379. fprintf(stream, "%s: %s\n", prop_name, data_str.c_str());
  2380. return;
  2381. }
  2382. fprintf(stream, "%s: |\n", prop_name);
  2383. while ((pos_found = data_str.find('\n', pos_start)) != std::string::npos) {
  2384. fprintf(stream, " %s\n", data_str.substr(pos_start, pos_found-pos_start).c_str());
  2385. pos_start = pos_found + 1;
  2386. }
  2387. }
  2388. std::string get_sortable_timestamp() {
  2389. using clock = std::chrono::system_clock;
  2390. const clock::time_point current_time = clock::now();
  2391. const time_t as_time_t = clock::to_time_t(current_time);
  2392. char timestamp_no_ns[100];
  2393. std::strftime(timestamp_no_ns, 100, "%Y_%m_%d-%H_%M_%S", std::localtime(&as_time_t));
  2394. const int64_t ns = std::chrono::duration_cast<std::chrono::nanoseconds>(
  2395. current_time.time_since_epoch() % 1000000000).count();
  2396. char timestamp_ns[11];
  2397. snprintf(timestamp_ns, 11, "%09" PRId64, ns);
  2398. return std::string(timestamp_no_ns) + "." + std::string(timestamp_ns);
  2399. }
  2400. void dump_non_result_info_yaml(FILE * stream, const gpt_params & params, const llama_context * lctx,
  2401. const std::string & timestamp, const std::vector<int> & prompt_tokens, const char * model_desc) {
  2402. const llama_sampling_params & sparams = params.sparams;
  2403. fprintf(stream, "build_commit: %s\n", LLAMA_COMMIT);
  2404. fprintf(stream, "build_number: %d\n", LLAMA_BUILD_NUMBER);
  2405. fprintf(stream, "cpu_has_arm_fma: %s\n", ggml_cpu_has_arm_fma() ? "true" : "false");
  2406. fprintf(stream, "cpu_has_avx: %s\n", ggml_cpu_has_avx() ? "true" : "false");
  2407. fprintf(stream, "cpu_has_avx_vnni: %s\n", ggml_cpu_has_avx_vnni() ? "true" : "false");
  2408. fprintf(stream, "cpu_has_avx2: %s\n", ggml_cpu_has_avx2() ? "true" : "false");
  2409. fprintf(stream, "cpu_has_avx512: %s\n", ggml_cpu_has_avx512() ? "true" : "false");
  2410. fprintf(stream, "cpu_has_avx512_vbmi: %s\n", ggml_cpu_has_avx512_vbmi() ? "true" : "false");
  2411. fprintf(stream, "cpu_has_avx512_vnni: %s\n", ggml_cpu_has_avx512_vnni() ? "true" : "false");
  2412. fprintf(stream, "cpu_has_cuda: %s\n", ggml_cpu_has_cuda() ? "true" : "false");
  2413. fprintf(stream, "cpu_has_vulkan: %s\n", ggml_cpu_has_vulkan() ? "true" : "false");
  2414. fprintf(stream, "cpu_has_clblast: %s\n", ggml_cpu_has_clblast() ? "true" : "false");
  2415. fprintf(stream, "cpu_has_kompute: %s\n", ggml_cpu_has_kompute() ? "true" : "false");
  2416. fprintf(stream, "cpu_has_fma: %s\n", ggml_cpu_has_fma() ? "true" : "false");
  2417. fprintf(stream, "cpu_has_gpublas: %s\n", ggml_cpu_has_gpublas() ? "true" : "false");
  2418. fprintf(stream, "cpu_has_neon: %s\n", ggml_cpu_has_neon() ? "true" : "false");
  2419. fprintf(stream, "cpu_has_f16c: %s\n", ggml_cpu_has_f16c() ? "true" : "false");
  2420. fprintf(stream, "cpu_has_fp16_va: %s\n", ggml_cpu_has_fp16_va() ? "true" : "false");
  2421. fprintf(stream, "cpu_has_wasm_simd: %s\n", ggml_cpu_has_wasm_simd() ? "true" : "false");
  2422. fprintf(stream, "cpu_has_blas: %s\n", ggml_cpu_has_blas() ? "true" : "false");
  2423. fprintf(stream, "cpu_has_sse3: %s\n", ggml_cpu_has_sse3() ? "true" : "false");
  2424. fprintf(stream, "cpu_has_vsx: %s\n", ggml_cpu_has_vsx() ? "true" : "false");
  2425. fprintf(stream, "cpu_has_matmul_int8: %s\n", ggml_cpu_has_matmul_int8() ? "true" : "false");
  2426. #ifdef NDEBUG
  2427. fprintf(stream, "debug: false\n");
  2428. #else
  2429. fprintf(stream, "debug: true\n");
  2430. #endif // NDEBUG
  2431. fprintf(stream, "model_desc: %s\n", model_desc);
  2432. fprintf(stream, "n_vocab: %d # output size of the final layer, 32001 for some models\n", llama_n_vocab(llama_get_model(lctx)));
  2433. #ifdef __OPTIMIZE__
  2434. fprintf(stream, "optimize: true\n");
  2435. #else
  2436. fprintf(stream, "optimize: false\n");
  2437. #endif // __OPTIMIZE__
  2438. fprintf(stream, "time: %s\n", timestamp.c_str());
  2439. fprintf(stream, "\n");
  2440. fprintf(stream, "###############\n");
  2441. fprintf(stream, "# User Inputs #\n");
  2442. fprintf(stream, "###############\n");
  2443. fprintf(stream, "\n");
  2444. fprintf(stream, "alias: %s # default: unknown\n", params.model_alias.c_str());
  2445. fprintf(stream, "batch_size: %d # default: 512\n", params.n_batch);
  2446. dump_string_yaml_multiline(stream, "cfg_negative_prompt", sparams.cfg_negative_prompt.c_str());
  2447. fprintf(stream, "cfg_scale: %f # default: 1.0\n", sparams.cfg_scale);
  2448. fprintf(stream, "chunks: %d # default: -1 (unlimited)\n", params.n_chunks);
  2449. fprintf(stream, "color: %s # default: false\n", params.use_color ? "true" : "false");
  2450. fprintf(stream, "ctx_size: %d # default: 512\n", params.n_ctx);
  2451. fprintf(stream, "escape: %s # default: false\n", params.escape ? "true" : "false");
  2452. fprintf(stream, "file: # never logged, see prompt instead. Can still be specified for input.\n");
  2453. fprintf(stream, "frequency_penalty: %f # default: 0.0 \n", sparams.penalty_freq);
  2454. dump_string_yaml_multiline(stream, "grammar", sparams.grammar.c_str());
  2455. fprintf(stream, "grammar-file: # never logged, see grammar instead. Can still be specified for input.\n");
  2456. fprintf(stream, "hellaswag: %s # default: false\n", params.hellaswag ? "true" : "false");
  2457. fprintf(stream, "hellaswag_tasks: %zu # default: 400\n", params.hellaswag_tasks);
  2458. const auto logit_bias_eos = sparams.logit_bias.find(llama_token_eos(llama_get_model(lctx)));
  2459. const bool ignore_eos = logit_bias_eos != sparams.logit_bias.end() && logit_bias_eos->second == -INFINITY;
  2460. fprintf(stream, "ignore_eos: %s # default: false\n", ignore_eos ? "true" : "false");
  2461. dump_string_yaml_multiline(stream, "in_prefix", params.input_prefix.c_str());
  2462. fprintf(stream, "in_prefix_bos: %s # default: false\n", params.input_prefix_bos ? "true" : "false");
  2463. dump_string_yaml_multiline(stream, "in_suffix", params.input_prefix.c_str());
  2464. fprintf(stream, "instruct: %s # default: false\n", params.instruct ? "true" : "false");
  2465. fprintf(stream, "interactive: %s # default: false\n", params.interactive ? "true" : "false");
  2466. fprintf(stream, "interactive_specials: %s # default: false\n", params.interactive_specials ? "true" : "false");
  2467. fprintf(stream, "interactive_first: %s # default: false\n", params.interactive_first ? "true" : "false");
  2468. fprintf(stream, "keep: %d # default: 0\n", params.n_keep);
  2469. fprintf(stream, "logdir: %s # default: unset (no logging)\n", params.logdir.c_str());
  2470. fprintf(stream, "logit_bias:\n");
  2471. for (std::pair<llama_token, float> lb : sparams.logit_bias) {
  2472. if (ignore_eos && lb.first == logit_bias_eos->first) {
  2473. continue;
  2474. }
  2475. fprintf(stream, " %d: %f", lb.first, lb.second);
  2476. }
  2477. fprintf(stream, "lora:\n");
  2478. for (std::tuple<std::string, float> la : params.lora_adapter) {
  2479. if (std::get<1>(la) != 1.0f) {
  2480. continue;
  2481. }
  2482. fprintf(stream, " - %s\n", std::get<0>(la).c_str());
  2483. }
  2484. fprintf(stream, "lora_scaled:\n");
  2485. for (std::tuple<std::string, float> la : params.lora_adapter) {
  2486. if (std::get<1>(la) == 1.0f) {
  2487. continue;
  2488. }
  2489. fprintf(stream, " - %s: %f\n", std::get<0>(la).c_str(), std::get<1>(la));
  2490. }
  2491. fprintf(stream, "lora_base: %s\n", params.lora_base.c_str());
  2492. fprintf(stream, "main_gpu: %d # default: 0\n", params.main_gpu);
  2493. fprintf(stream, "min_keep: %d # default: 0 (disabled)\n", sparams.min_keep);
  2494. fprintf(stream, "mirostat: %d # default: 0 (disabled)\n", sparams.mirostat);
  2495. fprintf(stream, "mirostat_ent: %f # default: 5.0\n", sparams.mirostat_tau);
  2496. fprintf(stream, "mirostat_lr: %f # default: 0.1\n", sparams.mirostat_eta);
  2497. fprintf(stream, "mlock: %s # default: false\n", params.use_mlock ? "true" : "false");
  2498. fprintf(stream, "model: %s # default: %s\n", params.model.c_str(), DEFAULT_MODEL_PATH);
  2499. fprintf(stream, "model_draft: %s # default:\n", params.model_draft.c_str());
  2500. fprintf(stream, "multiline_input: %s # default: false\n", params.multiline_input ? "true" : "false");
  2501. fprintf(stream, "n_gpu_layers: %d # default: -1\n", params.n_gpu_layers);
  2502. fprintf(stream, "n_predict: %d # default: -1 (unlimited)\n", params.n_predict);
  2503. fprintf(stream, "n_probs: %d # only used by server binary, default: 0\n", sparams.n_probs);
  2504. fprintf(stream, "no_mmap: %s # default: false\n", !params.use_mmap ? "true" : "false");
  2505. fprintf(stream, "penalize_nl: %s # default: false\n", sparams.penalize_nl ? "true" : "false");
  2506. fprintf(stream, "ppl_output_type: %d # default: 0\n", params.ppl_output_type);
  2507. fprintf(stream, "ppl_stride: %d # default: 0\n", params.ppl_stride);
  2508. fprintf(stream, "presence_penalty: %f # default: 0.0\n", sparams.penalty_present);
  2509. dump_string_yaml_multiline(stream, "prompt", params.prompt.c_str());
  2510. fprintf(stream, "prompt_cache: %s\n", params.path_prompt_cache.c_str());
  2511. fprintf(stream, "prompt_cache_all: %s # default: false\n", params.prompt_cache_all ? "true" : "false");
  2512. fprintf(stream, "prompt_cache_ro: %s # default: false\n", params.prompt_cache_ro ? "true" : "false");
  2513. dump_vector_int_yaml(stream, "prompt_tokens", prompt_tokens);
  2514. fprintf(stream, "random_prompt: %s # default: false\n", params.random_prompt ? "true" : "false");
  2515. fprintf(stream, "repeat_penalty: %f # default: 1.1\n", sparams.penalty_repeat);
  2516. fprintf(stream, "reverse_prompt:\n");
  2517. for (std::string ap : params.antiprompt) {
  2518. size_t pos = 0;
  2519. while ((pos = ap.find('\n', pos)) != std::string::npos) {
  2520. ap.replace(pos, 1, "\\n");
  2521. pos += 1;
  2522. }
  2523. fprintf(stream, " - %s\n", ap.c_str());
  2524. }
  2525. fprintf(stream, "rope_freq_base: %f # default: 10000.0\n", params.rope_freq_base);
  2526. fprintf(stream, "rope_freq_scale: %f # default: 1.0\n", params.rope_freq_scale);
  2527. fprintf(stream, "seed: %u # default: -1 (random seed)\n", params.seed);
  2528. fprintf(stream, "simple_io: %s # default: false\n", params.simple_io ? "true" : "false");
  2529. fprintf(stream, "cont_batching: %s # default: false\n", params.cont_batching ? "true" : "false");
  2530. fprintf(stream, "flash_attn: %s # default: false\n", params.flash_attn ? "true" : "false");
  2531. fprintf(stream, "temp: %f # default: 0.8\n", sparams.temp);
  2532. const std::vector<float> tensor_split_vector(params.tensor_split, params.tensor_split + llama_max_devices());
  2533. dump_vector_float_yaml(stream, "tensor_split", tensor_split_vector);
  2534. fprintf(stream, "tfs: %f # default: 1.0\n", sparams.tfs_z);
  2535. fprintf(stream, "threads: %d # default: %u\n", params.n_threads, std::thread::hardware_concurrency());
  2536. fprintf(stream, "top_k: %d # default: 40\n", sparams.top_k);
  2537. fprintf(stream, "top_p: %f # default: 0.95\n", sparams.top_p);
  2538. fprintf(stream, "min_p: %f # default: 0.0\n", sparams.min_p);
  2539. fprintf(stream, "typical_p: %f # default: 1.0\n", sparams.typical_p);
  2540. fprintf(stream, "verbose_prompt: %s # default: false\n", params.verbose_prompt ? "true" : "false");
  2541. fprintf(stream, "display_prompt: %s # default: true\n", params.display_prompt ? "true" : "false");
  2542. }
  2543. //
  2544. // KV cache utils
  2545. //
  2546. void dump_kv_cache_view(const llama_kv_cache_view & view, int row_size) {
  2547. static const char slot_chars[] = ".123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+";
  2548. printf("=== Dumping KV cache. total cells %d, max sequences per cell %d, populated cells %d, total tokens in cache %d, largest empty slot=%d @ %d",
  2549. view.n_cells, view.n_seq_max, view.used_cells, view.token_count, view.max_contiguous, view.max_contiguous_idx);
  2550. llama_kv_cache_view_cell * c_curr = view.cells;
  2551. llama_seq_id * cs_curr = view.cells_sequences;
  2552. for (int i = 0; i < view.n_cells; i++, c_curr++, cs_curr += view.n_seq_max) {
  2553. if (i % row_size == 0) {
  2554. printf("\n%5d: ", i);
  2555. }
  2556. int seq_count = 0;
  2557. for (int j = 0; j < view.n_seq_max; j++) {
  2558. if (cs_curr[j] >= 0) { seq_count++; }
  2559. }
  2560. putchar(slot_chars[std::min(sizeof(slot_chars) - 2, size_t(seq_count))]);
  2561. }
  2562. printf("\n=== Done dumping\n");
  2563. }
  2564. void dump_kv_cache_view_seqs(const llama_kv_cache_view & view, int row_size) {
  2565. static const char slot_chars[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  2566. printf("=== Dumping KV cache. total cells %d, max sequences per cell %d, populated cells %d, total tokens in cache %d, largest empty slot=%d @ %d\n",
  2567. view.n_cells, view.n_seq_max, view.used_cells, view.token_count, view.max_contiguous, view.max_contiguous_idx);
  2568. std::unordered_map<llama_seq_id, size_t> seqs;
  2569. llama_kv_cache_view_cell * c_curr = view.cells;
  2570. llama_seq_id * cs_curr = view.cells_sequences;
  2571. for (int i = 0; i < view.n_cells; i++, c_curr++, cs_curr += view.n_seq_max) {
  2572. for (int j = 0; j < view.n_seq_max; j++) {
  2573. if (cs_curr[j] < 0) { continue; }
  2574. if (seqs.find(cs_curr[j]) == seqs.end()) {
  2575. if (seqs.size() + 1 >= sizeof(slot_chars)) { break; }
  2576. const size_t sz = seqs.size();
  2577. seqs[cs_curr[j]] = sz;
  2578. }
  2579. }
  2580. if (seqs.size() + 1 >= sizeof(slot_chars)) { break; }
  2581. }
  2582. printf("=== Sequence legend: ");
  2583. for (const auto & it : seqs) {
  2584. printf("%zu=%d, ", it.second, it.first);
  2585. }
  2586. printf("'+'=other sequence ids");
  2587. c_curr = view.cells;
  2588. cs_curr = view.cells_sequences;
  2589. for (int i = 0; i < view.n_cells; i++, c_curr++, cs_curr += view.n_seq_max) {
  2590. if (i % row_size == 0) {
  2591. printf("\n%5d: ", i);
  2592. }
  2593. for (int j = 0; j < view.n_seq_max; j++) {
  2594. if (cs_curr[j] >= 0) {
  2595. const auto & it = seqs.find(cs_curr[j]);
  2596. putchar(it != seqs.end() ? int(slot_chars[it->second]) : '+');
  2597. } else {
  2598. putchar('.');
  2599. }
  2600. }
  2601. putchar(' ');
  2602. }
  2603. printf("\n=== Done dumping\n");
  2604. }
  2605. void llama_embd_normalize(const float * inp, float * out, int n) {
  2606. double sum = 0.0;
  2607. for (int i = 0; i < n; i++) {
  2608. sum += inp[i] * inp[i];
  2609. }
  2610. sum = sqrt(sum);
  2611. const float norm = sum > 0.0 ? 1.0f / sum : 0.0f;
  2612. for (int i = 0; i < n; i++) {
  2613. out[i] = inp[i] * norm;
  2614. }
  2615. }
  2616. float llama_embd_similarity_cos(const float * embd1, const float * embd2, int n){
  2617. double sum = 0.0;
  2618. double sum1 = 0.0;
  2619. double sum2 = 0.0;
  2620. for (int i = 0; i < n; i++) {
  2621. sum += embd1[i] * embd2[i];
  2622. sum1 += embd1[i] * embd1[i];
  2623. sum2 += embd2[i] * embd2[i];
  2624. }
  2625. return sum / (sqrt(sum1) * sqrt(sum2));
  2626. }
  2627. //
  2628. // Control vector utils
  2629. //
  2630. static llama_control_vector_data llama_control_vector_load_one(const llama_control_vector_load_info & load_info) {
  2631. int32_t n_tensors;
  2632. size_t n_bytes = 0;
  2633. uint32_t max_direction_layer = 0;
  2634. llama_control_vector_data result = { -1, {} };
  2635. // calculate size of ctx needed for tensors, ensure tensors are f32, and find max layer
  2636. {
  2637. struct ggml_init_params meta_params = {
  2638. /* .mem_size = */ ggml_tensor_overhead() * 128 + ggml_graph_overhead(),
  2639. /* .mem_buffer = */ nullptr,
  2640. /* .no_alloc = */ true,
  2641. };
  2642. ggml_context * meta_ctx = ggml_init(meta_params);
  2643. struct gguf_init_params meta_gguf_params = {
  2644. /* .no_alloc = */ true,
  2645. /* .ctx = */ &meta_ctx,
  2646. };
  2647. struct gguf_context * meta_ctx_gguf = gguf_init_from_file(load_info.fname.c_str(), meta_gguf_params);
  2648. if (!meta_ctx_gguf) {
  2649. fprintf(stderr, "%s: failed to load control vector from %s\n", __func__, load_info.fname.c_str());
  2650. ggml_free(meta_ctx);
  2651. return result;
  2652. }
  2653. n_tensors = gguf_get_n_tensors(meta_ctx_gguf);
  2654. for (int i = 0; i < n_tensors; i++) {
  2655. std::string name = gguf_get_tensor_name(meta_ctx_gguf, i);
  2656. // split on '.'
  2657. size_t dotpos = name.find('.');
  2658. if (dotpos != std::string::npos && name.substr(0, dotpos) == "direction") {
  2659. try {
  2660. uint32_t layer = std::stoi(name.substr(dotpos + 1));
  2661. if (layer == 0) {
  2662. fprintf(stderr, "%s: direction tensor invalid in %s\n", __func__, load_info.fname.c_str());
  2663. ggml_free(meta_ctx);
  2664. gguf_free(meta_ctx_gguf);
  2665. return result;
  2666. }
  2667. if (layer > max_direction_layer) {
  2668. max_direction_layer = layer;
  2669. }
  2670. } catch (...) {
  2671. fprintf(stderr, "%s: direction tensor invalid in %s\n", __func__, load_info.fname.c_str());
  2672. ggml_free(meta_ctx);
  2673. gguf_free(meta_ctx_gguf);
  2674. return result;
  2675. }
  2676. }
  2677. struct ggml_tensor * tensor_meta = ggml_get_tensor(meta_ctx, name.c_str());
  2678. if (tensor_meta->type != GGML_TYPE_F32 || ggml_n_dims(tensor_meta) != 1) {
  2679. fprintf(stderr, "%s: direction tensor invalid in %s\n", __func__, load_info.fname.c_str());
  2680. ggml_free(meta_ctx);
  2681. gguf_free(meta_ctx_gguf);
  2682. return result;
  2683. }
  2684. if (result.n_embd == -1) {
  2685. result.n_embd = ggml_nelements(tensor_meta);
  2686. } else if (ggml_nelements(tensor_meta) != result.n_embd) {
  2687. fprintf(stderr, "%s: direction tensor sizes mismatched in %s\n", __func__, load_info.fname.c_str());
  2688. ggml_free(meta_ctx);
  2689. gguf_free(meta_ctx_gguf);
  2690. return result;
  2691. }
  2692. n_bytes += ggml_nbytes(tensor_meta);
  2693. }
  2694. ggml_free(meta_ctx);
  2695. gguf_free(meta_ctx_gguf);
  2696. }
  2697. if (n_tensors == 0) {
  2698. fprintf(stderr, "%s: no direction tensors found in %s\n", __func__, load_info.fname.c_str());
  2699. return result;
  2700. }
  2701. // load and scale tensors into final control vector context
  2702. struct ggml_init_params ggml_params = {
  2703. /* .mem_size = */ ggml_tensor_overhead() * n_tensors + n_bytes,
  2704. /* .mem_buffer = */ nullptr,
  2705. /* .no_alloc = */ false,
  2706. };
  2707. struct ggml_context * ctx = ggml_init(ggml_params);
  2708. struct gguf_init_params params = {
  2709. /*.no_alloc = */ false,
  2710. /*.ctx = */ &ctx,
  2711. };
  2712. struct gguf_context * ctx_gguf = gguf_init_from_file(load_info.fname.c_str(), params);
  2713. if (!ctx_gguf) {
  2714. fprintf(stderr, "%s: failed to load control vector from %s\n", __func__, load_info.fname.c_str());
  2715. ggml_free(ctx);
  2716. return result;
  2717. }
  2718. // do not store data for layer 0 (it's not used)
  2719. result.data.resize(result.n_embd * max_direction_layer);
  2720. for (uint32_t il = 1; il <= max_direction_layer; il++) {
  2721. const std::string name = "direction." + std::to_string(il);
  2722. const ggml_tensor * tensor = ggml_get_tensor(ctx, name.c_str());
  2723. float * dst = result.data.data() + result.n_embd * (il - 1);
  2724. if (tensor) {
  2725. const float * src = (const float *) tensor->data;
  2726. for (int j = 0; j < result.n_embd; j++) {
  2727. dst[j] = src[j] * load_info.strength;
  2728. }
  2729. } else {
  2730. for (int j = 0; j < result.n_embd; j++) {
  2731. dst[j] = 0.0f;
  2732. }
  2733. }
  2734. }
  2735. return result;
  2736. }
  2737. llama_control_vector_data llama_control_vector_load(const std::vector<llama_control_vector_load_info> & load_infos) {
  2738. llama_control_vector_data result = { -1, {} };
  2739. for (const auto & info : load_infos) {
  2740. auto cur = llama_control_vector_load_one(info);
  2741. if (cur.n_embd == -1) {
  2742. return result;
  2743. }
  2744. if (result.n_embd != -1 && (result.n_embd != cur.n_embd || result.data.size() != cur.data.size())) {
  2745. fprintf(stderr, "%s: control vector in %s does not match previous vector dimensions\n", __func__, info.fname.c_str());
  2746. return result;
  2747. }
  2748. if (result.n_embd == -1) {
  2749. result = std::move(cur);
  2750. } else {
  2751. for (size_t i = 0; i < cur.data.size(); i++) {
  2752. result.data[i] += cur.data[i];
  2753. }
  2754. }
  2755. }
  2756. if (result.n_embd == -1) {
  2757. fprintf(stderr, "%s: no vectors passed\n", __func__);
  2758. }
  2759. return result;
  2760. }