arg.cpp 135 KB

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