1
0

arg.cpp 135 KB

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