common.cpp 111 KB

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