arg.cpp 165 KB

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