arg.cpp 135 KB

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