arg.cpp 136 KB

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