1
0

arg.cpp 144 KB

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