arg.cpp 155 KB

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