arg.cpp 142 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379
  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. }
  848. if (!params.kv_overrides.empty()) {
  849. params.kv_overrides.emplace_back();
  850. params.kv_overrides.back().key[0] = 0;
  851. }
  852. if (!params.tensor_buft_overrides.empty()) {
  853. params.tensor_buft_overrides.push_back({nullptr, nullptr});
  854. }
  855. if (params.reranking && params.embedding) {
  856. throw std::invalid_argument("error: either --embedding or --reranking can be specified, but not both");
  857. }
  858. if (!params.chat_template.empty() && !common_chat_verify_template(params.chat_template, params.use_jinja)) {
  859. throw std::runtime_error(string_format(
  860. "error: the supplied chat template is not supported: %s%s\n",
  861. params.chat_template.c_str(),
  862. params.use_jinja ? "" : "\nnote: llama.cpp was started without --jinja, we only support commonly used templates"
  863. ));
  864. }
  865. return true;
  866. }
  867. static void common_params_print_usage(common_params_context & ctx_arg) {
  868. auto print_options = [](std::vector<common_arg *> & options) {
  869. for (common_arg * opt : options) {
  870. printf("%s", opt->to_string().c_str());
  871. }
  872. };
  873. std::vector<common_arg *> common_options;
  874. std::vector<common_arg *> sparam_options;
  875. std::vector<common_arg *> specific_options;
  876. for (auto & opt : ctx_arg.options) {
  877. // in case multiple LLAMA_EXAMPLE_* are set, we prioritize the LLAMA_EXAMPLE_* matching current example
  878. if (opt.is_sparam) {
  879. sparam_options.push_back(&opt);
  880. } else if (opt.in_example(ctx_arg.ex)) {
  881. specific_options.push_back(&opt);
  882. } else {
  883. common_options.push_back(&opt);
  884. }
  885. }
  886. printf("----- common params -----\n\n");
  887. print_options(common_options);
  888. printf("\n\n----- sampling params -----\n\n");
  889. print_options(sparam_options);
  890. // TODO: maybe convert enum llama_example to string
  891. printf("\n\n----- example-specific params -----\n\n");
  892. print_options(specific_options);
  893. }
  894. static void common_params_print_completion(common_params_context & ctx_arg) {
  895. std::vector<common_arg *> common_options;
  896. std::vector<common_arg *> sparam_options;
  897. std::vector<common_arg *> specific_options;
  898. for (auto & opt : ctx_arg.options) {
  899. if (opt.is_sparam) {
  900. sparam_options.push_back(&opt);
  901. } else if (opt.in_example(ctx_arg.ex)) {
  902. specific_options.push_back(&opt);
  903. } else {
  904. common_options.push_back(&opt);
  905. }
  906. }
  907. printf("_llama_completions() {\n");
  908. printf(" local cur prev opts\n");
  909. printf(" COMPREPLY=()\n");
  910. printf(" cur=\"${COMP_WORDS[COMP_CWORD]}\"\n");
  911. printf(" prev=\"${COMP_WORDS[COMP_CWORD-1]}\"\n\n");
  912. printf(" opts=\"");
  913. auto print_options = [](const std::vector<common_arg *> & options) {
  914. for (const common_arg * opt : options) {
  915. for (const char * arg : opt->args) {
  916. printf("%s ", arg);
  917. }
  918. }
  919. };
  920. print_options(common_options);
  921. print_options(sparam_options);
  922. print_options(specific_options);
  923. printf("\"\n\n");
  924. printf(" case \"$prev\" in\n");
  925. printf(" --model)\n");
  926. printf(" COMPREPLY=( $(compgen -f -X '!*.gguf' -- \"$cur\") $(compgen -d -- \"$cur\") )\n");
  927. printf(" return 0\n");
  928. printf(" ;;\n");
  929. printf(" --grammar-file)\n");
  930. printf(" COMPREPLY=( $(compgen -f -X '!*.gbnf' -- \"$cur\") $(compgen -d -- \"$cur\") )\n");
  931. printf(" return 0\n");
  932. printf(" ;;\n");
  933. printf(" --chat-template-file)\n");
  934. printf(" COMPREPLY=( $(compgen -f -X '!*.jinja' -- \"$cur\") $(compgen -d -- \"$cur\") )\n");
  935. printf(" return 0\n");
  936. printf(" ;;\n");
  937. printf(" *)\n");
  938. printf(" COMPREPLY=( $(compgen -W \"${opts}\" -- \"$cur\") )\n");
  939. printf(" return 0\n");
  940. printf(" ;;\n");
  941. printf(" esac\n");
  942. printf("}\n\n");
  943. std::set<std::string> executables = {
  944. "llama-batched",
  945. "llama-batched-bench",
  946. "llama-bench",
  947. "llama-cli",
  948. "llama-convert-llama2c-to-ggml",
  949. "llama-cvector-generator",
  950. "llama-embedding",
  951. "llama-eval-callback",
  952. "llama-export-lora",
  953. "llama-gen-docs",
  954. "llama-gguf",
  955. "llama-gguf-hash",
  956. "llama-gguf-split",
  957. "llama-gritlm",
  958. "llama-imatrix",
  959. "llama-infill",
  960. "llama-mtmd-cli",
  961. "llama-llava-clip-quantize-cli",
  962. "llama-lookahead",
  963. "llama-lookup",
  964. "llama-lookup-create",
  965. "llama-lookup-merge",
  966. "llama-lookup-stats",
  967. "llama-parallel",
  968. "llama-passkey",
  969. "llama-perplexity",
  970. "llama-q8dot",
  971. "llama-quantize",
  972. "llama-qwen2vl-cli",
  973. "llama-retrieval",
  974. "llama-run",
  975. "llama-save-load-state",
  976. "llama-server",
  977. "llama-simple",
  978. "llama-simple-chat",
  979. "llama-speculative",
  980. "llama-speculative-simple",
  981. "llama-tokenize",
  982. "llama-tts",
  983. "llama-vdot"
  984. };
  985. for (const auto& exe : executables) {
  986. printf("complete -F _llama_completions %s\n", exe.c_str());
  987. }
  988. }
  989. static std::vector<ggml_backend_dev_t> parse_device_list(const std::string & value) {
  990. std::vector<ggml_backend_dev_t> devices;
  991. auto dev_names = string_split<std::string>(value, ',');
  992. if (dev_names.empty()) {
  993. throw std::invalid_argument("no devices specified");
  994. }
  995. if (dev_names.size() == 1 && dev_names[0] == "none") {
  996. devices.push_back(nullptr);
  997. } else {
  998. for (const auto & device : dev_names) {
  999. auto * dev = ggml_backend_dev_by_name(device.c_str());
  1000. if (!dev || ggml_backend_dev_type(dev) != GGML_BACKEND_DEVICE_TYPE_GPU) {
  1001. throw std::invalid_argument(string_format("invalid device: %s", device.c_str()));
  1002. }
  1003. devices.push_back(dev);
  1004. }
  1005. devices.push_back(nullptr);
  1006. }
  1007. return devices;
  1008. }
  1009. static void add_rpc_devices(std::string servers) {
  1010. auto rpc_servers = string_split<std::string>(servers, ',');
  1011. if (rpc_servers.empty()) {
  1012. throw std::invalid_argument("no RPC servers specified");
  1013. }
  1014. ggml_backend_reg_t rpc_reg = ggml_backend_reg_by_name("RPC");
  1015. if (!rpc_reg) {
  1016. throw std::invalid_argument("failed to find RPC backend");
  1017. }
  1018. typedef ggml_backend_dev_t (*ggml_backend_rpc_add_device_t)(const char * endpoint);
  1019. 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");
  1020. if (!ggml_backend_rpc_add_device_fn) {
  1021. throw std::invalid_argument("failed to find RPC device add function");
  1022. }
  1023. for (const auto & server : rpc_servers) {
  1024. ggml_backend_dev_t dev = ggml_backend_rpc_add_device_fn(server.c_str());
  1025. if (dev) {
  1026. ggml_backend_device_register(dev);
  1027. } else {
  1028. throw std::invalid_argument("failed to register RPC device");
  1029. }
  1030. }
  1031. }
  1032. bool common_params_parse(int argc, char ** argv, common_params & params, llama_example ex, void(*print_usage)(int, char **)) {
  1033. auto ctx_arg = common_params_parser_init(params, ex, print_usage);
  1034. const common_params params_org = ctx_arg.params; // the example can modify the default params
  1035. try {
  1036. if (!common_params_parse_ex(argc, argv, ctx_arg)) {
  1037. ctx_arg.params = params_org;
  1038. return false;
  1039. }
  1040. if (ctx_arg.params.usage) {
  1041. common_params_print_usage(ctx_arg);
  1042. if (ctx_arg.print_usage) {
  1043. ctx_arg.print_usage(argc, argv);
  1044. }
  1045. exit(0);
  1046. }
  1047. if (ctx_arg.params.completion) {
  1048. common_params_print_completion(ctx_arg);
  1049. exit(0);
  1050. }
  1051. } catch (const std::invalid_argument & ex) {
  1052. fprintf(stderr, "%s\n", ex.what());
  1053. ctx_arg.params = params_org;
  1054. return false;
  1055. } catch (std::exception & ex) {
  1056. fprintf(stderr, "%s\n", ex.what());
  1057. exit(1); // for other exceptions, we exit with status code 1
  1058. }
  1059. return true;
  1060. }
  1061. static std::string list_builtin_chat_templates() {
  1062. std::vector<const char *> supported_tmpl;
  1063. int32_t res = llama_chat_builtin_templates(nullptr, 0);
  1064. supported_tmpl.resize(res);
  1065. res = llama_chat_builtin_templates(supported_tmpl.data(), supported_tmpl.size());
  1066. std::ostringstream msg;
  1067. for (auto & tmpl : supported_tmpl) {
  1068. msg << tmpl << (&tmpl == &supported_tmpl.back() ? "" : ", ");
  1069. }
  1070. return msg.str();
  1071. }
  1072. common_params_context common_params_parser_init(common_params & params, llama_example ex, void(*print_usage)(int, char **)) {
  1073. // load dynamic backends
  1074. ggml_backend_load_all();
  1075. common_params_context ctx_arg(params);
  1076. ctx_arg.print_usage = print_usage;
  1077. ctx_arg.ex = ex;
  1078. std::string sampler_type_chars;
  1079. std::string sampler_type_names;
  1080. for (const auto & sampler : params.sampling.samplers) {
  1081. sampler_type_chars += common_sampler_type_to_chr(sampler);
  1082. sampler_type_names += common_sampler_type_to_str(sampler) + ";";
  1083. }
  1084. sampler_type_names.pop_back();
  1085. /**
  1086. * filter options by example
  1087. * rules:
  1088. * - all examples inherit options from LLAMA_EXAMPLE_COMMON
  1089. * - if LLAMA_EXAMPLE_* is set (other than COMMON), we only show the option in the corresponding example
  1090. * - if both {LLAMA_EXAMPLE_COMMON, LLAMA_EXAMPLE_*,} are set, we will prioritize the LLAMA_EXAMPLE_* matching current example
  1091. */
  1092. auto add_opt = [&](common_arg arg) {
  1093. if ((arg.in_example(ex) || arg.in_example(LLAMA_EXAMPLE_COMMON)) && !arg.is_exclude(ex)) {
  1094. ctx_arg.options.push_back(std::move(arg));
  1095. }
  1096. };
  1097. add_opt(common_arg(
  1098. {"-h", "--help", "--usage"},
  1099. "print usage and exit",
  1100. [](common_params & params) {
  1101. params.usage = true;
  1102. }
  1103. ));
  1104. add_opt(common_arg(
  1105. {"--version"},
  1106. "show version and build info",
  1107. [](common_params &) {
  1108. fprintf(stderr, "version: %d (%s)\n", LLAMA_BUILD_NUMBER, LLAMA_COMMIT);
  1109. fprintf(stderr, "built with %s for %s\n", LLAMA_COMPILER, LLAMA_BUILD_TARGET);
  1110. exit(0);
  1111. }
  1112. ));
  1113. add_opt(common_arg(
  1114. {"--completion-bash"},
  1115. "print source-able bash completion script for llama.cpp",
  1116. [](common_params & params) {
  1117. params.completion = true;
  1118. }
  1119. ));
  1120. add_opt(common_arg(
  1121. {"--verbose-prompt"},
  1122. string_format("print a verbose prompt before generation (default: %s)", params.verbose_prompt ? "true" : "false"),
  1123. [](common_params & params) {
  1124. params.verbose_prompt = true;
  1125. }
  1126. ));
  1127. add_opt(common_arg(
  1128. {"--no-display-prompt"},
  1129. string_format("don't print prompt at generation (default: %s)", !params.display_prompt ? "true" : "false"),
  1130. [](common_params & params) {
  1131. params.display_prompt = false;
  1132. }
  1133. ).set_examples({LLAMA_EXAMPLE_MAIN}));
  1134. add_opt(common_arg(
  1135. {"-co", "--color"},
  1136. string_format("colorise output to distinguish prompt and user input from generations (default: %s)", params.use_color ? "true" : "false"),
  1137. [](common_params & params) {
  1138. params.use_color = true;
  1139. }
  1140. ).set_examples({LLAMA_EXAMPLE_MAIN, LLAMA_EXAMPLE_SPECULATIVE, LLAMA_EXAMPLE_LOOKUP}));
  1141. add_opt(common_arg(
  1142. {"-t", "--threads"}, "N",
  1143. string_format("number of threads to use during generation (default: %d)", params.cpuparams.n_threads),
  1144. [](common_params & params, int value) {
  1145. params.cpuparams.n_threads = value;
  1146. if (params.cpuparams.n_threads <= 0) {
  1147. params.cpuparams.n_threads = std::thread::hardware_concurrency();
  1148. }
  1149. }
  1150. ).set_env("LLAMA_ARG_THREADS"));
  1151. add_opt(common_arg(
  1152. {"-tb", "--threads-batch"}, "N",
  1153. "number of threads to use during batch and prompt processing (default: same as --threads)",
  1154. [](common_params & params, int value) {
  1155. params.cpuparams_batch.n_threads = value;
  1156. if (params.cpuparams_batch.n_threads <= 0) {
  1157. params.cpuparams_batch.n_threads = std::thread::hardware_concurrency();
  1158. }
  1159. }
  1160. ));
  1161. add_opt(common_arg(
  1162. {"-C", "--cpu-mask"}, "M",
  1163. "CPU affinity mask: arbitrarily long hex. Complements cpu-range (default: \"\")",
  1164. [](common_params & params, const std::string & mask) {
  1165. params.cpuparams.mask_valid = true;
  1166. if (!parse_cpu_mask(mask, params.cpuparams.cpumask)) {
  1167. throw std::invalid_argument("invalid cpumask");
  1168. }
  1169. }
  1170. ));
  1171. add_opt(common_arg(
  1172. {"-Cr", "--cpu-range"}, "lo-hi",
  1173. "range of CPUs for affinity. Complements --cpu-mask",
  1174. [](common_params & params, const std::string & range) {
  1175. params.cpuparams.mask_valid = true;
  1176. if (!parse_cpu_range(range, params.cpuparams.cpumask)) {
  1177. throw std::invalid_argument("invalid range");
  1178. }
  1179. }
  1180. ));
  1181. add_opt(common_arg(
  1182. {"--cpu-strict"}, "<0|1>",
  1183. string_format("use strict CPU placement (default: %u)\n", (unsigned) params.cpuparams.strict_cpu),
  1184. [](common_params & params, const std::string & value) {
  1185. params.cpuparams.strict_cpu = std::stoul(value);
  1186. }
  1187. ));
  1188. add_opt(common_arg(
  1189. {"--prio"}, "N",
  1190. string_format("set process/thread priority : 0-normal, 1-medium, 2-high, 3-realtime (default: %d)\n", params.cpuparams.priority),
  1191. [](common_params & params, int prio) {
  1192. if (prio < 0 || prio > 3) {
  1193. throw std::invalid_argument("invalid value");
  1194. }
  1195. params.cpuparams.priority = (enum ggml_sched_priority) prio;
  1196. }
  1197. ));
  1198. add_opt(common_arg(
  1199. {"--poll"}, "<0...100>",
  1200. string_format("use polling level to wait for work (0 - no polling, default: %u)\n", (unsigned) params.cpuparams.poll),
  1201. [](common_params & params, const std::string & value) {
  1202. params.cpuparams.poll = std::stoul(value);
  1203. }
  1204. ));
  1205. add_opt(common_arg(
  1206. {"-Cb", "--cpu-mask-batch"}, "M",
  1207. "CPU affinity mask: arbitrarily long hex. Complements cpu-range-batch (default: same as --cpu-mask)",
  1208. [](common_params & params, const std::string & mask) {
  1209. params.cpuparams_batch.mask_valid = true;
  1210. if (!parse_cpu_mask(mask, params.cpuparams_batch.cpumask)) {
  1211. throw std::invalid_argument("invalid cpumask");
  1212. }
  1213. }
  1214. ));
  1215. add_opt(common_arg(
  1216. {"-Crb", "--cpu-range-batch"}, "lo-hi",
  1217. "ranges of CPUs for affinity. Complements --cpu-mask-batch",
  1218. [](common_params & params, const std::string & range) {
  1219. params.cpuparams_batch.mask_valid = true;
  1220. if (!parse_cpu_range(range, params.cpuparams_batch.cpumask)) {
  1221. throw std::invalid_argument("invalid range");
  1222. }
  1223. }
  1224. ));
  1225. add_opt(common_arg(
  1226. {"--cpu-strict-batch"}, "<0|1>",
  1227. "use strict CPU placement (default: same as --cpu-strict)",
  1228. [](common_params & params, int value) {
  1229. params.cpuparams_batch.strict_cpu = value;
  1230. }
  1231. ));
  1232. add_opt(common_arg(
  1233. {"--prio-batch"}, "N",
  1234. string_format("set process/thread priority : 0-normal, 1-medium, 2-high, 3-realtime (default: %d)\n", params.cpuparams_batch.priority),
  1235. [](common_params & params, int prio) {
  1236. if (prio < 0 || prio > 3) {
  1237. throw std::invalid_argument("invalid value");
  1238. }
  1239. params.cpuparams_batch.priority = (enum ggml_sched_priority) prio;
  1240. }
  1241. ));
  1242. add_opt(common_arg(
  1243. {"--poll-batch"}, "<0|1>",
  1244. "use polling to wait for work (default: same as --poll)",
  1245. [](common_params & params, int value) {
  1246. params.cpuparams_batch.poll = value;
  1247. }
  1248. ));
  1249. add_opt(common_arg(
  1250. {"-lcs", "--lookup-cache-static"}, "FNAME",
  1251. "path to static lookup cache to use for lookup decoding (not updated by generation)",
  1252. [](common_params & params, const std::string & value) {
  1253. params.lookup_cache_static = value;
  1254. }
  1255. ).set_examples({LLAMA_EXAMPLE_LOOKUP}));
  1256. add_opt(common_arg(
  1257. {"-lcd", "--lookup-cache-dynamic"}, "FNAME",
  1258. "path to dynamic lookup cache to use for lookup decoding (updated by generation)",
  1259. [](common_params & params, const std::string & value) {
  1260. params.lookup_cache_dynamic = value;
  1261. }
  1262. ).set_examples({LLAMA_EXAMPLE_LOOKUP}));
  1263. add_opt(common_arg(
  1264. {"-c", "--ctx-size"}, "N",
  1265. string_format("size of the prompt context (default: %d, 0 = loaded from model)", params.n_ctx),
  1266. [](common_params & params, int value) {
  1267. params.n_ctx = value;
  1268. }
  1269. ).set_env("LLAMA_ARG_CTX_SIZE"));
  1270. add_opt(common_arg(
  1271. {"-n", "--predict", "--n-predict"}, "N",
  1272. string_format(
  1273. ex == LLAMA_EXAMPLE_MAIN
  1274. ? "number of tokens to predict (default: %d, -1 = infinity, -2 = until context filled)"
  1275. : "number of tokens to predict (default: %d, -1 = infinity)",
  1276. params.n_predict),
  1277. [](common_params & params, int value) {
  1278. params.n_predict = value;
  1279. }
  1280. ).set_env("LLAMA_ARG_N_PREDICT"));
  1281. add_opt(common_arg(
  1282. {"-b", "--batch-size"}, "N",
  1283. string_format("logical maximum batch size (default: %d)", params.n_batch),
  1284. [](common_params & params, int value) {
  1285. params.n_batch = value;
  1286. }
  1287. ).set_env("LLAMA_ARG_BATCH"));
  1288. add_opt(common_arg(
  1289. {"-ub", "--ubatch-size"}, "N",
  1290. string_format("physical maximum batch size (default: %d)", params.n_ubatch),
  1291. [](common_params & params, int value) {
  1292. params.n_ubatch = value;
  1293. }
  1294. ).set_env("LLAMA_ARG_UBATCH"));
  1295. add_opt(common_arg(
  1296. {"--keep"}, "N",
  1297. string_format("number of tokens to keep from the initial prompt (default: %d, -1 = all)", params.n_keep),
  1298. [](common_params & params, int value) {
  1299. params.n_keep = value;
  1300. }
  1301. ));
  1302. add_opt(common_arg(
  1303. {"--swa-full"},
  1304. string_format("use full-size SWA cache (default: %s)\n"
  1305. "[(more info)](https://github.com/ggml-org/llama.cpp/pull/13194#issuecomment-2868343055)", params.swa_full ? "true" : "false"),
  1306. [](common_params & params) {
  1307. params.swa_full = true;
  1308. }
  1309. ).set_env("LLAMA_ARG_SWA_FULL"));
  1310. add_opt(common_arg(
  1311. {"--no-context-shift"},
  1312. string_format("disables context shift on infinite text generation (default: %s)", params.ctx_shift ? "disabled" : "enabled"),
  1313. [](common_params & params) {
  1314. params.ctx_shift = false;
  1315. }
  1316. ).set_examples({LLAMA_EXAMPLE_MAIN, LLAMA_EXAMPLE_SERVER, LLAMA_EXAMPLE_IMATRIX, LLAMA_EXAMPLE_PERPLEXITY}).set_env("LLAMA_ARG_NO_CONTEXT_SHIFT"));
  1317. add_opt(common_arg(
  1318. {"--chunks"}, "N",
  1319. string_format("max number of chunks to process (default: %d, -1 = all)", params.n_chunks),
  1320. [](common_params & params, int value) {
  1321. params.n_chunks = value;
  1322. }
  1323. ).set_examples({LLAMA_EXAMPLE_IMATRIX, LLAMA_EXAMPLE_PERPLEXITY, LLAMA_EXAMPLE_RETRIEVAL}));
  1324. add_opt(common_arg(
  1325. {"-fa", "--flash-attn"},
  1326. string_format("enable Flash Attention (default: %s)", params.flash_attn ? "enabled" : "disabled"),
  1327. [](common_params & params) {
  1328. params.flash_attn = true;
  1329. }
  1330. ).set_env("LLAMA_ARG_FLASH_ATTN"));
  1331. add_opt(common_arg(
  1332. {"-p", "--prompt"}, "PROMPT",
  1333. "prompt to start generation with; for system message, use -sys",
  1334. [](common_params & params, const std::string & value) {
  1335. params.prompt = value;
  1336. }
  1337. ).set_excludes({LLAMA_EXAMPLE_SERVER}));
  1338. add_opt(common_arg(
  1339. {"-sys", "--system-prompt"}, "PROMPT",
  1340. "system prompt to use with model (if applicable, depending on chat template)",
  1341. [](common_params & params, const std::string & value) {
  1342. params.system_prompt = value;
  1343. }
  1344. ).set_examples({LLAMA_EXAMPLE_MAIN}));
  1345. add_opt(common_arg(
  1346. {"--no-perf"},
  1347. string_format("disable internal libllama performance timings (default: %s)", params.no_perf ? "true" : "false"),
  1348. [](common_params & params) {
  1349. params.no_perf = true;
  1350. params.sampling.no_perf = true;
  1351. }
  1352. ).set_env("LLAMA_ARG_NO_PERF"));
  1353. add_opt(common_arg(
  1354. {"-f", "--file"}, "FNAME",
  1355. "a file containing the prompt (default: none)",
  1356. [](common_params & params, const std::string & value) {
  1357. params.prompt = read_file(value);
  1358. // store the external file name in params
  1359. params.prompt_file = value;
  1360. if (!params.prompt.empty() && params.prompt.back() == '\n') {
  1361. params.prompt.pop_back();
  1362. }
  1363. }
  1364. ).set_excludes({LLAMA_EXAMPLE_SERVER}));
  1365. add_opt(common_arg(
  1366. {"-sysf", "--system-prompt-file"}, "FNAME",
  1367. "a file containing the system prompt (default: none)",
  1368. [](common_params & params, const std::string & value) {
  1369. params.system_prompt = read_file(value);
  1370. if (!params.system_prompt.empty() && params.system_prompt.back() == '\n') {
  1371. params.system_prompt.pop_back();
  1372. }
  1373. }
  1374. ).set_examples({LLAMA_EXAMPLE_MAIN}));
  1375. add_opt(common_arg(
  1376. {"--in-file"}, "FNAME",
  1377. "an input file (repeat to specify multiple files)",
  1378. [](common_params & params, const std::string & value) {
  1379. std::ifstream file(value);
  1380. if (!file) {
  1381. throw std::runtime_error(string_format("error: failed to open file '%s'\n", value.c_str()));
  1382. }
  1383. params.in_files.push_back(value);
  1384. }
  1385. ).set_examples({LLAMA_EXAMPLE_IMATRIX}));
  1386. add_opt(common_arg(
  1387. {"-bf", "--binary-file"}, "FNAME",
  1388. "binary file containing the prompt (default: none)",
  1389. [](common_params & params, const std::string & value) {
  1390. std::ifstream file(value, std::ios::binary);
  1391. if (!file) {
  1392. throw std::runtime_error(string_format("error: failed to open file '%s'\n", value.c_str()));
  1393. }
  1394. // store the external file name in params
  1395. params.prompt_file = value;
  1396. std::ostringstream ss;
  1397. ss << file.rdbuf();
  1398. params.prompt = ss.str();
  1399. fprintf(stderr, "Read %zu bytes from binary file %s\n", params.prompt.size(), value.c_str());
  1400. }
  1401. ).set_excludes({LLAMA_EXAMPLE_SERVER}));
  1402. add_opt(common_arg(
  1403. {"-e", "--escape"},
  1404. string_format("process escapes sequences (\\n, \\r, \\t, \\', \\\", \\\\) (default: %s)", params.escape ? "true" : "false"),
  1405. [](common_params & params) {
  1406. params.escape = true;
  1407. }
  1408. ));
  1409. add_opt(common_arg(
  1410. {"--no-escape"},
  1411. "do not process escape sequences",
  1412. [](common_params & params) {
  1413. params.escape = false;
  1414. }
  1415. ));
  1416. add_opt(common_arg(
  1417. {"-ptc", "--print-token-count"}, "N",
  1418. string_format("print token count every N tokens (default: %d)", params.n_print),
  1419. [](common_params & params, int value) {
  1420. params.n_print = value;
  1421. }
  1422. ).set_examples({LLAMA_EXAMPLE_MAIN}));
  1423. add_opt(common_arg(
  1424. {"--prompt-cache"}, "FNAME",
  1425. "file to cache prompt state for faster startup (default: none)",
  1426. [](common_params & params, const std::string & value) {
  1427. params.path_prompt_cache = value;
  1428. }
  1429. ).set_examples({LLAMA_EXAMPLE_MAIN}));
  1430. add_opt(common_arg(
  1431. {"--prompt-cache-all"},
  1432. "if specified, saves user input and generations to cache as well\n",
  1433. [](common_params & params) {
  1434. params.prompt_cache_all = true;
  1435. }
  1436. ).set_examples({LLAMA_EXAMPLE_MAIN}));
  1437. add_opt(common_arg(
  1438. {"--prompt-cache-ro"},
  1439. "if specified, uses the prompt cache but does not update it",
  1440. [](common_params & params) {
  1441. params.prompt_cache_ro = true;
  1442. }
  1443. ).set_examples({LLAMA_EXAMPLE_MAIN}));
  1444. add_opt(common_arg(
  1445. {"-r", "--reverse-prompt"}, "PROMPT",
  1446. "halt generation at PROMPT, return control in interactive mode\n",
  1447. [](common_params & params, const std::string & value) {
  1448. params.antiprompt.emplace_back(value);
  1449. }
  1450. ).set_examples({LLAMA_EXAMPLE_MAIN}));
  1451. add_opt(common_arg(
  1452. {"-sp", "--special"},
  1453. string_format("special tokens output enabled (default: %s)", params.special ? "true" : "false"),
  1454. [](common_params & params) {
  1455. params.special = true;
  1456. }
  1457. ).set_examples({LLAMA_EXAMPLE_MAIN, LLAMA_EXAMPLE_SERVER}));
  1458. add_opt(common_arg(
  1459. {"-cnv", "--conversation"},
  1460. "run in conversation mode:\n"
  1461. "- does not print special tokens and suffix/prefix\n"
  1462. "- interactive mode is also enabled\n"
  1463. "(default: auto enabled if chat template is available)",
  1464. [](common_params & params) {
  1465. params.conversation_mode = COMMON_CONVERSATION_MODE_ENABLED;
  1466. }
  1467. ).set_examples({LLAMA_EXAMPLE_MAIN}));
  1468. add_opt(common_arg(
  1469. {"-no-cnv", "--no-conversation"},
  1470. "force disable conversation mode (default: false)",
  1471. [](common_params & params) {
  1472. params.conversation_mode = COMMON_CONVERSATION_MODE_DISABLED;
  1473. }
  1474. ).set_examples({LLAMA_EXAMPLE_MAIN}));
  1475. add_opt(common_arg(
  1476. {"-st", "--single-turn"},
  1477. "run conversation for a single turn only, then exit when done\n"
  1478. "will not be interactive if first turn is predefined with --prompt\n"
  1479. "(default: false)",
  1480. [](common_params & params) {
  1481. params.single_turn = true;
  1482. }
  1483. ).set_examples({LLAMA_EXAMPLE_MAIN}));
  1484. add_opt(common_arg(
  1485. {"-i", "--interactive"},
  1486. string_format("run in interactive mode (default: %s)", params.interactive ? "true" : "false"),
  1487. [](common_params & params) {
  1488. params.interactive = true;
  1489. }
  1490. ).set_examples({LLAMA_EXAMPLE_MAIN}));
  1491. add_opt(common_arg(
  1492. {"-if", "--interactive-first"},
  1493. string_format("run in interactive mode and wait for input right away (default: %s)", params.interactive_first ? "true" : "false"),
  1494. [](common_params & params) {
  1495. params.interactive_first = true;
  1496. }
  1497. ).set_examples({LLAMA_EXAMPLE_MAIN}));
  1498. add_opt(common_arg(
  1499. {"-mli", "--multiline-input"},
  1500. "allows you to write or paste multiple lines without ending each in '\\'",
  1501. [](common_params & params) {
  1502. params.multiline_input = true;
  1503. }
  1504. ).set_examples({LLAMA_EXAMPLE_MAIN}));
  1505. add_opt(common_arg(
  1506. {"--in-prefix-bos"},
  1507. "prefix BOS to user inputs, preceding the `--in-prefix` string",
  1508. [](common_params & params) {
  1509. params.input_prefix_bos = true;
  1510. params.enable_chat_template = false;
  1511. }
  1512. ).set_examples({LLAMA_EXAMPLE_MAIN}));
  1513. add_opt(common_arg(
  1514. {"--in-prefix"}, "STRING",
  1515. "string to prefix user inputs with (default: empty)",
  1516. [](common_params & params, const std::string & value) {
  1517. params.input_prefix = value;
  1518. params.enable_chat_template = false;
  1519. }
  1520. ).set_examples({LLAMA_EXAMPLE_MAIN}));
  1521. add_opt(common_arg(
  1522. {"--in-suffix"}, "STRING",
  1523. "string to suffix after user inputs with (default: empty)",
  1524. [](common_params & params, const std::string & value) {
  1525. params.input_suffix = value;
  1526. params.enable_chat_template = false;
  1527. }
  1528. ).set_examples({LLAMA_EXAMPLE_MAIN}));
  1529. add_opt(common_arg(
  1530. {"--no-warmup"},
  1531. "skip warming up the model with an empty run",
  1532. [](common_params & params) {
  1533. params.warmup = false;
  1534. }
  1535. ).set_examples({LLAMA_EXAMPLE_MAIN, LLAMA_EXAMPLE_SERVER, LLAMA_EXAMPLE_EMBEDDING, LLAMA_EXAMPLE_RETRIEVAL}));
  1536. add_opt(common_arg(
  1537. {"--spm-infill"},
  1538. string_format(
  1539. "use Suffix/Prefix/Middle pattern for infill (instead of Prefix/Suffix/Middle) as some models prefer this. (default: %s)",
  1540. params.spm_infill ? "enabled" : "disabled"
  1541. ),
  1542. [](common_params & params) {
  1543. params.spm_infill = true;
  1544. }
  1545. ).set_examples({LLAMA_EXAMPLE_SERVER}));
  1546. add_opt(common_arg(
  1547. {"--samplers"}, "SAMPLERS",
  1548. string_format("samplers that will be used for generation in the order, separated by \';\'\n(default: %s)", sampler_type_names.c_str()),
  1549. [](common_params & params, const std::string & value) {
  1550. const auto sampler_names = string_split<std::string>(value, ';');
  1551. params.sampling.samplers = common_sampler_types_from_names(sampler_names, true);
  1552. }
  1553. ).set_sparam());
  1554. add_opt(common_arg(
  1555. {"-s", "--seed"}, "SEED",
  1556. string_format("RNG seed (default: %d, use random seed for %d)", params.sampling.seed, LLAMA_DEFAULT_SEED),
  1557. [](common_params & params, const std::string & value) {
  1558. params.sampling.seed = std::stoul(value);
  1559. }
  1560. ).set_sparam());
  1561. add_opt(common_arg(
  1562. {"--sampling-seq", "--sampler-seq"}, "SEQUENCE",
  1563. string_format("simplified sequence for samplers that will be used (default: %s)", sampler_type_chars.c_str()),
  1564. [](common_params & params, const std::string & value) {
  1565. params.sampling.samplers = common_sampler_types_from_chars(value);
  1566. }
  1567. ).set_sparam());
  1568. add_opt(common_arg(
  1569. {"--ignore-eos"},
  1570. "ignore end of stream token and continue generating (implies --logit-bias EOS-inf)",
  1571. [](common_params & params) {
  1572. params.sampling.ignore_eos = true;
  1573. }
  1574. ).set_sparam());
  1575. add_opt(common_arg(
  1576. {"--temp"}, "N",
  1577. string_format("temperature (default: %.1f)", (double)params.sampling.temp),
  1578. [](common_params & params, const std::string & value) {
  1579. params.sampling.temp = std::stof(value);
  1580. params.sampling.temp = std::max(params.sampling.temp, 0.0f);
  1581. }
  1582. ).set_sparam());
  1583. add_opt(common_arg(
  1584. {"--top-k"}, "N",
  1585. string_format("top-k sampling (default: %d, 0 = disabled)", params.sampling.top_k),
  1586. [](common_params & params, int value) {
  1587. params.sampling.top_k = value;
  1588. }
  1589. ).set_sparam());
  1590. add_opt(common_arg(
  1591. {"--top-p"}, "N",
  1592. string_format("top-p sampling (default: %.1f, 1.0 = disabled)", (double)params.sampling.top_p),
  1593. [](common_params & params, const std::string & value) {
  1594. params.sampling.top_p = std::stof(value);
  1595. }
  1596. ).set_sparam());
  1597. add_opt(common_arg(
  1598. {"--min-p"}, "N",
  1599. string_format("min-p sampling (default: %.1f, 0.0 = disabled)", (double)params.sampling.min_p),
  1600. [](common_params & params, const std::string & value) {
  1601. params.sampling.min_p = std::stof(value);
  1602. }
  1603. ).set_sparam());
  1604. add_opt(common_arg(
  1605. {"--top-nsigma"}, "N",
  1606. string_format("top-n-sigma sampling (default: %.1f, -1.0 = disabled)", params.sampling.top_n_sigma),
  1607. [](common_params & params, const std::string & value) {
  1608. params.sampling.top_n_sigma = std::stof(value);
  1609. }
  1610. ).set_examples({LLAMA_EXAMPLE_MAIN}).set_sparam());
  1611. add_opt(common_arg(
  1612. {"--xtc-probability"}, "N",
  1613. string_format("xtc probability (default: %.1f, 0.0 = disabled)", (double)params.sampling.xtc_probability),
  1614. [](common_params & params, const std::string & value) {
  1615. params.sampling.xtc_probability = std::stof(value);
  1616. }
  1617. ).set_sparam());
  1618. add_opt(common_arg(
  1619. {"--xtc-threshold"}, "N",
  1620. string_format("xtc threshold (default: %.1f, 1.0 = disabled)", (double)params.sampling.xtc_threshold),
  1621. [](common_params & params, const std::string & value) {
  1622. params.sampling.xtc_threshold = std::stof(value);
  1623. }
  1624. ).set_sparam());
  1625. add_opt(common_arg(
  1626. {"--typical"}, "N",
  1627. string_format("locally typical sampling, parameter p (default: %.1f, 1.0 = disabled)", (double)params.sampling.typ_p),
  1628. [](common_params & params, const std::string & value) {
  1629. params.sampling.typ_p = std::stof(value);
  1630. }
  1631. ).set_sparam());
  1632. add_opt(common_arg(
  1633. {"--repeat-last-n"}, "N",
  1634. string_format("last n tokens to consider for penalize (default: %d, 0 = disabled, -1 = ctx_size)", params.sampling.penalty_last_n),
  1635. [](common_params & params, int value) {
  1636. if (value < -1) {
  1637. throw std::runtime_error(string_format("error: invalid repeat-last-n = %d\n", value));
  1638. }
  1639. params.sampling.penalty_last_n = value;
  1640. params.sampling.n_prev = std::max(params.sampling.n_prev, params.sampling.penalty_last_n);
  1641. }
  1642. ).set_sparam());
  1643. add_opt(common_arg(
  1644. {"--repeat-penalty"}, "N",
  1645. string_format("penalize repeat sequence of tokens (default: %.1f, 1.0 = disabled)", (double)params.sampling.penalty_repeat),
  1646. [](common_params & params, const std::string & value) {
  1647. params.sampling.penalty_repeat = std::stof(value);
  1648. }
  1649. ).set_sparam());
  1650. add_opt(common_arg(
  1651. {"--presence-penalty"}, "N",
  1652. string_format("repeat alpha presence penalty (default: %.1f, 0.0 = disabled)", (double)params.sampling.penalty_present),
  1653. [](common_params & params, const std::string & value) {
  1654. params.sampling.penalty_present = std::stof(value);
  1655. }
  1656. ).set_sparam());
  1657. add_opt(common_arg(
  1658. {"--frequency-penalty"}, "N",
  1659. string_format("repeat alpha frequency penalty (default: %.1f, 0.0 = disabled)", (double)params.sampling.penalty_freq),
  1660. [](common_params & params, const std::string & value) {
  1661. params.sampling.penalty_freq = std::stof(value);
  1662. }
  1663. ).set_sparam());
  1664. add_opt(common_arg(
  1665. {"--dry-multiplier"}, "N",
  1666. string_format("set DRY sampling multiplier (default: %.1f, 0.0 = disabled)", (double)params.sampling.dry_multiplier),
  1667. [](common_params & params, const std::string & value) {
  1668. params.sampling.dry_multiplier = std::stof(value);
  1669. }
  1670. ).set_sparam());
  1671. add_opt(common_arg(
  1672. {"--dry-base"}, "N",
  1673. string_format("set DRY sampling base value (default: %.2f)", (double)params.sampling.dry_base),
  1674. [](common_params & params, const std::string & value) {
  1675. float potential_base = std::stof(value);
  1676. if (potential_base >= 1.0f)
  1677. {
  1678. params.sampling.dry_base = potential_base;
  1679. }
  1680. }
  1681. ).set_sparam());
  1682. add_opt(common_arg(
  1683. {"--dry-allowed-length"}, "N",
  1684. string_format("set allowed length for DRY sampling (default: %d)", params.sampling.dry_allowed_length),
  1685. [](common_params & params, int value) {
  1686. params.sampling.dry_allowed_length = value;
  1687. }
  1688. ).set_sparam());
  1689. add_opt(common_arg(
  1690. {"--dry-penalty-last-n"}, "N",
  1691. string_format("set DRY penalty for the last n tokens (default: %d, 0 = disable, -1 = context size)", params.sampling.dry_penalty_last_n),
  1692. [](common_params & params, int value) {
  1693. if (value < -1) {
  1694. throw std::runtime_error(string_format("error: invalid dry-penalty-last-n = %d\n", value));
  1695. }
  1696. params.sampling.dry_penalty_last_n = value;
  1697. }
  1698. ).set_sparam());
  1699. add_opt(common_arg(
  1700. {"--dry-sequence-breaker"}, "STRING",
  1701. 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",
  1702. params.sampling.dry_sequence_breakers.empty() ? "none" :
  1703. std::accumulate(std::next(params.sampling.dry_sequence_breakers.begin()),
  1704. params.sampling.dry_sequence_breakers.end(),
  1705. std::string("'") + (params.sampling.dry_sequence_breakers[0] == "\n" ? "\\n" : params.sampling.dry_sequence_breakers[0]) + "'",
  1706. [](const std::string& a, const std::string& b) {
  1707. std::string formatted_b = (b == "\n") ? "\\n" : b;
  1708. return a + ", '" + formatted_b + "'";
  1709. }).c_str()),
  1710. [](common_params & params, const std::string & value) {
  1711. static bool defaults_cleared = false;
  1712. if (!defaults_cleared) {
  1713. params.sampling.dry_sequence_breakers.clear();
  1714. defaults_cleared = true;
  1715. }
  1716. if (value == "none") {
  1717. params.sampling.dry_sequence_breakers.clear();
  1718. } else {
  1719. params.sampling.dry_sequence_breakers.emplace_back(value);
  1720. }
  1721. }
  1722. ).set_sparam());
  1723. add_opt(common_arg(
  1724. {"--dynatemp-range"}, "N",
  1725. string_format("dynamic temperature range (default: %.1f, 0.0 = disabled)", (double)params.sampling.dynatemp_range),
  1726. [](common_params & params, const std::string & value) {
  1727. params.sampling.dynatemp_range = std::stof(value);
  1728. }
  1729. ).set_sparam());
  1730. add_opt(common_arg(
  1731. {"--dynatemp-exp"}, "N",
  1732. string_format("dynamic temperature exponent (default: %.1f)", (double)params.sampling.dynatemp_exponent),
  1733. [](common_params & params, const std::string & value) {
  1734. params.sampling.dynatemp_exponent = std::stof(value);
  1735. }
  1736. ).set_sparam());
  1737. add_opt(common_arg(
  1738. {"--mirostat"}, "N",
  1739. string_format("use Mirostat sampling.\nTop K, Nucleus and Locally Typical samplers are ignored if used.\n"
  1740. "(default: %d, 0 = disabled, 1 = Mirostat, 2 = Mirostat 2.0)", params.sampling.mirostat),
  1741. [](common_params & params, int value) {
  1742. params.sampling.mirostat = value;
  1743. }
  1744. ).set_sparam());
  1745. add_opt(common_arg(
  1746. {"--mirostat-lr"}, "N",
  1747. string_format("Mirostat learning rate, parameter eta (default: %.1f)", (double)params.sampling.mirostat_eta),
  1748. [](common_params & params, const std::string & value) {
  1749. params.sampling.mirostat_eta = std::stof(value);
  1750. }
  1751. ).set_sparam());
  1752. add_opt(common_arg(
  1753. {"--mirostat-ent"}, "N",
  1754. string_format("Mirostat target entropy, parameter tau (default: %.1f)", (double)params.sampling.mirostat_tau),
  1755. [](common_params & params, const std::string & value) {
  1756. params.sampling.mirostat_tau = std::stof(value);
  1757. }
  1758. ).set_sparam());
  1759. add_opt(common_arg(
  1760. {"-l", "--logit-bias"}, "TOKEN_ID(+/-)BIAS",
  1761. "modifies the likelihood of token appearing in the completion,\n"
  1762. "i.e. `--logit-bias 15043+1` to increase likelihood of token ' Hello',\n"
  1763. "or `--logit-bias 15043-1` to decrease likelihood of token ' Hello'",
  1764. [](common_params & params, const std::string & value) {
  1765. std::stringstream ss(value);
  1766. llama_token key;
  1767. char sign;
  1768. std::string value_str;
  1769. try {
  1770. if (ss >> key && ss >> sign && std::getline(ss, value_str) && (sign == '+' || sign == '-')) {
  1771. const float bias = std::stof(value_str) * ((sign == '-') ? -1.0f : 1.0f);
  1772. params.sampling.logit_bias.push_back({key, bias});
  1773. } else {
  1774. throw std::invalid_argument("invalid input format");
  1775. }
  1776. } catch (const std::exception&) {
  1777. throw std::invalid_argument("invalid input format");
  1778. }
  1779. }
  1780. ).set_sparam());
  1781. add_opt(common_arg(
  1782. {"--grammar"}, "GRAMMAR",
  1783. string_format("BNF-like grammar to constrain generations (see samples in grammars/ dir) (default: '%s')", params.sampling.grammar.c_str()),
  1784. [](common_params & params, const std::string & value) {
  1785. params.sampling.grammar = value;
  1786. }
  1787. ).set_sparam());
  1788. add_opt(common_arg(
  1789. {"--grammar-file"}, "FNAME",
  1790. "file to read grammar from",
  1791. [](common_params & params, const std::string & value) {
  1792. params.sampling.grammar = read_file(value);
  1793. }
  1794. ).set_sparam());
  1795. add_opt(common_arg(
  1796. {"-j", "--json-schema"}, "SCHEMA",
  1797. "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",
  1798. [](common_params & params, const std::string & value) {
  1799. params.sampling.grammar = json_schema_to_grammar(json::parse(value));
  1800. }
  1801. ).set_sparam());
  1802. add_opt(common_arg(
  1803. {"-jf", "--json-schema-file"}, "FILE",
  1804. "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",
  1805. [](common_params & params, const std::string & value) {
  1806. std::ifstream file(value);
  1807. if (!file) {
  1808. throw std::runtime_error(string_format("error: failed to open file '%s'\n", value.c_str()));
  1809. }
  1810. std::string schema;
  1811. std::copy(
  1812. std::istreambuf_iterator<char>(file),
  1813. std::istreambuf_iterator<char>(),
  1814. std::back_inserter(schema)
  1815. );
  1816. params.sampling.grammar = json_schema_to_grammar(json::parse(schema));
  1817. }
  1818. ).set_sparam());
  1819. add_opt(common_arg(
  1820. {"--pooling"}, "{none,mean,cls,last,rank}",
  1821. "pooling type for embeddings, use model default if unspecified",
  1822. [](common_params & params, const std::string & value) {
  1823. /**/ if (value == "none") { params.pooling_type = LLAMA_POOLING_TYPE_NONE; }
  1824. else if (value == "mean") { params.pooling_type = LLAMA_POOLING_TYPE_MEAN; }
  1825. else if (value == "cls") { params.pooling_type = LLAMA_POOLING_TYPE_CLS; }
  1826. else if (value == "last") { params.pooling_type = LLAMA_POOLING_TYPE_LAST; }
  1827. else if (value == "rank") { params.pooling_type = LLAMA_POOLING_TYPE_RANK; }
  1828. else { throw std::invalid_argument("invalid value"); }
  1829. }
  1830. ).set_examples({LLAMA_EXAMPLE_EMBEDDING, LLAMA_EXAMPLE_RETRIEVAL, LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_POOLING"));
  1831. add_opt(common_arg(
  1832. {"--attention"}, "{causal,non-causal}",
  1833. "attention type for embeddings, use model default if unspecified",
  1834. [](common_params & params, const std::string & value) {
  1835. /**/ if (value == "causal") { params.attention_type = LLAMA_ATTENTION_TYPE_CAUSAL; }
  1836. else if (value == "non-causal") { params.attention_type = LLAMA_ATTENTION_TYPE_NON_CAUSAL; }
  1837. else { throw std::invalid_argument("invalid value"); }
  1838. }
  1839. ).set_examples({LLAMA_EXAMPLE_EMBEDDING}));
  1840. add_opt(common_arg(
  1841. {"--rope-scaling"}, "{none,linear,yarn}",
  1842. "RoPE frequency scaling method, defaults to linear unless specified by the model",
  1843. [](common_params & params, const std::string & value) {
  1844. /**/ if (value == "none") { params.rope_scaling_type = LLAMA_ROPE_SCALING_TYPE_NONE; }
  1845. else if (value == "linear") { params.rope_scaling_type = LLAMA_ROPE_SCALING_TYPE_LINEAR; }
  1846. else if (value == "yarn") { params.rope_scaling_type = LLAMA_ROPE_SCALING_TYPE_YARN; }
  1847. else { throw std::invalid_argument("invalid value"); }
  1848. }
  1849. ).set_env("LLAMA_ARG_ROPE_SCALING_TYPE"));
  1850. add_opt(common_arg(
  1851. {"--rope-scale"}, "N",
  1852. "RoPE context scaling factor, expands context by a factor of N",
  1853. [](common_params & params, const std::string & value) {
  1854. params.rope_freq_scale = 1.0f / std::stof(value);
  1855. }
  1856. ).set_env("LLAMA_ARG_ROPE_SCALE"));
  1857. add_opt(common_arg(
  1858. {"--rope-freq-base"}, "N",
  1859. "RoPE base frequency, used by NTK-aware scaling (default: loaded from model)",
  1860. [](common_params & params, const std::string & value) {
  1861. params.rope_freq_base = std::stof(value);
  1862. }
  1863. ).set_env("LLAMA_ARG_ROPE_FREQ_BASE"));
  1864. add_opt(common_arg(
  1865. {"--rope-freq-scale"}, "N",
  1866. "RoPE frequency scaling factor, expands context by a factor of 1/N",
  1867. [](common_params & params, const std::string & value) {
  1868. params.rope_freq_scale = std::stof(value);
  1869. }
  1870. ).set_env("LLAMA_ARG_ROPE_FREQ_SCALE"));
  1871. add_opt(common_arg(
  1872. {"--yarn-orig-ctx"}, "N",
  1873. string_format("YaRN: original context size of model (default: %d = model training context size)", params.yarn_orig_ctx),
  1874. [](common_params & params, int value) {
  1875. params.yarn_orig_ctx = value;
  1876. }
  1877. ).set_env("LLAMA_ARG_YARN_ORIG_CTX"));
  1878. add_opt(common_arg(
  1879. {"--yarn-ext-factor"}, "N",
  1880. string_format("YaRN: extrapolation mix factor (default: %.1f, 0.0 = full interpolation)", (double)params.yarn_ext_factor),
  1881. [](common_params & params, const std::string & value) {
  1882. params.yarn_ext_factor = std::stof(value);
  1883. }
  1884. ).set_env("LLAMA_ARG_YARN_EXT_FACTOR"));
  1885. add_opt(common_arg(
  1886. {"--yarn-attn-factor"}, "N",
  1887. string_format("YaRN: scale sqrt(t) or attention magnitude (default: %.1f)", (double)params.yarn_attn_factor),
  1888. [](common_params & params, const std::string & value) {
  1889. params.yarn_attn_factor = std::stof(value);
  1890. }
  1891. ).set_env("LLAMA_ARG_YARN_ATTN_FACTOR"));
  1892. add_opt(common_arg(
  1893. {"--yarn-beta-slow"}, "N",
  1894. string_format("YaRN: high correction dim or alpha (default: %.1f)", (double)params.yarn_beta_slow),
  1895. [](common_params & params, const std::string & value) {
  1896. params.yarn_beta_slow = std::stof(value);
  1897. }
  1898. ).set_env("LLAMA_ARG_YARN_BETA_SLOW"));
  1899. add_opt(common_arg(
  1900. {"--yarn-beta-fast"}, "N",
  1901. string_format("YaRN: low correction dim or beta (default: %.1f)", (double)params.yarn_beta_fast),
  1902. [](common_params & params, const std::string & value) {
  1903. params.yarn_beta_fast = std::stof(value);
  1904. }
  1905. ).set_env("LLAMA_ARG_YARN_BETA_FAST"));
  1906. add_opt(common_arg(
  1907. {"-gan", "--grp-attn-n"}, "N",
  1908. string_format("group-attention factor (default: %d)", params.grp_attn_n),
  1909. [](common_params & params, int value) {
  1910. params.grp_attn_n = value;
  1911. }
  1912. ).set_env("LLAMA_ARG_GRP_ATTN_N").set_examples({LLAMA_EXAMPLE_MAIN, LLAMA_EXAMPLE_PASSKEY}));
  1913. add_opt(common_arg(
  1914. {"-gaw", "--grp-attn-w"}, "N",
  1915. string_format("group-attention width (default: %d)", params.grp_attn_w),
  1916. [](common_params & params, int value) {
  1917. params.grp_attn_w = value;
  1918. }
  1919. ).set_env("LLAMA_ARG_GRP_ATTN_W").set_examples({LLAMA_EXAMPLE_MAIN}));
  1920. add_opt(common_arg(
  1921. {"-nkvo", "--no-kv-offload"},
  1922. "disable KV offload",
  1923. [](common_params & params) {
  1924. params.no_kv_offload = true;
  1925. }
  1926. ).set_env("LLAMA_ARG_NO_KV_OFFLOAD"));
  1927. add_opt(common_arg(
  1928. {"-ctk", "--cache-type-k"}, "TYPE",
  1929. string_format(
  1930. "KV cache data type for K\n"
  1931. "allowed values: %s\n"
  1932. "(default: %s)",
  1933. get_all_kv_cache_types().c_str(),
  1934. ggml_type_name(params.cache_type_k)
  1935. ),
  1936. [](common_params & params, const std::string & value) {
  1937. params.cache_type_k = kv_cache_type_from_str(value);
  1938. }
  1939. ).set_env("LLAMA_ARG_CACHE_TYPE_K"));
  1940. add_opt(common_arg(
  1941. {"-ctv", "--cache-type-v"}, "TYPE",
  1942. string_format(
  1943. "KV cache data type for V\n"
  1944. "allowed values: %s\n"
  1945. "(default: %s)",
  1946. get_all_kv_cache_types().c_str(),
  1947. ggml_type_name(params.cache_type_v)
  1948. ),
  1949. [](common_params & params, const std::string & value) {
  1950. params.cache_type_v = kv_cache_type_from_str(value);
  1951. }
  1952. ).set_env("LLAMA_ARG_CACHE_TYPE_V"));
  1953. add_opt(common_arg(
  1954. {"--hellaswag"},
  1955. "compute HellaSwag score over random tasks from datafile supplied with -f",
  1956. [](common_params & params) {
  1957. params.hellaswag = true;
  1958. }
  1959. ).set_examples({LLAMA_EXAMPLE_PERPLEXITY}));
  1960. add_opt(common_arg(
  1961. {"--hellaswag-tasks"}, "N",
  1962. string_format("number of tasks to use when computing the HellaSwag score (default: %zu)", params.hellaswag_tasks),
  1963. [](common_params & params, int value) {
  1964. params.hellaswag_tasks = value;
  1965. }
  1966. ).set_examples({LLAMA_EXAMPLE_PERPLEXITY}));
  1967. add_opt(common_arg(
  1968. {"--winogrande"},
  1969. "compute Winogrande score over random tasks from datafile supplied with -f",
  1970. [](common_params & params) {
  1971. params.winogrande = true;
  1972. }
  1973. ).set_examples({LLAMA_EXAMPLE_PERPLEXITY}));
  1974. add_opt(common_arg(
  1975. {"--winogrande-tasks"}, "N",
  1976. string_format("number of tasks to use when computing the Winogrande score (default: %zu)", params.winogrande_tasks),
  1977. [](common_params & params, int value) {
  1978. params.winogrande_tasks = value;
  1979. }
  1980. ).set_examples({LLAMA_EXAMPLE_PERPLEXITY}));
  1981. add_opt(common_arg(
  1982. {"--multiple-choice"},
  1983. "compute multiple choice score over random tasks from datafile supplied with -f",
  1984. [](common_params & params) {
  1985. params.multiple_choice = true;
  1986. }
  1987. ).set_examples({LLAMA_EXAMPLE_PERPLEXITY}));
  1988. add_opt(common_arg(
  1989. {"--multiple-choice-tasks"}, "N",
  1990. string_format("number of tasks to use when computing the multiple choice score (default: %zu)", params.multiple_choice_tasks),
  1991. [](common_params & params, int value) {
  1992. params.multiple_choice_tasks = value;
  1993. }
  1994. ).set_examples({LLAMA_EXAMPLE_PERPLEXITY}));
  1995. add_opt(common_arg(
  1996. {"--kl-divergence"},
  1997. "computes KL-divergence to logits provided via --kl-divergence-base",
  1998. [](common_params & params) {
  1999. params.kl_divergence = true;
  2000. }
  2001. ).set_examples({LLAMA_EXAMPLE_PERPLEXITY}));
  2002. add_opt(common_arg(
  2003. {"--save-all-logits", "--kl-divergence-base"}, "FNAME",
  2004. "set logits file",
  2005. [](common_params & params, const std::string & value) {
  2006. params.logits_file = value;
  2007. }
  2008. ).set_examples({LLAMA_EXAMPLE_PERPLEXITY}));
  2009. add_opt(common_arg(
  2010. {"--ppl-stride"}, "N",
  2011. string_format("stride for perplexity calculation (default: %d)", params.ppl_stride),
  2012. [](common_params & params, int value) {
  2013. params.ppl_stride = value;
  2014. }
  2015. ).set_examples({LLAMA_EXAMPLE_PERPLEXITY}));
  2016. add_opt(common_arg(
  2017. {"--ppl-output-type"}, "<0|1>",
  2018. string_format("output type for perplexity calculation (default: %d)", params.ppl_output_type),
  2019. [](common_params & params, int value) {
  2020. params.ppl_output_type = value;
  2021. }
  2022. ).set_examples({LLAMA_EXAMPLE_PERPLEXITY}));
  2023. add_opt(common_arg(
  2024. {"-dt", "--defrag-thold"}, "N",
  2025. string_format("KV cache defragmentation threshold (default: %.1f, < 0 - disabled)", (double)params.defrag_thold),
  2026. [](common_params & params, const std::string & value) {
  2027. params.defrag_thold = std::stof(value);
  2028. }
  2029. ).set_env("LLAMA_ARG_DEFRAG_THOLD"));
  2030. add_opt(common_arg(
  2031. {"-np", "--parallel"}, "N",
  2032. string_format("number of parallel sequences to decode (default: %d)", params.n_parallel),
  2033. [](common_params & params, int value) {
  2034. params.n_parallel = value;
  2035. }
  2036. ).set_env("LLAMA_ARG_N_PARALLEL"));
  2037. add_opt(common_arg(
  2038. {"-ns", "--sequences"}, "N",
  2039. string_format("number of sequences to decode (default: %d)", params.n_sequences),
  2040. [](common_params & params, int value) {
  2041. params.n_sequences = value;
  2042. }
  2043. ).set_examples({LLAMA_EXAMPLE_PARALLEL}));
  2044. add_opt(common_arg(
  2045. {"-cb", "--cont-batching"},
  2046. string_format("enable continuous batching (a.k.a dynamic batching) (default: %s)", params.cont_batching ? "enabled" : "disabled"),
  2047. [](common_params & params) {
  2048. params.cont_batching = true;
  2049. }
  2050. ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_CONT_BATCHING"));
  2051. add_opt(common_arg(
  2052. {"-nocb", "--no-cont-batching"},
  2053. "disable continuous batching",
  2054. [](common_params & params) {
  2055. params.cont_batching = false;
  2056. }
  2057. ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_NO_CONT_BATCHING"));
  2058. add_opt(common_arg(
  2059. {"--mmproj"}, "FILE",
  2060. "path to a multimodal projector file. see tools/mtmd/README.md\n"
  2061. "note: if -hf is used, this argument can be omitted",
  2062. [](common_params & params, const std::string & value) {
  2063. params.mmproj.path = value;
  2064. }
  2065. ).set_examples(mmproj_examples).set_env("LLAMA_ARG_MMPROJ"));
  2066. add_opt(common_arg(
  2067. {"--mmproj-url"}, "URL",
  2068. "URL to a multimodal projector file. see tools/mtmd/README.md",
  2069. [](common_params & params, const std::string & value) {
  2070. params.mmproj.url = value;
  2071. }
  2072. ).set_examples(mmproj_examples).set_env("LLAMA_ARG_MMPROJ_URL"));
  2073. add_opt(common_arg(
  2074. {"--no-mmproj"},
  2075. "explicitly disable multimodal projector, useful when using -hf",
  2076. [](common_params & params) {
  2077. params.no_mmproj = true;
  2078. }
  2079. ).set_examples(mmproj_examples).set_env("LLAMA_ARG_NO_MMPROJ"));
  2080. add_opt(common_arg(
  2081. {"--no-mmproj-offload"},
  2082. "do not offload multimodal projector to GPU",
  2083. [](common_params & params) {
  2084. params.mmproj_use_gpu = false;
  2085. }
  2086. ).set_examples(mmproj_examples).set_env("LLAMA_ARG_NO_MMPROJ_OFFLOAD"));
  2087. add_opt(common_arg(
  2088. {"--image", "--audio"}, "FILE",
  2089. "path to an image or audio file. use with multimodal models, can be repeated if you have multiple files\n",
  2090. [](common_params & params, const std::string & value) {
  2091. params.image.emplace_back(value);
  2092. }
  2093. ).set_examples({LLAMA_EXAMPLE_MTMD}));
  2094. if (llama_supports_rpc()) {
  2095. add_opt(common_arg(
  2096. {"--rpc"}, "SERVERS",
  2097. "comma separated list of RPC servers",
  2098. [](common_params & params, const std::string & value) {
  2099. add_rpc_devices(value);
  2100. GGML_UNUSED(params);
  2101. }
  2102. ).set_env("LLAMA_ARG_RPC"));
  2103. }
  2104. add_opt(common_arg(
  2105. {"--mlock"},
  2106. "force system to keep model in RAM rather than swapping or compressing",
  2107. [](common_params & params) {
  2108. params.use_mlock = true;
  2109. }
  2110. ).set_env("LLAMA_ARG_MLOCK"));
  2111. add_opt(common_arg(
  2112. {"--no-mmap"},
  2113. "do not memory-map model (slower load but may reduce pageouts if not using mlock)",
  2114. [](common_params & params) {
  2115. params.use_mmap = false;
  2116. }
  2117. ).set_env("LLAMA_ARG_NO_MMAP"));
  2118. add_opt(common_arg(
  2119. {"--numa"}, "TYPE",
  2120. "attempt optimizations that help on some NUMA systems\n"
  2121. "- distribute: spread execution evenly over all nodes\n"
  2122. "- isolate: only spawn threads on CPUs on the node that execution started on\n"
  2123. "- numactl: use the CPU map provided by numactl\n"
  2124. "if run without this previously, it is recommended to drop the system page cache before using this\n"
  2125. "see https://github.com/ggml-org/llama.cpp/issues/1437",
  2126. [](common_params & params, const std::string & value) {
  2127. /**/ if (value == "distribute" || value == "") { params.numa = GGML_NUMA_STRATEGY_DISTRIBUTE; }
  2128. else if (value == "isolate") { params.numa = GGML_NUMA_STRATEGY_ISOLATE; }
  2129. else if (value == "numactl") { params.numa = GGML_NUMA_STRATEGY_NUMACTL; }
  2130. else { throw std::invalid_argument("invalid value"); }
  2131. }
  2132. ).set_env("LLAMA_ARG_NUMA"));
  2133. add_opt(common_arg(
  2134. {"-dev", "--device"}, "<dev1,dev2,..>",
  2135. "comma-separated list of devices to use for offloading (none = don't offload)\n"
  2136. "use --list-devices to see a list of available devices",
  2137. [](common_params & params, const std::string & value) {
  2138. params.devices = parse_device_list(value);
  2139. }
  2140. ).set_env("LLAMA_ARG_DEVICE"));
  2141. add_opt(common_arg(
  2142. {"--list-devices"},
  2143. "print list of available devices and exit",
  2144. [](common_params &) {
  2145. std::vector<ggml_backend_dev_t> rpc_devices;
  2146. std::vector<ggml_backend_dev_t> all_devices;
  2147. for (size_t i = 0; i < ggml_backend_dev_count(); ++i) {
  2148. auto * dev = ggml_backend_dev_get(i);
  2149. if (ggml_backend_dev_type(dev) == GGML_BACKEND_DEVICE_TYPE_GPU) {
  2150. ggml_backend_reg_t reg = ggml_backend_dev_backend_reg(dev);
  2151. if (ggml_backend_reg_name(reg) == std::string("RPC")) {
  2152. rpc_devices.push_back(dev);
  2153. } else {
  2154. all_devices.push_back(dev);
  2155. }
  2156. }
  2157. }
  2158. // insert RPC devices in front
  2159. all_devices.insert(all_devices.begin(), rpc_devices.begin(), rpc_devices.end());
  2160. printf("Available devices:\n");
  2161. for (size_t i = 0; i < all_devices.size(); ++i) {
  2162. auto * dev = all_devices[i];
  2163. size_t free, total;
  2164. ggml_backend_dev_memory(dev, &free, &total);
  2165. 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);
  2166. }
  2167. exit(0);
  2168. }
  2169. ));
  2170. add_opt(common_arg(
  2171. {"--override-tensor", "-ot"}, "<tensor name pattern>=<buffer type>,...",
  2172. "override tensor buffer type", [](common_params & params, const std::string & value) {
  2173. /* static */ std::map<std::string, ggml_backend_buffer_type_t> buft_list;
  2174. if (buft_list.empty()) {
  2175. // enumerate all the devices and add their buffer types to the list
  2176. for (size_t i = 0; i < ggml_backend_dev_count(); ++i) {
  2177. auto * dev = ggml_backend_dev_get(i);
  2178. auto * buft = ggml_backend_dev_buffer_type(dev);
  2179. if (buft) {
  2180. buft_list[ggml_backend_buft_name(buft)] = buft;
  2181. }
  2182. }
  2183. }
  2184. for (const auto & override : string_split<std::string>(value, ',')) {
  2185. std::string::size_type pos = override.find('=');
  2186. if (pos == std::string::npos) {
  2187. throw std::invalid_argument("invalid value");
  2188. }
  2189. std::string tensor_name = override.substr(0, pos);
  2190. std::string buffer_type = override.substr(pos + 1);
  2191. if (buft_list.find(buffer_type) == buft_list.end()) {
  2192. printf("Available buffer types:\n");
  2193. for (const auto & it : buft_list) {
  2194. printf(" %s\n", ggml_backend_buft_name(it.second));
  2195. }
  2196. throw std::invalid_argument("unknown buffer type");
  2197. }
  2198. // FIXME: this leaks memory
  2199. params.tensor_buft_overrides.push_back({strdup(tensor_name.c_str()), buft_list.at(buffer_type)});
  2200. }
  2201. }
  2202. ));
  2203. add_opt(common_arg(
  2204. {"-ngl", "--gpu-layers", "--n-gpu-layers"}, "N",
  2205. "number of layers to store in VRAM",
  2206. [](common_params & params, int value) {
  2207. params.n_gpu_layers = value;
  2208. if (!llama_supports_gpu_offload()) {
  2209. fprintf(stderr, "warning: no usable GPU found, --gpu-layers option will be ignored\n");
  2210. fprintf(stderr, "warning: one possible reason is that llama.cpp was compiled without GPU support\n");
  2211. fprintf(stderr, "warning: consult docs/build.md for compilation instructions\n");
  2212. }
  2213. }
  2214. ).set_env("LLAMA_ARG_N_GPU_LAYERS"));
  2215. add_opt(common_arg(
  2216. {"-sm", "--split-mode"}, "{none,layer,row}",
  2217. "how to split the model across multiple GPUs, one of:\n"
  2218. "- none: use one GPU only\n"
  2219. "- layer (default): split layers and KV across GPUs\n"
  2220. "- row: split rows across GPUs",
  2221. [](common_params & params, const std::string & value) {
  2222. std::string arg_next = value;
  2223. if (arg_next == "none") {
  2224. params.split_mode = LLAMA_SPLIT_MODE_NONE;
  2225. } else if (arg_next == "layer") {
  2226. params.split_mode = LLAMA_SPLIT_MODE_LAYER;
  2227. } else if (arg_next == "row") {
  2228. params.split_mode = LLAMA_SPLIT_MODE_ROW;
  2229. } else {
  2230. throw std::invalid_argument("invalid value");
  2231. }
  2232. if (!llama_supports_gpu_offload()) {
  2233. fprintf(stderr, "warning: llama.cpp was compiled without support for GPU offload. Setting the split mode has no effect.\n");
  2234. }
  2235. }
  2236. ).set_env("LLAMA_ARG_SPLIT_MODE"));
  2237. add_opt(common_arg(
  2238. {"-ts", "--tensor-split"}, "N0,N1,N2,...",
  2239. "fraction of the model to offload to each GPU, comma-separated list of proportions, e.g. 3,1",
  2240. [](common_params & params, const std::string & value) {
  2241. std::string arg_next = value;
  2242. // split string by , and /
  2243. const std::regex regex{ R"([,/]+)" };
  2244. std::sregex_token_iterator it{ arg_next.begin(), arg_next.end(), regex, -1 };
  2245. std::vector<std::string> split_arg{ it, {} };
  2246. if (split_arg.size() >= llama_max_devices()) {
  2247. throw std::invalid_argument(
  2248. string_format("got %d input configs, but system only has %d devices", (int)split_arg.size(), (int)llama_max_devices())
  2249. );
  2250. }
  2251. for (size_t i = 0; i < llama_max_devices(); ++i) {
  2252. if (i < split_arg.size()) {
  2253. params.tensor_split[i] = std::stof(split_arg[i]);
  2254. } else {
  2255. params.tensor_split[i] = 0.0f;
  2256. }
  2257. }
  2258. if (!llama_supports_gpu_offload()) {
  2259. fprintf(stderr, "warning: llama.cpp was compiled without support for GPU offload. Setting a tensor split has no effect.\n");
  2260. }
  2261. }
  2262. ).set_env("LLAMA_ARG_TENSOR_SPLIT"));
  2263. add_opt(common_arg(
  2264. {"-mg", "--main-gpu"}, "INDEX",
  2265. 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),
  2266. [](common_params & params, int value) {
  2267. params.main_gpu = value;
  2268. if (!llama_supports_gpu_offload()) {
  2269. fprintf(stderr, "warning: llama.cpp was compiled without support for GPU offload. Setting the main GPU has no effect.\n");
  2270. }
  2271. }
  2272. ).set_env("LLAMA_ARG_MAIN_GPU"));
  2273. add_opt(common_arg(
  2274. {"--check-tensors"},
  2275. string_format("check model tensor data for invalid values (default: %s)", params.check_tensors ? "true" : "false"),
  2276. [](common_params & params) {
  2277. params.check_tensors = true;
  2278. }
  2279. ));
  2280. add_opt(common_arg(
  2281. {"--override-kv"}, "KEY=TYPE:VALUE",
  2282. "advanced option to override model metadata by key. may be specified multiple times.\n"
  2283. "types: int, float, bool, str. example: --override-kv tokenizer.ggml.add_bos_token=bool:false",
  2284. [](common_params & params, const std::string & value) {
  2285. if (!string_parse_kv_override(value.c_str(), params.kv_overrides)) {
  2286. throw std::runtime_error(string_format("error: Invalid type for KV override: %s\n", value.c_str()));
  2287. }
  2288. }
  2289. ));
  2290. add_opt(common_arg(
  2291. {"--no-op-offload"},
  2292. string_format("disable offloading host tensor operations to device (default: %s)", params.no_op_offload ? "true" : "false"),
  2293. [](common_params & params) {
  2294. params.no_op_offload = true;
  2295. }
  2296. ));
  2297. add_opt(common_arg(
  2298. {"--lora"}, "FNAME",
  2299. "path to LoRA adapter (can be repeated to use multiple adapters)",
  2300. [](common_params & params, const std::string & value) {
  2301. params.lora_adapters.push_back({ std::string(value), 1.0, nullptr });
  2302. }
  2303. // 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
  2304. ).set_examples({LLAMA_EXAMPLE_COMMON, LLAMA_EXAMPLE_EXPORT_LORA}));
  2305. add_opt(common_arg(
  2306. {"--lora-scaled"}, "FNAME", "SCALE",
  2307. "path to LoRA adapter with user defined scaling (can be repeated to use multiple adapters)",
  2308. [](common_params & params, const std::string & fname, const std::string & scale) {
  2309. params.lora_adapters.push_back({ fname, std::stof(scale), nullptr });
  2310. }
  2311. // 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
  2312. ).set_examples({LLAMA_EXAMPLE_COMMON, LLAMA_EXAMPLE_EXPORT_LORA}));
  2313. add_opt(common_arg(
  2314. {"--control-vector"}, "FNAME",
  2315. "add a control vector\nnote: this argument can be repeated to add multiple control vectors",
  2316. [](common_params & params, const std::string & value) {
  2317. params.control_vectors.push_back({ 1.0f, value, });
  2318. }
  2319. ));
  2320. add_opt(common_arg(
  2321. {"--control-vector-scaled"}, "FNAME", "SCALE",
  2322. "add a control vector with user defined scaling SCALE\n"
  2323. "note: this argument can be repeated to add multiple scaled control vectors",
  2324. [](common_params & params, const std::string & fname, const std::string & scale) {
  2325. params.control_vectors.push_back({ std::stof(scale), fname });
  2326. }
  2327. ));
  2328. add_opt(common_arg(
  2329. {"--control-vector-layer-range"}, "START", "END",
  2330. "layer range to apply the control vector(s) to, start and end inclusive",
  2331. [](common_params & params, const std::string & start, const std::string & end) {
  2332. params.control_vector_layer_start = std::stoi(start);
  2333. params.control_vector_layer_end = std::stoi(end);
  2334. }
  2335. ));
  2336. add_opt(common_arg(
  2337. {"-a", "--alias"}, "STRING",
  2338. "set alias for model name (to be used by REST API)",
  2339. [](common_params & params, const std::string & value) {
  2340. params.model_alias = value;
  2341. }
  2342. ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_ALIAS"));
  2343. add_opt(common_arg(
  2344. {"-m", "--model"}, "FNAME",
  2345. ex == LLAMA_EXAMPLE_EXPORT_LORA
  2346. ? std::string("model path from which to load base model")
  2347. : string_format(
  2348. "model path (default: `models/$filename` with filename from `--hf-file` "
  2349. "or `--model-url` if set, otherwise %s)", DEFAULT_MODEL_PATH
  2350. ),
  2351. [](common_params & params, const std::string & value) {
  2352. params.model.path = value;
  2353. }
  2354. ).set_examples({LLAMA_EXAMPLE_COMMON, LLAMA_EXAMPLE_EXPORT_LORA}).set_env("LLAMA_ARG_MODEL"));
  2355. add_opt(common_arg(
  2356. {"-mu", "--model-url"}, "MODEL_URL",
  2357. "model download url (default: unused)",
  2358. [](common_params & params, const std::string & value) {
  2359. params.model.url = value;
  2360. }
  2361. ).set_env("LLAMA_ARG_MODEL_URL"));
  2362. add_opt(common_arg(
  2363. {"-hf", "-hfr", "--hf-repo"}, "<user>/<model>[:quant]",
  2364. "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"
  2365. "mmproj is also downloaded automatically if available. to disable, add --no-mmproj\n"
  2366. "example: unsloth/phi-4-GGUF:q4_k_m\n"
  2367. "(default: unused)",
  2368. [](common_params & params, const std::string & value) {
  2369. params.model.hf_repo = value;
  2370. }
  2371. ).set_env("LLAMA_ARG_HF_REPO"));
  2372. add_opt(common_arg(
  2373. {"-hfd", "-hfrd", "--hf-repo-draft"}, "<user>/<model>[:quant]",
  2374. "Same as --hf-repo, but for the draft model (default: unused)",
  2375. [](common_params & params, const std::string & value) {
  2376. params.speculative.model.hf_repo = value;
  2377. }
  2378. ).set_env("LLAMA_ARG_HFD_REPO"));
  2379. add_opt(common_arg(
  2380. {"-hff", "--hf-file"}, "FILE",
  2381. "Hugging Face model file. If specified, it will override the quant in --hf-repo (default: unused)",
  2382. [](common_params & params, const std::string & value) {
  2383. params.model.hf_file = value;
  2384. }
  2385. ).set_env("LLAMA_ARG_HF_FILE"));
  2386. add_opt(common_arg(
  2387. {"-hfv", "-hfrv", "--hf-repo-v"}, "<user>/<model>[:quant]",
  2388. "Hugging Face model repository for the vocoder model (default: unused)",
  2389. [](common_params & params, const std::string & value) {
  2390. params.vocoder.model.hf_repo = value;
  2391. }
  2392. ).set_env("LLAMA_ARG_HF_REPO_V"));
  2393. add_opt(common_arg(
  2394. {"-hffv", "--hf-file-v"}, "FILE",
  2395. "Hugging Face model file for the vocoder model (default: unused)",
  2396. [](common_params & params, const std::string & value) {
  2397. params.vocoder.model.hf_file = value;
  2398. }
  2399. ).set_env("LLAMA_ARG_HF_FILE_V"));
  2400. add_opt(common_arg(
  2401. {"-hft", "--hf-token"}, "TOKEN",
  2402. "Hugging Face access token (default: value from HF_TOKEN environment variable)",
  2403. [](common_params & params, const std::string & value) {
  2404. params.hf_token = value;
  2405. }
  2406. ).set_env("HF_TOKEN"));
  2407. add_opt(common_arg(
  2408. {"--context-file"}, "FNAME",
  2409. "file to load context from (repeat to specify multiple files)",
  2410. [](common_params & params, const std::string & value) {
  2411. std::ifstream file(value, std::ios::binary);
  2412. if (!file) {
  2413. throw std::runtime_error(string_format("error: failed to open file '%s'\n", value.c_str()));
  2414. }
  2415. params.context_files.push_back(value);
  2416. }
  2417. ).set_examples({LLAMA_EXAMPLE_RETRIEVAL}));
  2418. add_opt(common_arg(
  2419. {"--chunk-size"}, "N",
  2420. string_format("minimum length of embedded text chunks (default: %d)", params.chunk_size),
  2421. [](common_params & params, int value) {
  2422. params.chunk_size = value;
  2423. }
  2424. ).set_examples({LLAMA_EXAMPLE_RETRIEVAL}));
  2425. add_opt(common_arg(
  2426. {"--chunk-separator"}, "STRING",
  2427. string_format("separator between chunks (default: '%s')", params.chunk_separator.c_str()),
  2428. [](common_params & params, const std::string & value) {
  2429. params.chunk_separator = value;
  2430. }
  2431. ).set_examples({LLAMA_EXAMPLE_RETRIEVAL}));
  2432. add_opt(common_arg(
  2433. {"--junk"}, "N",
  2434. string_format("number of times to repeat the junk text (default: %d)", params.n_junk),
  2435. [](common_params & params, int value) {
  2436. params.n_junk = value;
  2437. }
  2438. ).set_examples({LLAMA_EXAMPLE_PASSKEY, LLAMA_EXAMPLE_PARALLEL}));
  2439. add_opt(common_arg(
  2440. {"--pos"}, "N",
  2441. string_format("position of the passkey in the junk text (default: %d)", params.i_pos),
  2442. [](common_params & params, int value) {
  2443. params.i_pos = value;
  2444. }
  2445. ).set_examples({LLAMA_EXAMPLE_PASSKEY}));
  2446. add_opt(common_arg(
  2447. {"-o", "--output", "--output-file"}, "FNAME",
  2448. string_format("output file (default: '%s')", params.out_file.c_str()),
  2449. [](common_params & params, const std::string & value) {
  2450. params.out_file = value;
  2451. }
  2452. ).set_examples({LLAMA_EXAMPLE_IMATRIX, LLAMA_EXAMPLE_CVECTOR_GENERATOR, LLAMA_EXAMPLE_EXPORT_LORA, LLAMA_EXAMPLE_TTS}));
  2453. add_opt(common_arg(
  2454. {"-ofreq", "--output-frequency"}, "N",
  2455. string_format("output the imatrix every N iterations (default: %d)", params.n_out_freq),
  2456. [](common_params & params, int value) {
  2457. params.n_out_freq = value;
  2458. }
  2459. ).set_examples({LLAMA_EXAMPLE_IMATRIX}));
  2460. add_opt(common_arg(
  2461. {"--save-frequency"}, "N",
  2462. string_format("save an imatrix copy every N iterations (default: %d)", params.n_save_freq),
  2463. [](common_params & params, int value) {
  2464. params.n_save_freq = value;
  2465. }
  2466. ).set_examples({LLAMA_EXAMPLE_IMATRIX}));
  2467. add_opt(common_arg(
  2468. {"--process-output"},
  2469. string_format("collect data for the output tensor (default: %s)", params.process_output ? "true" : "false"),
  2470. [](common_params & params) {
  2471. params.process_output = true;
  2472. }
  2473. ).set_examples({LLAMA_EXAMPLE_IMATRIX}));
  2474. add_opt(common_arg(
  2475. {"--no-ppl"},
  2476. string_format("do not compute perplexity (default: %s)", params.compute_ppl ? "true" : "false"),
  2477. [](common_params & params) {
  2478. params.compute_ppl = false;
  2479. }
  2480. ).set_examples({LLAMA_EXAMPLE_IMATRIX}));
  2481. add_opt(common_arg(
  2482. {"--chunk", "--from-chunk"}, "N",
  2483. string_format("start processing the input from chunk N (default: %d)", params.i_chunk),
  2484. [](common_params & params, int value) {
  2485. params.i_chunk = value;
  2486. }
  2487. ).set_examples({LLAMA_EXAMPLE_IMATRIX}));
  2488. add_opt(common_arg(
  2489. {"--parse-special"},
  2490. string_format("prase special tokens (chat, tool, etc) (default: %s)", params.parse_special ? "true" : "false"),
  2491. [](common_params & params) {
  2492. params.parse_special = true;
  2493. }
  2494. ).set_examples({LLAMA_EXAMPLE_IMATRIX}));
  2495. add_opt(common_arg(
  2496. {"-pps"},
  2497. string_format("is the prompt shared across parallel sequences (default: %s)", params.is_pp_shared ? "true" : "false"),
  2498. [](common_params & params) {
  2499. params.is_pp_shared = true;
  2500. }
  2501. ).set_examples({LLAMA_EXAMPLE_BENCH, LLAMA_EXAMPLE_PARALLEL}));
  2502. add_opt(common_arg(
  2503. {"-npp"}, "n0,n1,...",
  2504. "number of prompt tokens",
  2505. [](common_params & params, const std::string & value) {
  2506. auto p = string_split<int>(value, ',');
  2507. params.n_pp.insert(params.n_pp.end(), p.begin(), p.end());
  2508. }
  2509. ).set_examples({LLAMA_EXAMPLE_BENCH}));
  2510. add_opt(common_arg(
  2511. {"-ntg"}, "n0,n1,...",
  2512. "number of text generation tokens",
  2513. [](common_params & params, const std::string & value) {
  2514. auto p = string_split<int>(value, ',');
  2515. params.n_tg.insert(params.n_tg.end(), p.begin(), p.end());
  2516. }
  2517. ).set_examples({LLAMA_EXAMPLE_BENCH}));
  2518. add_opt(common_arg(
  2519. {"-npl"}, "n0,n1,...",
  2520. "number of parallel prompts",
  2521. [](common_params & params, const std::string & value) {
  2522. auto p = string_split<int>(value, ',');
  2523. params.n_pl.insert(params.n_pl.end(), p.begin(), p.end());
  2524. }
  2525. ).set_examples({LLAMA_EXAMPLE_BENCH}));
  2526. add_opt(common_arg(
  2527. {"--embd-normalize"}, "N",
  2528. string_format("normalisation for embeddings (default: %d) (-1=none, 0=max absolute int16, 1=taxicab, 2=euclidean, >2=p-norm)", params.embd_normalize),
  2529. [](common_params & params, int value) {
  2530. params.embd_normalize = value;
  2531. }
  2532. ).set_examples({LLAMA_EXAMPLE_EMBEDDING}));
  2533. add_opt(common_arg(
  2534. {"--embd-output-format"}, "FORMAT",
  2535. "empty = default, \"array\" = [[],[]...], \"json\" = openai style, \"json+\" = same \"json\" + cosine similarity matrix",
  2536. [](common_params & params, const std::string & value) {
  2537. params.embd_out = value;
  2538. }
  2539. ).set_examples({LLAMA_EXAMPLE_EMBEDDING}));
  2540. add_opt(common_arg(
  2541. {"--embd-separator"}, "STRING",
  2542. "separator of embeddings (default \\n) for example \"<#sep#>\"",
  2543. [](common_params & params, const std::string & value) {
  2544. params.embd_sep = value;
  2545. }
  2546. ).set_examples({LLAMA_EXAMPLE_EMBEDDING}));
  2547. add_opt(common_arg(
  2548. {"--host"}, "HOST",
  2549. string_format("ip address to listen, or bind to an UNIX socket if the address ends with .sock (default: %s)", params.hostname.c_str()),
  2550. [](common_params & params, const std::string & value) {
  2551. params.hostname = value;
  2552. }
  2553. ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_HOST"));
  2554. add_opt(common_arg(
  2555. {"--port"}, "PORT",
  2556. string_format("port to listen (default: %d)", params.port),
  2557. [](common_params & params, int value) {
  2558. params.port = value;
  2559. }
  2560. ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_PORT"));
  2561. add_opt(common_arg(
  2562. {"--path"}, "PATH",
  2563. string_format("path to serve static files from (default: %s)", params.public_path.c_str()),
  2564. [](common_params & params, const std::string & value) {
  2565. params.public_path = value;
  2566. }
  2567. ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_STATIC_PATH"));
  2568. add_opt(common_arg(
  2569. {"--no-webui"},
  2570. string_format("Disable the Web UI (default: %s)", params.webui ? "enabled" : "disabled"),
  2571. [](common_params & params) {
  2572. params.webui = false;
  2573. }
  2574. ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_NO_WEBUI"));
  2575. add_opt(common_arg(
  2576. {"--embedding", "--embeddings"},
  2577. string_format("restrict to only support embedding use case; use only with dedicated embedding models (default: %s)", params.embedding ? "enabled" : "disabled"),
  2578. [](common_params & params) {
  2579. params.embedding = true;
  2580. }
  2581. ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_EMBEDDINGS"));
  2582. add_opt(common_arg(
  2583. {"--reranking", "--rerank"},
  2584. string_format("enable reranking endpoint on server (default: %s)", params.reranking ? "enabled" : "disabled"),
  2585. [](common_params & params) {
  2586. params.reranking = true;
  2587. }
  2588. ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_RERANKING"));
  2589. add_opt(common_arg(
  2590. {"--api-key"}, "KEY",
  2591. "API key to use for authentication (default: none)",
  2592. [](common_params & params, const std::string & value) {
  2593. params.api_keys.push_back(value);
  2594. }
  2595. ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_API_KEY"));
  2596. add_opt(common_arg(
  2597. {"--api-key-file"}, "FNAME",
  2598. "path to file containing API keys (default: none)",
  2599. [](common_params & params, const std::string & value) {
  2600. std::ifstream key_file(value);
  2601. if (!key_file) {
  2602. throw std::runtime_error(string_format("error: failed to open file '%s'\n", value.c_str()));
  2603. }
  2604. std::string key;
  2605. while (std::getline(key_file, key)) {
  2606. if (!key.empty()) {
  2607. params.api_keys.push_back(key);
  2608. }
  2609. }
  2610. key_file.close();
  2611. }
  2612. ).set_examples({LLAMA_EXAMPLE_SERVER}));
  2613. add_opt(common_arg(
  2614. {"--ssl-key-file"}, "FNAME",
  2615. "path to file a PEM-encoded SSL private key",
  2616. [](common_params & params, const std::string & value) {
  2617. params.ssl_file_key = value;
  2618. }
  2619. ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_SSL_KEY_FILE"));
  2620. add_opt(common_arg(
  2621. {"--ssl-cert-file"}, "FNAME",
  2622. "path to file a PEM-encoded SSL certificate",
  2623. [](common_params & params, const std::string & value) {
  2624. params.ssl_file_cert = value;
  2625. }
  2626. ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_SSL_CERT_FILE"));
  2627. add_opt(common_arg(
  2628. {"-to", "--timeout"}, "N",
  2629. string_format("server read/write timeout in seconds (default: %d)", params.timeout_read),
  2630. [](common_params & params, int value) {
  2631. params.timeout_read = value;
  2632. params.timeout_write = value;
  2633. }
  2634. ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_TIMEOUT"));
  2635. add_opt(common_arg(
  2636. {"--threads-http"}, "N",
  2637. string_format("number of threads used to process HTTP requests (default: %d)", params.n_threads_http),
  2638. [](common_params & params, int value) {
  2639. params.n_threads_http = value;
  2640. }
  2641. ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_THREADS_HTTP"));
  2642. add_opt(common_arg(
  2643. {"--cache-reuse"}, "N",
  2644. string_format(
  2645. "min chunk size to attempt reusing from the cache via KV shifting (default: %d)\n"
  2646. "[(card)](https://ggml.ai/f0.png)", params.n_cache_reuse
  2647. ),
  2648. [](common_params & params, int value) {
  2649. params.n_cache_reuse = value;
  2650. }
  2651. ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_CACHE_REUSE"));
  2652. add_opt(common_arg(
  2653. {"--metrics"},
  2654. string_format("enable prometheus compatible metrics endpoint (default: %s)", params.endpoint_metrics ? "enabled" : "disabled"),
  2655. [](common_params & params) {
  2656. params.endpoint_metrics = true;
  2657. }
  2658. ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_ENDPOINT_METRICS"));
  2659. add_opt(common_arg(
  2660. {"--slots"},
  2661. string_format("enable slots monitoring endpoint (default: %s)", params.endpoint_slots ? "enabled" : "disabled"),
  2662. [](common_params & params) {
  2663. params.endpoint_slots = true;
  2664. }
  2665. ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_ENDPOINT_SLOTS"));
  2666. add_opt(common_arg(
  2667. {"--props"},
  2668. string_format("enable changing global properties via POST /props (default: %s)", params.endpoint_props ? "enabled" : "disabled"),
  2669. [](common_params & params) {
  2670. params.endpoint_props = true;
  2671. }
  2672. ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_ENDPOINT_PROPS"));
  2673. add_opt(common_arg(
  2674. {"--no-slots"},
  2675. "disables slots monitoring endpoint",
  2676. [](common_params & params) {
  2677. params.endpoint_slots = false;
  2678. }
  2679. ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_NO_ENDPOINT_SLOTS"));
  2680. add_opt(common_arg(
  2681. {"--slot-save-path"}, "PATH",
  2682. "path to save slot kv cache (default: disabled)",
  2683. [](common_params & params, const std::string & value) {
  2684. params.slot_save_path = value;
  2685. // if doesn't end with DIRECTORY_SEPARATOR, add it
  2686. if (!params.slot_save_path.empty() && params.slot_save_path[params.slot_save_path.size() - 1] != DIRECTORY_SEPARATOR) {
  2687. params.slot_save_path += DIRECTORY_SEPARATOR;
  2688. }
  2689. }
  2690. ).set_examples({LLAMA_EXAMPLE_SERVER}));
  2691. add_opt(common_arg(
  2692. {"--jinja"},
  2693. "use jinja template for chat (default: disabled)",
  2694. [](common_params & params) {
  2695. params.use_jinja = true;
  2696. }
  2697. ).set_examples({LLAMA_EXAMPLE_SERVER, LLAMA_EXAMPLE_MAIN}).set_env("LLAMA_ARG_JINJA"));
  2698. add_opt(common_arg(
  2699. {"--reasoning-format"}, "FORMAT",
  2700. "controls whether thought tags are allowed and/or extracted from the response, and in which format they're returned; one of:\n"
  2701. "- none: leaves thoughts unparsed in `message.content`\n"
  2702. "- deepseek: puts thoughts in `message.reasoning_content` (except in streaming mode, which behaves as `none`)\n"
  2703. "(default: deepseek)",
  2704. [](common_params & params, const std::string & value) {
  2705. /**/ if (value == "deepseek") { params.reasoning_format = COMMON_REASONING_FORMAT_DEEPSEEK; }
  2706. else if (value == "none") { params.reasoning_format = COMMON_REASONING_FORMAT_NONE; }
  2707. else { throw std::invalid_argument("invalid value"); }
  2708. }
  2709. ).set_examples({LLAMA_EXAMPLE_SERVER, LLAMA_EXAMPLE_MAIN}).set_env("LLAMA_ARG_THINK"));
  2710. add_opt(common_arg(
  2711. {"--reasoning-budget"}, "N",
  2712. "controls the amount of thinking allowed; currently only one of: -1 for unrestricted thinking budget, or 0 to disable thinking (default: -1)",
  2713. [](common_params & params, int value) {
  2714. if (value != 0 && value != -1) { throw std::invalid_argument("invalid value"); }
  2715. params.reasoning_budget = value;
  2716. }
  2717. ).set_examples({LLAMA_EXAMPLE_SERVER, LLAMA_EXAMPLE_MAIN}).set_env("LLAMA_ARG_THINK_BUDGET"));
  2718. add_opt(common_arg(
  2719. {"--chat-template"}, "JINJA_TEMPLATE",
  2720. string_format(
  2721. "set custom jinja chat template (default: template taken from model's metadata)\n"
  2722. "if suffix/prefix are specified, template will be disabled\n"
  2723. "only commonly used templates are accepted (unless --jinja is set before this flag):\n"
  2724. "list of built-in templates:\n%s", list_builtin_chat_templates().c_str()
  2725. ),
  2726. [](common_params & params, const std::string & value) {
  2727. params.chat_template = value;
  2728. }
  2729. ).set_examples({LLAMA_EXAMPLE_MAIN, LLAMA_EXAMPLE_SERVER, LLAMA_EXAMPLE_MTMD}).set_env("LLAMA_ARG_CHAT_TEMPLATE"));
  2730. add_opt(common_arg(
  2731. {"--chat-template-file"}, "JINJA_TEMPLATE_FILE",
  2732. string_format(
  2733. "set custom jinja chat template file (default: template taken from model's metadata)\n"
  2734. "if suffix/prefix are specified, template will be disabled\n"
  2735. "only commonly used templates are accepted (unless --jinja is set before this flag):\n"
  2736. "list of built-in templates:\n%s", list_builtin_chat_templates().c_str()
  2737. ),
  2738. [](common_params & params, const std::string & value) {
  2739. params.chat_template = read_file(value);
  2740. }
  2741. ).set_examples({LLAMA_EXAMPLE_MAIN, LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_CHAT_TEMPLATE_FILE"));
  2742. add_opt(common_arg(
  2743. {"--no-prefill-assistant"},
  2744. string_format(
  2745. "whether to prefill the assistant's response if the last message is an assistant message (default: prefill enabled)\n"
  2746. "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"
  2747. ),
  2748. [](common_params & params) {
  2749. params.prefill_assistant = false;
  2750. }
  2751. ).set_examples({LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_NO_PREFILL_ASSISTANT"));
  2752. add_opt(common_arg(
  2753. {"-sps", "--slot-prompt-similarity"}, "SIMILARITY",
  2754. 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),
  2755. [](common_params & params, const std::string & value) {
  2756. params.slot_prompt_similarity = std::stof(value);
  2757. }
  2758. ).set_examples({LLAMA_EXAMPLE_SERVER}));
  2759. add_opt(common_arg(
  2760. {"--lora-init-without-apply"},
  2761. string_format("load LoRA adapters without applying them (apply later via POST /lora-adapters) (default: %s)", params.lora_init_without_apply ? "enabled" : "disabled"),
  2762. [](common_params & params) {
  2763. params.lora_init_without_apply = true;
  2764. }
  2765. ).set_examples({LLAMA_EXAMPLE_SERVER}));
  2766. add_opt(common_arg(
  2767. {"--simple-io"},
  2768. "use basic IO for better compatibility in subprocesses and limited consoles",
  2769. [](common_params & params) {
  2770. params.simple_io = true;
  2771. }
  2772. ).set_examples({LLAMA_EXAMPLE_MAIN}));
  2773. add_opt(common_arg(
  2774. {"--positive-file"}, "FNAME",
  2775. string_format("positive prompts file, one prompt per line (default: '%s')", params.cvector_positive_file.c_str()),
  2776. [](common_params & params, const std::string & value) {
  2777. params.cvector_positive_file = value;
  2778. }
  2779. ).set_examples({LLAMA_EXAMPLE_CVECTOR_GENERATOR}));
  2780. add_opt(common_arg(
  2781. {"--negative-file"}, "FNAME",
  2782. string_format("negative prompts file, one prompt per line (default: '%s')", params.cvector_negative_file.c_str()),
  2783. [](common_params & params, const std::string & value) {
  2784. params.cvector_negative_file = value;
  2785. }
  2786. ).set_examples({LLAMA_EXAMPLE_CVECTOR_GENERATOR}));
  2787. add_opt(common_arg(
  2788. {"--pca-batch"}, "N",
  2789. string_format("batch size used for PCA. Larger batch runs faster, but uses more memory (default: %d)", params.n_pca_batch),
  2790. [](common_params & params, int value) {
  2791. params.n_pca_batch = value;
  2792. }
  2793. ).set_examples({LLAMA_EXAMPLE_CVECTOR_GENERATOR}));
  2794. add_opt(common_arg(
  2795. {"--pca-iter"}, "N",
  2796. string_format("number of iterations used for PCA (default: %d)", params.n_pca_iterations),
  2797. [](common_params & params, int value) {
  2798. params.n_pca_iterations = value;
  2799. }
  2800. ).set_examples({LLAMA_EXAMPLE_CVECTOR_GENERATOR}));
  2801. add_opt(common_arg(
  2802. {"--method"}, "{pca, mean}",
  2803. "dimensionality reduction method to be used (default: pca)",
  2804. [](common_params & params, const std::string & value) {
  2805. /**/ if (value == "pca") { params.cvector_dimre_method = DIMRE_METHOD_PCA; }
  2806. else if (value == "mean") { params.cvector_dimre_method = DIMRE_METHOD_MEAN; }
  2807. else { throw std::invalid_argument("invalid value"); }
  2808. }
  2809. ).set_examples({LLAMA_EXAMPLE_CVECTOR_GENERATOR}));
  2810. add_opt(common_arg(
  2811. {"--output-format"}, "{md,jsonl}",
  2812. "output format for batched-bench results (default: md)",
  2813. [](common_params & params, const std::string & value) {
  2814. /**/ if (value == "jsonl") { params.batched_bench_output_jsonl = true; }
  2815. else if (value == "md") { params.batched_bench_output_jsonl = false; }
  2816. else { throw std::invalid_argument("invalid value"); }
  2817. }
  2818. ).set_examples({LLAMA_EXAMPLE_BENCH}));
  2819. add_opt(common_arg(
  2820. {"--log-disable"},
  2821. "Log disable",
  2822. [](common_params &) {
  2823. common_log_pause(common_log_main());
  2824. }
  2825. ));
  2826. add_opt(common_arg(
  2827. {"--log-file"}, "FNAME",
  2828. "Log to file",
  2829. [](common_params &, const std::string & value) {
  2830. common_log_set_file(common_log_main(), value.c_str());
  2831. }
  2832. ));
  2833. add_opt(common_arg(
  2834. {"--log-colors"},
  2835. "Enable colored logging",
  2836. [](common_params &) {
  2837. common_log_set_colors(common_log_main(), true);
  2838. }
  2839. ).set_env("LLAMA_LOG_COLORS"));
  2840. add_opt(common_arg(
  2841. {"-v", "--verbose", "--log-verbose"},
  2842. "Set verbosity level to infinity (i.e. log all messages, useful for debugging)",
  2843. [](common_params & params) {
  2844. params.verbosity = INT_MAX;
  2845. common_log_set_verbosity_thold(INT_MAX);
  2846. }
  2847. ));
  2848. add_opt(common_arg(
  2849. {"--offline"},
  2850. "Offline mode: forces use of cache, prevents network access",
  2851. [](common_params & params) {
  2852. params.offline = true;
  2853. }
  2854. ).set_env("LLAMA_OFFLINE"));
  2855. add_opt(common_arg(
  2856. {"-lv", "--verbosity", "--log-verbosity"}, "N",
  2857. "Set the verbosity threshold. Messages with a higher verbosity will be ignored.",
  2858. [](common_params & params, int value) {
  2859. params.verbosity = value;
  2860. common_log_set_verbosity_thold(value);
  2861. }
  2862. ).set_env("LLAMA_LOG_VERBOSITY"));
  2863. add_opt(common_arg(
  2864. {"--log-prefix"},
  2865. "Enable prefix in log messages",
  2866. [](common_params &) {
  2867. common_log_set_prefix(common_log_main(), true);
  2868. }
  2869. ).set_env("LLAMA_LOG_PREFIX"));
  2870. add_opt(common_arg(
  2871. {"--log-timestamps"},
  2872. "Enable timestamps in log messages",
  2873. [](common_params &) {
  2874. common_log_set_timestamps(common_log_main(), true);
  2875. }
  2876. ).set_env("LLAMA_LOG_TIMESTAMPS"));
  2877. // speculative parameters
  2878. add_opt(common_arg(
  2879. {"-td", "--threads-draft"}, "N",
  2880. "number of threads to use during generation (default: same as --threads)",
  2881. [](common_params & params, int value) {
  2882. params.speculative.cpuparams.n_threads = value;
  2883. if (params.speculative.cpuparams.n_threads <= 0) {
  2884. params.speculative.cpuparams.n_threads = std::thread::hardware_concurrency();
  2885. }
  2886. }
  2887. ).set_examples({LLAMA_EXAMPLE_SPECULATIVE}));
  2888. add_opt(common_arg(
  2889. {"-tbd", "--threads-batch-draft"}, "N",
  2890. "number of threads to use during batch and prompt processing (default: same as --threads-draft)",
  2891. [](common_params & params, int value) {
  2892. params.speculative.cpuparams_batch.n_threads = value;
  2893. if (params.speculative.cpuparams_batch.n_threads <= 0) {
  2894. params.speculative.cpuparams_batch.n_threads = std::thread::hardware_concurrency();
  2895. }
  2896. }
  2897. ).set_examples({LLAMA_EXAMPLE_SPECULATIVE}));
  2898. add_opt(common_arg(
  2899. {"-Cd", "--cpu-mask-draft"}, "M",
  2900. "Draft model CPU affinity mask. Complements cpu-range-draft (default: same as --cpu-mask)",
  2901. [](common_params & params, const std::string & mask) {
  2902. params.speculative.cpuparams.mask_valid = true;
  2903. if (!parse_cpu_mask(mask, params.speculative.cpuparams.cpumask)) {
  2904. throw std::invalid_argument("invalid cpumask");
  2905. }
  2906. }
  2907. ).set_examples({LLAMA_EXAMPLE_SPECULATIVE}));
  2908. add_opt(common_arg(
  2909. {"-Crd", "--cpu-range-draft"}, "lo-hi",
  2910. "Ranges of CPUs for affinity. Complements --cpu-mask-draft",
  2911. [](common_params & params, const std::string & range) {
  2912. params.speculative.cpuparams.mask_valid = true;
  2913. if (!parse_cpu_range(range, params.speculative.cpuparams.cpumask)) {
  2914. throw std::invalid_argument("invalid range");
  2915. }
  2916. }
  2917. ).set_examples({LLAMA_EXAMPLE_SPECULATIVE}));
  2918. add_opt(common_arg(
  2919. {"--cpu-strict-draft"}, "<0|1>",
  2920. "Use strict CPU placement for draft model (default: same as --cpu-strict)",
  2921. [](common_params & params, int value) {
  2922. params.speculative.cpuparams.strict_cpu = value;
  2923. }
  2924. ).set_examples({LLAMA_EXAMPLE_SPECULATIVE}));
  2925. add_opt(common_arg(
  2926. {"--prio-draft"}, "N",
  2927. string_format("set draft process/thread priority : 0-normal, 1-medium, 2-high, 3-realtime (default: %d)\n", params.speculative.cpuparams.priority),
  2928. [](common_params & params, int prio) {
  2929. if (prio < 0 || prio > 3) {
  2930. throw std::invalid_argument("invalid value");
  2931. }
  2932. params.speculative.cpuparams.priority = (enum ggml_sched_priority) prio;
  2933. }
  2934. ).set_examples({LLAMA_EXAMPLE_SPECULATIVE}));
  2935. add_opt(common_arg(
  2936. {"--poll-draft"}, "<0|1>",
  2937. "Use polling to wait for draft model work (default: same as --poll])",
  2938. [](common_params & params, int value) {
  2939. params.speculative.cpuparams.poll = value;
  2940. }
  2941. ).set_examples({LLAMA_EXAMPLE_SPECULATIVE}));
  2942. add_opt(common_arg(
  2943. {"-Cbd", "--cpu-mask-batch-draft"}, "M",
  2944. "Draft model CPU affinity mask. Complements cpu-range-draft (default: same as --cpu-mask)",
  2945. [](common_params & params, const std::string & mask) {
  2946. params.speculative.cpuparams_batch.mask_valid = true;
  2947. if (!parse_cpu_mask(mask, params.speculative.cpuparams_batch.cpumask)) {
  2948. throw std::invalid_argument("invalid cpumask");
  2949. }
  2950. }
  2951. ).set_examples({LLAMA_EXAMPLE_SPECULATIVE}));
  2952. add_opt(common_arg(
  2953. {"-Crbd", "--cpu-range-batch-draft"}, "lo-hi",
  2954. "Ranges of CPUs for affinity. Complements --cpu-mask-draft-batch)",
  2955. [](common_params & params, const std::string & range) {
  2956. params.speculative.cpuparams_batch.mask_valid = true;
  2957. if (!parse_cpu_range(range, params.speculative.cpuparams_batch.cpumask)) {
  2958. throw std::invalid_argument("invalid cpumask");
  2959. }
  2960. }
  2961. ).set_examples({LLAMA_EXAMPLE_SPECULATIVE}));
  2962. add_opt(common_arg(
  2963. {"--cpu-strict-batch-draft"}, "<0|1>",
  2964. "Use strict CPU placement for draft model (default: --cpu-strict-draft)",
  2965. [](common_params & params, int value) {
  2966. params.speculative.cpuparams_batch.strict_cpu = value;
  2967. }
  2968. ).set_examples({LLAMA_EXAMPLE_SPECULATIVE}));
  2969. add_opt(common_arg(
  2970. {"--prio-batch-draft"}, "N",
  2971. string_format("set draft process/thread priority : 0-normal, 1-medium, 2-high, 3-realtime (default: %d)\n", params.speculative.cpuparams_batch.priority),
  2972. [](common_params & params, int prio) {
  2973. if (prio < 0 || prio > 3) {
  2974. throw std::invalid_argument("invalid value");
  2975. }
  2976. params.speculative.cpuparams_batch.priority = (enum ggml_sched_priority) prio;
  2977. }
  2978. ).set_examples({LLAMA_EXAMPLE_SPECULATIVE}));
  2979. add_opt(common_arg(
  2980. {"--poll-batch-draft"}, "<0|1>",
  2981. "Use polling to wait for draft model work (default: --poll-draft)",
  2982. [](common_params & params, int value) {
  2983. params.speculative.cpuparams_batch.poll = value;
  2984. }
  2985. ).set_examples({LLAMA_EXAMPLE_SPECULATIVE}));
  2986. add_opt(common_arg(
  2987. {"--draft-max", "--draft", "--draft-n"}, "N",
  2988. string_format("number of tokens to draft for speculative decoding (default: %d)", params.speculative.n_max),
  2989. [](common_params & params, int value) {
  2990. params.speculative.n_max = value;
  2991. }
  2992. ).set_examples({LLAMA_EXAMPLE_SPECULATIVE, LLAMA_EXAMPLE_LOOKUP, LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_DRAFT_MAX"));
  2993. add_opt(common_arg(
  2994. {"--draft-min", "--draft-n-min"}, "N",
  2995. string_format("minimum number of draft tokens to use for speculative decoding (default: %d)", params.speculative.n_min),
  2996. [](common_params & params, int value) {
  2997. params.speculative.n_min = value;
  2998. }
  2999. ).set_examples({LLAMA_EXAMPLE_SPECULATIVE, LLAMA_EXAMPLE_LOOKUP, LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_DRAFT_MIN"));
  3000. add_opt(common_arg(
  3001. {"--draft-p-split"}, "P",
  3002. string_format("speculative decoding split probability (default: %.1f)", (double)params.speculative.p_split),
  3003. [](common_params & params, const std::string & value) {
  3004. params.speculative.p_split = std::stof(value);
  3005. }
  3006. ).set_examples({LLAMA_EXAMPLE_SPECULATIVE}).set_env("LLAMA_ARG_DRAFT_P_SPLIT"));
  3007. add_opt(common_arg(
  3008. {"--draft-p-min"}, "P",
  3009. string_format("minimum speculative decoding probability (greedy) (default: %.1f)", (double)params.speculative.p_min),
  3010. [](common_params & params, const std::string & value) {
  3011. params.speculative.p_min = std::stof(value);
  3012. }
  3013. ).set_examples({LLAMA_EXAMPLE_SPECULATIVE, LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_DRAFT_P_MIN"));
  3014. add_opt(common_arg(
  3015. {"-cd", "--ctx-size-draft"}, "N",
  3016. string_format("size of the prompt context for the draft model (default: %d, 0 = loaded from model)", params.speculative.n_ctx),
  3017. [](common_params & params, int value) {
  3018. params.speculative.n_ctx = value;
  3019. }
  3020. ).set_examples({LLAMA_EXAMPLE_SPECULATIVE, LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_CTX_SIZE_DRAFT"));
  3021. add_opt(common_arg(
  3022. {"-devd", "--device-draft"}, "<dev1,dev2,..>",
  3023. "comma-separated list of devices to use for offloading the draft model (none = don't offload)\n"
  3024. "use --list-devices to see a list of available devices",
  3025. [](common_params & params, const std::string & value) {
  3026. params.speculative.devices = parse_device_list(value);
  3027. }
  3028. ).set_examples({LLAMA_EXAMPLE_SPECULATIVE, LLAMA_EXAMPLE_SERVER}));
  3029. add_opt(common_arg(
  3030. {"-ngld", "--gpu-layers-draft", "--n-gpu-layers-draft"}, "N",
  3031. "number of layers to store in VRAM for the draft model",
  3032. [](common_params & params, int value) {
  3033. params.speculative.n_gpu_layers = value;
  3034. if (!llama_supports_gpu_offload()) {
  3035. fprintf(stderr, "warning: no usable GPU found, --gpu-layers-draft option will be ignored\n");
  3036. fprintf(stderr, "warning: one possible reason is that llama.cpp was compiled without GPU support\n");
  3037. fprintf(stderr, "warning: consult docs/build.md for compilation instructions\n");
  3038. }
  3039. }
  3040. ).set_examples({LLAMA_EXAMPLE_SPECULATIVE, LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_N_GPU_LAYERS_DRAFT"));
  3041. add_opt(common_arg(
  3042. {"-md", "--model-draft"}, "FNAME",
  3043. "draft model for speculative decoding (default: unused)",
  3044. [](common_params & params, const std::string & value) {
  3045. params.speculative.model.path = value;
  3046. }
  3047. ).set_examples({LLAMA_EXAMPLE_SPECULATIVE, LLAMA_EXAMPLE_SERVER}).set_env("LLAMA_ARG_MODEL_DRAFT"));
  3048. add_opt(common_arg(
  3049. {"-mv", "--model-vocoder"}, "FNAME",
  3050. "vocoder model for audio generation (default: unused)",
  3051. [](common_params & params, const std::string & value) {
  3052. params.vocoder.model.path = value;
  3053. }
  3054. ).set_examples({LLAMA_EXAMPLE_TTS, LLAMA_EXAMPLE_SERVER}));
  3055. add_opt(common_arg(
  3056. {"--tts-use-guide-tokens"},
  3057. "Use guide tokens to improve TTS word recall",
  3058. [](common_params & params) {
  3059. params.vocoder.use_guide_tokens = true;
  3060. }
  3061. ).set_examples({LLAMA_EXAMPLE_TTS, LLAMA_EXAMPLE_SERVER}));
  3062. add_opt(common_arg(
  3063. {"--tts-speaker-file"}, "FNAME",
  3064. "speaker file path for audio generation",
  3065. [](common_params & params, const std::string & value) {
  3066. params.vocoder.speaker_file = value;
  3067. }
  3068. ).set_examples({LLAMA_EXAMPLE_TTS}));
  3069. // model-specific
  3070. add_opt(common_arg(
  3071. {"--tts-oute-default"},
  3072. string_format("use default OuteTTS models (note: can download weights from the internet)"),
  3073. [](common_params & params) {
  3074. params.model.hf_repo = "OuteAI/OuteTTS-0.2-500M-GGUF";
  3075. params.model.hf_file = "OuteTTS-0.2-500M-Q8_0.gguf";
  3076. params.vocoder.model.hf_repo = "ggml-org/WavTokenizer";
  3077. params.vocoder.model.hf_file = "WavTokenizer-Large-75-F16.gguf";
  3078. }
  3079. ).set_examples({LLAMA_EXAMPLE_TTS}));
  3080. add_opt(common_arg(
  3081. {"--embd-bge-small-en-default"},
  3082. string_format("use default bge-small-en-v1.5 model (note: can download weights from the internet)"),
  3083. [](common_params & params) {
  3084. params.model.hf_repo = "ggml-org/bge-small-en-v1.5-Q8_0-GGUF";
  3085. params.model.hf_file = "bge-small-en-v1.5-q8_0.gguf";
  3086. params.pooling_type = LLAMA_POOLING_TYPE_NONE;
  3087. params.embd_normalize = 2;
  3088. params.n_ctx = 512;
  3089. params.verbose_prompt = true;
  3090. params.embedding = true;
  3091. }
  3092. ).set_examples({LLAMA_EXAMPLE_EMBEDDING, LLAMA_EXAMPLE_SERVER}));
  3093. add_opt(common_arg(
  3094. {"--embd-e5-small-en-default"},
  3095. string_format("use default e5-small-v2 model (note: can download weights from the internet)"),
  3096. [](common_params & params) {
  3097. params.model.hf_repo = "ggml-org/e5-small-v2-Q8_0-GGUF";
  3098. params.model.hf_file = "e5-small-v2-q8_0.gguf";
  3099. params.pooling_type = LLAMA_POOLING_TYPE_NONE;
  3100. params.embd_normalize = 2;
  3101. params.n_ctx = 512;
  3102. params.verbose_prompt = true;
  3103. params.embedding = true;
  3104. }
  3105. ).set_examples({LLAMA_EXAMPLE_EMBEDDING, LLAMA_EXAMPLE_SERVER}));
  3106. add_opt(common_arg(
  3107. {"--embd-gte-small-default"},
  3108. string_format("use default gte-small model (note: can download weights from the internet)"),
  3109. [](common_params & params) {
  3110. params.model.hf_repo = "ggml-org/gte-small-Q8_0-GGUF";
  3111. params.model.hf_file = "gte-small-q8_0.gguf";
  3112. params.pooling_type = LLAMA_POOLING_TYPE_NONE;
  3113. params.embd_normalize = 2;
  3114. params.n_ctx = 512;
  3115. params.verbose_prompt = true;
  3116. params.embedding = true;
  3117. }
  3118. ).set_examples({LLAMA_EXAMPLE_EMBEDDING, LLAMA_EXAMPLE_SERVER}));
  3119. add_opt(common_arg(
  3120. {"--fim-qwen-1.5b-default"},
  3121. string_format("use default Qwen 2.5 Coder 1.5B (note: can download weights from the internet)"),
  3122. [](common_params & params) {
  3123. params.model.hf_repo = "ggml-org/Qwen2.5-Coder-1.5B-Q8_0-GGUF";
  3124. params.model.hf_file = "qwen2.5-coder-1.5b-q8_0.gguf";
  3125. params.port = 8012;
  3126. params.n_gpu_layers = 99;
  3127. params.flash_attn = true;
  3128. params.n_ubatch = 1024;
  3129. params.n_batch = 1024;
  3130. params.n_ctx = 0;
  3131. params.n_cache_reuse = 256;
  3132. }
  3133. ).set_examples({LLAMA_EXAMPLE_SERVER}));
  3134. add_opt(common_arg(
  3135. {"--fim-qwen-3b-default"},
  3136. string_format("use default Qwen 2.5 Coder 3B (note: can download weights from the internet)"),
  3137. [](common_params & params) {
  3138. params.model.hf_repo = "ggml-org/Qwen2.5-Coder-3B-Q8_0-GGUF";
  3139. params.model.hf_file = "qwen2.5-coder-3b-q8_0.gguf";
  3140. params.port = 8012;
  3141. params.n_gpu_layers = 99;
  3142. params.flash_attn = true;
  3143. params.n_ubatch = 1024;
  3144. params.n_batch = 1024;
  3145. params.n_ctx = 0;
  3146. params.n_cache_reuse = 256;
  3147. }
  3148. ).set_examples({LLAMA_EXAMPLE_SERVER}));
  3149. add_opt(common_arg(
  3150. {"--fim-qwen-7b-default"},
  3151. string_format("use default Qwen 2.5 Coder 7B (note: can download weights from the internet)"),
  3152. [](common_params & params) {
  3153. params.model.hf_repo = "ggml-org/Qwen2.5-Coder-7B-Q8_0-GGUF";
  3154. params.model.hf_file = "qwen2.5-coder-7b-q8_0.gguf";
  3155. params.port = 8012;
  3156. params.n_gpu_layers = 99;
  3157. params.flash_attn = true;
  3158. params.n_ubatch = 1024;
  3159. params.n_batch = 1024;
  3160. params.n_ctx = 0;
  3161. params.n_cache_reuse = 256;
  3162. }
  3163. ).set_examples({LLAMA_EXAMPLE_SERVER}));
  3164. add_opt(common_arg(
  3165. {"--fim-qwen-7b-spec"},
  3166. string_format("use Qwen 2.5 Coder 7B + 0.5B draft for speculative decoding (note: can download weights from the internet)"),
  3167. [](common_params & params) {
  3168. params.model.hf_repo = "ggml-org/Qwen2.5-Coder-7B-Q8_0-GGUF";
  3169. params.model.hf_file = "qwen2.5-coder-7b-q8_0.gguf";
  3170. params.speculative.model.hf_repo = "ggml-org/Qwen2.5-Coder-0.5B-Q8_0-GGUF";
  3171. params.speculative.model.hf_file = "qwen2.5-coder-0.5b-q8_0.gguf";
  3172. params.speculative.n_gpu_layers = 99;
  3173. params.port = 8012;
  3174. params.n_gpu_layers = 99;
  3175. params.flash_attn = true;
  3176. params.n_ubatch = 1024;
  3177. params.n_batch = 1024;
  3178. params.n_ctx = 0;
  3179. params.n_cache_reuse = 256;
  3180. }
  3181. ).set_examples({LLAMA_EXAMPLE_SERVER}));
  3182. add_opt(common_arg(
  3183. {"--fim-qwen-14b-spec"},
  3184. string_format("use Qwen 2.5 Coder 14B + 0.5B draft for speculative decoding (note: can download weights from the internet)"),
  3185. [](common_params & params) {
  3186. params.model.hf_repo = "ggml-org/Qwen2.5-Coder-14B-Q8_0-GGUF";
  3187. params.model.hf_file = "qwen2.5-coder-14b-q8_0.gguf";
  3188. params.speculative.model.hf_repo = "ggml-org/Qwen2.5-Coder-0.5B-Q8_0-GGUF";
  3189. params.speculative.model.hf_file = "qwen2.5-coder-0.5b-q8_0.gguf";
  3190. params.speculative.n_gpu_layers = 99;
  3191. params.port = 8012;
  3192. params.n_gpu_layers = 99;
  3193. params.flash_attn = true;
  3194. params.n_ubatch = 1024;
  3195. params.n_batch = 1024;
  3196. params.n_ctx = 0;
  3197. params.n_cache_reuse = 256;
  3198. }
  3199. ).set_examples({LLAMA_EXAMPLE_SERVER}));
  3200. return ctx_arg;
  3201. }