arg.cpp 173 KB

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