arg.cpp 165 KB

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