arg.cpp 150 KB

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