arg.cpp 136 KB

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