arg.cpp 149 KB

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