1
0

arg.cpp 139 KB

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