arg.cpp 174 KB

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