arg.cpp 177 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182
  1. #include "arg.h"
  2. #include "chat.h"
  3. #include "common.h"
  4. #include "gguf.h" // for reading GGUF splits
  5. #include "json-schema-to-grammar.h"
  6. #include "log.h"
  7. #include "sampling.h"
  8. // fix problem with std::min and std::max
  9. #if defined(_WIN32)
  10. #define WIN32_LEAN_AND_MEAN
  11. #ifndef NOMINMAX
  12. # define NOMINMAX
  13. #endif
  14. #include <windows.h>
  15. #endif
  16. #define JSON_ASSERT GGML_ASSERT
  17. #include <nlohmann/json.hpp>
  18. #include <algorithm>
  19. #include <climits>
  20. #include <cstdarg>
  21. #include <filesystem>
  22. #include <fstream>
  23. #include <future>
  24. #include <list>
  25. #include <regex>
  26. #include <set>
  27. #include <string>
  28. #include <thread>
  29. #include <vector>
  30. //#define LLAMA_USE_CURL
  31. #if defined(LLAMA_USE_CURL)
  32. #include <curl/curl.h>
  33. #include <curl/easy.h>
  34. #else
  35. #include <cpp-httplib/httplib.h>
  36. #endif
  37. #ifdef __linux__
  38. #include <linux/limits.h>
  39. #elif defined(_WIN32)
  40. # if !defined(PATH_MAX)
  41. # define PATH_MAX MAX_PATH
  42. # endif
  43. #elif defined(_AIX)
  44. #include <sys/limits.h>
  45. #else
  46. #include <sys/syslimits.h>
  47. #endif
  48. #define LLAMA_MAX_URL_LENGTH 2084 // Maximum URL Length in Chrome: 2083
  49. using json = nlohmann::ordered_json;
  50. std::initializer_list<enum llama_example> mmproj_examples = {
  51. LLAMA_EXAMPLE_MTMD,
  52. LLAMA_EXAMPLE_SERVER,
  53. };
  54. static std::string read_file(const std::string & fname) {
  55. std::ifstream file(fname);
  56. if (!file) {
  57. throw std::runtime_error(string_format("error: failed to open file '%s'\n", fname.c_str()));
  58. }
  59. std::string content((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
  60. file.close();
  61. return content;
  62. }
  63. static void write_file(const std::string & fname, const std::string & content) {
  64. const std::string fname_tmp = fname + ".tmp";
  65. std::ofstream file(fname_tmp);
  66. if (!file) {
  67. throw std::runtime_error(string_format("error: failed to open file '%s'\n", fname.c_str()));
  68. }
  69. try {
  70. file << content;
  71. file.close();
  72. // Makes write atomic
  73. if (rename(fname_tmp.c_str(), fname.c_str()) != 0) {
  74. LOG_ERR("%s: unable to rename file: %s to %s\n", __func__, fname_tmp.c_str(), fname.c_str());
  75. // If rename fails, try to delete the temporary file
  76. if (remove(fname_tmp.c_str()) != 0) {
  77. LOG_ERR("%s: unable to delete temporary file: %s\n", __func__, fname_tmp.c_str());
  78. }
  79. }
  80. } catch (...) {
  81. // If anything fails, try to delete the temporary file
  82. if (remove(fname_tmp.c_str()) != 0) {
  83. LOG_ERR("%s: unable to delete temporary file: %s\n", __func__, fname_tmp.c_str());
  84. }
  85. throw std::runtime_error(string_format("error: failed to write file '%s'\n", fname.c_str()));
  86. }
  87. }
  88. common_arg & common_arg::set_examples(std::initializer_list<enum llama_example> examples) {
  89. this->examples = std::move(examples);
  90. return *this;
  91. }
  92. common_arg & common_arg::set_excludes(std::initializer_list<enum llama_example> excludes) {
  93. this->excludes = std::move(excludes);
  94. return *this;
  95. }
  96. common_arg & common_arg::set_env(const char * env) {
  97. help = help + "\n(env: " + env + ")";
  98. this->env = env;
  99. return *this;
  100. }
  101. common_arg & common_arg::set_sparam() {
  102. is_sparam = true;
  103. return *this;
  104. }
  105. bool common_arg::in_example(enum llama_example ex) {
  106. return examples.find(ex) != examples.end();
  107. }
  108. bool common_arg::is_exclude(enum llama_example ex) {
  109. return excludes.find(ex) != excludes.end();
  110. }
  111. bool common_arg::get_value_from_env(std::string & output) {
  112. if (env == nullptr) return false;
  113. char * value = std::getenv(env);
  114. if (value) {
  115. output = value;
  116. return true;
  117. }
  118. return false;
  119. }
  120. bool common_arg::has_value_from_env() {
  121. return env != nullptr && std::getenv(env);
  122. }
  123. static std::vector<std::string> break_str_into_lines(std::string input, size_t max_char_per_line) {
  124. std::vector<std::string> result;
  125. std::istringstream iss(input);
  126. std::string line;
  127. auto add_line = [&](const std::string& l) {
  128. if (l.length() <= max_char_per_line) {
  129. result.push_back(l);
  130. } else {
  131. std::istringstream line_stream(l);
  132. std::string word, current_line;
  133. while (line_stream >> word) {
  134. if (current_line.length() + !current_line.empty() + word.length() > max_char_per_line) {
  135. if (!current_line.empty()) result.push_back(current_line);
  136. current_line = word;
  137. } else {
  138. current_line += (!current_line.empty() ? " " : "") + word;
  139. }
  140. }
  141. if (!current_line.empty()) result.push_back(current_line);
  142. }
  143. };
  144. while (std::getline(iss, line)) {
  145. add_line(line);
  146. }
  147. return result;
  148. }
  149. std::string common_arg::to_string() {
  150. // params for printing to console
  151. const static int n_leading_spaces = 40;
  152. const static int n_char_per_line_help = 70; // TODO: detect this based on current console
  153. std::string leading_spaces(n_leading_spaces, ' ');
  154. std::ostringstream ss;
  155. for (const auto arg : args) {
  156. if (arg == args.front()) {
  157. if (args.size() == 1) {
  158. ss << arg;
  159. } else {
  160. // first arg is usually abbreviation, we need padding to make it more beautiful
  161. auto tmp = std::string(arg) + ", ";
  162. auto spaces = std::string(std::max(0, 7 - (int)tmp.size()), ' ');
  163. ss << tmp << spaces;
  164. }
  165. } else {
  166. ss << arg << (arg != args.back() ? ", " : "");
  167. }
  168. }
  169. if (value_hint) ss << " " << value_hint;
  170. if (value_hint_2) ss << " " << value_hint_2;
  171. if (ss.tellp() > n_leading_spaces - 3) {
  172. // current line is too long, add new line
  173. ss << "\n" << leading_spaces;
  174. } else {
  175. // padding between arg and help, same line
  176. ss << std::string(leading_spaces.size() - ss.tellp(), ' ');
  177. }
  178. const auto help_lines = break_str_into_lines(help, n_char_per_line_help);
  179. for (const auto & line : help_lines) {
  180. ss << (&line == &help_lines.front() ? "" : leading_spaces) << line << "\n";
  181. }
  182. return ss.str();
  183. }
  184. //
  185. // downloader
  186. //
  187. struct common_hf_file_res {
  188. std::string repo; // repo name with ":tag" removed
  189. std::string ggufFile;
  190. std::string mmprojFile;
  191. };
  192. #ifdef LLAMA_USE_CURL
  193. bool common_has_curl() {
  194. return true;
  195. }
  196. //
  197. // CURL utils
  198. //
  199. using curl_ptr = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>;
  200. // cannot use unique_ptr for curl_slist, because we cannot update without destroying the old one
  201. struct curl_slist_ptr {
  202. struct curl_slist * ptr = nullptr;
  203. ~curl_slist_ptr() {
  204. if (ptr) {
  205. curl_slist_free_all(ptr);
  206. }
  207. }
  208. };
  209. static CURLcode common_curl_perf(CURL * curl) {
  210. CURLcode res = curl_easy_perform(curl);
  211. if (res != CURLE_OK) {
  212. LOG_ERR("%s: curl_easy_perform() failed\n", __func__);
  213. }
  214. return res;
  215. }
  216. // Send a HEAD request to retrieve the etag and last-modified headers
  217. struct common_load_model_from_url_headers {
  218. std::string etag;
  219. std::string last_modified;
  220. std::string accept_ranges;
  221. };
  222. struct FILE_deleter {
  223. void operator()(FILE * f) const { fclose(f); }
  224. };
  225. static size_t common_header_callback(char * buffer, size_t, size_t n_items, void * userdata) {
  226. common_load_model_from_url_headers * headers = (common_load_model_from_url_headers *) userdata;
  227. static std::regex header_regex("([^:]+): (.*)\r\n");
  228. static std::regex etag_regex("ETag", std::regex_constants::icase);
  229. static std::regex last_modified_regex("Last-Modified", std::regex_constants::icase);
  230. static std::regex accept_ranges_regex("Accept-Ranges", std::regex_constants::icase);
  231. std::string header(buffer, n_items);
  232. std::smatch match;
  233. if (std::regex_match(header, match, header_regex)) {
  234. const std::string & key = match[1];
  235. const std::string & value = match[2];
  236. if (std::regex_match(key, match, etag_regex)) {
  237. headers->etag = value;
  238. } else if (std::regex_match(key, match, last_modified_regex)) {
  239. headers->last_modified = value;
  240. } else if (std::regex_match(key, match, accept_ranges_regex)) {
  241. headers->accept_ranges = value;
  242. }
  243. }
  244. return n_items;
  245. }
  246. static size_t common_write_callback(void * data, size_t size, size_t nmemb, void * fd) {
  247. return std::fwrite(data, size, nmemb, static_cast<FILE *>(fd));
  248. }
  249. // helper function to hide password in URL
  250. static std::string llama_download_hide_password_in_url(const std::string & url) {
  251. // Use regex to match and replace the user[:password]@ pattern in URLs
  252. // Pattern: scheme://[user[:password]@]host[...]
  253. static const std::regex url_regex(R"(^(?:[A-Za-z][A-Za-z0-9+.-]://)(?:[^/@]+@)?.$)");
  254. std::smatch match;
  255. if (std::regex_match(url, match, url_regex)) {
  256. // match[1] = scheme (e.g., "https://")
  257. // match[2] = user[:password]@ part
  258. // match[3] = rest of URL (host and path)
  259. return match[1].str() + "********@" + match[3].str();
  260. }
  261. return url; // No credentials found or malformed URL
  262. }
  263. static void common_curl_easy_setopt_head(CURL * curl, const std::string & url) {
  264. // Set the URL, allow to follow http redirection
  265. curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
  266. curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
  267. # if defined(_WIN32)
  268. // CURLSSLOPT_NATIVE_CA tells libcurl to use standard certificate store of
  269. // operating system. Currently implemented under MS-Windows.
  270. curl_easy_setopt(curl, CURLOPT_SSL_OPTIONS, CURLSSLOPT_NATIVE_CA);
  271. # endif
  272. curl_easy_setopt(curl, CURLOPT_NOBODY, 1L); // will trigger the HEAD verb
  273. curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 1L); // hide head request progress
  274. curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, common_header_callback);
  275. }
  276. static void common_curl_easy_setopt_get(CURL * curl) {
  277. curl_easy_setopt(curl, CURLOPT_NOBODY, 0L);
  278. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, common_write_callback);
  279. // display download progress
  280. curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0L);
  281. }
  282. static bool common_pull_file(CURL * curl, const std::string & path_temporary) {
  283. if (std::filesystem::exists(path_temporary)) {
  284. const std::string partial_size = std::to_string(std::filesystem::file_size(path_temporary));
  285. LOG_INF("%s: server supports range requests, resuming download from byte %s\n", __func__, partial_size.c_str());
  286. const std::string range_str = partial_size + "-";
  287. curl_easy_setopt(curl, CURLOPT_RANGE, range_str.c_str());
  288. }
  289. // Always open file in append mode could be resuming
  290. std::unique_ptr<FILE, FILE_deleter> outfile(fopen(path_temporary.c_str(), "ab"));
  291. if (!outfile) {
  292. LOG_ERR("%s: error opening local file for writing: %s\n", __func__, path_temporary.c_str());
  293. return false;
  294. }
  295. common_curl_easy_setopt_get(curl);
  296. curl_easy_setopt(curl, CURLOPT_WRITEDATA, outfile.get());
  297. return common_curl_perf(curl) == CURLE_OK;
  298. }
  299. static bool common_download_head(CURL * curl,
  300. curl_slist_ptr & http_headers,
  301. const std::string & url,
  302. const std::string & bearer_token) {
  303. if (!curl) {
  304. LOG_ERR("%s: error initializing libcurl\n", __func__);
  305. return false;
  306. }
  307. http_headers.ptr = curl_slist_append(http_headers.ptr, "User-Agent: llama-cpp");
  308. // Check if hf-token or bearer-token was specified
  309. if (!bearer_token.empty()) {
  310. std::string auth_header = "Authorization: Bearer " + bearer_token;
  311. http_headers.ptr = curl_slist_append(http_headers.ptr, auth_header.c_str());
  312. }
  313. curl_easy_setopt(curl, CURLOPT_HTTPHEADER, http_headers.ptr);
  314. common_curl_easy_setopt_head(curl, url);
  315. return common_curl_perf(curl) == CURLE_OK;
  316. }
  317. // download one single file from remote URL to local path
  318. static bool common_download_file_single_online(const std::string & url,
  319. const std::string & path,
  320. const std::string & bearer_token) {
  321. // If the file exists, check its JSON metadata companion file.
  322. std::string metadata_path = path + ".json";
  323. static const int max_attempts = 3;
  324. static const int retry_delay_seconds = 2;
  325. for (int i = 0; i < max_attempts; ++i) {
  326. nlohmann::json metadata; // TODO @ngxson : get rid of this json, use regex instead
  327. std::string etag;
  328. std::string last_modified;
  329. // Check if the file already exists locally
  330. const auto file_exists = std::filesystem::exists(path);
  331. if (file_exists) {
  332. // Try and read the JSON metadata file (note: stream autoclosed upon exiting this block).
  333. std::ifstream metadata_in(metadata_path);
  334. if (metadata_in.good()) {
  335. try {
  336. metadata_in >> metadata;
  337. LOG_DBG("%s: previous metadata file found %s: %s\n", __func__, metadata_path.c_str(),
  338. metadata.dump().c_str());
  339. if (metadata.contains("etag") && metadata.at("etag").is_string()) {
  340. etag = metadata.at("etag");
  341. }
  342. if (metadata.contains("lastModified") && metadata.at("lastModified").is_string()) {
  343. last_modified = metadata.at("lastModified");
  344. }
  345. } catch (const nlohmann::json::exception & e) {
  346. LOG_ERR("%s: error reading metadata file %s: %s\n", __func__, metadata_path.c_str(), e.what());
  347. }
  348. }
  349. // if we cannot open the metadata file, we assume that the downloaded file is not valid (etag and last-modified are left empty, so we will download it again)
  350. } else {
  351. LOG_INF("%s: no previous model file found %s\n", __func__, path.c_str());
  352. }
  353. bool head_request_ok = false;
  354. bool should_download = !file_exists; // by default, we should download if the file does not exist
  355. // Initialize libcurl
  356. curl_ptr curl(curl_easy_init(), &curl_easy_cleanup);
  357. common_load_model_from_url_headers headers;
  358. curl_easy_setopt(curl.get(), CURLOPT_HEADERDATA, &headers);
  359. curl_slist_ptr http_headers;
  360. const bool was_perform_successful = common_download_head(curl.get(), http_headers, url, bearer_token);
  361. if (!was_perform_successful) {
  362. head_request_ok = false;
  363. }
  364. long http_code = 0;
  365. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &http_code);
  366. if (http_code == 200) {
  367. head_request_ok = true;
  368. } else {
  369. LOG_WRN("%s: HEAD invalid http status code received: %ld\n", __func__, http_code);
  370. head_request_ok = false;
  371. }
  372. // if head_request_ok is false, we don't have the etag or last-modified headers
  373. // we leave should_download as-is, which is true if the file does not exist
  374. bool should_download_from_scratch = false;
  375. if (head_request_ok) {
  376. // check if ETag or Last-Modified headers are different
  377. // if it is, we need to download the file again
  378. if (!etag.empty() && etag != headers.etag) {
  379. LOG_WRN("%s: ETag header is different (%s != %s): triggering a new download\n", __func__, etag.c_str(),
  380. headers.etag.c_str());
  381. should_download = true;
  382. should_download_from_scratch = true;
  383. } else if (!last_modified.empty() && last_modified != headers.last_modified) {
  384. LOG_WRN("%s: Last-Modified header is different (%s != %s): triggering a new download\n", __func__,
  385. last_modified.c_str(), headers.last_modified.c_str());
  386. should_download = true;
  387. should_download_from_scratch = true;
  388. }
  389. }
  390. const bool accept_ranges_supported = !headers.accept_ranges.empty() && headers.accept_ranges != "none";
  391. if (should_download) {
  392. if (file_exists &&
  393. !accept_ranges_supported) { // Resumable downloads not supported, delete and start again.
  394. LOG_WRN("%s: deleting previous downloaded file: %s\n", __func__, path.c_str());
  395. if (remove(path.c_str()) != 0) {
  396. LOG_ERR("%s: unable to delete file: %s\n", __func__, path.c_str());
  397. return false;
  398. }
  399. }
  400. const std::string path_temporary = path + ".downloadInProgress";
  401. if (should_download_from_scratch) {
  402. if (std::filesystem::exists(path_temporary)) {
  403. if (remove(path_temporary.c_str()) != 0) {
  404. LOG_ERR("%s: unable to delete file: %s\n", __func__, path_temporary.c_str());
  405. return false;
  406. }
  407. }
  408. if (std::filesystem::exists(path)) {
  409. if (remove(path.c_str()) != 0) {
  410. LOG_ERR("%s: unable to delete file: %s\n", __func__, path.c_str());
  411. return false;
  412. }
  413. }
  414. }
  415. // Write the updated JSON metadata file.
  416. metadata.update({
  417. { "url", url },
  418. { "etag", headers.etag },
  419. { "lastModified", headers.last_modified }
  420. });
  421. write_file(metadata_path, metadata.dump(4));
  422. LOG_DBG("%s: file metadata saved: %s\n", __func__, metadata_path.c_str());
  423. // start the download
  424. LOG_INF("%s: trying to download model from %s to %s (server_etag:%s, server_last_modified:%s)...\n",
  425. __func__, llama_download_hide_password_in_url(url).c_str(), path_temporary.c_str(),
  426. headers.etag.c_str(), headers.last_modified.c_str());
  427. const bool was_pull_successful = common_pull_file(curl.get(), path_temporary);
  428. if (!was_pull_successful) {
  429. if (i + 1 < max_attempts) {
  430. const int exponential_backoff_delay = std::pow(retry_delay_seconds, i) * 1000;
  431. LOG_WRN("%s: retrying after %d milliseconds...\n", __func__, exponential_backoff_delay);
  432. std::this_thread::sleep_for(std::chrono::milliseconds(exponential_backoff_delay));
  433. } else {
  434. LOG_ERR("%s: curl_easy_perform() failed after %d attempts\n", __func__, max_attempts);
  435. }
  436. continue;
  437. }
  438. long http_code = 0;
  439. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &http_code);
  440. if (http_code < 200 || http_code >= 400) {
  441. LOG_ERR("%s: invalid http status code received: %ld\n", __func__, http_code);
  442. return false;
  443. }
  444. if (rename(path_temporary.c_str(), path.c_str()) != 0) {
  445. LOG_ERR("%s: unable to rename file: %s to %s\n", __func__, path_temporary.c_str(), path.c_str());
  446. return false;
  447. }
  448. } else {
  449. LOG_INF("%s: using cached file: %s\n", __func__, path.c_str());
  450. }
  451. break;
  452. }
  453. return true;
  454. }
  455. std::pair<long, std::vector<char>> common_remote_get_content(const std::string & url, const common_remote_params & params) {
  456. curl_ptr curl(curl_easy_init(), &curl_easy_cleanup);
  457. curl_slist_ptr http_headers;
  458. std::vector<char> res_buffer;
  459. curl_easy_setopt(curl.get(), CURLOPT_URL, url.c_str());
  460. curl_easy_setopt(curl.get(), CURLOPT_NOPROGRESS, 1L);
  461. curl_easy_setopt(curl.get(), CURLOPT_FOLLOWLOCATION, 1L);
  462. curl_easy_setopt(curl.get(), CURLOPT_VERBOSE, 1L);
  463. typedef size_t(*CURLOPT_WRITEFUNCTION_PTR)(void * ptr, size_t size, size_t nmemb, void * data);
  464. auto write_callback = [](void * ptr, size_t size, size_t nmemb, void * data) -> size_t {
  465. auto data_vec = static_cast<std::vector<char> *>(data);
  466. data_vec->insert(data_vec->end(), (char *)ptr, (char *)ptr + size * nmemb);
  467. return size * nmemb;
  468. };
  469. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, static_cast<CURLOPT_WRITEFUNCTION_PTR>(write_callback));
  470. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &res_buffer);
  471. #if defined(_WIN32)
  472. curl_easy_setopt(curl.get(), CURLOPT_SSL_OPTIONS, CURLSSLOPT_NATIVE_CA);
  473. #endif
  474. if (params.timeout > 0) {
  475. curl_easy_setopt(curl.get(), CURLOPT_TIMEOUT, params.timeout);
  476. }
  477. if (params.max_size > 0) {
  478. curl_easy_setopt(curl.get(), CURLOPT_MAXFILESIZE, params.max_size);
  479. }
  480. http_headers.ptr = curl_slist_append(http_headers.ptr, "User-Agent: llama-cpp");
  481. for (const auto & header : params.headers) {
  482. http_headers.ptr = curl_slist_append(http_headers.ptr, header.c_str());
  483. }
  484. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, http_headers.ptr);
  485. CURLcode res = curl_easy_perform(curl.get());
  486. if (res != CURLE_OK) {
  487. std::string error_msg = curl_easy_strerror(res);
  488. throw std::runtime_error("error: cannot make GET request: " + error_msg);
  489. }
  490. long res_code;
  491. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &res_code);
  492. return { res_code, std::move(res_buffer) };
  493. }
  494. #else
  495. bool common_has_curl() {
  496. return false;
  497. }
  498. struct common_url {
  499. std::string scheme;
  500. std::string user;
  501. std::string password;
  502. std::string host;
  503. std::string path;
  504. };
  505. static common_url parse_url(const std::string & url) {
  506. common_url parts;
  507. auto scheme_end = url.find("://");
  508. if (scheme_end == std::string::npos) {
  509. throw std::runtime_error("invalid URL: no scheme");
  510. }
  511. parts.scheme = url.substr(0, scheme_end);
  512. if (parts.scheme != "http" && parts.scheme != "https") {
  513. throw std::runtime_error("unsupported URL scheme: " + parts.scheme);
  514. }
  515. auto rest = url.substr(scheme_end + 3);
  516. auto at_pos = rest.find('@');
  517. if (at_pos != std::string::npos) {
  518. auto auth = rest.substr(0, at_pos);
  519. auto colon_pos = auth.find(':');
  520. if (colon_pos != std::string::npos) {
  521. parts.user = auth.substr(0, colon_pos);
  522. parts.password = auth.substr(colon_pos + 1);
  523. } else {
  524. parts.user = auth;
  525. }
  526. rest = rest.substr(at_pos + 1);
  527. }
  528. auto slash_pos = rest.find('/');
  529. if (slash_pos != std::string::npos) {
  530. parts.host = rest.substr(0, slash_pos);
  531. parts.path = rest.substr(slash_pos);
  532. } else {
  533. parts.host = rest;
  534. parts.path = "/";
  535. }
  536. return parts;
  537. }
  538. static std::pair<httplib::Client, common_url> http_client(const std::string & url) {
  539. common_url parts = parse_url(url);
  540. if (parts.host.empty()) {
  541. throw std::runtime_error("error: invalid URL format");
  542. }
  543. if (!parts.user.empty()) {
  544. throw std::runtime_error("error: user:password@ not supported yet"); // TODO
  545. }
  546. httplib::Client cli(parts.scheme + "://" + parts.host);
  547. cli.set_follow_location(true);
  548. // TODO cert
  549. return { std::move(cli), std::move(parts) };
  550. }
  551. static std::string show_masked_url(const common_url & parts) {
  552. return parts.scheme + "://" + (parts.user.empty() ? "" : "****:****@") + parts.host + parts.path;
  553. }
  554. static void print_progress(size_t current, size_t total) { // TODO isatty
  555. if (!total) {
  556. return;
  557. }
  558. size_t width = 50;
  559. size_t pct = (100 * current) / total;
  560. size_t pos = (width * current) / total;
  561. std::cout << "["
  562. << std::string(pos, '=')
  563. << (pos < width ? ">" : "")
  564. << std::string(width - pos, ' ')
  565. << "] " << std::setw(3) << pct << "% ("
  566. << current / (1024 * 1024) << " MB / "
  567. << total / (1024 * 1024) << " MB)\r";
  568. std::cout.flush();
  569. }
  570. struct common_file_metadata {
  571. std::string etag;
  572. std::string last_modified;
  573. };
  574. static std::optional<common_file_metadata> read_metadata(const std::string & path) {
  575. if (!std::filesystem::exists(path)) {
  576. return std::nullopt;
  577. }
  578. nlohmann::json metadata_json;
  579. common_file_metadata metadata;
  580. std::ifstream metadata_in(path);
  581. try {
  582. metadata_in >> metadata_json;
  583. LOG_DBG("%s: previous metadata file found %s: %s\n", __func__, path.c_str(),
  584. metadata_json.dump().c_str());
  585. if (metadata_json.contains("etag") && metadata_json.at("etag").is_string()) {
  586. metadata.etag = metadata_json.at("etag");
  587. }
  588. if (metadata_json.contains("lastModified") && metadata_json.at("lastModified").is_string()) {
  589. metadata.last_modified = metadata_json.at("lastModified");
  590. }
  591. } catch (const nlohmann::json::exception & e) {
  592. LOG_ERR("%s: error reading metadata file %s: %s\n", __func__, path.c_str(), e.what());
  593. return std::nullopt;
  594. }
  595. return metadata;
  596. }
  597. static void write_metadata(const std::string & path,
  598. const std::string & url,
  599. const common_file_metadata & metadata) {
  600. nlohmann::json metadata_json = {
  601. { "url", url },
  602. { "etag", metadata.etag },
  603. { "lastModified", metadata.last_modified }
  604. };
  605. write_file(path, metadata_json.dump(4));
  606. LOG_DBG("%s: file metadata saved: %s\n", __func__, path.c_str());
  607. }
  608. static bool common_pull_file(httplib::Client & cli,
  609. const std::string & resolve_path,
  610. const std::string & path_tmp,
  611. bool supports_ranges,
  612. size_t existing_size,
  613. size_t & total_size) {
  614. std::ofstream ofs(path_tmp, std::ios::binary | std::ios::app);
  615. if (!ofs.is_open()) {
  616. LOG_ERR("%s: error opening local file for writing: %s\n", __func__, path_tmp.c_str());
  617. return false;
  618. }
  619. httplib::Headers headers;
  620. if (supports_ranges && existing_size > 0) {
  621. headers.emplace("Range", "bytes=" + std::to_string(existing_size) + "-");
  622. }
  623. std::atomic<size_t> downloaded{existing_size};
  624. auto res = cli.Get(resolve_path, headers,
  625. [&](const httplib::Response &response) {
  626. if (existing_size > 0 && response.status != 206) {
  627. LOG_WRN("%s: server did not respond with 206 Partial Content for a resume request. Status: %d\n", __func__, response.status);
  628. return false;
  629. }
  630. if (existing_size == 0 && response.status != 200) {
  631. LOG_WRN("%s: download received non-successful status code: %d\n", __func__, response.status);
  632. return false;
  633. }
  634. if (total_size == 0 && response.has_header("Content-Length")) {
  635. try {
  636. size_t content_length = std::stoull(response.get_header_value("Content-Length"));
  637. total_size = existing_size + content_length;
  638. } catch (const std::exception &e) {
  639. LOG_WRN("%s: invalid Content-Length header: %s\n", __func__, e.what());
  640. }
  641. }
  642. return true;
  643. },
  644. [&](const char *data, size_t len) {
  645. ofs.write(data, len);
  646. if (!ofs) {
  647. LOG_ERR("%s: error writing to file: %s\n", __func__, path_tmp.c_str());
  648. return false;
  649. }
  650. downloaded += len;
  651. print_progress(downloaded, total_size);
  652. return true;
  653. },
  654. nullptr
  655. );
  656. std::cout << "\n";
  657. if (!res) {
  658. LOG_ERR("%s: error during download. Status: %d\n", __func__, res ? res->status : -1);
  659. return false;
  660. }
  661. return true;
  662. }
  663. // download one single file from remote URL to local path
  664. static bool common_download_file_single_online(const std::string & url,
  665. const std::string & path,
  666. const std::string & bearer_token) {
  667. // If the file exists, check its JSON metadata companion file.
  668. std::string metadata_path = path + ".json";
  669. static const int max_attempts = 3;
  670. static const int retry_delay_seconds = 2;
  671. auto [cli, parts] = http_client(url);
  672. httplib::Headers default_headers = {{"User-Agent", "llama-cpp"}};
  673. if (!bearer_token.empty()) {
  674. default_headers.insert({"Authorization", "Bearer " + bearer_token});
  675. }
  676. cli.set_default_headers(default_headers);
  677. common_file_metadata last;
  678. const bool file_exists = std::filesystem::exists(path);
  679. if (file_exists) {
  680. if (auto opt = read_metadata(metadata_path)) {
  681. last = *opt;
  682. }
  683. } else {
  684. LOG_INF("%s: no previous model file found %s\n", __func__, path.c_str());
  685. }
  686. for (int i = 0; i < max_attempts; ++i) {
  687. auto head = cli.Head(parts.path);
  688. bool head_ok = head && head->status >= 200 && head->status < 300;
  689. if (!head_ok) {
  690. LOG_WRN("%s: HEAD invalid http status code received: %d\n", __func__, head ? head->status : -1);
  691. if (file_exists) {
  692. LOG_INF("%s: Using cached file (HEAD failed): %s\n", __func__, path.c_str());
  693. return true;
  694. }
  695. }
  696. common_file_metadata current;
  697. if (head_ok) {
  698. if (head->has_header("ETag")) {
  699. current.etag = head->get_header_value("ETag");
  700. }
  701. if (head->has_header("Last-Modified")) {
  702. current.last_modified = head->get_header_value("Last-Modified");
  703. }
  704. }
  705. size_t total_size = 0;
  706. if (head_ok && head->has_header("Content-Length")) {
  707. try {
  708. total_size = std::stoull(head->get_header_value("Content-Length"));
  709. } catch (const std::exception& e) {
  710. LOG_WRN("%s: Invalid Content-Length in HEAD response: %s\n", __func__, e.what());
  711. }
  712. }
  713. bool supports_ranges = false;
  714. if (head_ok && head->has_header("Accept-Ranges")) {
  715. supports_ranges = head->get_header_value("Accept-Ranges") != "none";
  716. }
  717. bool should_download_from_scratch = false;
  718. if (head_ok) {
  719. if (!last.etag.empty() && last.etag != current.etag) {
  720. LOG_WRN("%s: ETag header is different (%s != %s): triggering a new download\n", __func__,
  721. last.etag.c_str(), current.etag.c_str());
  722. should_download_from_scratch = true;
  723. } else if (!last.last_modified.empty() && last.last_modified != current.last_modified) {
  724. LOG_WRN("%s: Last-Modified header is different (%s != %s): triggering a new download\n", __func__,
  725. last.last_modified.c_str(), current.last_modified.c_str());
  726. should_download_from_scratch = true;
  727. }
  728. }
  729. if (file_exists) {
  730. if (!should_download_from_scratch) {
  731. LOG_INF("%s: using cached file: %s\n", __func__, path.c_str());
  732. return true;
  733. }
  734. LOG_WRN("%s: deleting previous downloaded file: %s\n", __func__, path.c_str());
  735. if (remove(path.c_str()) != 0) {
  736. LOG_ERR("%s: unable to delete file: %s\n", __func__, path.c_str());
  737. return false;
  738. }
  739. }
  740. const std::string path_temporary = path + ".downloadInProgress";
  741. size_t existing_size = 0;
  742. if (std::filesystem::exists(path_temporary)) {
  743. if (supports_ranges && !should_download_from_scratch) {
  744. existing_size = std::filesystem::file_size(path_temporary);
  745. } else if (remove(path_temporary.c_str()) != 0) {
  746. LOG_ERR("%s: unable to delete file: %s\n", __func__, path_temporary.c_str());
  747. return false;
  748. }
  749. }
  750. // start the download
  751. LOG_INF("%s: trying to download model from %s to %s (server_etag:%s, server_last_modified:%s)...\n",
  752. __func__, show_masked_url(parts).c_str(), path_temporary.c_str(),
  753. current.etag.c_str(), current.last_modified.c_str());
  754. const bool was_pull_successful = common_pull_file(cli, parts.path, path_temporary, supports_ranges, existing_size, total_size);
  755. if (!was_pull_successful) {
  756. if (i + 1 < max_attempts) {
  757. const int exponential_backoff_delay = std::pow(retry_delay_seconds, i) * 1000;
  758. LOG_WRN("%s: retrying after %d milliseconds...\n", __func__, exponential_backoff_delay);
  759. std::this_thread::sleep_for(std::chrono::milliseconds(exponential_backoff_delay));
  760. } else {
  761. LOG_ERR("%s: download failed after %d attempts\n", __func__, max_attempts);
  762. }
  763. continue;
  764. }
  765. if (std::rename(path_temporary.c_str(), path.c_str()) != 0) {
  766. LOG_ERR("%s: unable to rename file: %s to %s\n", __func__, path_temporary.c_str(), path.c_str());
  767. return false;
  768. }
  769. write_metadata(metadata_path, url, current);
  770. break;
  771. }
  772. return true;
  773. }
  774. std::pair<long, std::vector<char>> common_remote_get_content(const std::string & url,
  775. const common_remote_params & params) {
  776. auto [cli, parts] = http_client(url);
  777. httplib::Headers headers = {{"User-Agent", "llama-cpp"}};
  778. for (const auto & header : params.headers) {
  779. size_t pos = header.find(':');
  780. if (pos != std::string::npos) {
  781. headers.emplace(header.substr(0, pos), header.substr(pos + 1));
  782. } else {
  783. headers.emplace(header, "");
  784. }
  785. }
  786. if (params.timeout > 0) {
  787. cli.set_read_timeout(params.timeout, 0);
  788. cli.set_write_timeout(params.timeout, 0);
  789. }
  790. std::vector<char> buf;
  791. auto res = cli.Get(parts.path, headers,
  792. [&](const char *data, size_t len) {
  793. buf.insert(buf.end(), data, data + len);
  794. return params.max_size == 0 ||
  795. buf.size() <= static_cast<size_t>(params.max_size);
  796. },
  797. nullptr
  798. );
  799. if (!res) {
  800. throw std::runtime_error("error: cannot make GET request");
  801. }
  802. return { res->status, std::move(buf) };
  803. }
  804. #endif // LLAMA_USE_CURL
  805. static bool common_download_file_single(const std::string & url,
  806. const std::string & path,
  807. const std::string & bearer_token,
  808. bool offline) {
  809. if (!offline) {
  810. return common_download_file_single_online(url, path, bearer_token);
  811. }
  812. if (!std::filesystem::exists(path)) {
  813. LOG_ERR("%s: required file is not available in cache (offline mode): %s\n", __func__, path.c_str());
  814. return false;
  815. }
  816. LOG_INF("%s: using cached file (offline mode): %s\n", __func__, path.c_str());
  817. return true;
  818. }
  819. // download multiple files from remote URLs to local paths
  820. // the input is a vector of pairs <url, path>
  821. static bool common_download_file_multiple(const std::vector<std::pair<std::string, std::string>> & urls, const std::string & bearer_token, bool offline) {
  822. // Prepare download in parallel
  823. std::vector<std::future<bool>> futures_download;
  824. for (auto const & item : urls) {
  825. futures_download.push_back(std::async(std::launch::async, [bearer_token, offline](const std::pair<std::string, std::string> & it) -> bool {
  826. return common_download_file_single(it.first, it.second, bearer_token, offline);
  827. }, item));
  828. }
  829. // Wait for all downloads to complete
  830. for (auto & f : futures_download) {
  831. if (!f.get()) {
  832. return false;
  833. }
  834. }
  835. return true;
  836. }
  837. static bool common_download_model(
  838. const common_params_model & model,
  839. const std::string & bearer_token,
  840. bool offline) {
  841. // Basic validation of the model.url
  842. if (model.url.empty()) {
  843. LOG_ERR("%s: invalid model url\n", __func__);
  844. return false;
  845. }
  846. if (!common_download_file_single(model.url, model.path, bearer_token, offline)) {
  847. return false;
  848. }
  849. // check for additional GGUFs split to download
  850. int n_split = 0;
  851. {
  852. struct gguf_init_params gguf_params = {
  853. /*.no_alloc = */ true,
  854. /*.ctx = */ NULL,
  855. };
  856. auto * ctx_gguf = gguf_init_from_file(model.path.c_str(), gguf_params);
  857. if (!ctx_gguf) {
  858. LOG_ERR("\n%s: failed to load input GGUF from %s\n", __func__, model.path.c_str());
  859. return false;
  860. }
  861. auto key_n_split = gguf_find_key(ctx_gguf, LLM_KV_SPLIT_COUNT);
  862. if (key_n_split >= 0) {
  863. n_split = gguf_get_val_u16(ctx_gguf, key_n_split);
  864. }
  865. gguf_free(ctx_gguf);
  866. }
  867. if (n_split > 1) {
  868. char split_prefix[PATH_MAX] = {0};
  869. char split_url_prefix[LLAMA_MAX_URL_LENGTH] = {0};
  870. // Verify the first split file format
  871. // and extract split URL and PATH prefixes
  872. {
  873. if (!llama_split_prefix(split_prefix, sizeof(split_prefix), model.path.c_str(), 0, n_split)) {
  874. LOG_ERR("\n%s: unexpected model file name: %s n_split=%d\n", __func__, model.path.c_str(), n_split);
  875. return false;
  876. }
  877. if (!llama_split_prefix(split_url_prefix, sizeof(split_url_prefix), model.url.c_str(), 0, n_split)) {
  878. LOG_ERR("\n%s: unexpected model url: %s n_split=%d\n", __func__, model.url.c_str(), n_split);
  879. return false;
  880. }
  881. }
  882. std::vector<std::pair<std::string, std::string>> urls;
  883. for (int idx = 1; idx < n_split; idx++) {
  884. char split_path[PATH_MAX] = {0};
  885. llama_split_path(split_path, sizeof(split_path), split_prefix, idx, n_split);
  886. char split_url[LLAMA_MAX_URL_LENGTH] = {0};
  887. llama_split_path(split_url, sizeof(split_url), split_url_prefix, idx, n_split);
  888. if (std::string(split_path) == model.path) {
  889. continue; // skip the already downloaded file
  890. }
  891. urls.push_back({split_url, split_path});
  892. }
  893. // Download in parallel
  894. common_download_file_multiple(urls, bearer_token, offline);
  895. }
  896. return true;
  897. }
  898. /**
  899. * Allow getting the HF file from the HF repo with tag (like ollama), for example:
  900. * - bartowski/Llama-3.2-3B-Instruct-GGUF:q4
  901. * - bartowski/Llama-3.2-3B-Instruct-GGUF:Q4_K_M
  902. * - bartowski/Llama-3.2-3B-Instruct-GGUF:q5_k_s
  903. * Tag is optional, default to "latest" (meaning it checks for Q4_K_M first, then Q4, then if not found, return the first GGUF file in repo)
  904. *
  905. * Return pair of <repo, file> (with "repo" already having tag removed)
  906. *
  907. * Note: we use the Ollama-compatible HF API, but not using the blobId. Instead, we use the special "ggufFile" field which returns the value for "hf_file". This is done to be backward-compatible with existing cache files.
  908. */
  909. static struct common_hf_file_res common_get_hf_file(const std::string & hf_repo_with_tag, const std::string & bearer_token, bool offline) {
  910. auto parts = string_split<std::string>(hf_repo_with_tag, ':');
  911. std::string tag = parts.size() > 1 ? parts.back() : "latest";
  912. std::string hf_repo = parts[0];
  913. if (string_split<std::string>(hf_repo, '/').size() != 2) {
  914. throw std::invalid_argument("error: invalid HF repo format, expected <user>/<model>[:quant]\n");
  915. }
  916. std::string url = get_model_endpoint() + "v2/" + hf_repo + "/manifests/" + tag;
  917. // headers
  918. std::vector<std::string> headers;
  919. headers.push_back("Accept: application/json");
  920. if (!bearer_token.empty()) {
  921. headers.push_back("Authorization: Bearer " + bearer_token);
  922. }
  923. // Important: the User-Agent must be "llama-cpp" to get the "ggufFile" field in the response
  924. // User-Agent header is already set in common_remote_get_content, no need to set it here
  925. // we use "=" to avoid clashing with other component, while still being allowed on windows
  926. std::string cached_response_fname = "manifest=" + hf_repo + "=" + tag + ".json";
  927. string_replace_all(cached_response_fname, "/", "_");
  928. std::string cached_response_path = fs_get_cache_file(cached_response_fname);
  929. // make the request
  930. common_remote_params params;
  931. params.headers = headers;
  932. long res_code = 0;
  933. std::string res_str;
  934. bool use_cache = false;
  935. if (!offline) {
  936. try {
  937. auto res = common_remote_get_content(url, params);
  938. res_code = res.first;
  939. res_str = std::string(res.second.data(), res.second.size());
  940. } catch (const std::exception & e) {
  941. LOG_WRN("error: failed to get manifest at %s: %s\n", url.c_str(), e.what());
  942. }
  943. }
  944. if (res_code == 0) {
  945. if (std::filesystem::exists(cached_response_path)) {
  946. LOG_WRN("trying to read manifest from cache: %s\n", cached_response_path.c_str());
  947. res_str = read_file(cached_response_path);
  948. res_code = 200;
  949. use_cache = true;
  950. } else {
  951. throw std::runtime_error(
  952. offline ? "error: failed to get manifest (offline mode)"
  953. : "error: failed to get manifest (check your internet connection)");
  954. }
  955. }
  956. std::string ggufFile;
  957. std::string mmprojFile;
  958. if (res_code == 200 || res_code == 304) {
  959. try {
  960. auto j = json::parse(res_str);
  961. if (j.contains("ggufFile") && j["ggufFile"].contains("rfilename")) {
  962. ggufFile = j["ggufFile"]["rfilename"].get<std::string>();
  963. }
  964. if (j.contains("mmprojFile") && j["mmprojFile"].contains("rfilename")) {
  965. mmprojFile = j["mmprojFile"]["rfilename"].get<std::string>();
  966. }
  967. } catch (const std::exception & e) {
  968. throw std::runtime_error(std::string("error parsing manifest JSON: ") + e.what());
  969. }
  970. if (!use_cache) {
  971. // if not using cached response, update the cache file
  972. write_file(cached_response_path, res_str);
  973. }
  974. } else if (res_code == 401) {
  975. throw std::runtime_error("error: model is private or does not exist; if you are accessing a gated model, please provide a valid HF token");
  976. } else {
  977. throw std::runtime_error(string_format("error from HF API, response code: %ld, data: %s", res_code, res_str.c_str()));
  978. }
  979. // check response
  980. if (ggufFile.empty()) {
  981. throw std::runtime_error("error: model does not have ggufFile");
  982. }
  983. return { hf_repo, ggufFile, mmprojFile };
  984. }
  985. //
  986. // Docker registry functions
  987. //
  988. static std::string common_docker_get_token(const std::string & repo) {
  989. std::string url = "https://auth.docker.io/token?service=registry.docker.io&scope=repository:" + repo + ":pull";
  990. common_remote_params params;
  991. auto res = common_remote_get_content(url, params);
  992. if (res.first != 200) {
  993. throw std::runtime_error("Failed to get Docker registry token, HTTP code: " + std::to_string(res.first));
  994. }
  995. std::string response_str(res.second.begin(), res.second.end());
  996. nlohmann::ordered_json response = nlohmann::ordered_json::parse(response_str);
  997. if (!response.contains("token")) {
  998. throw std::runtime_error("Docker registry token response missing 'token' field");
  999. }
  1000. return response["token"].get<std::string>();
  1001. }
  1002. static std::string common_docker_resolve_model(const std::string & docker) {
  1003. // Parse ai/smollm2:135M-Q4_0
  1004. size_t colon_pos = docker.find(':');
  1005. std::string repo, tag;
  1006. if (colon_pos != std::string::npos) {
  1007. repo = docker.substr(0, colon_pos);
  1008. tag = docker.substr(colon_pos + 1);
  1009. } else {
  1010. repo = docker;
  1011. tag = "latest";
  1012. }
  1013. // ai/ is the default
  1014. size_t slash_pos = docker.find('/');
  1015. if (slash_pos == std::string::npos) {
  1016. repo.insert(0, "ai/");
  1017. }
  1018. LOG_INF("%s: Downloading Docker Model: %s:%s\n", __func__, repo.c_str(), tag.c_str());
  1019. try {
  1020. // --- helper: digest validation ---
  1021. auto validate_oci_digest = [](const std::string & digest) -> std::string {
  1022. // Expected: algo:hex ; start with sha256 (64 hex chars)
  1023. // You can extend this map if supporting other algorithms in future.
  1024. static const std::regex re("^sha256:([a-fA-F0-9]{64})$");
  1025. std::smatch m;
  1026. if (!std::regex_match(digest, m, re)) {
  1027. throw std::runtime_error("Invalid OCI digest format received in manifest: " + digest);
  1028. }
  1029. // normalize hex to lowercase
  1030. std::string normalized = digest;
  1031. std::transform(normalized.begin()+7, normalized.end(), normalized.begin()+7, [](unsigned char c){
  1032. return std::tolower(c);
  1033. });
  1034. return normalized;
  1035. };
  1036. std::string token = common_docker_get_token(repo); // Get authentication token
  1037. // Get manifest
  1038. const std::string url_prefix = "https://registry-1.docker.io/v2/" + repo;
  1039. std::string manifest_url = url_prefix + "/manifests/" + tag;
  1040. common_remote_params manifest_params;
  1041. manifest_params.headers.push_back("Authorization: Bearer " + token);
  1042. manifest_params.headers.push_back(
  1043. "Accept: application/vnd.docker.distribution.manifest.v2+json,application/vnd.oci.image.manifest.v1+json");
  1044. auto manifest_res = common_remote_get_content(manifest_url, manifest_params);
  1045. if (manifest_res.first != 200) {
  1046. throw std::runtime_error("Failed to get Docker manifest, HTTP code: " + std::to_string(manifest_res.first));
  1047. }
  1048. std::string manifest_str(manifest_res.second.begin(), manifest_res.second.end());
  1049. nlohmann::ordered_json manifest = nlohmann::ordered_json::parse(manifest_str);
  1050. std::string gguf_digest; // Find the GGUF layer
  1051. if (manifest.contains("layers")) {
  1052. for (const auto & layer : manifest["layers"]) {
  1053. if (layer.contains("mediaType")) {
  1054. std::string media_type = layer["mediaType"].get<std::string>();
  1055. if (media_type == "application/vnd.docker.ai.gguf.v3" ||
  1056. media_type.find("gguf") != std::string::npos) {
  1057. gguf_digest = layer["digest"].get<std::string>();
  1058. break;
  1059. }
  1060. }
  1061. }
  1062. }
  1063. if (gguf_digest.empty()) {
  1064. throw std::runtime_error("No GGUF layer found in Docker manifest");
  1065. }
  1066. // Validate & normalize digest
  1067. gguf_digest = validate_oci_digest(gguf_digest);
  1068. LOG_DBG("%s: Using validated digest: %s\n", __func__, gguf_digest.c_str());
  1069. // Prepare local filename
  1070. std::string model_filename = repo;
  1071. std::replace(model_filename.begin(), model_filename.end(), '/', '_');
  1072. model_filename += "_" + tag + ".gguf";
  1073. std::string local_path = fs_get_cache_file(model_filename);
  1074. const std::string blob_url = url_prefix + "/blobs/" + gguf_digest;
  1075. if (!common_download_file_single(blob_url, local_path, token, false)) {
  1076. throw std::runtime_error("Failed to download Docker Model");
  1077. }
  1078. LOG_INF("%s: Downloaded Docker Model to: %s\n", __func__, local_path.c_str());
  1079. return local_path;
  1080. } catch (const std::exception & e) {
  1081. LOG_ERR("%s: Docker Model download failed: %s\n", __func__, e.what());
  1082. throw;
  1083. }
  1084. }
  1085. //
  1086. // utils
  1087. //
  1088. // Helper function to parse tensor buffer override strings
  1089. static void parse_tensor_buffer_overrides(const std::string & value, std::vector<llama_model_tensor_buft_override> & overrides) {
  1090. std::map<std::string, ggml_backend_buffer_type_t> buft_list;
  1091. for (size_t i = 0; i < ggml_backend_dev_count(); ++i) {
  1092. auto * dev = ggml_backend_dev_get(i);
  1093. auto * buft = ggml_backend_dev_buffer_type(dev);
  1094. if (buft) {
  1095. buft_list[ggml_backend_buft_name(buft)] = buft;
  1096. }
  1097. }
  1098. for (const auto & override : string_split<std::string>(value, ',')) {
  1099. std::string::size_type pos = override.find('=');
  1100. if (pos == std::string::npos) {
  1101. throw std::invalid_argument("invalid value");
  1102. }
  1103. std::string tensor_name = override.substr(0, pos);
  1104. std::string buffer_type = override.substr(pos + 1);
  1105. if (buft_list.find(buffer_type) == buft_list.end()) {
  1106. printf("Available buffer types:\n");
  1107. for (const auto & it : buft_list) {
  1108. printf(" %s\n", ggml_backend_buft_name(it.second));
  1109. }
  1110. throw std::invalid_argument("unknown buffer type");
  1111. }
  1112. // keep strings alive and avoid leaking memory by storing them in a static vector
  1113. static std::list<std::string> buft_overrides;
  1114. buft_overrides.push_back(tensor_name);
  1115. overrides.push_back({buft_overrides.back().c_str(), buft_list.at(buffer_type)});
  1116. }
  1117. }
  1118. struct handle_model_result {
  1119. bool found_mmproj = false;
  1120. common_params_model mmproj;
  1121. };
  1122. static handle_model_result common_params_handle_model(
  1123. struct common_params_model & model,
  1124. const std::string & bearer_token,
  1125. const std::string & model_path_default,
  1126. bool offline) {
  1127. handle_model_result result;
  1128. // handle pre-fill default model path and url based on hf_repo and hf_file
  1129. {
  1130. if (!model.docker_repo.empty()) { // Handle Docker URLs by resolving them to local paths
  1131. model.path = common_docker_resolve_model(model.docker_repo);
  1132. } else if (!model.hf_repo.empty()) {
  1133. // short-hand to avoid specifying --hf-file -> default it to --model
  1134. if (model.hf_file.empty()) {
  1135. if (model.path.empty()) {
  1136. auto auto_detected = common_get_hf_file(model.hf_repo, bearer_token, offline);
  1137. if (auto_detected.repo.empty() || auto_detected.ggufFile.empty()) {
  1138. exit(1); // built without CURL, error message already printed
  1139. }
  1140. model.hf_repo = auto_detected.repo;
  1141. model.hf_file = auto_detected.ggufFile;
  1142. if (!auto_detected.mmprojFile.empty()) {
  1143. result.found_mmproj = true;
  1144. result.mmproj.hf_repo = model.hf_repo;
  1145. result.mmproj.hf_file = auto_detected.mmprojFile;
  1146. }
  1147. } else {
  1148. model.hf_file = model.path;
  1149. }
  1150. }
  1151. std::string model_endpoint = get_model_endpoint();
  1152. model.url = model_endpoint + model.hf_repo + "/resolve/main/" + model.hf_file;
  1153. // make sure model path is present (for caching purposes)
  1154. if (model.path.empty()) {
  1155. // this is to avoid different repo having same file name, or same file name in different subdirs
  1156. std::string filename = model.hf_repo + "_" + model.hf_file;
  1157. // to make sure we don't have any slashes in the filename
  1158. string_replace_all(filename, "/", "_");
  1159. model.path = fs_get_cache_file(filename);
  1160. }
  1161. } else if (!model.url.empty()) {
  1162. if (model.path.empty()) {
  1163. auto f = string_split<std::string>(model.url, '#').front();
  1164. f = string_split<std::string>(f, '?').front();
  1165. model.path = fs_get_cache_file(string_split<std::string>(f, '/').back());
  1166. }
  1167. } else if (model.path.empty()) {
  1168. model.path = model_path_default;
  1169. }
  1170. }
  1171. // then, download it if needed
  1172. if (!model.url.empty()) {
  1173. bool ok = common_download_model(model, bearer_token, offline);
  1174. if (!ok) {
  1175. LOG_ERR("error: failed to download model from %s\n", model.url.c_str());
  1176. exit(1);
  1177. }
  1178. }
  1179. return result;
  1180. }
  1181. const std::vector<ggml_type> kv_cache_types = {
  1182. GGML_TYPE_F32,
  1183. GGML_TYPE_F16,
  1184. GGML_TYPE_BF16,
  1185. GGML_TYPE_Q8_0,
  1186. GGML_TYPE_Q4_0,
  1187. GGML_TYPE_Q4_1,
  1188. GGML_TYPE_IQ4_NL,
  1189. GGML_TYPE_Q5_0,
  1190. GGML_TYPE_Q5_1,
  1191. };
  1192. static ggml_type kv_cache_type_from_str(const std::string & s) {
  1193. for (const auto & type : kv_cache_types) {
  1194. if (ggml_type_name(type) == s) {
  1195. return type;
  1196. }
  1197. }
  1198. throw std::runtime_error("Unsupported cache type: " + s);
  1199. }
  1200. static std::string get_all_kv_cache_types() {
  1201. std::ostringstream msg;
  1202. for (const auto & type : kv_cache_types) {
  1203. msg << ggml_type_name(type) << (&type == &kv_cache_types.back() ? "" : ", ");
  1204. }
  1205. return msg.str();
  1206. }
  1207. //
  1208. // CLI argument parsing functions
  1209. //
  1210. static bool common_params_parse_ex(int argc, char ** argv, common_params_context & ctx_arg) {
  1211. common_params & params = ctx_arg.params;
  1212. std::unordered_map<std::string, common_arg *> arg_to_options;
  1213. for (auto & opt : ctx_arg.options) {
  1214. for (const auto & arg : opt.args) {
  1215. arg_to_options[arg] = &opt;
  1216. }
  1217. }
  1218. // handle environment variables
  1219. for (auto & opt : ctx_arg.options) {
  1220. std::string value;
  1221. if (opt.get_value_from_env(value)) {
  1222. try {
  1223. if (opt.handler_void && (value == "1" || value == "true")) {
  1224. opt.handler_void(params);
  1225. }
  1226. if (opt.handler_int) {
  1227. opt.handler_int(params, std::stoi(value));
  1228. }
  1229. if (opt.handler_string) {
  1230. opt.handler_string(params, value);
  1231. continue;
  1232. }
  1233. } catch (std::exception & e) {
  1234. throw std::invalid_argument(string_format(
  1235. "error while handling environment variable \"%s\": %s\n\n", opt.env, e.what()));
  1236. }
  1237. }
  1238. }
  1239. // handle command line arguments
  1240. auto check_arg = [&](int i) {
  1241. if (i+1 >= argc) {
  1242. throw std::invalid_argument("expected value for argument");
  1243. }
  1244. };
  1245. for (int i = 1; i < argc; i++) {
  1246. const std::string arg_prefix = "--";
  1247. std::string arg = argv[i];
  1248. if (arg.compare(0, arg_prefix.size(), arg_prefix) == 0) {
  1249. std::replace(arg.begin(), arg.end(), '_', '-');
  1250. }
  1251. if (arg_to_options.find(arg) == arg_to_options.end()) {
  1252. throw std::invalid_argument(string_format("error: invalid argument: %s", arg.c_str()));
  1253. }
  1254. auto opt = *arg_to_options[arg];
  1255. if (opt.has_value_from_env()) {
  1256. fprintf(stderr, "warn: %s environment variable is set, but will be overwritten by command line argument %s\n", opt.env, arg.c_str());
  1257. }
  1258. try {
  1259. if (opt.handler_void) {
  1260. opt.handler_void(params);
  1261. continue;
  1262. }
  1263. // arg with single value
  1264. check_arg(i);
  1265. std::string val = argv[++i];
  1266. if (opt.handler_int) {
  1267. opt.handler_int(params, std::stoi(val));
  1268. continue;
  1269. }
  1270. if (opt.handler_string) {
  1271. opt.handler_string(params, val);
  1272. continue;
  1273. }
  1274. // arg with 2 values
  1275. check_arg(i);
  1276. std::string val2 = argv[++i];
  1277. if (opt.handler_str_str) {
  1278. opt.handler_str_str(params, val, val2);
  1279. continue;
  1280. }
  1281. } catch (std::exception & e) {
  1282. throw std::invalid_argument(string_format(
  1283. "error while handling argument \"%s\": %s\n\n"
  1284. "usage:\n%s\n\nto show complete usage, run with -h",
  1285. arg.c_str(), e.what(), arg_to_options[arg]->to_string().c_str()));
  1286. }
  1287. }
  1288. postprocess_cpu_params(params.cpuparams, nullptr);
  1289. postprocess_cpu_params(params.cpuparams_batch, &params.cpuparams);
  1290. postprocess_cpu_params(params.speculative.cpuparams, &params.cpuparams);
  1291. postprocess_cpu_params(params.speculative.cpuparams_batch, &params.cpuparams_batch);
  1292. if (params.prompt_cache_all && (params.interactive || params.interactive_first)) {
  1293. throw std::invalid_argument("error: --prompt-cache-all not supported in interactive mode yet\n");
  1294. }
  1295. // handle model and download
  1296. {
  1297. auto res = common_params_handle_model(params.model, params.hf_token, DEFAULT_MODEL_PATH, params.offline);
  1298. if (params.no_mmproj) {
  1299. params.mmproj = {};
  1300. } else if (res.found_mmproj && params.mmproj.path.empty() && params.mmproj.url.empty()) {
  1301. // optionally, handle mmproj model when -hf is specified
  1302. params.mmproj = res.mmproj;
  1303. }
  1304. // only download mmproj if the current example is using it
  1305. for (auto & ex : mmproj_examples) {
  1306. if (ctx_arg.ex == ex) {
  1307. common_params_handle_model(params.mmproj, params.hf_token, "", params.offline);
  1308. break;
  1309. }
  1310. }
  1311. common_params_handle_model(params.speculative.model, params.hf_token, "", params.offline);
  1312. common_params_handle_model(params.vocoder.model, params.hf_token, "", params.offline);
  1313. }
  1314. if (params.escape) {
  1315. string_process_escapes(params.prompt);
  1316. string_process_escapes(params.input_prefix);
  1317. string_process_escapes(params.input_suffix);
  1318. for (auto & antiprompt : params.antiprompt) {
  1319. string_process_escapes(antiprompt);
  1320. }
  1321. for (auto & seq_breaker : params.sampling.dry_sequence_breakers) {
  1322. string_process_escapes(seq_breaker);
  1323. }
  1324. for (auto & pair : params.speculative.replacements) {
  1325. string_process_escapes(pair.first);
  1326. string_process_escapes(pair.second);
  1327. }
  1328. }
  1329. if (!params.kv_overrides.empty()) {
  1330. params.kv_overrides.emplace_back();
  1331. params.kv_overrides.back().key[0] = 0;
  1332. }
  1333. if (!params.tensor_buft_overrides.empty()) {
  1334. params.tensor_buft_overrides.push_back({nullptr, nullptr});
  1335. }
  1336. if (!params.speculative.tensor_buft_overrides.empty()) {
  1337. params.speculative.tensor_buft_overrides.push_back({nullptr, nullptr});
  1338. }
  1339. if (!params.chat_template.empty() && !common_chat_verify_template(params.chat_template, params.use_jinja)) {
  1340. throw std::runtime_error(string_format(
  1341. "error: the supplied chat template is not supported: %s%s\n",
  1342. params.chat_template.c_str(),
  1343. params.use_jinja ? "" : "\nnote: llama.cpp was started without --jinja, we only support commonly used templates"
  1344. ));
  1345. }
  1346. return true;
  1347. }
  1348. static void common_params_print_usage(common_params_context & ctx_arg) {
  1349. auto print_options = [](std::vector<common_arg *> & options) {
  1350. for (common_arg * opt : options) {
  1351. printf("%s", opt->to_string().c_str());
  1352. }
  1353. };
  1354. std::vector<common_arg *> common_options;
  1355. std::vector<common_arg *> sparam_options;
  1356. std::vector<common_arg *> specific_options;
  1357. for (auto & opt : ctx_arg.options) {
  1358. // in case multiple LLAMA_EXAMPLE_* are set, we prioritize the LLAMA_EXAMPLE_* matching current example
  1359. if (opt.is_sparam) {
  1360. sparam_options.push_back(&opt);
  1361. } else if (opt.in_example(ctx_arg.ex)) {
  1362. specific_options.push_back(&opt);
  1363. } else {
  1364. common_options.push_back(&opt);
  1365. }
  1366. }
  1367. printf("----- common params -----\n\n");
  1368. print_options(common_options);
  1369. printf("\n\n----- sampling params -----\n\n");
  1370. print_options(sparam_options);
  1371. // TODO: maybe convert enum llama_example to string
  1372. printf("\n\n----- example-specific params -----\n\n");
  1373. print_options(specific_options);
  1374. }
  1375. static void common_params_print_completion(common_params_context & ctx_arg) {
  1376. std::vector<common_arg *> common_options;
  1377. std::vector<common_arg *> sparam_options;
  1378. std::vector<common_arg *> specific_options;
  1379. for (auto & opt : ctx_arg.options) {
  1380. if (opt.is_sparam) {
  1381. sparam_options.push_back(&opt);
  1382. } else if (opt.in_example(ctx_arg.ex)) {
  1383. specific_options.push_back(&opt);
  1384. } else {
  1385. common_options.push_back(&opt);
  1386. }
  1387. }
  1388. printf("_llama_completions() {\n");
  1389. printf(" local cur prev opts\n");
  1390. printf(" COMPREPLY=()\n");
  1391. printf(" cur=\"${COMP_WORDS[COMP_CWORD]}\"\n");
  1392. printf(" prev=\"${COMP_WORDS[COMP_CWORD-1]}\"\n\n");
  1393. printf(" opts=\"");
  1394. auto print_options = [](const std::vector<common_arg *> & options) {
  1395. for (const common_arg * opt : options) {
  1396. for (const char * arg : opt->args) {
  1397. printf("%s ", arg);
  1398. }
  1399. }
  1400. };
  1401. print_options(common_options);
  1402. print_options(sparam_options);
  1403. print_options(specific_options);
  1404. printf("\"\n\n");
  1405. printf(" case \"$prev\" in\n");
  1406. printf(" --model|-m)\n");
  1407. printf(" COMPREPLY=( $(compgen -f -X '!*.gguf' -- \"$cur\") $(compgen -d -- \"$cur\") )\n");
  1408. printf(" return 0\n");
  1409. printf(" ;;\n");
  1410. printf(" --grammar-file)\n");
  1411. printf(" COMPREPLY=( $(compgen -f -X '!*.gbnf' -- \"$cur\") $(compgen -d -- \"$cur\") )\n");
  1412. printf(" return 0\n");
  1413. printf(" ;;\n");
  1414. printf(" --chat-template-file)\n");
  1415. printf(" COMPREPLY=( $(compgen -f -X '!*.jinja' -- \"$cur\") $(compgen -d -- \"$cur\") )\n");
  1416. printf(" return 0\n");
  1417. printf(" ;;\n");
  1418. printf(" *)\n");
  1419. printf(" COMPREPLY=( $(compgen -W \"${opts}\" -- \"$cur\") )\n");
  1420. printf(" return 0\n");
  1421. printf(" ;;\n");
  1422. printf(" esac\n");
  1423. printf("}\n\n");
  1424. std::set<std::string> executables = {
  1425. "llama-batched",
  1426. "llama-batched-bench",
  1427. "llama-bench",
  1428. "llama-cli",
  1429. "llama-convert-llama2c-to-ggml",
  1430. "llama-cvector-generator",
  1431. "llama-embedding",
  1432. "llama-eval-callback",
  1433. "llama-export-lora",
  1434. "llama-gen-docs",
  1435. "llama-gguf",
  1436. "llama-gguf-hash",
  1437. "llama-gguf-split",
  1438. "llama-gritlm",
  1439. "llama-imatrix",
  1440. "llama-infill",
  1441. "llama-mtmd-cli",
  1442. "llama-llava-clip-quantize-cli",
  1443. "llama-lookahead",
  1444. "llama-lookup",
  1445. "llama-lookup-create",
  1446. "llama-lookup-merge",
  1447. "llama-lookup-stats",
  1448. "llama-parallel",
  1449. "llama-passkey",
  1450. "llama-perplexity",
  1451. "llama-q8dot",
  1452. "llama-quantize",
  1453. "llama-qwen2vl-cli",
  1454. "llama-retrieval",
  1455. "llama-run",
  1456. "llama-save-load-state",
  1457. "llama-server",
  1458. "llama-simple",
  1459. "llama-simple-chat",
  1460. "llama-speculative",
  1461. "llama-speculative-simple",
  1462. "llama-tokenize",
  1463. "llama-tts",
  1464. "llama-vdot"
  1465. };
  1466. for (const auto& exe : executables) {
  1467. printf("complete -F _llama_completions %s\n", exe.c_str());
  1468. }
  1469. }
  1470. static std::vector<ggml_backend_dev_t> parse_device_list(const std::string & value) {
  1471. std::vector<ggml_backend_dev_t> devices;
  1472. auto dev_names = string_split<std::string>(value, ',');
  1473. if (dev_names.empty()) {
  1474. throw std::invalid_argument("no devices specified");
  1475. }
  1476. if (dev_names.size() == 1 && dev_names[0] == "none") {
  1477. devices.push_back(nullptr);
  1478. } else {
  1479. for (const auto & device : dev_names) {
  1480. auto * dev = ggml_backend_dev_by_name(device.c_str());
  1481. if (!dev || ggml_backend_dev_type(dev) == GGML_BACKEND_DEVICE_TYPE_CPU) {
  1482. throw std::invalid_argument(string_format("invalid device: %s", device.c_str()));
  1483. }
  1484. devices.push_back(dev);
  1485. }
  1486. devices.push_back(nullptr);
  1487. }
  1488. return devices;
  1489. }
  1490. static void add_rpc_devices(const std::string & servers) {
  1491. auto rpc_servers = string_split<std::string>(servers, ',');
  1492. if (rpc_servers.empty()) {
  1493. throw std::invalid_argument("no RPC servers specified");
  1494. }
  1495. ggml_backend_reg_t rpc_reg = ggml_backend_reg_by_name("RPC");
  1496. if (!rpc_reg) {
  1497. throw std::invalid_argument("failed to find RPC backend");
  1498. }
  1499. typedef ggml_backend_dev_t (*ggml_backend_rpc_add_device_t)(const char * endpoint);
  1500. ggml_backend_rpc_add_device_t ggml_backend_rpc_add_device_fn = (ggml_backend_rpc_add_device_t) ggml_backend_reg_get_proc_address(rpc_reg, "ggml_backend_rpc_add_device");
  1501. if (!ggml_backend_rpc_add_device_fn) {
  1502. throw std::invalid_argument("failed to find RPC device add function");
  1503. }
  1504. for (const auto & server : rpc_servers) {
  1505. ggml_backend_dev_t dev = ggml_backend_rpc_add_device_fn(server.c_str());
  1506. if (dev) {
  1507. ggml_backend_device_register(dev);
  1508. } else {
  1509. throw std::invalid_argument("failed to register RPC device");
  1510. }
  1511. }
  1512. }
  1513. bool common_params_parse(int argc, char ** argv, common_params & params, llama_example ex, void(*print_usage)(int, char **)) {
  1514. auto ctx_arg = common_params_parser_init(params, ex, print_usage);
  1515. const common_params params_org = ctx_arg.params; // the example can modify the default params
  1516. try {
  1517. if (!common_params_parse_ex(argc, argv, ctx_arg)) {
  1518. ctx_arg.params = params_org;
  1519. return false;
  1520. }
  1521. if (ctx_arg.params.usage) {
  1522. common_params_print_usage(ctx_arg);
  1523. if (ctx_arg.print_usage) {
  1524. ctx_arg.print_usage(argc, argv);
  1525. }
  1526. exit(0);
  1527. }
  1528. if (ctx_arg.params.completion) {
  1529. common_params_print_completion(ctx_arg);
  1530. exit(0);
  1531. }
  1532. params.lr.init();
  1533. } catch (const std::invalid_argument & ex) {
  1534. fprintf(stderr, "%s\n", ex.what());
  1535. ctx_arg.params = params_org;
  1536. return false;
  1537. } catch (std::exception & ex) {
  1538. fprintf(stderr, "%s\n", ex.what());
  1539. exit(1); // for other exceptions, we exit with status code 1
  1540. }
  1541. return true;
  1542. }
  1543. static std::string list_builtin_chat_templates() {
  1544. std::vector<const char *> supported_tmpl;
  1545. int32_t res = llama_chat_builtin_templates(nullptr, 0);
  1546. supported_tmpl.resize(res);
  1547. res = llama_chat_builtin_templates(supported_tmpl.data(), supported_tmpl.size());
  1548. std::ostringstream msg;
  1549. for (auto & tmpl : supported_tmpl) {
  1550. msg << tmpl << (&tmpl == &supported_tmpl.back() ? "" : ", ");
  1551. }
  1552. return msg.str();
  1553. }
  1554. static bool is_truthy(const std::string & value) {
  1555. return value == "on" || value == "enabled" || value == "1";
  1556. }
  1557. static bool is_falsey(const std::string & value) {
  1558. return value == "off" || value == "disabled" || value == "0";
  1559. }
  1560. static bool is_autoy(const std::string & value) {
  1561. return value == "auto" || value == "-1";
  1562. }
  1563. common_params_context common_params_parser_init(common_params & params, llama_example ex, void(*print_usage)(int, char **)) {
  1564. // load dynamic backends
  1565. ggml_backend_load_all();
  1566. common_params_context ctx_arg(params);
  1567. ctx_arg.print_usage = print_usage;
  1568. ctx_arg.ex = ex;
  1569. std::string sampler_type_chars;
  1570. std::string sampler_type_names;
  1571. for (const auto & sampler : params.sampling.samplers) {
  1572. sampler_type_chars += common_sampler_type_to_chr(sampler);
  1573. sampler_type_names += common_sampler_type_to_str(sampler) + ";";
  1574. }
  1575. sampler_type_names.pop_back();
  1576. /**
  1577. * filter options by example
  1578. * rules:
  1579. * - all examples inherit options from LLAMA_EXAMPLE_COMMON
  1580. * - if LLAMA_EXAMPLE_* is set (other than COMMON), we only show the option in the corresponding example
  1581. * - if both {LLAMA_EXAMPLE_COMMON, LLAMA_EXAMPLE_*,} are set, we will prioritize the LLAMA_EXAMPLE_* matching current example
  1582. */
  1583. auto add_opt = [&](common_arg arg) {
  1584. if ((arg.in_example(ex) || arg.in_example(LLAMA_EXAMPLE_COMMON)) && !arg.is_exclude(ex)) {
  1585. ctx_arg.options.push_back(std::move(arg));
  1586. }
  1587. };
  1588. add_opt(common_arg(
  1589. {"-h", "--help", "--usage"},
  1590. "print usage and exit",
  1591. [](common_params & params) {
  1592. params.usage = true;
  1593. }
  1594. ));
  1595. add_opt(common_arg(
  1596. {"--version"},
  1597. "show version and build info",
  1598. [](common_params &) {
  1599. fprintf(stderr, "version: %d (%s)\n", LLAMA_BUILD_NUMBER, LLAMA_COMMIT);
  1600. fprintf(stderr, "built with %s for %s\n", LLAMA_COMPILER, LLAMA_BUILD_TARGET);
  1601. exit(0);
  1602. }
  1603. ));
  1604. add_opt(common_arg(
  1605. {"--completion-bash"},
  1606. "print source-able bash completion script for llama.cpp",
  1607. [](common_params & params) {
  1608. params.completion = true;
  1609. }
  1610. ));
  1611. add_opt(common_arg(
  1612. {"--verbose-prompt"},
  1613. string_format("print a verbose prompt before generation (default: %s)", params.verbose_prompt ? "true" : "false"),
  1614. [](common_params & params) {
  1615. params.verbose_prompt = true;
  1616. }
  1617. ));
  1618. add_opt(common_arg(
  1619. {"--no-display-prompt"},
  1620. string_format("don't print prompt at generation (default: %s)", !params.display_prompt ? "true" : "false"),
  1621. [](common_params & params) {
  1622. params.display_prompt = false;
  1623. }
  1624. ).set_examples({LLAMA_EXAMPLE_MAIN}));
  1625. add_opt(common_arg(
  1626. {"-co", "--color"},
  1627. string_format("colorise output to distinguish prompt and user input from generations (default: %s)", params.use_color ? "true" : "false"),
  1628. [](common_params & params) {
  1629. params.use_color = true;
  1630. }
  1631. ).set_examples({LLAMA_EXAMPLE_MAIN, LLAMA_EXAMPLE_SPECULATIVE, LLAMA_EXAMPLE_LOOKUP}));
  1632. add_opt(common_arg(
  1633. {"-t", "--threads"}, "N",
  1634. string_format("number of threads to use during generation (default: %d)", params.cpuparams.n_threads),
  1635. [](common_params & params, int value) {
  1636. params.cpuparams.n_threads = value;
  1637. if (params.cpuparams.n_threads <= 0) {
  1638. params.cpuparams.n_threads = std::thread::hardware_concurrency();
  1639. }
  1640. }
  1641. ).set_env("LLAMA_ARG_THREADS"));
  1642. add_opt(common_arg(
  1643. {"-tb", "--threads-batch"}, "N",
  1644. "number of threads to use during batch and prompt processing (default: same as --threads)",
  1645. [](common_params & params, int value) {
  1646. params.cpuparams_batch.n_threads = value;
  1647. if (params.cpuparams_batch.n_threads <= 0) {
  1648. params.cpuparams_batch.n_threads = std::thread::hardware_concurrency();
  1649. }
  1650. }
  1651. ));
  1652. add_opt(common_arg(
  1653. {"-C", "--cpu-mask"}, "M",
  1654. "CPU affinity mask: arbitrarily long hex. Complements cpu-range (default: \"\")",
  1655. [](common_params & params, const std::string & mask) {
  1656. params.cpuparams.mask_valid = true;
  1657. if (!parse_cpu_mask(mask, params.cpuparams.cpumask)) {
  1658. throw std::invalid_argument("invalid cpumask");
  1659. }
  1660. }
  1661. ));
  1662. add_opt(common_arg(
  1663. {"-Cr", "--cpu-range"}, "lo-hi",
  1664. "range of CPUs for affinity. Complements --cpu-mask",
  1665. [](common_params & params, const std::string & range) {
  1666. params.cpuparams.mask_valid = true;
  1667. if (!parse_cpu_range(range, params.cpuparams.cpumask)) {
  1668. throw std::invalid_argument("invalid range");
  1669. }
  1670. }
  1671. ));
  1672. add_opt(common_arg(
  1673. {"--cpu-strict"}, "<0|1>",
  1674. string_format("use strict CPU placement (default: %u)\n", (unsigned) params.cpuparams.strict_cpu),
  1675. [](common_params & params, const std::string & value) {
  1676. params.cpuparams.strict_cpu = std::stoul(value);
  1677. }
  1678. ));
  1679. add_opt(common_arg(
  1680. {"--prio"}, "N",
  1681. string_format("set process/thread priority : low(-1), normal(0), medium(1), high(2), realtime(3) (default: %d)\n", params.cpuparams.priority),
  1682. [](common_params & params, int prio) {
  1683. if (prio < GGML_SCHED_PRIO_LOW || prio > GGML_SCHED_PRIO_REALTIME) {
  1684. throw std::invalid_argument("invalid value");
  1685. }
  1686. params.cpuparams.priority = (enum ggml_sched_priority) prio;
  1687. }
  1688. ));
  1689. add_opt(common_arg(
  1690. {"--poll"}, "<0...100>",
  1691. string_format("use polling level to wait for work (0 - no polling, default: %u)\n", (unsigned) params.cpuparams.poll),
  1692. [](common_params & params, const std::string & value) {
  1693. params.cpuparams.poll = std::stoul(value);
  1694. }
  1695. ));
  1696. add_opt(common_arg(
  1697. {"-Cb", "--cpu-mask-batch"}, "M",
  1698. "CPU affinity mask: arbitrarily long hex. Complements cpu-range-batch (default: same as --cpu-mask)",
  1699. [](common_params & params, const std::string & mask) {
  1700. params.cpuparams_batch.mask_valid = true;
  1701. if (!parse_cpu_mask(mask, params.cpuparams_batch.cpumask)) {
  1702. throw std::invalid_argument("invalid cpumask");
  1703. }
  1704. }
  1705. ));
  1706. add_opt(common_arg(
  1707. {"-Crb", "--cpu-range-batch"}, "lo-hi",
  1708. "ranges of CPUs for affinity. Complements --cpu-mask-batch",
  1709. [](common_params & params, const std::string & range) {
  1710. params.cpuparams_batch.mask_valid = true;
  1711. if (!parse_cpu_range(range, params.cpuparams_batch.cpumask)) {
  1712. throw std::invalid_argument("invalid range");
  1713. }
  1714. }
  1715. ));
  1716. add_opt(common_arg(
  1717. {"--cpu-strict-batch"}, "<0|1>",
  1718. "use strict CPU placement (default: same as --cpu-strict)",
  1719. [](common_params & params, int value) {
  1720. params.cpuparams_batch.strict_cpu = value;
  1721. }
  1722. ));
  1723. add_opt(common_arg(
  1724. {"--prio-batch"}, "N",
  1725. string_format("set process/thread priority : 0-normal, 1-medium, 2-high, 3-realtime (default: %d)\n", params.cpuparams_batch.priority),
  1726. [](common_params & params, int prio) {
  1727. if (prio < 0 || prio > 3) {
  1728. throw std::invalid_argument("invalid value");
  1729. }
  1730. params.cpuparams_batch.priority = (enum ggml_sched_priority) prio;
  1731. }
  1732. ));
  1733. add_opt(common_arg(
  1734. {"--poll-batch"}, "<0|1>",
  1735. "use polling to wait for work (default: same as --poll)",
  1736. [](common_params & params, int value) {
  1737. params.cpuparams_batch.poll = value;
  1738. }
  1739. ));
  1740. add_opt(common_arg(
  1741. {"-lcs", "--lookup-cache-static"}, "FNAME",
  1742. "path to static lookup cache to use for lookup decoding (not updated by generation)",
  1743. [](common_params & params, const std::string & value) {
  1744. params.lookup_cache_static = value;
  1745. }
  1746. ).set_examples({LLAMA_EXAMPLE_LOOKUP}));
  1747. add_opt(common_arg(
  1748. {"-lcd", "--lookup-cache-dynamic"}, "FNAME",
  1749. "path to dynamic lookup cache to use for lookup decoding (updated by generation)",
  1750. [](common_params & params, const std::string & value) {
  1751. params.lookup_cache_dynamic = value;
  1752. }
  1753. ).set_examples({LLAMA_EXAMPLE_LOOKUP}));
  1754. add_opt(common_arg(
  1755. {"-c", "--ctx-size"}, "N",
  1756. string_format("size of the prompt context (default: %d, 0 = loaded from model)", params.n_ctx),
  1757. [](common_params & params, int value) {
  1758. params.n_ctx = value;
  1759. }
  1760. ).set_env("LLAMA_ARG_CTX_SIZE"));
  1761. add_opt(common_arg(
  1762. {"-n", "--predict", "--n-predict"}, "N",
  1763. string_format(
  1764. ex == LLAMA_EXAMPLE_MAIN
  1765. ? "number of tokens to predict (default: %d, -1 = infinity, -2 = until context filled)"
  1766. : "number of tokens to predict (default: %d, -1 = infinity)",
  1767. params.n_predict),
  1768. [](common_params & params, int value) {
  1769. params.n_predict = value;
  1770. }
  1771. ).set_env("LLAMA_ARG_N_PREDICT"));
  1772. add_opt(common_arg(
  1773. {"-b", "--batch-size"}, "N",
  1774. string_format("logical maximum batch size (default: %d)", params.n_batch),
  1775. [](common_params & params, int value) {
  1776. params.n_batch = value;
  1777. }
  1778. ).set_env("LLAMA_ARG_BATCH"));
  1779. add_opt(common_arg(
  1780. {"-ub", "--ubatch-size"}, "N",
  1781. string_format("physical maximum batch size (default: %d)", params.n_ubatch),
  1782. [](common_params & params, int value) {
  1783. params.n_ubatch = value;
  1784. }
  1785. ).set_env("LLAMA_ARG_UBATCH"));
  1786. add_opt(common_arg(
  1787. {"--keep"}, "N",
  1788. string_format("number of tokens to keep from the initial prompt (default: %d, -1 = all)", params.n_keep),
  1789. [](common_params & params, int value) {
  1790. params.n_keep = value;
  1791. }
  1792. ));
  1793. add_opt(common_arg(
  1794. {"--swa-full"},
  1795. string_format("use full-size SWA cache (default: %s)\n"
  1796. "[(more info)](https://github.com/ggml-org/llama.cpp/pull/13194#issuecomment-2868343055)", params.swa_full ? "true" : "false"),
  1797. [](common_params & params) {
  1798. params.swa_full = true;
  1799. }
  1800. ).set_env("LLAMA_ARG_SWA_FULL"));
  1801. add_opt(common_arg(
  1802. {"--swa-checkpoints"}, "N",
  1803. string_format("max number of SWA checkpoints per slot to create (default: %d)\n"
  1804. "[(more info)](https://github.com/ggml-org/llama.cpp/pull/15293)", params.n_swa_checkpoints),
  1805. [](common_params & params, int value) {
  1806. params.n_swa_checkpoints = value;
  1807. }
  1808. ).set_env("LLAMA_ARG_SWA_CHECKPOINTS").set_examples({LLAMA_EXAMPLE_SERVER}));
  1809. add_opt(common_arg(
  1810. {"--kv-unified", "-kvu"},
  1811. string_format("use single unified KV buffer for the KV cache of all sequences (default: %s)\n"
  1812. "[(more info)](https://github.com/ggml-org/llama.cpp/pull/14363)", params.kv_unified ? "true" : "false"),
  1813. [](common_params & params) {
  1814. params.kv_unified = true;
  1815. }
  1816. ).set_env("LLAMA_ARG_KV_SPLIT"));
  1817. add_opt(common_arg(
  1818. {"--no-context-shift"},
  1819. string_format("disables context shift on infinite text generation (default: %s)", params.ctx_shift ? "disabled" : "enabled"),
  1820. [](common_params & params) {
  1821. params.ctx_shift = false;
  1822. }
  1823. ).set_examples({LLAMA_EXAMPLE_MAIN, LLAMA_EXAMPLE_SERVER, LLAMA_EXAMPLE_IMATRIX, LLAMA_EXAMPLE_PERPLEXITY}).set_env("LLAMA_ARG_NO_CONTEXT_SHIFT"));
  1824. add_opt(common_arg(
  1825. {"--context-shift"},
  1826. string_format("enables context shift on infinite text generation (default: %s)", params.ctx_shift ? "enabled" : "disabled"),
  1827. [](common_params & params) {
  1828. params.ctx_shift = true;
  1829. }
  1830. ).set_examples({LLAMA_EXAMPLE_MAIN, LLAMA_EXAMPLE_SERVER, LLAMA_EXAMPLE_IMATRIX, LLAMA_EXAMPLE_PERPLEXITY}).set_env("LLAMA_ARG_CONTEXT_SHIFT"));
  1831. add_opt(common_arg(
  1832. {"--chunks"}, "N",
  1833. string_format("max number of chunks to process (default: %d, -1 = all)", params.n_chunks),
  1834. [](common_params & params, int value) {
  1835. params.n_chunks = value;
  1836. }
  1837. ).set_examples({LLAMA_EXAMPLE_IMATRIX, LLAMA_EXAMPLE_PERPLEXITY, LLAMA_EXAMPLE_RETRIEVAL}));
  1838. add_opt(common_arg({ "-fa", "--flash-attn" }, "[on|off|auto]",
  1839. string_format("set Flash Attention use ('on', 'off', or 'auto', default: '%s')",
  1840. llama_flash_attn_type_name(params.flash_attn_type)),
  1841. [](common_params & params, const std::string & value) {
  1842. if (is_truthy(value)) {
  1843. params.flash_attn_type = LLAMA_FLASH_ATTN_TYPE_ENABLED;
  1844. } else if (is_falsey(value)) {
  1845. params.flash_attn_type = LLAMA_FLASH_ATTN_TYPE_DISABLED;
  1846. } else if (is_autoy(value)) {
  1847. params.flash_attn_type = LLAMA_FLASH_ATTN_TYPE_AUTO;
  1848. } else {
  1849. throw std::runtime_error(
  1850. string_format("error: unkown value for --flash-attn: '%s'\n", value.c_str()));
  1851. }
  1852. }).set_env("LLAMA_ARG_FLASH_ATTN"));
  1853. add_opt(common_arg(
  1854. {"-p", "--prompt"}, "PROMPT",
  1855. "prompt to start generation with; for system message, use -sys",
  1856. [](common_params & params, const std::string & value) {
  1857. params.prompt = value;
  1858. }
  1859. ).set_excludes({LLAMA_EXAMPLE_SERVER}));
  1860. add_opt(common_arg(
  1861. {"-sys", "--system-prompt"}, "PROMPT",
  1862. "system prompt to use with model (if applicable, depending on chat template)",
  1863. [](common_params & params, const std::string & value) {
  1864. params.system_prompt = value;
  1865. }
  1866. ).set_examples({LLAMA_EXAMPLE_MAIN, LLAMA_EXAMPLE_DIFFUSION}));
  1867. add_opt(common_arg(
  1868. {"--no-perf"},
  1869. string_format("disable internal libllama performance timings (default: %s)", params.no_perf ? "true" : "false"),
  1870. [](common_params & params) {
  1871. params.no_perf = true;
  1872. params.sampling.no_perf = true;
  1873. }
  1874. ).set_env("LLAMA_ARG_NO_PERF"));
  1875. add_opt(common_arg(
  1876. {"-f", "--file"}, "FNAME",
  1877. "a file containing the prompt (default: none)",
  1878. [](common_params & params, const std::string & value) {
  1879. params.prompt = read_file(value);
  1880. // store the external file name in params
  1881. params.prompt_file = value;
  1882. if (!params.prompt.empty() && params.prompt.back() == '\n') {
  1883. params.prompt.pop_back();
  1884. }
  1885. }
  1886. ).set_excludes({LLAMA_EXAMPLE_SERVER}));
  1887. add_opt(common_arg(
  1888. {"-sysf", "--system-prompt-file"}, "FNAME",
  1889. "a file containing the system prompt (default: none)",
  1890. [](common_params & params, const std::string & value) {
  1891. params.system_prompt = read_file(value);
  1892. if (!params.system_prompt.empty() && params.system_prompt.back() == '\n') {
  1893. params.system_prompt.pop_back();
  1894. }
  1895. }
  1896. ).set_examples({LLAMA_EXAMPLE_MAIN}));
  1897. add_opt(common_arg(
  1898. {"--in-file"}, "FNAME",
  1899. "an input file (repeat to specify multiple files)",
  1900. [](common_params & params, const std::string & value) {
  1901. std::ifstream file(value);
  1902. if (!file) {
  1903. throw std::runtime_error(string_format("error: failed to open file '%s'\n", value.c_str()));
  1904. }
  1905. params.in_files.push_back(value);
  1906. }
  1907. ).set_examples({LLAMA_EXAMPLE_IMATRIX}));
  1908. add_opt(common_arg(
  1909. {"-bf", "--binary-file"}, "FNAME",
  1910. "binary file containing the prompt (default: none)",
  1911. [](common_params & params, const std::string & value) {
  1912. std::ifstream file(value, std::ios::binary);
  1913. if (!file) {
  1914. throw std::runtime_error(string_format("error: failed to open file '%s'\n", value.c_str()));
  1915. }
  1916. // store the external file name in params
  1917. params.prompt_file = value;
  1918. std::ostringstream ss;
  1919. ss << file.rdbuf();
  1920. params.prompt = ss.str();
  1921. fprintf(stderr, "Read %zu bytes from binary file %s\n", params.prompt.size(), value.c_str());
  1922. }
  1923. ).set_excludes({LLAMA_EXAMPLE_SERVER}));
  1924. add_opt(common_arg(
  1925. {"-e", "--escape"},
  1926. string_format("process escapes sequences (\\n, \\r, \\t, \\', \\\", \\\\) (default: %s)", params.escape ? "true" : "false"),
  1927. [](common_params & params) {
  1928. params.escape = true;
  1929. }
  1930. ));
  1931. add_opt(common_arg(
  1932. {"--no-escape"},
  1933. "do not process escape sequences",
  1934. [](common_params & params) {
  1935. params.escape = false;
  1936. }
  1937. ));
  1938. add_opt(common_arg(
  1939. {"-ptc", "--print-token-count"}, "N",
  1940. string_format("print token count every N tokens (default: %d)", params.n_print),
  1941. [](common_params & params, int value) {
  1942. params.n_print = value;
  1943. }
  1944. ).set_examples({LLAMA_EXAMPLE_MAIN}));
  1945. add_opt(common_arg(
  1946. {"--prompt-cache"}, "FNAME",
  1947. "file to cache prompt state for faster startup (default: none)",
  1948. [](common_params & params, const std::string & value) {
  1949. params.path_prompt_cache = value;
  1950. }
  1951. ).set_examples({LLAMA_EXAMPLE_MAIN}));
  1952. add_opt(common_arg(
  1953. {"--prompt-cache-all"},
  1954. "if specified, saves user input and generations to cache as well\n",
  1955. [](common_params & params) {
  1956. params.prompt_cache_all = true;
  1957. }
  1958. ).set_examples({LLAMA_EXAMPLE_MAIN}));
  1959. add_opt(common_arg(
  1960. {"--prompt-cache-ro"},
  1961. "if specified, uses the prompt cache but does not update it",
  1962. [](common_params & params) {
  1963. params.prompt_cache_ro = true;
  1964. }
  1965. ).set_examples({LLAMA_EXAMPLE_MAIN}));
  1966. add_opt(common_arg(
  1967. {"-r", "--reverse-prompt"}, "PROMPT",
  1968. "halt generation at PROMPT, return control in interactive mode\n",
  1969. [](common_params & params, const std::string & value) {
  1970. params.antiprompt.emplace_back(value);
  1971. }
  1972. ).set_examples({LLAMA_EXAMPLE_MAIN, LLAMA_EXAMPLE_SERVER}));
  1973. add_opt(common_arg(
  1974. {"-sp", "--special"},
  1975. string_format("special tokens output enabled (default: %s)", params.special ? "true" : "false"),
  1976. [](common_params & params) {
  1977. params.special = true;
  1978. }
  1979. ).set_examples({LLAMA_EXAMPLE_MAIN, LLAMA_EXAMPLE_SERVER}));
  1980. add_opt(common_arg(
  1981. {"-cnv", "--conversation"},
  1982. "run in conversation mode:\n"
  1983. "- does not print special tokens and suffix/prefix\n"
  1984. "- interactive mode is also enabled\n"
  1985. "(default: auto enabled if chat template is available)",
  1986. [](common_params & params) {
  1987. params.conversation_mode = COMMON_CONVERSATION_MODE_ENABLED;
  1988. }
  1989. ).set_examples({LLAMA_EXAMPLE_MAIN}));
  1990. add_opt(common_arg(
  1991. {"-no-cnv", "--no-conversation"},
  1992. "force disable conversation mode (default: false)",
  1993. [](common_params & params) {
  1994. params.conversation_mode = COMMON_CONVERSATION_MODE_DISABLED;
  1995. }
  1996. ).set_examples({LLAMA_EXAMPLE_MAIN}));
  1997. add_opt(common_arg(
  1998. {"-st", "--single-turn"},
  1999. "run conversation for a single turn only, then exit when done\n"
  2000. "will not be interactive if first turn is predefined with --prompt\n"
  2001. "(default: false)",
  2002. [](common_params & params) {
  2003. params.single_turn = true;
  2004. }
  2005. ).set_examples({LLAMA_EXAMPLE_MAIN}));
  2006. add_opt(common_arg(
  2007. {"-i", "--interactive"},
  2008. string_format("run in interactive mode (default: %s)", params.interactive ? "true" : "false"),
  2009. [](common_params & params) {
  2010. params.interactive = true;
  2011. }
  2012. ).set_examples({LLAMA_EXAMPLE_MAIN}));
  2013. add_opt(common_arg(
  2014. {"-if", "--interactive-first"},
  2015. string_format("run in interactive mode and wait for input right away (default: %s)", params.interactive_first ? "true" : "false"),
  2016. [](common_params & params) {
  2017. params.interactive_first = true;
  2018. }
  2019. ).set_examples({LLAMA_EXAMPLE_MAIN}));
  2020. add_opt(common_arg(
  2021. {"-mli", "--multiline-input"},
  2022. "allows you to write or paste multiple lines without ending each in '\\'",
  2023. [](common_params & params) {
  2024. params.multiline_input = true;
  2025. }
  2026. ).set_examples({LLAMA_EXAMPLE_MAIN}));
  2027. add_opt(common_arg(
  2028. {"--in-prefix-bos"},
  2029. "prefix BOS to user inputs, preceding the `--in-prefix` string",
  2030. [](common_params & params) {
  2031. params.input_prefix_bos = true;
  2032. params.enable_chat_template = false;
  2033. }
  2034. ).set_examples({LLAMA_EXAMPLE_MAIN}));
  2035. add_opt(common_arg(
  2036. {"--in-prefix"}, "STRING",
  2037. "string to prefix user inputs with (default: empty)",
  2038. [](common_params & params, const std::string & value) {
  2039. params.input_prefix = value;
  2040. params.enable_chat_template = false;
  2041. }
  2042. ).set_examples({LLAMA_EXAMPLE_MAIN}));
  2043. add_opt(common_arg(
  2044. {"--in-suffix"}, "STRING",
  2045. "string to suffix after user inputs with (default: empty)",
  2046. [](common_params & params, const std::string & value) {
  2047. params.input_suffix = value;
  2048. params.enable_chat_template = false;
  2049. }
  2050. ).set_examples({LLAMA_EXAMPLE_MAIN}));
  2051. add_opt(common_arg(
  2052. {"--no-warmup"},
  2053. "skip warming up the model with an empty run",
  2054. [](common_params & params) {
  2055. params.warmup = false;
  2056. }
  2057. ).set_examples({LLAMA_EXAMPLE_MAIN, LLAMA_EXAMPLE_SERVER, LLAMA_EXAMPLE_EMBEDDING, LLAMA_EXAMPLE_RETRIEVAL, LLAMA_EXAMPLE_PERPLEXITY}));
  2058. add_opt(common_arg(
  2059. {"--spm-infill"},
  2060. string_format(
  2061. "use Suffix/Prefix/Middle pattern for infill (instead of Prefix/Suffix/Middle) as some models prefer this. (default: %s)",
  2062. params.spm_infill ? "enabled" : "disabled"
  2063. ),
  2064. [](common_params & params) {
  2065. params.spm_infill = true;
  2066. }
  2067. ).set_examples({LLAMA_EXAMPLE_SERVER}));
  2068. add_opt(common_arg(
  2069. {"--samplers"}, "SAMPLERS",
  2070. string_format("samplers that will be used for generation in the order, separated by \';\'\n(default: %s)", sampler_type_names.c_str()),
  2071. [](common_params & params, const std::string & value) {
  2072. const auto sampler_names = string_split<std::string>(value, ';');
  2073. params.sampling.samplers = common_sampler_types_from_names(sampler_names, true);
  2074. }
  2075. ).set_sparam());
  2076. add_opt(common_arg(
  2077. {"-s", "--seed"}, "SEED",
  2078. string_format("RNG seed (default: %d, use random seed for %d)", params.sampling.seed, LLAMA_DEFAULT_SEED),
  2079. [](common_params & params, const std::string & value) {
  2080. params.sampling.seed = std::stoul(value);
  2081. }
  2082. ).set_sparam());
  2083. add_opt(common_arg(
  2084. {"--sampling-seq", "--sampler-seq"}, "SEQUENCE",
  2085. string_format("simplified sequence for samplers that will be used (default: %s)", sampler_type_chars.c_str()),
  2086. [](common_params & params, const std::string & value) {
  2087. params.sampling.samplers = common_sampler_types_from_chars(value);
  2088. }
  2089. ).set_sparam());
  2090. add_opt(common_arg(
  2091. {"--ignore-eos"},
  2092. "ignore end of stream token and continue generating (implies --logit-bias EOS-inf)",
  2093. [](common_params & params) {
  2094. params.sampling.ignore_eos = true;
  2095. }
  2096. ).set_sparam());
  2097. add_opt(common_arg(
  2098. {"--temp"}, "N",
  2099. string_format("temperature (default: %.1f)", (double)params.sampling.temp),
  2100. [](common_params & params, const std::string & value) {
  2101. params.sampling.temp = std::stof(value);
  2102. params.sampling.temp = std::max(params.sampling.temp, 0.0f);
  2103. }
  2104. ).set_sparam());
  2105. add_opt(common_arg(
  2106. {"--top-k"}, "N",
  2107. string_format("top-k sampling (default: %d, 0 = disabled)", params.sampling.top_k),
  2108. [](common_params & params, int value) {
  2109. params.sampling.top_k = value;
  2110. }
  2111. ).set_sparam());
  2112. add_opt(common_arg(
  2113. {"--top-p"}, "N",
  2114. string_format("top-p sampling (default: %.1f, 1.0 = disabled)", (double)params.sampling.top_p),
  2115. [](common_params & params, const std::string & value) {
  2116. params.sampling.top_p = std::stof(value);
  2117. }
  2118. ).set_sparam());
  2119. add_opt(common_arg(
  2120. {"--min-p"}, "N",
  2121. string_format("min-p sampling (default: %.1f, 0.0 = disabled)", (double)params.sampling.min_p),
  2122. [](common_params & params, const std::string & value) {
  2123. params.sampling.min_p = std::stof(value);
  2124. }
  2125. ).set_sparam());
  2126. add_opt(common_arg(
  2127. {"--top-nsigma"}, "N",
  2128. string_format("top-n-sigma sampling (default: %.1f, -1.0 = disabled)", params.sampling.top_n_sigma),
  2129. [](common_params & params, const std::string & value) {
  2130. params.sampling.top_n_sigma = std::stof(value);
  2131. }
  2132. ).set_sparam());
  2133. add_opt(common_arg(
  2134. {"--xtc-probability"}, "N",
  2135. string_format("xtc probability (default: %.1f, 0.0 = disabled)", (double)params.sampling.xtc_probability),
  2136. [](common_params & params, const std::string & value) {
  2137. params.sampling.xtc_probability = std::stof(value);
  2138. }
  2139. ).set_sparam());
  2140. add_opt(common_arg(
  2141. {"--xtc-threshold"}, "N",
  2142. string_format("xtc threshold (default: %.1f, 1.0 = disabled)", (double)params.sampling.xtc_threshold),
  2143. [](common_params & params, const std::string & value) {
  2144. params.sampling.xtc_threshold = std::stof(value);
  2145. }
  2146. ).set_sparam());
  2147. add_opt(common_arg(
  2148. {"--typical"}, "N",
  2149. string_format("locally typical sampling, parameter p (default: %.1f, 1.0 = disabled)", (double)params.sampling.typ_p),
  2150. [](common_params & params, const std::string & value) {
  2151. params.sampling.typ_p = std::stof(value);
  2152. }
  2153. ).set_sparam());
  2154. add_opt(common_arg(
  2155. {"--repeat-last-n"}, "N",
  2156. string_format("last n tokens to consider for penalize (default: %d, 0 = disabled, -1 = ctx_size)", params.sampling.penalty_last_n),
  2157. [](common_params & params, int value) {
  2158. if (value < -1) {
  2159. throw std::runtime_error(string_format("error: invalid repeat-last-n = %d\n", value));
  2160. }
  2161. params.sampling.penalty_last_n = value;
  2162. params.sampling.n_prev = std::max(params.sampling.n_prev, params.sampling.penalty_last_n);
  2163. }
  2164. ).set_sparam());
  2165. add_opt(common_arg(
  2166. {"--repeat-penalty"}, "N",
  2167. string_format("penalize repeat sequence of tokens (default: %.1f, 1.0 = disabled)", (double)params.sampling.penalty_repeat),
  2168. [](common_params & params, const std::string & value) {
  2169. params.sampling.penalty_repeat = std::stof(value);
  2170. }
  2171. ).set_sparam());
  2172. add_opt(common_arg(
  2173. {"--presence-penalty"}, "N",
  2174. string_format("repeat alpha presence penalty (default: %.1f, 0.0 = disabled)", (double)params.sampling.penalty_present),
  2175. [](common_params & params, const std::string & value) {
  2176. params.sampling.penalty_present = std::stof(value);
  2177. }
  2178. ).set_sparam());
  2179. add_opt(common_arg(
  2180. {"--frequency-penalty"}, "N",
  2181. string_format("repeat alpha frequency penalty (default: %.1f, 0.0 = disabled)", (double)params.sampling.penalty_freq),
  2182. [](common_params & params, const std::string & value) {
  2183. params.sampling.penalty_freq = std::stof(value);
  2184. }
  2185. ).set_sparam());
  2186. add_opt(common_arg(
  2187. {"--dry-multiplier"}, "N",
  2188. string_format("set DRY sampling multiplier (default: %.1f, 0.0 = disabled)", (double)params.sampling.dry_multiplier),
  2189. [](common_params & params, const std::string & value) {
  2190. params.sampling.dry_multiplier = std::stof(value);
  2191. }
  2192. ).set_sparam());
  2193. add_opt(common_arg(
  2194. {"--dry-base"}, "N",
  2195. string_format("set DRY sampling base value (default: %.2f)", (double)params.sampling.dry_base),
  2196. [](common_params & params, const std::string & value) {
  2197. float potential_base = std::stof(value);
  2198. if (potential_base >= 1.0f)
  2199. {
  2200. params.sampling.dry_base = potential_base;
  2201. }
  2202. }
  2203. ).set_sparam());
  2204. add_opt(common_arg(
  2205. {"--dry-allowed-length"}, "N",
  2206. string_format("set allowed length for DRY sampling (default: %d)", params.sampling.dry_allowed_length),
  2207. [](common_params & params, int value) {
  2208. params.sampling.dry_allowed_length = value;
  2209. }
  2210. ).set_sparam());
  2211. add_opt(common_arg(
  2212. {"--dry-penalty-last-n"}, "N",
  2213. string_format("set DRY penalty for the last n tokens (default: %d, 0 = disable, -1 = context size)", params.sampling.dry_penalty_last_n),
  2214. [](common_params & params, int value) {
  2215. if (value < -1) {
  2216. throw std::runtime_error(string_format("error: invalid dry-penalty-last-n = %d\n", value));
  2217. }
  2218. params.sampling.dry_penalty_last_n = value;
  2219. }
  2220. ).set_sparam());
  2221. add_opt(common_arg(
  2222. {"--dry-sequence-breaker"}, "STRING",
  2223. string_format("add sequence breaker for DRY sampling, clearing out default breakers (%s) in the process; use \"none\" to not use any sequence breakers\n",
  2224. params.sampling.dry_sequence_breakers.empty() ? "none" :
  2225. std::accumulate(std::next(params.sampling.dry_sequence_breakers.begin()),
  2226. params.sampling.dry_sequence_breakers.end(),
  2227. std::string("'") + (params.sampling.dry_sequence_breakers[0] == "\n" ? "\\n" : params.sampling.dry_sequence_breakers[0]) + "'",
  2228. [](const std::string& a, const std::string& b) {
  2229. std::string formatted_b = (b == "\n") ? "\\n" : b;
  2230. return a + ", '" + formatted_b + "'";
  2231. }).c_str()),
  2232. [](common_params & params, const std::string & value) {
  2233. static bool defaults_cleared = false;
  2234. if (!defaults_cleared) {
  2235. params.sampling.dry_sequence_breakers.clear();
  2236. defaults_cleared = true;
  2237. }
  2238. if (value == "none") {
  2239. params.sampling.dry_sequence_breakers.clear();
  2240. } else {
  2241. params.sampling.dry_sequence_breakers.emplace_back(value);
  2242. }
  2243. }
  2244. ).set_sparam());
  2245. add_opt(common_arg(
  2246. {"--dynatemp-range"}, "N",
  2247. string_format("dynamic temperature range (default: %.1f, 0.0 = disabled)", (double)params.sampling.dynatemp_range),
  2248. [](common_params & params, const std::string & value) {
  2249. params.sampling.dynatemp_range = std::stof(value);
  2250. }
  2251. ).set_sparam());
  2252. add_opt(common_arg(
  2253. {"--dynatemp-exp"}, "N",
  2254. string_format("dynamic temperature exponent (default: %.1f)", (double)params.sampling.dynatemp_exponent),
  2255. [](common_params & params, const std::string & value) {
  2256. params.sampling.dynatemp_exponent = std::stof(value);
  2257. }
  2258. ).set_sparam());
  2259. add_opt(common_arg(
  2260. {"--mirostat"}, "N",
  2261. string_format("use Mirostat sampling.\nTop K, Nucleus and Locally Typical samplers are ignored if used.\n"
  2262. "(default: %d, 0 = disabled, 1 = Mirostat, 2 = Mirostat 2.0)", params.sampling.mirostat),
  2263. [](common_params & params, int value) {
  2264. params.sampling.mirostat = value;
  2265. }
  2266. ).set_sparam());
  2267. add_opt(common_arg(
  2268. {"--mirostat-lr"}, "N",
  2269. string_format("Mirostat learning rate, parameter eta (default: %.1f)", (double)params.sampling.mirostat_eta),
  2270. [](common_params & params, const std::string & value) {
  2271. params.sampling.mirostat_eta = std::stof(value);
  2272. }
  2273. ).set_sparam());
  2274. add_opt(common_arg(
  2275. {"--mirostat-ent"}, "N",
  2276. string_format("Mirostat target entropy, parameter tau (default: %.1f)", (double)params.sampling.mirostat_tau),
  2277. [](common_params & params, const std::string & value) {
  2278. params.sampling.mirostat_tau = std::stof(value);
  2279. }
  2280. ).set_sparam());
  2281. add_opt(common_arg(
  2282. {"-l", "--logit-bias"}, "TOKEN_ID(+/-)BIAS",
  2283. "modifies the likelihood of token appearing in the completion,\n"
  2284. "i.e. `--logit-bias 15043+1` to increase likelihood of token ' Hello',\n"
  2285. "or `--logit-bias 15043-1` to decrease likelihood of token ' Hello'",
  2286. [](common_params & params, const std::string & value) {
  2287. std::stringstream ss(value);
  2288. llama_token key;
  2289. char sign;
  2290. std::string value_str;
  2291. try {
  2292. if (ss >> key && ss >> sign && std::getline(ss, value_str) && (sign == '+' || sign == '-')) {
  2293. const float bias = std::stof(value_str) * ((sign == '-') ? -1.0f : 1.0f);
  2294. params.sampling.logit_bias.push_back({key, bias});
  2295. } else {
  2296. throw std::invalid_argument("invalid input format");
  2297. }
  2298. } catch (const std::exception&) {
  2299. throw std::invalid_argument("invalid input format");
  2300. }
  2301. }
  2302. ).set_sparam());
  2303. add_opt(common_arg(
  2304. {"--grammar"}, "GRAMMAR",
  2305. string_format("BNF-like grammar to constrain generations (see samples in grammars/ dir) (default: '%s')", params.sampling.grammar.c_str()),
  2306. [](common_params & params, const std::string & value) {
  2307. params.sampling.grammar = value;
  2308. }
  2309. ).set_sparam());
  2310. add_opt(common_arg(
  2311. {"--grammar-file"}, "FNAME",
  2312. "file to read grammar from",
  2313. [](common_params & params, const std::string & value) {
  2314. params.sampling.grammar = read_file(value);
  2315. }
  2316. ).set_sparam());
  2317. add_opt(common_arg(
  2318. {"-j", "--json-schema"}, "SCHEMA",
  2319. "JSON schema to constrain generations (https://json-schema.org/), e.g. `{}` for any JSON object\nFor schemas w/ external $refs, use --grammar + example/json_schema_to_grammar.py instead",
  2320. [](common_params & params, const std::string & value) {
  2321. params.sampling.grammar = json_schema_to_grammar(json::parse(value));
  2322. }
  2323. ).set_sparam());
  2324. add_opt(common_arg(
  2325. {"-jf", "--json-schema-file"}, "FILE",
  2326. "File containing a JSON schema to constrain generations (https://json-schema.org/), e.g. `{}` for any JSON object\nFor schemas w/ external $refs, use --grammar + example/json_schema_to_grammar.py instead",
  2327. [](common_params & params, const std::string & value) {
  2328. std::ifstream file(value);
  2329. if (!file) {
  2330. throw std::runtime_error(string_format("error: failed to open file '%s'\n", value.c_str()));
  2331. }
  2332. std::string schema;
  2333. std::copy(
  2334. std::istreambuf_iterator<char>(file),
  2335. std::istreambuf_iterator<char>(),
  2336. std::back_inserter(schema)
  2337. );
  2338. params.sampling.grammar = json_schema_to_grammar(json::parse(schema));
  2339. }
  2340. ).set_sparam());
  2341. add_opt(common_arg(
  2342. {"--pooling"}, "{none,mean,cls,last,rank}",
  2343. "pooling type for embeddings, use model default if unspecified",
  2344. [](common_params & params, const std::string & value) {
  2345. /**/ if (value == "none") { params.pooling_type = LLAMA_POOLING_TYPE_NONE; }
  2346. else if (value == "mean") { params.pooling_type = LLAMA_POOLING_TYPE_MEAN; }
  2347. else if (value == "cls") { params.pooling_type = LLAMA_POOLING_TYPE_CLS; }
  2348. else if (value == "last") { params.pooling_type = LLAMA_POOLING_TYPE_LAST; }
  2349. else if (value == "rank") { params.pooling_type = LLAMA_POOLING_TYPE_RANK; }
  2350. else { throw std::invalid_argument("invalid value"); }
  2351. }
  2352. ).set_examples({LLAMA_EXAMPLE_EMBEDDING, LLAMA_EXAMPLE_RETRIEVAL, LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_POOLING"));
  2353. add_opt(common_arg(
  2354. {"--attention"}, "{causal,non-causal}",
  2355. "attention type for embeddings, use model default if unspecified",
  2356. [](common_params & params, const std::string & value) {
  2357. /**/ if (value == "causal") { params.attention_type = LLAMA_ATTENTION_TYPE_CAUSAL; }
  2358. else if (value == "non-causal") { params.attention_type = LLAMA_ATTENTION_TYPE_NON_CAUSAL; }
  2359. else { throw std::invalid_argument("invalid value"); }
  2360. }
  2361. ).set_examples({LLAMA_EXAMPLE_EMBEDDING}));
  2362. add_opt(common_arg(
  2363. {"--rope-scaling"}, "{none,linear,yarn}",
  2364. "RoPE frequency scaling method, defaults to linear unless specified by the model",
  2365. [](common_params & params, const std::string & value) {
  2366. /**/ if (value == "none") { params.rope_scaling_type = LLAMA_ROPE_SCALING_TYPE_NONE; }
  2367. else if (value == "linear") { params.rope_scaling_type = LLAMA_ROPE_SCALING_TYPE_LINEAR; }
  2368. else if (value == "yarn") { params.rope_scaling_type = LLAMA_ROPE_SCALING_TYPE_YARN; }
  2369. else { throw std::invalid_argument("invalid value"); }
  2370. }
  2371. ).set_env("LLAMA_ARG_ROPE_SCALING_TYPE"));
  2372. add_opt(common_arg(
  2373. {"--rope-scale"}, "N",
  2374. "RoPE context scaling factor, expands context by a factor of N",
  2375. [](common_params & params, const std::string & value) {
  2376. params.rope_freq_scale = 1.0f / std::stof(value);
  2377. }
  2378. ).set_env("LLAMA_ARG_ROPE_SCALE"));
  2379. add_opt(common_arg(
  2380. {"--rope-freq-base"}, "N",
  2381. "RoPE base frequency, used by NTK-aware scaling (default: loaded from model)",
  2382. [](common_params & params, const std::string & value) {
  2383. params.rope_freq_base = std::stof(value);
  2384. }
  2385. ).set_env("LLAMA_ARG_ROPE_FREQ_BASE"));
  2386. add_opt(common_arg(
  2387. {"--rope-freq-scale"}, "N",
  2388. "RoPE frequency scaling factor, expands context by a factor of 1/N",
  2389. [](common_params & params, const std::string & value) {
  2390. params.rope_freq_scale = std::stof(value);
  2391. }
  2392. ).set_env("LLAMA_ARG_ROPE_FREQ_SCALE"));
  2393. add_opt(common_arg(
  2394. {"--yarn-orig-ctx"}, "N",
  2395. string_format("YaRN: original context size of model (default: %d = model training context size)", params.yarn_orig_ctx),
  2396. [](common_params & params, int value) {
  2397. params.yarn_orig_ctx = value;
  2398. }
  2399. ).set_env("LLAMA_ARG_YARN_ORIG_CTX"));
  2400. add_opt(common_arg(
  2401. {"--yarn-ext-factor"}, "N",
  2402. string_format("YaRN: extrapolation mix factor (default: %.1f, 0.0 = full interpolation)", (double)params.yarn_ext_factor),
  2403. [](common_params & params, const std::string & value) {
  2404. params.yarn_ext_factor = std::stof(value);
  2405. }
  2406. ).set_env("LLAMA_ARG_YARN_EXT_FACTOR"));
  2407. add_opt(common_arg(
  2408. {"--yarn-attn-factor"}, "N",
  2409. string_format("YaRN: scale sqrt(t) or attention magnitude (default: %.1f)", (double)params.yarn_attn_factor),
  2410. [](common_params & params, const std::string & value) {
  2411. params.yarn_attn_factor = std::stof(value);
  2412. }
  2413. ).set_env("LLAMA_ARG_YARN_ATTN_FACTOR"));
  2414. add_opt(common_arg(
  2415. {"--yarn-beta-slow"}, "N",
  2416. string_format("YaRN: high correction dim or alpha (default: %.1f)", (double)params.yarn_beta_slow),
  2417. [](common_params & params, const std::string & value) {
  2418. params.yarn_beta_slow = std::stof(value);
  2419. }
  2420. ).set_env("LLAMA_ARG_YARN_BETA_SLOW"));
  2421. add_opt(common_arg(
  2422. {"--yarn-beta-fast"}, "N",
  2423. string_format("YaRN: low correction dim or beta (default: %.1f)", (double)params.yarn_beta_fast),
  2424. [](common_params & params, const std::string & value) {
  2425. params.yarn_beta_fast = std::stof(value);
  2426. }
  2427. ).set_env("LLAMA_ARG_YARN_BETA_FAST"));
  2428. add_opt(common_arg(
  2429. {"-gan", "--grp-attn-n"}, "N",
  2430. string_format("group-attention factor (default: %d)", params.grp_attn_n),
  2431. [](common_params & params, int value) {
  2432. params.grp_attn_n = value;
  2433. }
  2434. ).set_env("LLAMA_ARG_GRP_ATTN_N").set_examples({LLAMA_EXAMPLE_MAIN, LLAMA_EXAMPLE_PASSKEY}));
  2435. add_opt(common_arg(
  2436. {"-gaw", "--grp-attn-w"}, "N",
  2437. string_format("group-attention width (default: %d)", params.grp_attn_w),
  2438. [](common_params & params, int value) {
  2439. params.grp_attn_w = value;
  2440. }
  2441. ).set_env("LLAMA_ARG_GRP_ATTN_W").set_examples({LLAMA_EXAMPLE_MAIN}));
  2442. add_opt(common_arg(
  2443. {"-nkvo", "--no-kv-offload"},
  2444. "disable KV offload",
  2445. [](common_params & params) {
  2446. params.no_kv_offload = true;
  2447. }
  2448. ).set_env("LLAMA_ARG_NO_KV_OFFLOAD"));
  2449. add_opt(common_arg(
  2450. {"-nr", "--no-repack"},
  2451. "disable weight repacking",
  2452. [](common_params & params) {
  2453. params.no_extra_bufts = true;
  2454. }
  2455. ).set_env("LLAMA_ARG_NO_REPACK"));
  2456. add_opt(common_arg(
  2457. {"-ctk", "--cache-type-k"}, "TYPE",
  2458. string_format(
  2459. "KV cache data type for K\n"
  2460. "allowed values: %s\n"
  2461. "(default: %s)",
  2462. get_all_kv_cache_types().c_str(),
  2463. ggml_type_name(params.cache_type_k)
  2464. ),
  2465. [](common_params & params, const std::string & value) {
  2466. params.cache_type_k = kv_cache_type_from_str(value);
  2467. }
  2468. ).set_env("LLAMA_ARG_CACHE_TYPE_K"));
  2469. add_opt(common_arg(
  2470. {"-ctv", "--cache-type-v"}, "TYPE",
  2471. string_format(
  2472. "KV cache data type for V\n"
  2473. "allowed values: %s\n"
  2474. "(default: %s)",
  2475. get_all_kv_cache_types().c_str(),
  2476. ggml_type_name(params.cache_type_v)
  2477. ),
  2478. [](common_params & params, const std::string & value) {
  2479. params.cache_type_v = kv_cache_type_from_str(value);
  2480. }
  2481. ).set_env("LLAMA_ARG_CACHE_TYPE_V"));
  2482. add_opt(common_arg(
  2483. {"--hellaswag"},
  2484. "compute HellaSwag score over random tasks from datafile supplied with -f",
  2485. [](common_params & params) {
  2486. params.hellaswag = true;
  2487. }
  2488. ).set_examples({LLAMA_EXAMPLE_PERPLEXITY}));
  2489. add_opt(common_arg(
  2490. {"--hellaswag-tasks"}, "N",
  2491. string_format("number of tasks to use when computing the HellaSwag score (default: %zu)", params.hellaswag_tasks),
  2492. [](common_params & params, int value) {
  2493. params.hellaswag_tasks = value;
  2494. }
  2495. ).set_examples({LLAMA_EXAMPLE_PERPLEXITY}));
  2496. add_opt(common_arg(
  2497. {"--winogrande"},
  2498. "compute Winogrande score over random tasks from datafile supplied with -f",
  2499. [](common_params & params) {
  2500. params.winogrande = true;
  2501. }
  2502. ).set_examples({LLAMA_EXAMPLE_PERPLEXITY}));
  2503. add_opt(common_arg(
  2504. {"--winogrande-tasks"}, "N",
  2505. string_format("number of tasks to use when computing the Winogrande score (default: %zu)", params.winogrande_tasks),
  2506. [](common_params & params, int value) {
  2507. params.winogrande_tasks = value;
  2508. }
  2509. ).set_examples({LLAMA_EXAMPLE_PERPLEXITY}));
  2510. add_opt(common_arg(
  2511. {"--multiple-choice"},
  2512. "compute multiple choice score over random tasks from datafile supplied with -f",
  2513. [](common_params & params) {
  2514. params.multiple_choice = true;
  2515. }
  2516. ).set_examples({LLAMA_EXAMPLE_PERPLEXITY}));
  2517. add_opt(common_arg(
  2518. {"--multiple-choice-tasks"}, "N",
  2519. string_format("number of tasks to use when computing the multiple choice score (default: %zu)", params.multiple_choice_tasks),
  2520. [](common_params & params, int value) {
  2521. params.multiple_choice_tasks = value;
  2522. }
  2523. ).set_examples({LLAMA_EXAMPLE_PERPLEXITY}));
  2524. add_opt(common_arg(
  2525. {"--kl-divergence"},
  2526. "computes KL-divergence to logits provided via --kl-divergence-base",
  2527. [](common_params & params) {
  2528. params.kl_divergence = true;
  2529. }
  2530. ).set_examples({LLAMA_EXAMPLE_PERPLEXITY}));
  2531. add_opt(common_arg(
  2532. {"--save-all-logits", "--kl-divergence-base"}, "FNAME",
  2533. "set logits file",
  2534. [](common_params & params, const std::string & value) {
  2535. params.logits_file = value;
  2536. }
  2537. ).set_examples({LLAMA_EXAMPLE_PERPLEXITY}));
  2538. add_opt(common_arg(
  2539. {"--ppl-stride"}, "N",
  2540. string_format("stride for perplexity calculation (default: %d)", params.ppl_stride),
  2541. [](common_params & params, int value) {
  2542. params.ppl_stride = value;
  2543. }
  2544. ).set_examples({LLAMA_EXAMPLE_PERPLEXITY}));
  2545. add_opt(common_arg(
  2546. {"--ppl-output-type"}, "<0|1>",
  2547. string_format("output type for perplexity calculation (default: %d)", params.ppl_output_type),
  2548. [](common_params & params, int value) {
  2549. params.ppl_output_type = value;
  2550. }
  2551. ).set_examples({LLAMA_EXAMPLE_PERPLEXITY}));
  2552. add_opt(common_arg(
  2553. {"-dt", "--defrag-thold"}, "N",
  2554. string_format("KV cache defragmentation threshold (DEPRECATED)"),
  2555. [](common_params & params, const std::string & value) {
  2556. GGML_UNUSED(params);
  2557. GGML_UNUSED(value);
  2558. LOG_WRN("DEPRECATED: --defrag-thold is deprecated and no longer necessary to specify\n");
  2559. }
  2560. ).set_env("LLAMA_ARG_DEFRAG_THOLD"));
  2561. add_opt(common_arg(
  2562. {"-np", "--parallel"}, "N",
  2563. string_format("number of parallel sequences to decode (default: %d)", params.n_parallel),
  2564. [](common_params & params, int value) {
  2565. params.n_parallel = value;
  2566. }
  2567. ).set_env("LLAMA_ARG_N_PARALLEL"));
  2568. add_opt(common_arg(
  2569. {"-ns", "--sequences"}, "N",
  2570. string_format("number of sequences to decode (default: %d)", params.n_sequences),
  2571. [](common_params & params, int value) {
  2572. params.n_sequences = value;
  2573. }
  2574. ).set_examples({LLAMA_EXAMPLE_PARALLEL}));
  2575. add_opt(common_arg(
  2576. {"-cb", "--cont-batching"},
  2577. string_format("enable continuous batching (a.k.a dynamic batching) (default: %s)", params.cont_batching ? "enabled" : "disabled"),
  2578. [](common_params & params) {
  2579. params.cont_batching = true;
  2580. }
  2581. ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_CONT_BATCHING"));
  2582. add_opt(common_arg(
  2583. {"-nocb", "--no-cont-batching"},
  2584. "disable continuous batching",
  2585. [](common_params & params) {
  2586. params.cont_batching = false;
  2587. }
  2588. ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_NO_CONT_BATCHING"));
  2589. add_opt(common_arg(
  2590. {"--mmproj"}, "FILE",
  2591. "path to a multimodal projector file. see tools/mtmd/README.md\n"
  2592. "note: if -hf is used, this argument can be omitted",
  2593. [](common_params & params, const std::string & value) {
  2594. params.mmproj.path = value;
  2595. }
  2596. ).set_examples(mmproj_examples).set_env("LLAMA_ARG_MMPROJ"));
  2597. add_opt(common_arg(
  2598. {"--mmproj-url"}, "URL",
  2599. "URL to a multimodal projector file. see tools/mtmd/README.md",
  2600. [](common_params & params, const std::string & value) {
  2601. params.mmproj.url = value;
  2602. }
  2603. ).set_examples(mmproj_examples).set_env("LLAMA_ARG_MMPROJ_URL"));
  2604. add_opt(common_arg(
  2605. {"--no-mmproj"},
  2606. "explicitly disable multimodal projector, useful when using -hf",
  2607. [](common_params & params) {
  2608. params.no_mmproj = true;
  2609. }
  2610. ).set_examples(mmproj_examples).set_env("LLAMA_ARG_NO_MMPROJ"));
  2611. add_opt(common_arg(
  2612. {"--no-mmproj-offload"},
  2613. "do not offload multimodal projector to GPU",
  2614. [](common_params & params) {
  2615. params.mmproj_use_gpu = false;
  2616. }
  2617. ).set_examples(mmproj_examples).set_env("LLAMA_ARG_NO_MMPROJ_OFFLOAD"));
  2618. add_opt(common_arg(
  2619. {"--image", "--audio"}, "FILE",
  2620. "path to an image or audio file. use with multimodal models, can be repeated if you have multiple files\n",
  2621. [](common_params & params, const std::string & value) {
  2622. params.image.emplace_back(value);
  2623. }
  2624. ).set_examples({LLAMA_EXAMPLE_MTMD}));
  2625. if (llama_supports_rpc()) {
  2626. add_opt(common_arg(
  2627. {"--rpc"}, "SERVERS",
  2628. "comma separated list of RPC servers",
  2629. [](common_params & params, const std::string & value) {
  2630. add_rpc_devices(value);
  2631. GGML_UNUSED(params);
  2632. }
  2633. ).set_env("LLAMA_ARG_RPC"));
  2634. }
  2635. add_opt(common_arg(
  2636. {"--mlock"},
  2637. "force system to keep model in RAM rather than swapping or compressing",
  2638. [](common_params & params) {
  2639. params.use_mlock = true;
  2640. }
  2641. ).set_env("LLAMA_ARG_MLOCK"));
  2642. add_opt(common_arg(
  2643. {"--no-mmap"},
  2644. "do not memory-map model (slower load but may reduce pageouts if not using mlock)",
  2645. [](common_params & params) {
  2646. params.use_mmap = false;
  2647. }
  2648. ).set_env("LLAMA_ARG_NO_MMAP"));
  2649. add_opt(common_arg(
  2650. {"--numa"}, "TYPE",
  2651. "attempt optimizations that help on some NUMA systems\n"
  2652. "- distribute: spread execution evenly over all nodes\n"
  2653. "- isolate: only spawn threads on CPUs on the node that execution started on\n"
  2654. "- numactl: use the CPU map provided by numactl\n"
  2655. "if run without this previously, it is recommended to drop the system page cache before using this\n"
  2656. "see https://github.com/ggml-org/llama.cpp/issues/1437",
  2657. [](common_params & params, const std::string & value) {
  2658. /**/ if (value == "distribute" || value == "") { params.numa = GGML_NUMA_STRATEGY_DISTRIBUTE; }
  2659. else if (value == "isolate") { params.numa = GGML_NUMA_STRATEGY_ISOLATE; }
  2660. else if (value == "numactl") { params.numa = GGML_NUMA_STRATEGY_NUMACTL; }
  2661. else { throw std::invalid_argument("invalid value"); }
  2662. }
  2663. ).set_env("LLAMA_ARG_NUMA"));
  2664. add_opt(common_arg(
  2665. {"-dev", "--device"}, "<dev1,dev2,..>",
  2666. "comma-separated list of devices to use for offloading (none = don't offload)\n"
  2667. "use --list-devices to see a list of available devices",
  2668. [](common_params & params, const std::string & value) {
  2669. params.devices = parse_device_list(value);
  2670. }
  2671. ).set_env("LLAMA_ARG_DEVICE"));
  2672. add_opt(common_arg(
  2673. {"--list-devices"},
  2674. "print list of available devices and exit",
  2675. [](common_params &) {
  2676. std::vector<ggml_backend_dev_t> devices;
  2677. for (size_t i = 0; i < ggml_backend_dev_count(); ++i) {
  2678. auto * dev = ggml_backend_dev_get(i);
  2679. if (ggml_backend_dev_type(dev) != GGML_BACKEND_DEVICE_TYPE_CPU) {
  2680. devices.push_back(dev);
  2681. }
  2682. }
  2683. printf("Available devices:\n");
  2684. for (auto * dev : devices) {
  2685. size_t free, total;
  2686. ggml_backend_dev_memory(dev, &free, &total);
  2687. printf(" %s: %s (%zu MiB, %zu MiB free)\n", ggml_backend_dev_name(dev), ggml_backend_dev_description(dev), total / 1024 / 1024, free / 1024 / 1024);
  2688. }
  2689. exit(0);
  2690. }
  2691. ));
  2692. add_opt(common_arg(
  2693. {"--override-tensor", "-ot"}, "<tensor name pattern>=<buffer type>,...",
  2694. "override tensor buffer type", [](common_params & params, const std::string & value) {
  2695. parse_tensor_buffer_overrides(value, params.tensor_buft_overrides);
  2696. }
  2697. ));
  2698. add_opt(common_arg(
  2699. {"--override-tensor-draft", "-otd"}, "<tensor name pattern>=<buffer type>,...",
  2700. "override tensor buffer type for draft model", [](common_params & params, const std::string & value) {
  2701. parse_tensor_buffer_overrides(value, params.speculative.tensor_buft_overrides);
  2702. }
  2703. ).set_examples({LLAMA_EXAMPLE_SPECULATIVE, LLAMA_EXAMPLE_SERVER}));
  2704. add_opt(common_arg(
  2705. {"--cpu-moe", "-cmoe"},
  2706. "keep all Mixture of Experts (MoE) weights in the CPU",
  2707. [](common_params & params) {
  2708. params.tensor_buft_overrides.push_back(llm_ffn_exps_cpu_override());
  2709. }
  2710. ).set_env("LLAMA_ARG_CPU_MOE"));
  2711. add_opt(common_arg(
  2712. {"--n-cpu-moe", "-ncmoe"}, "N",
  2713. "keep the Mixture of Experts (MoE) weights of the first N layers in the CPU",
  2714. [](common_params & params, int value) {
  2715. if (value < 0) {
  2716. throw std::invalid_argument("invalid value");
  2717. }
  2718. for (int i = 0; i < value; ++i) {
  2719. // keep strings alive and avoid leaking memory by storing them in a static vector
  2720. static std::list<std::string> buft_overrides;
  2721. buft_overrides.push_back(llm_ffn_exps_block_regex(i));
  2722. params.tensor_buft_overrides.push_back({buft_overrides.back().c_str(), ggml_backend_cpu_buffer_type()});
  2723. }
  2724. }
  2725. ).set_env("LLAMA_ARG_N_CPU_MOE"));
  2726. add_opt(common_arg(
  2727. {"--cpu-moe-draft", "-cmoed"},
  2728. "keep all Mixture of Experts (MoE) weights in the CPU for the draft model",
  2729. [](common_params & params) {
  2730. params.speculative.tensor_buft_overrides.push_back(llm_ffn_exps_cpu_override());
  2731. }
  2732. ).set_examples({LLAMA_EXAMPLE_SPECULATIVE, LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_CPU_MOE_DRAFT"));
  2733. add_opt(common_arg(
  2734. {"--n-cpu-moe-draft", "-ncmoed"}, "N",
  2735. "keep the Mixture of Experts (MoE) weights of the first N layers in the CPU for the draft model",
  2736. [](common_params & params, int value) {
  2737. if (value < 0) {
  2738. throw std::invalid_argument("invalid value");
  2739. }
  2740. for (int i = 0; i < value; ++i) {
  2741. static std::list<std::string> buft_overrides_draft;
  2742. buft_overrides_draft.push_back(llm_ffn_exps_block_regex(i));
  2743. params.speculative.tensor_buft_overrides.push_back({buft_overrides_draft.back().c_str(), ggml_backend_cpu_buffer_type()});
  2744. }
  2745. }
  2746. ).set_examples({LLAMA_EXAMPLE_SPECULATIVE, LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_N_CPU_MOE_DRAFT"));
  2747. add_opt(common_arg(
  2748. {"-ngl", "--gpu-layers", "--n-gpu-layers"}, "N",
  2749. string_format("max. number of layers to store in VRAM (default: %d)", params.n_gpu_layers),
  2750. [](common_params & params, int value) {
  2751. params.n_gpu_layers = value;
  2752. if (!llama_supports_gpu_offload()) {
  2753. fprintf(stderr, "warning: no usable GPU found, --gpu-layers option will be ignored\n");
  2754. fprintf(stderr, "warning: one possible reason is that llama.cpp was compiled without GPU support\n");
  2755. fprintf(stderr, "warning: consult docs/build.md for compilation instructions\n");
  2756. }
  2757. }
  2758. ).set_env("LLAMA_ARG_N_GPU_LAYERS"));
  2759. add_opt(common_arg(
  2760. {"-sm", "--split-mode"}, "{none,layer,row}",
  2761. "how to split the model across multiple GPUs, one of:\n"
  2762. "- none: use one GPU only\n"
  2763. "- layer (default): split layers and KV across GPUs\n"
  2764. "- row: split rows across GPUs",
  2765. [](common_params & params, const std::string & value) {
  2766. std::string arg_next = value;
  2767. if (arg_next == "none") {
  2768. params.split_mode = LLAMA_SPLIT_MODE_NONE;
  2769. } else if (arg_next == "layer") {
  2770. params.split_mode = LLAMA_SPLIT_MODE_LAYER;
  2771. } else if (arg_next == "row") {
  2772. params.split_mode = LLAMA_SPLIT_MODE_ROW;
  2773. } else {
  2774. throw std::invalid_argument("invalid value");
  2775. }
  2776. if (!llama_supports_gpu_offload()) {
  2777. fprintf(stderr, "warning: llama.cpp was compiled without support for GPU offload. Setting the split mode has no effect.\n");
  2778. }
  2779. }
  2780. ).set_env("LLAMA_ARG_SPLIT_MODE"));
  2781. add_opt(common_arg(
  2782. {"-ts", "--tensor-split"}, "N0,N1,N2,...",
  2783. "fraction of the model to offload to each GPU, comma-separated list of proportions, e.g. 3,1",
  2784. [](common_params & params, const std::string & value) {
  2785. std::string arg_next = value;
  2786. // split string by , and /
  2787. const std::regex regex{ R"([,/]+)" };
  2788. std::sregex_token_iterator it{ arg_next.begin(), arg_next.end(), regex, -1 };
  2789. std::vector<std::string> split_arg{ it, {} };
  2790. if (split_arg.size() >= llama_max_devices()) {
  2791. throw std::invalid_argument(
  2792. string_format("got %d input configs, but system only has %d devices", (int)split_arg.size(), (int)llama_max_devices())
  2793. );
  2794. }
  2795. for (size_t i = 0; i < llama_max_devices(); ++i) {
  2796. if (i < split_arg.size()) {
  2797. params.tensor_split[i] = std::stof(split_arg[i]);
  2798. } else {
  2799. params.tensor_split[i] = 0.0f;
  2800. }
  2801. }
  2802. if (!llama_supports_gpu_offload()) {
  2803. fprintf(stderr, "warning: llama.cpp was compiled without support for GPU offload. Setting a tensor split has no effect.\n");
  2804. }
  2805. }
  2806. ).set_env("LLAMA_ARG_TENSOR_SPLIT"));
  2807. add_opt(common_arg(
  2808. {"-mg", "--main-gpu"}, "INDEX",
  2809. string_format("the GPU to use for the model (with split-mode = none), or for intermediate results and KV (with split-mode = row) (default: %d)", params.main_gpu),
  2810. [](common_params & params, int value) {
  2811. params.main_gpu = value;
  2812. if (!llama_supports_gpu_offload()) {
  2813. fprintf(stderr, "warning: llama.cpp was compiled without support for GPU offload. Setting the main GPU has no effect.\n");
  2814. }
  2815. }
  2816. ).set_env("LLAMA_ARG_MAIN_GPU"));
  2817. add_opt(common_arg(
  2818. {"--check-tensors"},
  2819. string_format("check model tensor data for invalid values (default: %s)", params.check_tensors ? "true" : "false"),
  2820. [](common_params & params) {
  2821. params.check_tensors = true;
  2822. }
  2823. ));
  2824. add_opt(common_arg(
  2825. {"--override-kv"}, "KEY=TYPE:VALUE",
  2826. "advanced option to override model metadata by key. may be specified multiple times.\n"
  2827. "types: int, float, bool, str. example: --override-kv tokenizer.ggml.add_bos_token=bool:false",
  2828. [](common_params & params, const std::string & value) {
  2829. if (!string_parse_kv_override(value.c_str(), params.kv_overrides)) {
  2830. throw std::runtime_error(string_format("error: Invalid type for KV override: %s\n", value.c_str()));
  2831. }
  2832. }
  2833. ));
  2834. add_opt(common_arg(
  2835. {"--no-op-offload"},
  2836. string_format("disable offloading host tensor operations to device (default: %s)", params.no_op_offload ? "true" : "false"),
  2837. [](common_params & params) {
  2838. params.no_op_offload = true;
  2839. }
  2840. ));
  2841. add_opt(common_arg(
  2842. {"--lora"}, "FNAME",
  2843. "path to LoRA adapter (can be repeated to use multiple adapters)",
  2844. [](common_params & params, const std::string & value) {
  2845. params.lora_adapters.push_back({ std::string(value), 1.0, "", "", nullptr });
  2846. }
  2847. // we define this arg on both COMMON and EXPORT_LORA, so when showing help message of export-lora, it will be categorized as "example-specific" arg
  2848. ).set_examples({LLAMA_EXAMPLE_COMMON, LLAMA_EXAMPLE_EXPORT_LORA}));
  2849. add_opt(common_arg(
  2850. {"--lora-scaled"}, "FNAME", "SCALE",
  2851. "path to LoRA adapter with user defined scaling (can be repeated to use multiple adapters)",
  2852. [](common_params & params, const std::string & fname, const std::string & scale) {
  2853. params.lora_adapters.push_back({ fname, std::stof(scale), "", "", nullptr });
  2854. }
  2855. // we define this arg on both COMMON and EXPORT_LORA, so when showing help message of export-lora, it will be categorized as "example-specific" arg
  2856. ).set_examples({LLAMA_EXAMPLE_COMMON, LLAMA_EXAMPLE_EXPORT_LORA}));
  2857. add_opt(common_arg(
  2858. {"--control-vector"}, "FNAME",
  2859. "add a control vector\nnote: this argument can be repeated to add multiple control vectors",
  2860. [](common_params & params, const std::string & value) {
  2861. params.control_vectors.push_back({ 1.0f, value, });
  2862. }
  2863. ));
  2864. add_opt(common_arg(
  2865. {"--control-vector-scaled"}, "FNAME", "SCALE",
  2866. "add a control vector with user defined scaling SCALE\n"
  2867. "note: this argument can be repeated to add multiple scaled control vectors",
  2868. [](common_params & params, const std::string & fname, const std::string & scale) {
  2869. params.control_vectors.push_back({ std::stof(scale), fname });
  2870. }
  2871. ));
  2872. add_opt(common_arg(
  2873. {"--control-vector-layer-range"}, "START", "END",
  2874. "layer range to apply the control vector(s) to, start and end inclusive",
  2875. [](common_params & params, const std::string & start, const std::string & end) {
  2876. params.control_vector_layer_start = std::stoi(start);
  2877. params.control_vector_layer_end = std::stoi(end);
  2878. }
  2879. ));
  2880. add_opt(common_arg(
  2881. {"-a", "--alias"}, "STRING",
  2882. "set alias for model name (to be used by REST API)",
  2883. [](common_params & params, const std::string & value) {
  2884. params.model_alias = value;
  2885. }
  2886. ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_ALIAS"));
  2887. add_opt(common_arg(
  2888. {"-m", "--model"}, "FNAME",
  2889. ex == LLAMA_EXAMPLE_EXPORT_LORA
  2890. ? std::string("model path from which to load base model")
  2891. : string_format(
  2892. "model path (default: `models/$filename` with filename from `--hf-file` "
  2893. "or `--model-url` if set, otherwise %s)", DEFAULT_MODEL_PATH
  2894. ),
  2895. [](common_params & params, const std::string & value) {
  2896. params.model.path = value;
  2897. }
  2898. ).set_examples({LLAMA_EXAMPLE_COMMON, LLAMA_EXAMPLE_EXPORT_LORA}).set_env("LLAMA_ARG_MODEL"));
  2899. add_opt(common_arg(
  2900. {"-mu", "--model-url"}, "MODEL_URL",
  2901. "model download url (default: unused)",
  2902. [](common_params & params, const std::string & value) {
  2903. params.model.url = value;
  2904. }
  2905. ).set_env("LLAMA_ARG_MODEL_URL"));
  2906. add_opt(common_arg(
  2907. { "-dr", "--docker-repo" }, "[<repo>/]<model>[:quant]",
  2908. "Docker Hub model repository. repo is optional, default to ai/. quant is optional, default to :latest.\n"
  2909. "example: gemma3\n"
  2910. "(default: unused)",
  2911. [](common_params & params, const std::string & value) {
  2912. params.model.docker_repo = value;
  2913. }
  2914. ).set_env("LLAMA_ARG_DOCKER_REPO"));
  2915. add_opt(common_arg(
  2916. {"-hf", "-hfr", "--hf-repo"}, "<user>/<model>[:quant]",
  2917. "Hugging Face model repository; quant is optional, case-insensitive, default to Q4_K_M, or falls back to the first file in the repo if Q4_K_M doesn't exist.\n"
  2918. "mmproj is also downloaded automatically if available. to disable, add --no-mmproj\n"
  2919. "example: unsloth/phi-4-GGUF:q4_k_m\n"
  2920. "(default: unused)",
  2921. [](common_params & params, const std::string & value) {
  2922. params.model.hf_repo = value;
  2923. }
  2924. ).set_env("LLAMA_ARG_HF_REPO"));
  2925. add_opt(common_arg(
  2926. {"-hfd", "-hfrd", "--hf-repo-draft"}, "<user>/<model>[:quant]",
  2927. "Same as --hf-repo, but for the draft model (default: unused)",
  2928. [](common_params & params, const std::string & value) {
  2929. params.speculative.model.hf_repo = value;
  2930. }
  2931. ).set_env("LLAMA_ARG_HFD_REPO"));
  2932. add_opt(common_arg(
  2933. {"-hff", "--hf-file"}, "FILE",
  2934. "Hugging Face model file. If specified, it will override the quant in --hf-repo (default: unused)",
  2935. [](common_params & params, const std::string & value) {
  2936. params.model.hf_file = value;
  2937. }
  2938. ).set_env("LLAMA_ARG_HF_FILE"));
  2939. add_opt(common_arg(
  2940. {"-hfv", "-hfrv", "--hf-repo-v"}, "<user>/<model>[:quant]",
  2941. "Hugging Face model repository for the vocoder model (default: unused)",
  2942. [](common_params & params, const std::string & value) {
  2943. params.vocoder.model.hf_repo = value;
  2944. }
  2945. ).set_env("LLAMA_ARG_HF_REPO_V"));
  2946. add_opt(common_arg(
  2947. {"-hffv", "--hf-file-v"}, "FILE",
  2948. "Hugging Face model file for the vocoder model (default: unused)",
  2949. [](common_params & params, const std::string & value) {
  2950. params.vocoder.model.hf_file = value;
  2951. }
  2952. ).set_env("LLAMA_ARG_HF_FILE_V"));
  2953. add_opt(common_arg(
  2954. {"-hft", "--hf-token"}, "TOKEN",
  2955. "Hugging Face access token (default: value from HF_TOKEN environment variable)",
  2956. [](common_params & params, const std::string & value) {
  2957. params.hf_token = value;
  2958. }
  2959. ).set_env("HF_TOKEN"));
  2960. add_opt(common_arg(
  2961. {"--context-file"}, "FNAME",
  2962. "file to load context from (repeat to specify multiple files)",
  2963. [](common_params & params, const std::string & value) {
  2964. std::ifstream file(value, std::ios::binary);
  2965. if (!file) {
  2966. throw std::runtime_error(string_format("error: failed to open file '%s'\n", value.c_str()));
  2967. }
  2968. params.context_files.push_back(value);
  2969. }
  2970. ).set_examples({LLAMA_EXAMPLE_RETRIEVAL}));
  2971. add_opt(common_arg(
  2972. {"--chunk-size"}, "N",
  2973. string_format("minimum length of embedded text chunks (default: %d)", params.chunk_size),
  2974. [](common_params & params, int value) {
  2975. params.chunk_size = value;
  2976. }
  2977. ).set_examples({LLAMA_EXAMPLE_RETRIEVAL}));
  2978. add_opt(common_arg(
  2979. {"--chunk-separator"}, "STRING",
  2980. string_format("separator between chunks (default: '%s')", params.chunk_separator.c_str()),
  2981. [](common_params & params, const std::string & value) {
  2982. params.chunk_separator = value;
  2983. }
  2984. ).set_examples({LLAMA_EXAMPLE_RETRIEVAL}));
  2985. add_opt(common_arg(
  2986. {"--junk"}, "N",
  2987. string_format("number of times to repeat the junk text (default: %d)", params.n_junk),
  2988. [](common_params & params, int value) {
  2989. params.n_junk = value;
  2990. }
  2991. ).set_examples({LLAMA_EXAMPLE_PASSKEY, LLAMA_EXAMPLE_PARALLEL}));
  2992. add_opt(common_arg(
  2993. {"--pos"}, "N",
  2994. string_format("position of the passkey in the junk text (default: %d)", params.i_pos),
  2995. [](common_params & params, int value) {
  2996. params.i_pos = value;
  2997. }
  2998. ).set_examples({LLAMA_EXAMPLE_PASSKEY}));
  2999. add_opt(common_arg(
  3000. {"-o", "--output", "--output-file"}, "FNAME",
  3001. string_format("output file (default: '%s')", params.out_file.c_str()),
  3002. [](common_params & params, const std::string & value) {
  3003. params.out_file = value;
  3004. }
  3005. ).set_examples({LLAMA_EXAMPLE_IMATRIX, LLAMA_EXAMPLE_CVECTOR_GENERATOR, LLAMA_EXAMPLE_EXPORT_LORA, LLAMA_EXAMPLE_TTS, LLAMA_EXAMPLE_FINETUNE}));
  3006. add_opt(common_arg(
  3007. {"-ofreq", "--output-frequency"}, "N",
  3008. string_format("output the imatrix every N iterations (default: %d)", params.n_out_freq),
  3009. [](common_params & params, int value) {
  3010. params.n_out_freq = value;
  3011. }
  3012. ).set_examples({LLAMA_EXAMPLE_IMATRIX}));
  3013. add_opt(common_arg(
  3014. {"--output-format"}, "{gguf,dat}",
  3015. string_format("output format for imatrix file (default: %s)", params.imat_dat > 0 ? "dat" : "gguf"),
  3016. [](common_params & params, const std::string & value) {
  3017. /**/ if (value == "gguf") { params.imat_dat = -1; }
  3018. else if (value == "dat") { params.imat_dat = 1; }
  3019. else { throw std::invalid_argument("invalid output format"); }
  3020. }
  3021. ).set_examples({LLAMA_EXAMPLE_IMATRIX}));
  3022. add_opt(common_arg(
  3023. {"--save-frequency"}, "N",
  3024. string_format("save an imatrix copy every N iterations (default: %d)", params.n_save_freq),
  3025. [](common_params & params, int value) {
  3026. params.n_save_freq = value;
  3027. }
  3028. ).set_examples({LLAMA_EXAMPLE_IMATRIX}));
  3029. add_opt(common_arg(
  3030. {"--process-output"},
  3031. string_format("collect data for the output tensor (default: %s)", params.process_output ? "true" : "false"),
  3032. [](common_params & params) {
  3033. params.process_output = true;
  3034. }
  3035. ).set_examples({LLAMA_EXAMPLE_IMATRIX}));
  3036. add_opt(common_arg(
  3037. {"--no-ppl"},
  3038. string_format("do not compute perplexity (default: %s)", params.compute_ppl ? "true" : "false"),
  3039. [](common_params & params) {
  3040. params.compute_ppl = false;
  3041. }
  3042. ).set_examples({LLAMA_EXAMPLE_IMATRIX}));
  3043. add_opt(common_arg(
  3044. {"--chunk", "--from-chunk"}, "N",
  3045. string_format("start processing the input from chunk N (default: %d)", params.i_chunk),
  3046. [](common_params & params, int value) {
  3047. params.i_chunk = value;
  3048. }
  3049. ).set_examples({LLAMA_EXAMPLE_IMATRIX}));
  3050. add_opt(common_arg(
  3051. {"--show-statistics"},
  3052. string_format("show imatrix statistics and then exit (default: %s)", params.show_statistics ? "true" : "false"),
  3053. [](common_params & params) {
  3054. params.show_statistics = true;
  3055. }
  3056. ).set_examples({LLAMA_EXAMPLE_IMATRIX}));
  3057. add_opt(common_arg(
  3058. {"--parse-special"},
  3059. string_format("prase special tokens (chat, tool, etc) (default: %s)", params.parse_special ? "true" : "false"),
  3060. [](common_params & params) {
  3061. params.parse_special = true;
  3062. }
  3063. ).set_examples({LLAMA_EXAMPLE_IMATRIX}));
  3064. add_opt(common_arg(
  3065. {"-pps"},
  3066. string_format("is the prompt shared across parallel sequences (default: %s)", params.is_pp_shared ? "true" : "false"),
  3067. [](common_params & params) {
  3068. params.is_pp_shared = true;
  3069. }
  3070. ).set_examples({LLAMA_EXAMPLE_BENCH, LLAMA_EXAMPLE_PARALLEL}));
  3071. add_opt(common_arg(
  3072. {"-npp"}, "n0,n1,...",
  3073. "number of prompt tokens",
  3074. [](common_params & params, const std::string & value) {
  3075. auto p = string_split<int>(value, ',');
  3076. params.n_pp.insert(params.n_pp.end(), p.begin(), p.end());
  3077. }
  3078. ).set_examples({LLAMA_EXAMPLE_BENCH}));
  3079. add_opt(common_arg(
  3080. {"-ntg"}, "n0,n1,...",
  3081. "number of text generation tokens",
  3082. [](common_params & params, const std::string & value) {
  3083. auto p = string_split<int>(value, ',');
  3084. params.n_tg.insert(params.n_tg.end(), p.begin(), p.end());
  3085. }
  3086. ).set_examples({LLAMA_EXAMPLE_BENCH}));
  3087. add_opt(common_arg(
  3088. {"-npl"}, "n0,n1,...",
  3089. "number of parallel prompts",
  3090. [](common_params & params, const std::string & value) {
  3091. auto p = string_split<int>(value, ',');
  3092. params.n_pl.insert(params.n_pl.end(), p.begin(), p.end());
  3093. }
  3094. ).set_examples({LLAMA_EXAMPLE_BENCH}));
  3095. add_opt(common_arg(
  3096. {"--embd-normalize"}, "N",
  3097. string_format("normalisation for embeddings (default: %d) (-1=none, 0=max absolute int16, 1=taxicab, 2=euclidean, >2=p-norm)", params.embd_normalize),
  3098. [](common_params & params, int value) {
  3099. params.embd_normalize = value;
  3100. }
  3101. ).set_examples({LLAMA_EXAMPLE_EMBEDDING}));
  3102. add_opt(common_arg(
  3103. {"--embd-output-format"}, "FORMAT",
  3104. "empty = default, \"array\" = [[],[]...], \"json\" = openai style, \"json+\" = same \"json\" + cosine similarity matrix",
  3105. [](common_params & params, const std::string & value) {
  3106. params.embd_out = value;
  3107. }
  3108. ).set_examples({LLAMA_EXAMPLE_EMBEDDING}));
  3109. add_opt(common_arg(
  3110. {"--embd-separator"}, "STRING",
  3111. "separator of embeddings (default \\n) for example \"<#sep#>\"",
  3112. [](common_params & params, const std::string & value) {
  3113. params.embd_sep = value;
  3114. }
  3115. ).set_examples({LLAMA_EXAMPLE_EMBEDDING}));
  3116. add_opt(common_arg(
  3117. {"--cls-separator"}, "STRING",
  3118. "separator of classification sequences (default \\t) for example \"<#seq#>\"",
  3119. [](common_params & params, const std::string & value) {
  3120. params.cls_sep = value;
  3121. }
  3122. ).set_examples({LLAMA_EXAMPLE_EMBEDDING}));
  3123. add_opt(common_arg(
  3124. {"--host"}, "HOST",
  3125. string_format("ip address to listen, or bind to an UNIX socket if the address ends with .sock (default: %s)", params.hostname.c_str()),
  3126. [](common_params & params, const std::string & value) {
  3127. params.hostname = value;
  3128. }
  3129. ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_HOST"));
  3130. add_opt(common_arg(
  3131. {"--port"}, "PORT",
  3132. string_format("port to listen (default: %d)", params.port),
  3133. [](common_params & params, int value) {
  3134. params.port = value;
  3135. }
  3136. ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_PORT"));
  3137. add_opt(common_arg(
  3138. {"--path"}, "PATH",
  3139. string_format("path to serve static files from (default: %s)", params.public_path.c_str()),
  3140. [](common_params & params, const std::string & value) {
  3141. params.public_path = value;
  3142. }
  3143. ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_STATIC_PATH"));
  3144. add_opt(common_arg(
  3145. {"--api-prefix"}, "PREFIX",
  3146. string_format("prefix path the server serves from, without the trailing slash (default: %s)", params.api_prefix.c_str()),
  3147. [](common_params & params, const std::string & value) {
  3148. params.api_prefix = value;
  3149. }
  3150. ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_API_PREFIX"));
  3151. add_opt(common_arg(
  3152. {"--no-webui"},
  3153. string_format("Disable the Web UI (default: %s)", params.webui ? "enabled" : "disabled"),
  3154. [](common_params & params) {
  3155. params.webui = false;
  3156. }
  3157. ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_NO_WEBUI"));
  3158. add_opt(common_arg(
  3159. {"--embedding", "--embeddings"},
  3160. string_format("restrict to only support embedding use case; use only with dedicated embedding models (default: %s)", params.embedding ? "enabled" : "disabled"),
  3161. [](common_params & params) {
  3162. params.embedding = true;
  3163. }
  3164. ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_EMBEDDINGS"));
  3165. add_opt(common_arg(
  3166. {"--reranking", "--rerank"},
  3167. string_format("enable reranking endpoint on server (default: %s)", "disabled"),
  3168. [](common_params & params) {
  3169. params.embedding = true;
  3170. params.pooling_type = LLAMA_POOLING_TYPE_RANK;
  3171. }
  3172. ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_RERANKING"));
  3173. add_opt(common_arg(
  3174. {"--api-key"}, "KEY",
  3175. "API key to use for authentication (default: none)",
  3176. [](common_params & params, const std::string & value) {
  3177. params.api_keys.push_back(value);
  3178. }
  3179. ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_API_KEY"));
  3180. add_opt(common_arg(
  3181. {"--api-key-file"}, "FNAME",
  3182. "path to file containing API keys (default: none)",
  3183. [](common_params & params, const std::string & value) {
  3184. std::ifstream key_file(value);
  3185. if (!key_file) {
  3186. throw std::runtime_error(string_format("error: failed to open file '%s'\n", value.c_str()));
  3187. }
  3188. std::string key;
  3189. while (std::getline(key_file, key)) {
  3190. if (!key.empty()) {
  3191. params.api_keys.push_back(key);
  3192. }
  3193. }
  3194. key_file.close();
  3195. }
  3196. ).set_examples({LLAMA_EXAMPLE_SERVER}));
  3197. add_opt(common_arg(
  3198. {"--ssl-key-file"}, "FNAME",
  3199. "path to file a PEM-encoded SSL private key",
  3200. [](common_params & params, const std::string & value) {
  3201. params.ssl_file_key = value;
  3202. }
  3203. ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_SSL_KEY_FILE"));
  3204. add_opt(common_arg(
  3205. {"--ssl-cert-file"}, "FNAME",
  3206. "path to file a PEM-encoded SSL certificate",
  3207. [](common_params & params, const std::string & value) {
  3208. params.ssl_file_cert = value;
  3209. }
  3210. ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_SSL_CERT_FILE"));
  3211. add_opt(common_arg(
  3212. {"--chat-template-kwargs"}, "STRING",
  3213. string_format("sets additional params for the json template parser"),
  3214. [](common_params & params, const std::string & value) {
  3215. auto parsed = json::parse(value);
  3216. for (const auto & item : parsed.items()) {
  3217. params.default_template_kwargs[item.key()] = item.value().dump();
  3218. }
  3219. }
  3220. ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_CHAT_TEMPLATE_KWARGS"));
  3221. add_opt(common_arg(
  3222. {"-to", "--timeout"}, "N",
  3223. string_format("server read/write timeout in seconds (default: %d)", params.timeout_read),
  3224. [](common_params & params, int value) {
  3225. params.timeout_read = value;
  3226. params.timeout_write = value;
  3227. }
  3228. ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_TIMEOUT"));
  3229. add_opt(common_arg(
  3230. {"--threads-http"}, "N",
  3231. string_format("number of threads used to process HTTP requests (default: %d)", params.n_threads_http),
  3232. [](common_params & params, int value) {
  3233. params.n_threads_http = value;
  3234. }
  3235. ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_THREADS_HTTP"));
  3236. add_opt(common_arg(
  3237. {"--cache-reuse"}, "N",
  3238. string_format(
  3239. "min chunk size to attempt reusing from the cache via KV shifting (default: %d)\n"
  3240. "[(card)](https://ggml.ai/f0.png)", params.n_cache_reuse
  3241. ),
  3242. [](common_params & params, int value) {
  3243. params.n_cache_reuse = value;
  3244. }
  3245. ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_CACHE_REUSE"));
  3246. add_opt(common_arg(
  3247. {"--metrics"},
  3248. string_format("enable prometheus compatible metrics endpoint (default: %s)", params.endpoint_metrics ? "enabled" : "disabled"),
  3249. [](common_params & params) {
  3250. params.endpoint_metrics = true;
  3251. }
  3252. ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_ENDPOINT_METRICS"));
  3253. add_opt(common_arg(
  3254. {"--props"},
  3255. string_format("enable changing global properties via POST /props (default: %s)", params.endpoint_props ? "enabled" : "disabled"),
  3256. [](common_params & params) {
  3257. params.endpoint_props = true;
  3258. }
  3259. ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_ENDPOINT_PROPS"));
  3260. add_opt(common_arg(
  3261. {"--slots"},
  3262. string_format("enable slots monitoring endpoint (default: %s)", params.endpoint_slots ? "enabled" : "disabled"),
  3263. [](common_params & params) {
  3264. params.endpoint_slots = true;
  3265. }
  3266. ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_ENDPOINT_SLOTS"));
  3267. add_opt(common_arg(
  3268. {"--no-slots"},
  3269. "disables slots monitoring endpoint",
  3270. [](common_params & params) {
  3271. params.endpoint_slots = false;
  3272. }
  3273. ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_NO_ENDPOINT_SLOTS"));
  3274. add_opt(common_arg(
  3275. {"--slot-save-path"}, "PATH",
  3276. "path to save slot kv cache (default: disabled)",
  3277. [](common_params & params, const std::string & value) {
  3278. params.slot_save_path = value;
  3279. // if doesn't end with DIRECTORY_SEPARATOR, add it
  3280. if (!params.slot_save_path.empty() && params.slot_save_path[params.slot_save_path.size() - 1] != DIRECTORY_SEPARATOR) {
  3281. params.slot_save_path += DIRECTORY_SEPARATOR;
  3282. }
  3283. }
  3284. ).set_examples({LLAMA_EXAMPLE_SERVER}));
  3285. add_opt(common_arg(
  3286. {"--jinja"},
  3287. "use jinja template for chat (default: disabled)",
  3288. [](common_params & params) {
  3289. params.use_jinja = true;
  3290. }
  3291. ).set_examples({LLAMA_EXAMPLE_SERVER, LLAMA_EXAMPLE_MAIN}).set_env("LLAMA_ARG_JINJA"));
  3292. add_opt(common_arg(
  3293. {"--reasoning-format"}, "FORMAT",
  3294. "controls whether thought tags are allowed and/or extracted from the response, and in which format they're returned; one of:\n"
  3295. "- none: leaves thoughts unparsed in `message.content`\n"
  3296. "- deepseek: puts thoughts in `message.reasoning_content` (except in streaming mode, which behaves as `none`)\n"
  3297. "(default: auto)",
  3298. [](common_params & params, const std::string & value) {
  3299. params.reasoning_format = common_reasoning_format_from_name(value);
  3300. }
  3301. ).set_examples({LLAMA_EXAMPLE_SERVER, LLAMA_EXAMPLE_MAIN}).set_env("LLAMA_ARG_THINK"));
  3302. add_opt(common_arg(
  3303. {"--reasoning-budget"}, "N",
  3304. "controls the amount of thinking allowed; currently only one of: -1 for unrestricted thinking budget, or 0 to disable thinking (default: -1)",
  3305. [](common_params & params, int value) {
  3306. if (value != 0 && value != -1) { throw std::invalid_argument("invalid value"); }
  3307. params.reasoning_budget = value;
  3308. }
  3309. ).set_examples({LLAMA_EXAMPLE_SERVER, LLAMA_EXAMPLE_MAIN}).set_env("LLAMA_ARG_THINK_BUDGET"));
  3310. add_opt(common_arg(
  3311. {"--chat-template"}, "JINJA_TEMPLATE",
  3312. string_format(
  3313. "set custom jinja chat template (default: template taken from model's metadata)\n"
  3314. "if suffix/prefix are specified, template will be disabled\n"
  3315. "only commonly used templates are accepted (unless --jinja is set before this flag):\n"
  3316. "list of built-in templates:\n%s", list_builtin_chat_templates().c_str()
  3317. ),
  3318. [](common_params & params, const std::string & value) {
  3319. params.chat_template = value;
  3320. }
  3321. ).set_examples({LLAMA_EXAMPLE_MAIN, LLAMA_EXAMPLE_SERVER, LLAMA_EXAMPLE_MTMD}).set_env("LLAMA_ARG_CHAT_TEMPLATE"));
  3322. add_opt(common_arg(
  3323. {"--chat-template-file"}, "JINJA_TEMPLATE_FILE",
  3324. string_format(
  3325. "set custom jinja chat template file (default: template taken from model's metadata)\n"
  3326. "if suffix/prefix are specified, template will be disabled\n"
  3327. "only commonly used templates are accepted (unless --jinja is set before this flag):\n"
  3328. "list of built-in templates:\n%s", list_builtin_chat_templates().c_str()
  3329. ),
  3330. [](common_params & params, const std::string & value) {
  3331. params.chat_template = read_file(value);
  3332. }
  3333. ).set_examples({LLAMA_EXAMPLE_MAIN, LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_CHAT_TEMPLATE_FILE"));
  3334. add_opt(common_arg(
  3335. {"--no-prefill-assistant"},
  3336. string_format(
  3337. "whether to prefill the assistant's response if the last message is an assistant message (default: prefill enabled)\n"
  3338. "when this flag is set, if the last message is an assistant message then it will be treated as a full message and not prefilled\n"
  3339. ),
  3340. [](common_params & params) {
  3341. params.prefill_assistant = false;
  3342. }
  3343. ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_NO_PREFILL_ASSISTANT"));
  3344. add_opt(common_arg(
  3345. {"-sps", "--slot-prompt-similarity"}, "SIMILARITY",
  3346. string_format("how much the prompt of a request must match the prompt of a slot in order to use that slot (default: %.2f, 0.0 = disabled)\n", params.slot_prompt_similarity),
  3347. [](common_params & params, const std::string & value) {
  3348. params.slot_prompt_similarity = std::stof(value);
  3349. }
  3350. ).set_examples({LLAMA_EXAMPLE_SERVER}));
  3351. add_opt(common_arg(
  3352. {"--lora-init-without-apply"},
  3353. string_format("load LoRA adapters without applying them (apply later via POST /lora-adapters) (default: %s)", params.lora_init_without_apply ? "enabled" : "disabled"),
  3354. [](common_params & params) {
  3355. params.lora_init_without_apply = true;
  3356. }
  3357. ).set_examples({LLAMA_EXAMPLE_SERVER}));
  3358. add_opt(common_arg(
  3359. {"--simple-io"},
  3360. "use basic IO for better compatibility in subprocesses and limited consoles",
  3361. [](common_params & params) {
  3362. params.simple_io = true;
  3363. }
  3364. ).set_examples({LLAMA_EXAMPLE_MAIN}));
  3365. add_opt(common_arg(
  3366. {"--positive-file"}, "FNAME",
  3367. string_format("positive prompts file, one prompt per line (default: '%s')", params.cvector_positive_file.c_str()),
  3368. [](common_params & params, const std::string & value) {
  3369. params.cvector_positive_file = value;
  3370. }
  3371. ).set_examples({LLAMA_EXAMPLE_CVECTOR_GENERATOR}));
  3372. add_opt(common_arg(
  3373. {"--negative-file"}, "FNAME",
  3374. string_format("negative prompts file, one prompt per line (default: '%s')", params.cvector_negative_file.c_str()),
  3375. [](common_params & params, const std::string & value) {
  3376. params.cvector_negative_file = value;
  3377. }
  3378. ).set_examples({LLAMA_EXAMPLE_CVECTOR_GENERATOR}));
  3379. add_opt(common_arg(
  3380. {"--pca-batch"}, "N",
  3381. string_format("batch size used for PCA. Larger batch runs faster, but uses more memory (default: %d)", params.n_pca_batch),
  3382. [](common_params & params, int value) {
  3383. params.n_pca_batch = value;
  3384. }
  3385. ).set_examples({LLAMA_EXAMPLE_CVECTOR_GENERATOR}));
  3386. add_opt(common_arg(
  3387. {"--pca-iter"}, "N",
  3388. string_format("number of iterations used for PCA (default: %d)", params.n_pca_iterations),
  3389. [](common_params & params, int value) {
  3390. params.n_pca_iterations = value;
  3391. }
  3392. ).set_examples({LLAMA_EXAMPLE_CVECTOR_GENERATOR}));
  3393. add_opt(common_arg(
  3394. {"--method"}, "{pca, mean}",
  3395. "dimensionality reduction method to be used (default: pca)",
  3396. [](common_params & params, const std::string & value) {
  3397. /**/ if (value == "pca") { params.cvector_dimre_method = DIMRE_METHOD_PCA; }
  3398. else if (value == "mean") { params.cvector_dimre_method = DIMRE_METHOD_MEAN; }
  3399. else { throw std::invalid_argument("invalid value"); }
  3400. }
  3401. ).set_examples({LLAMA_EXAMPLE_CVECTOR_GENERATOR}));
  3402. add_opt(common_arg(
  3403. {"--output-format"}, "{md,jsonl}",
  3404. "output format for batched-bench results (default: md)",
  3405. [](common_params & params, const std::string & value) {
  3406. /**/ if (value == "jsonl") { params.batched_bench_output_jsonl = true; }
  3407. else if (value == "md") { params.batched_bench_output_jsonl = false; }
  3408. else { throw std::invalid_argument("invalid value"); }
  3409. }
  3410. ).set_examples({LLAMA_EXAMPLE_BENCH}));
  3411. add_opt(common_arg(
  3412. {"--log-disable"},
  3413. "Log disable",
  3414. [](common_params &) {
  3415. common_log_pause(common_log_main());
  3416. }
  3417. ));
  3418. add_opt(common_arg(
  3419. {"--log-file"}, "FNAME",
  3420. "Log to file",
  3421. [](common_params &, const std::string & value) {
  3422. common_log_set_file(common_log_main(), value.c_str());
  3423. }
  3424. ));
  3425. add_opt(common_arg({ "--log-colors" }, "[on|off|auto]",
  3426. "Set colored logging ('on', 'off', or 'auto', default: 'auto')\n"
  3427. "'auto' enables colors when output is to a terminal",
  3428. [](common_params &, const std::string & value) {
  3429. if (is_truthy(value)) {
  3430. common_log_set_colors(common_log_main(), LOG_COLORS_ENABLED);
  3431. } else if (is_falsey(value)) {
  3432. common_log_set_colors(common_log_main(), LOG_COLORS_DISABLED);
  3433. } else if (is_autoy(value)) {
  3434. common_log_set_colors(common_log_main(), LOG_COLORS_AUTO);
  3435. } else {
  3436. throw std::invalid_argument(
  3437. string_format("error: unkown value for --log-colors: '%s'\n", value.c_str()));
  3438. }
  3439. }).set_env("LLAMA_LOG_COLORS"));
  3440. add_opt(common_arg(
  3441. {"-v", "--verbose", "--log-verbose"},
  3442. "Set verbosity level to infinity (i.e. log all messages, useful for debugging)",
  3443. [](common_params & params) {
  3444. params.verbosity = INT_MAX;
  3445. common_log_set_verbosity_thold(INT_MAX);
  3446. }
  3447. ));
  3448. add_opt(common_arg(
  3449. {"--offline"},
  3450. "Offline mode: forces use of cache, prevents network access",
  3451. [](common_params & params) {
  3452. params.offline = true;
  3453. }
  3454. ).set_env("LLAMA_OFFLINE"));
  3455. add_opt(common_arg(
  3456. {"-lv", "--verbosity", "--log-verbosity"}, "N",
  3457. "Set the verbosity threshold. Messages with a higher verbosity will be ignored.",
  3458. [](common_params & params, int value) {
  3459. params.verbosity = value;
  3460. common_log_set_verbosity_thold(value);
  3461. }
  3462. ).set_env("LLAMA_LOG_VERBOSITY"));
  3463. add_opt(common_arg(
  3464. {"--log-prefix"},
  3465. "Enable prefix in log messages",
  3466. [](common_params &) {
  3467. common_log_set_prefix(common_log_main(), true);
  3468. }
  3469. ).set_env("LLAMA_LOG_PREFIX"));
  3470. add_opt(common_arg(
  3471. {"--log-timestamps"},
  3472. "Enable timestamps in log messages",
  3473. [](common_params &) {
  3474. common_log_set_timestamps(common_log_main(), true);
  3475. }
  3476. ).set_env("LLAMA_LOG_TIMESTAMPS"));
  3477. // speculative parameters
  3478. add_opt(common_arg(
  3479. {"-td", "--threads-draft"}, "N",
  3480. "number of threads to use during generation (default: same as --threads)",
  3481. [](common_params & params, int value) {
  3482. params.speculative.cpuparams.n_threads = value;
  3483. if (params.speculative.cpuparams.n_threads <= 0) {
  3484. params.speculative.cpuparams.n_threads = std::thread::hardware_concurrency();
  3485. }
  3486. }
  3487. ).set_examples({LLAMA_EXAMPLE_SPECULATIVE, LLAMA_EXAMPLE_SERVER}));
  3488. add_opt(common_arg(
  3489. {"-tbd", "--threads-batch-draft"}, "N",
  3490. "number of threads to use during batch and prompt processing (default: same as --threads-draft)",
  3491. [](common_params & params, int value) {
  3492. params.speculative.cpuparams_batch.n_threads = value;
  3493. if (params.speculative.cpuparams_batch.n_threads <= 0) {
  3494. params.speculative.cpuparams_batch.n_threads = std::thread::hardware_concurrency();
  3495. }
  3496. }
  3497. ).set_examples({LLAMA_EXAMPLE_SPECULATIVE, LLAMA_EXAMPLE_SERVER}));
  3498. add_opt(common_arg(
  3499. {"-Cd", "--cpu-mask-draft"}, "M",
  3500. "Draft model CPU affinity mask. Complements cpu-range-draft (default: same as --cpu-mask)",
  3501. [](common_params & params, const std::string & mask) {
  3502. params.speculative.cpuparams.mask_valid = true;
  3503. if (!parse_cpu_mask(mask, params.speculative.cpuparams.cpumask)) {
  3504. throw std::invalid_argument("invalid cpumask");
  3505. }
  3506. }
  3507. ).set_examples({LLAMA_EXAMPLE_SPECULATIVE}));
  3508. add_opt(common_arg(
  3509. {"-Crd", "--cpu-range-draft"}, "lo-hi",
  3510. "Ranges of CPUs for affinity. Complements --cpu-mask-draft",
  3511. [](common_params & params, const std::string & range) {
  3512. params.speculative.cpuparams.mask_valid = true;
  3513. if (!parse_cpu_range(range, params.speculative.cpuparams.cpumask)) {
  3514. throw std::invalid_argument("invalid range");
  3515. }
  3516. }
  3517. ).set_examples({LLAMA_EXAMPLE_SPECULATIVE}));
  3518. add_opt(common_arg(
  3519. {"--cpu-strict-draft"}, "<0|1>",
  3520. "Use strict CPU placement for draft model (default: same as --cpu-strict)",
  3521. [](common_params & params, int value) {
  3522. params.speculative.cpuparams.strict_cpu = value;
  3523. }
  3524. ).set_examples({LLAMA_EXAMPLE_SPECULATIVE}));
  3525. add_opt(common_arg(
  3526. {"--prio-draft"}, "N",
  3527. string_format("set draft process/thread priority : 0-normal, 1-medium, 2-high, 3-realtime (default: %d)\n", params.speculative.cpuparams.priority),
  3528. [](common_params & params, int prio) {
  3529. if (prio < 0 || prio > 3) {
  3530. throw std::invalid_argument("invalid value");
  3531. }
  3532. params.speculative.cpuparams.priority = (enum ggml_sched_priority) prio;
  3533. }
  3534. ).set_examples({LLAMA_EXAMPLE_SPECULATIVE}));
  3535. add_opt(common_arg(
  3536. {"--poll-draft"}, "<0|1>",
  3537. "Use polling to wait for draft model work (default: same as --poll])",
  3538. [](common_params & params, int value) {
  3539. params.speculative.cpuparams.poll = value;
  3540. }
  3541. ).set_examples({LLAMA_EXAMPLE_SPECULATIVE}));
  3542. add_opt(common_arg(
  3543. {"-Cbd", "--cpu-mask-batch-draft"}, "M",
  3544. "Draft model CPU affinity mask. Complements cpu-range-draft (default: same as --cpu-mask)",
  3545. [](common_params & params, const std::string & mask) {
  3546. params.speculative.cpuparams_batch.mask_valid = true;
  3547. if (!parse_cpu_mask(mask, params.speculative.cpuparams_batch.cpumask)) {
  3548. throw std::invalid_argument("invalid cpumask");
  3549. }
  3550. }
  3551. ).set_examples({LLAMA_EXAMPLE_SPECULATIVE}));
  3552. add_opt(common_arg(
  3553. {"-Crbd", "--cpu-range-batch-draft"}, "lo-hi",
  3554. "Ranges of CPUs for affinity. Complements --cpu-mask-draft-batch)",
  3555. [](common_params & params, const std::string & range) {
  3556. params.speculative.cpuparams_batch.mask_valid = true;
  3557. if (!parse_cpu_range(range, params.speculative.cpuparams_batch.cpumask)) {
  3558. throw std::invalid_argument("invalid cpumask");
  3559. }
  3560. }
  3561. ).set_examples({LLAMA_EXAMPLE_SPECULATIVE}));
  3562. add_opt(common_arg(
  3563. {"--cpu-strict-batch-draft"}, "<0|1>",
  3564. "Use strict CPU placement for draft model (default: --cpu-strict-draft)",
  3565. [](common_params & params, int value) {
  3566. params.speculative.cpuparams_batch.strict_cpu = value;
  3567. }
  3568. ).set_examples({LLAMA_EXAMPLE_SPECULATIVE}));
  3569. add_opt(common_arg(
  3570. {"--prio-batch-draft"}, "N",
  3571. string_format("set draft process/thread priority : 0-normal, 1-medium, 2-high, 3-realtime (default: %d)\n", params.speculative.cpuparams_batch.priority),
  3572. [](common_params & params, int prio) {
  3573. if (prio < 0 || prio > 3) {
  3574. throw std::invalid_argument("invalid value");
  3575. }
  3576. params.speculative.cpuparams_batch.priority = (enum ggml_sched_priority) prio;
  3577. }
  3578. ).set_examples({LLAMA_EXAMPLE_SPECULATIVE}));
  3579. add_opt(common_arg(
  3580. {"--poll-batch-draft"}, "<0|1>",
  3581. "Use polling to wait for draft model work (default: --poll-draft)",
  3582. [](common_params & params, int value) {
  3583. params.speculative.cpuparams_batch.poll = value;
  3584. }
  3585. ).set_examples({LLAMA_EXAMPLE_SPECULATIVE}));
  3586. add_opt(common_arg(
  3587. {"--draft-max", "--draft", "--draft-n"}, "N",
  3588. string_format("number of tokens to draft for speculative decoding (default: %d)", params.speculative.n_max),
  3589. [](common_params & params, int value) {
  3590. params.speculative.n_max = value;
  3591. }
  3592. ).set_examples({LLAMA_EXAMPLE_SPECULATIVE, LLAMA_EXAMPLE_LOOKUP, LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_DRAFT_MAX"));
  3593. add_opt(common_arg(
  3594. {"--draft-min", "--draft-n-min"}, "N",
  3595. string_format("minimum number of draft tokens to use for speculative decoding (default: %d)", params.speculative.n_min),
  3596. [](common_params & params, int value) {
  3597. params.speculative.n_min = value;
  3598. }
  3599. ).set_examples({LLAMA_EXAMPLE_SPECULATIVE, LLAMA_EXAMPLE_LOOKUP, LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_DRAFT_MIN"));
  3600. add_opt(common_arg(
  3601. {"--draft-p-split"}, "P",
  3602. string_format("speculative decoding split probability (default: %.1f)", (double)params.speculative.p_split),
  3603. [](common_params & params, const std::string & value) {
  3604. params.speculative.p_split = std::stof(value);
  3605. }
  3606. ).set_examples({LLAMA_EXAMPLE_SPECULATIVE}).set_env("LLAMA_ARG_DRAFT_P_SPLIT"));
  3607. add_opt(common_arg(
  3608. {"--draft-p-min"}, "P",
  3609. string_format("minimum speculative decoding probability (greedy) (default: %.1f)", (double)params.speculative.p_min),
  3610. [](common_params & params, const std::string & value) {
  3611. params.speculative.p_min = std::stof(value);
  3612. }
  3613. ).set_examples({LLAMA_EXAMPLE_SPECULATIVE, LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_DRAFT_P_MIN"));
  3614. add_opt(common_arg(
  3615. {"-cd", "--ctx-size-draft"}, "N",
  3616. string_format("size of the prompt context for the draft model (default: %d, 0 = loaded from model)", params.speculative.n_ctx),
  3617. [](common_params & params, int value) {
  3618. params.speculative.n_ctx = value;
  3619. }
  3620. ).set_examples({LLAMA_EXAMPLE_SPECULATIVE, LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_CTX_SIZE_DRAFT"));
  3621. add_opt(common_arg(
  3622. {"-devd", "--device-draft"}, "<dev1,dev2,..>",
  3623. "comma-separated list of devices to use for offloading the draft model (none = don't offload)\n"
  3624. "use --list-devices to see a list of available devices",
  3625. [](common_params & params, const std::string & value) {
  3626. params.speculative.devices = parse_device_list(value);
  3627. }
  3628. ).set_examples({LLAMA_EXAMPLE_SPECULATIVE, LLAMA_EXAMPLE_SERVER}));
  3629. add_opt(common_arg(
  3630. {"-ngld", "--gpu-layers-draft", "--n-gpu-layers-draft"}, "N",
  3631. "number of layers to store in VRAM for the draft model",
  3632. [](common_params & params, int value) {
  3633. params.speculative.n_gpu_layers = value;
  3634. if (!llama_supports_gpu_offload()) {
  3635. fprintf(stderr, "warning: no usable GPU found, --gpu-layers-draft option will be ignored\n");
  3636. fprintf(stderr, "warning: one possible reason is that llama.cpp was compiled without GPU support\n");
  3637. fprintf(stderr, "warning: consult docs/build.md for compilation instructions\n");
  3638. }
  3639. }
  3640. ).set_examples({LLAMA_EXAMPLE_SPECULATIVE, LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_N_GPU_LAYERS_DRAFT"));
  3641. add_opt(common_arg(
  3642. {"-md", "--model-draft"}, "FNAME",
  3643. "draft model for speculative decoding (default: unused)",
  3644. [](common_params & params, const std::string & value) {
  3645. params.speculative.model.path = value;
  3646. }
  3647. ).set_examples({LLAMA_EXAMPLE_SPECULATIVE, LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_MODEL_DRAFT"));
  3648. add_opt(common_arg(
  3649. {"--spec-replace"}, "TARGET", "DRAFT",
  3650. "translate the string in TARGET into DRAFT if the draft model and main model are not compatible",
  3651. [](common_params & params, const std::string & tgt, const std::string & dft) {
  3652. params.speculative.replacements.push_back({ tgt, dft });
  3653. }
  3654. ).set_examples({LLAMA_EXAMPLE_SPECULATIVE, LLAMA_EXAMPLE_SERVER}));
  3655. add_opt(common_arg(
  3656. {"-ctkd", "--cache-type-k-draft"}, "TYPE",
  3657. string_format(
  3658. "KV cache data type for K for the draft model\n"
  3659. "allowed values: %s\n"
  3660. "(default: %s)",
  3661. get_all_kv_cache_types().c_str(),
  3662. ggml_type_name(params.speculative.cache_type_k)
  3663. ),
  3664. [](common_params & params, const std::string & value) {
  3665. params.speculative.cache_type_k = kv_cache_type_from_str(value);
  3666. }
  3667. ).set_env("LLAMA_ARG_CACHE_TYPE_K_DRAFT"));
  3668. add_opt(common_arg(
  3669. {"-ctvd", "--cache-type-v-draft"}, "TYPE",
  3670. string_format(
  3671. "KV cache data type for V for the draft model\n"
  3672. "allowed values: %s\n"
  3673. "(default: %s)",
  3674. get_all_kv_cache_types().c_str(),
  3675. ggml_type_name(params.speculative.cache_type_v)
  3676. ),
  3677. [](common_params & params, const std::string & value) {
  3678. params.speculative.cache_type_v = kv_cache_type_from_str(value);
  3679. }
  3680. ).set_env("LLAMA_ARG_CACHE_TYPE_V_DRAFT"));
  3681. add_opt(common_arg(
  3682. {"-mv", "--model-vocoder"}, "FNAME",
  3683. "vocoder model for audio generation (default: unused)",
  3684. [](common_params & params, const std::string & value) {
  3685. params.vocoder.model.path = value;
  3686. }
  3687. ).set_examples({LLAMA_EXAMPLE_TTS, LLAMA_EXAMPLE_SERVER}));
  3688. add_opt(common_arg(
  3689. {"--tts-use-guide-tokens"},
  3690. "Use guide tokens to improve TTS word recall",
  3691. [](common_params & params) {
  3692. params.vocoder.use_guide_tokens = true;
  3693. }
  3694. ).set_examples({LLAMA_EXAMPLE_TTS, LLAMA_EXAMPLE_SERVER}));
  3695. add_opt(common_arg(
  3696. {"--tts-speaker-file"}, "FNAME",
  3697. "speaker file path for audio generation",
  3698. [](common_params & params, const std::string & value) {
  3699. params.vocoder.speaker_file = value;
  3700. }
  3701. ).set_examples({LLAMA_EXAMPLE_TTS}));
  3702. // model-specific
  3703. add_opt(common_arg(
  3704. {"--tts-oute-default"},
  3705. string_format("use default OuteTTS models (note: can download weights from the internet)"),
  3706. [](common_params & params) {
  3707. params.model.hf_repo = "OuteAI/OuteTTS-0.2-500M-GGUF";
  3708. params.model.hf_file = "OuteTTS-0.2-500M-Q8_0.gguf";
  3709. params.vocoder.model.hf_repo = "ggml-org/WavTokenizer";
  3710. params.vocoder.model.hf_file = "WavTokenizer-Large-75-F16.gguf";
  3711. }
  3712. ).set_examples({LLAMA_EXAMPLE_TTS}));
  3713. add_opt(common_arg(
  3714. {"--embd-bge-small-en-default"},
  3715. string_format("use default bge-small-en-v1.5 model (note: can download weights from the internet)"),
  3716. [](common_params & params) {
  3717. params.model.hf_repo = "ggml-org/bge-small-en-v1.5-Q8_0-GGUF";
  3718. params.model.hf_file = "bge-small-en-v1.5-q8_0.gguf";
  3719. params.pooling_type = LLAMA_POOLING_TYPE_NONE;
  3720. params.embd_normalize = 2;
  3721. params.n_ctx = 512;
  3722. params.verbose_prompt = true;
  3723. params.embedding = true;
  3724. }
  3725. ).set_examples({LLAMA_EXAMPLE_EMBEDDING, LLAMA_EXAMPLE_SERVER}));
  3726. add_opt(common_arg(
  3727. {"--embd-e5-small-en-default"},
  3728. string_format("use default e5-small-v2 model (note: can download weights from the internet)"),
  3729. [](common_params & params) {
  3730. params.model.hf_repo = "ggml-org/e5-small-v2-Q8_0-GGUF";
  3731. params.model.hf_file = "e5-small-v2-q8_0.gguf";
  3732. params.pooling_type = LLAMA_POOLING_TYPE_NONE;
  3733. params.embd_normalize = 2;
  3734. params.n_ctx = 512;
  3735. params.verbose_prompt = true;
  3736. params.embedding = true;
  3737. }
  3738. ).set_examples({LLAMA_EXAMPLE_EMBEDDING, LLAMA_EXAMPLE_SERVER}));
  3739. add_opt(common_arg(
  3740. {"--embd-gte-small-default"},
  3741. string_format("use default gte-small model (note: can download weights from the internet)"),
  3742. [](common_params & params) {
  3743. params.model.hf_repo = "ggml-org/gte-small-Q8_0-GGUF";
  3744. params.model.hf_file = "gte-small-q8_0.gguf";
  3745. params.pooling_type = LLAMA_POOLING_TYPE_NONE;
  3746. params.embd_normalize = 2;
  3747. params.n_ctx = 512;
  3748. params.verbose_prompt = true;
  3749. params.embedding = true;
  3750. }
  3751. ).set_examples({LLAMA_EXAMPLE_EMBEDDING, LLAMA_EXAMPLE_SERVER}));
  3752. add_opt(common_arg(
  3753. {"--fim-qwen-1.5b-default"},
  3754. string_format("use default Qwen 2.5 Coder 1.5B (note: can download weights from the internet)"),
  3755. [](common_params & params) {
  3756. params.model.hf_repo = "ggml-org/Qwen2.5-Coder-1.5B-Q8_0-GGUF";
  3757. params.model.hf_file = "qwen2.5-coder-1.5b-q8_0.gguf";
  3758. params.port = 8012;
  3759. params.n_ubatch = 1024;
  3760. params.n_batch = 1024;
  3761. params.n_ctx = 0;
  3762. params.n_cache_reuse = 256;
  3763. }
  3764. ).set_examples({LLAMA_EXAMPLE_SERVER}));
  3765. add_opt(common_arg(
  3766. {"--fim-qwen-3b-default"},
  3767. string_format("use default Qwen 2.5 Coder 3B (note: can download weights from the internet)"),
  3768. [](common_params & params) {
  3769. params.model.hf_repo = "ggml-org/Qwen2.5-Coder-3B-Q8_0-GGUF";
  3770. params.model.hf_file = "qwen2.5-coder-3b-q8_0.gguf";
  3771. params.port = 8012;
  3772. params.n_ubatch = 1024;
  3773. params.n_batch = 1024;
  3774. params.n_ctx = 0;
  3775. params.n_cache_reuse = 256;
  3776. }
  3777. ).set_examples({LLAMA_EXAMPLE_SERVER}));
  3778. add_opt(common_arg(
  3779. {"--fim-qwen-7b-default"},
  3780. string_format("use default Qwen 2.5 Coder 7B (note: can download weights from the internet)"),
  3781. [](common_params & params) {
  3782. params.model.hf_repo = "ggml-org/Qwen2.5-Coder-7B-Q8_0-GGUF";
  3783. params.model.hf_file = "qwen2.5-coder-7b-q8_0.gguf";
  3784. params.port = 8012;
  3785. params.n_ubatch = 1024;
  3786. params.n_batch = 1024;
  3787. params.n_ctx = 0;
  3788. params.n_cache_reuse = 256;
  3789. }
  3790. ).set_examples({LLAMA_EXAMPLE_SERVER}));
  3791. add_opt(common_arg(
  3792. {"--fim-qwen-7b-spec"},
  3793. string_format("use Qwen 2.5 Coder 7B + 0.5B draft for speculative decoding (note: can download weights from the internet)"),
  3794. [](common_params & params) {
  3795. params.model.hf_repo = "ggml-org/Qwen2.5-Coder-7B-Q8_0-GGUF";
  3796. params.model.hf_file = "qwen2.5-coder-7b-q8_0.gguf";
  3797. params.speculative.model.hf_repo = "ggml-org/Qwen2.5-Coder-0.5B-Q8_0-GGUF";
  3798. params.speculative.model.hf_file = "qwen2.5-coder-0.5b-q8_0.gguf";
  3799. params.port = 8012;
  3800. params.n_ubatch = 1024;
  3801. params.n_batch = 1024;
  3802. params.n_ctx = 0;
  3803. params.n_cache_reuse = 256;
  3804. }
  3805. ).set_examples({LLAMA_EXAMPLE_SERVER}));
  3806. add_opt(common_arg(
  3807. {"--fim-qwen-14b-spec"},
  3808. string_format("use Qwen 2.5 Coder 14B + 0.5B draft for speculative decoding (note: can download weights from the internet)"),
  3809. [](common_params & params) {
  3810. params.model.hf_repo = "ggml-org/Qwen2.5-Coder-14B-Q8_0-GGUF";
  3811. params.model.hf_file = "qwen2.5-coder-14b-q8_0.gguf";
  3812. params.speculative.model.hf_repo = "ggml-org/Qwen2.5-Coder-0.5B-Q8_0-GGUF";
  3813. params.speculative.model.hf_file = "qwen2.5-coder-0.5b-q8_0.gguf";
  3814. params.port = 8012;
  3815. params.n_ubatch = 1024;
  3816. params.n_batch = 1024;
  3817. params.n_ctx = 0;
  3818. params.n_cache_reuse = 256;
  3819. }
  3820. ).set_examples({LLAMA_EXAMPLE_SERVER}));
  3821. add_opt(common_arg(
  3822. {"--fim-qwen-30b-default"},
  3823. string_format("use default Qwen 3 Coder 30B A3B Instruct (note: can download weights from the internet)"),
  3824. [](common_params & params) {
  3825. params.model.hf_repo = "ggml-org/Qwen3-Coder-30B-A3B-Instruct-Q8_0-GGUF";
  3826. params.model.hf_file = "qwen3-coder-30b-a3b-instruct-q8_0.gguf";
  3827. params.port = 8012;
  3828. params.n_ubatch = 1024;
  3829. params.n_batch = 1024;
  3830. params.n_ctx = 0;
  3831. params.n_cache_reuse = 256;
  3832. }
  3833. ).set_examples({LLAMA_EXAMPLE_SERVER}));
  3834. add_opt(common_arg(
  3835. { "--diffusion-steps" }, "N",
  3836. string_format("number of diffusion steps (default: %d)", params.diffusion.steps),
  3837. [](common_params & params, int value) { params.diffusion.steps = value; }
  3838. ).set_examples({ LLAMA_EXAMPLE_DIFFUSION }));
  3839. add_opt(common_arg(
  3840. { "--diffusion-visual" },
  3841. string_format("enable visual diffusion mode (show progressive generation) (default: %s)",
  3842. params.diffusion.visual_mode ? "true" : "false"),
  3843. [](common_params & params) { params.diffusion.visual_mode = true; }
  3844. ).set_examples({ LLAMA_EXAMPLE_DIFFUSION }));
  3845. add_opt(common_arg(
  3846. { "--diffusion-eps" }, "F",
  3847. string_format("epsilon for timesteps (default: %.6f)", (double) params.diffusion.eps),
  3848. [](common_params & params, const std::string & value) { params.diffusion.eps = std::stof(value); }
  3849. ).set_examples({ LLAMA_EXAMPLE_DIFFUSION }));
  3850. add_opt(common_arg(
  3851. { "--diffusion-algorithm" }, "N",
  3852. string_format("diffusion algorithm: 0=ORIGIN, 1=ENTROPY_BASED, 2=MARGIN_BASED, 3=RANDOM, 4=LOW_CONFIDENCE (default: %d)",
  3853. params.diffusion.algorithm),
  3854. [](common_params & params, int value) { params.diffusion.algorithm = value; }
  3855. ).set_examples({ LLAMA_EXAMPLE_DIFFUSION }));
  3856. add_opt(common_arg(
  3857. { "--diffusion-alg-temp" }, "F",
  3858. string_format("dream algorithm temperature (default: %.3f)", (double) params.diffusion.alg_temp),
  3859. [](common_params & params, const std::string & value) { params.diffusion.alg_temp = std::stof(value); }
  3860. ).set_examples({ LLAMA_EXAMPLE_DIFFUSION }));
  3861. add_opt(common_arg(
  3862. { "--diffusion-block-length" }, "N",
  3863. string_format("llada block length for generation (default: %d)", params.diffusion.block_length),
  3864. [](common_params & params, int value) { params.diffusion.block_length = value; }
  3865. ).set_examples({ LLAMA_EXAMPLE_DIFFUSION }));
  3866. add_opt(common_arg(
  3867. { "--diffusion-cfg-scale" }, "F",
  3868. string_format("llada classifier-free guidance scale (default: %.3f)", (double) params.diffusion.cfg_scale),
  3869. [](common_params & params, const std::string & value) { params.diffusion.cfg_scale = std::stof(value); }
  3870. ).set_examples({ LLAMA_EXAMPLE_DIFFUSION }));
  3871. add_opt(common_arg(
  3872. { "--diffusion-add-gumbel-noise" }, "F",
  3873. string_format("add gumbel noise to the logits if temp > 0.0 (default: %s)", params.diffusion.add_gumbel_noise ? "true" : "false"),
  3874. [](common_params & params, const std::string & value) { params.diffusion.add_gumbel_noise = std::stof(value); }
  3875. ).set_examples({ LLAMA_EXAMPLE_DIFFUSION }));
  3876. add_opt(
  3877. common_arg({ "-lr", "--learning-rate" }, "ALPHA",
  3878. string_format(
  3879. "adamw or sgd optimizer alpha (default: %.2g); note: sgd alpha recommended ~10x (no momentum)",
  3880. (double) params.lr.lr0),
  3881. [](common_params & params, const std::string & value) { params.lr.lr0 = std::stof(value); })
  3882. .set_examples({ LLAMA_EXAMPLE_FINETUNE }));
  3883. add_opt(
  3884. common_arg({ "-lr-min", "--learning-rate-min" }, "ALPHA",
  3885. string_format(
  3886. "(if >0) final learning rate after decay (if -decay-epochs is set, default=%.2g)",
  3887. (double) params.lr.lr_min),
  3888. [](common_params & params, const std::string & value) { params.lr.lr_min = std::stof(value); })
  3889. .set_examples({ LLAMA_EXAMPLE_FINETUNE }));
  3890. add_opt(
  3891. common_arg({ "-decay-epochs", "--learning-rate-decay-epochs" }, "ALPHA",
  3892. string_format(
  3893. "(if >0) decay learning rate to -lr-min after this many epochs (exponential decay, default=%.2g)",
  3894. (double) params.lr.decay_epochs),
  3895. [](common_params & params, const std::string & value) { params.lr.decay_epochs = std::stof(value); })
  3896. .set_examples({ LLAMA_EXAMPLE_FINETUNE }));
  3897. add_opt(common_arg(
  3898. { "-wd", "--weight-decay" }, "WD",
  3899. string_format(
  3900. "adamw or sgd optimizer weight decay (0 is off; recommend very small e.g. 1e-9) (default: %.2g).",
  3901. (double) params.lr.wd),
  3902. [](common_params & params, const std::string & value) { params.lr.wd = std::stof(value); })
  3903. .set_examples({ LLAMA_EXAMPLE_FINETUNE }));
  3904. add_opt(common_arg({ "-val-split", "--val-split" }, "FRACTION",
  3905. string_format("fraction of data to use as validation set for training (default: %.2g).",
  3906. (double) params.val_split),
  3907. [](common_params & params, const std::string & value) { params.val_split = std::stof(value); })
  3908. .set_examples({ LLAMA_EXAMPLE_FINETUNE }));
  3909. add_opt(common_arg({ "-epochs", "--epochs" }, "N",
  3910. string_format("optimizer max # of epochs (default: %d)", params.lr.epochs),
  3911. [](common_params & params, int epochs) { params.lr.epochs = epochs; })
  3912. .set_examples({ LLAMA_EXAMPLE_FINETUNE }));
  3913. add_opt(common_arg({ "-opt", "--optimizer" }, "sgd|adamw", "adamw or sgd",
  3914. [](common_params & params, const std::string & name) {
  3915. params.optimizer = common_opt_get_optimizer(name.c_str());
  3916. if (params.optimizer == GGML_OPT_OPTIMIZER_TYPE_COUNT) {
  3917. throw std::invalid_argument("invalid --optimizer, valid options: adamw, sgd");
  3918. }
  3919. })
  3920. .set_examples({ LLAMA_EXAMPLE_FINETUNE }));
  3921. return ctx_arg;
  3922. }