arg.cpp 137 KB

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