arg.cpp 174 KB

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