arg.cpp 135 KB

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