arg.cpp 158 KB

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