arg.cpp 136 KB

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