arg.cpp 162 KB

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