arg.cpp 174 KB

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