common.cpp 133 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375
  1. #include "common.h"
  2. // Change JSON_ASSERT from assert() to GGML_ASSERT:
  3. #define JSON_ASSERT GGML_ASSERT
  4. #include "json.hpp"
  5. #include "json-schema-to-grammar.h"
  6. #include "llama.h"
  7. #include <algorithm>
  8. #include <cassert>
  9. #include <cinttypes>
  10. #include <cmath>
  11. #include <codecvt>
  12. #include <cstdarg>
  13. #include <cstring>
  14. #include <ctime>
  15. #include <fstream>
  16. #include <iostream>
  17. #include <iterator>
  18. #include <regex>
  19. #include <sstream>
  20. #include <string>
  21. #include <unordered_map>
  22. #include <unordered_set>
  23. #include <vector>
  24. #if defined(__APPLE__) && defined(__MACH__)
  25. #include <sys/types.h>
  26. #include <sys/sysctl.h>
  27. #endif
  28. #if defined(_WIN32)
  29. #define WIN32_LEAN_AND_MEAN
  30. #ifndef NOMINMAX
  31. # define NOMINMAX
  32. #endif
  33. #include <locale>
  34. #include <windows.h>
  35. #include <fcntl.h>
  36. #include <io.h>
  37. #else
  38. #include <sys/ioctl.h>
  39. #include <sys/stat.h>
  40. #include <unistd.h>
  41. #endif
  42. #if defined(LLAMA_USE_CURL)
  43. #include <curl/curl.h>
  44. #include <curl/easy.h>
  45. #include <thread>
  46. #include <future>
  47. #endif
  48. #if defined(_MSC_VER)
  49. #pragma warning(disable: 4244 4267) // possible loss of data
  50. #endif
  51. #if (defined(GGML_USE_CUDA) || defined(GGML_USE_SYCL))
  52. #define GGML_USE_CUDA_SYCL
  53. #endif
  54. #if (defined(GGML_USE_CUDA) || defined(GGML_USE_SYCL)) || defined(GGML_USE_VULKAN)
  55. #define GGML_USE_CUDA_SYCL_VULKAN
  56. #endif
  57. #if defined(LLAMA_USE_CURL)
  58. #ifdef __linux__
  59. #include <linux/limits.h>
  60. #elif defined(_WIN32)
  61. #define PATH_MAX MAX_PATH
  62. #else
  63. #include <sys/syslimits.h>
  64. #endif
  65. #define LLAMA_CURL_MAX_URL_LENGTH 2084 // Maximum URL Length in Chrome: 2083
  66. #endif // LLAMA_USE_CURL
  67. using json = nlohmann::ordered_json;
  68. //
  69. // CPU utils
  70. //
  71. int32_t cpu_get_num_physical_cores() {
  72. #ifdef __linux__
  73. // enumerate the set of thread siblings, num entries is num cores
  74. std::unordered_set<std::string> siblings;
  75. for (uint32_t cpu=0; cpu < UINT32_MAX; ++cpu) {
  76. std::ifstream thread_siblings("/sys/devices/system/cpu/cpu"
  77. + std::to_string(cpu) + "/topology/thread_siblings");
  78. if (!thread_siblings.is_open()) {
  79. break; // no more cpus
  80. }
  81. std::string line;
  82. if (std::getline(thread_siblings, line)) {
  83. siblings.insert(line);
  84. }
  85. }
  86. if (!siblings.empty()) {
  87. return static_cast<int32_t>(siblings.size());
  88. }
  89. #elif defined(__APPLE__) && defined(__MACH__)
  90. int32_t num_physical_cores;
  91. size_t len = sizeof(num_physical_cores);
  92. int result = sysctlbyname("hw.perflevel0.physicalcpu", &num_physical_cores, &len, NULL, 0);
  93. if (result == 0) {
  94. return num_physical_cores;
  95. }
  96. result = sysctlbyname("hw.physicalcpu", &num_physical_cores, &len, NULL, 0);
  97. if (result == 0) {
  98. return num_physical_cores;
  99. }
  100. #elif defined(_WIN32)
  101. //TODO: Implement
  102. #endif
  103. unsigned int n_threads = std::thread::hardware_concurrency();
  104. return n_threads > 0 ? (n_threads <= 4 ? n_threads : n_threads / 2) : 4;
  105. }
  106. #if defined(__x86_64__) && defined(__linux__) && !defined(__ANDROID__)
  107. #include <pthread.h>
  108. static void cpuid(unsigned leaf, unsigned subleaf,
  109. unsigned *eax, unsigned *ebx, unsigned *ecx, unsigned *edx) {
  110. __asm__("movq\t%%rbx,%%rsi\n\t"
  111. "cpuid\n\t"
  112. "xchgq\t%%rbx,%%rsi"
  113. : "=a"(*eax), "=S"(*ebx), "=c"(*ecx), "=d"(*edx)
  114. : "0"(leaf), "2"(subleaf));
  115. }
  116. static int pin_cpu(int cpu) {
  117. cpu_set_t mask;
  118. CPU_ZERO(&mask);
  119. CPU_SET(cpu, &mask);
  120. return pthread_setaffinity_np(pthread_self(), sizeof(mask), &mask);
  121. }
  122. static bool is_hybrid_cpu(void) {
  123. unsigned eax, ebx, ecx, edx;
  124. cpuid(7, 0, &eax, &ebx, &ecx, &edx);
  125. return !!(edx & (1u << 15));
  126. }
  127. static bool is_running_on_efficiency_core(void) {
  128. unsigned eax, ebx, ecx, edx;
  129. cpuid(0x1a, 0, &eax, &ebx, &ecx, &edx);
  130. int intel_atom = 0x20;
  131. int core_type = (eax & 0xff000000u) >> 24;
  132. return core_type == intel_atom;
  133. }
  134. static int cpu_count_math_cpus(int n_cpu) {
  135. int result = 0;
  136. for (int cpu = 0; cpu < n_cpu; ++cpu) {
  137. if (pin_cpu(cpu)) {
  138. return -1;
  139. }
  140. if (is_running_on_efficiency_core()) {
  141. continue; // efficiency cores harm lockstep threading
  142. }
  143. ++cpu; // hyperthreading isn't useful for linear algebra
  144. ++result;
  145. }
  146. return result;
  147. }
  148. #endif // __x86_64__ && __linux__
  149. /**
  150. * Returns number of CPUs on system that are useful for math.
  151. */
  152. int32_t cpu_get_num_math() {
  153. #if defined(__x86_64__) && defined(__linux__) && !defined(__ANDROID__)
  154. int n_cpu = sysconf(_SC_NPROCESSORS_ONLN);
  155. if (n_cpu < 1) {
  156. return cpu_get_num_physical_cores();
  157. }
  158. if (is_hybrid_cpu()) {
  159. cpu_set_t affinity;
  160. if (!pthread_getaffinity_np(pthread_self(), sizeof(affinity), &affinity)) {
  161. int result = cpu_count_math_cpus(n_cpu);
  162. pthread_setaffinity_np(pthread_self(), sizeof(affinity), &affinity);
  163. if (result > 0) {
  164. return result;
  165. }
  166. }
  167. }
  168. #endif
  169. return cpu_get_num_physical_cores();
  170. }
  171. //
  172. // CLI argument parsing
  173. //
  174. void gpt_params_handle_model_default(gpt_params & params) {
  175. if (!params.hf_repo.empty()) {
  176. // short-hand to avoid specifying --hf-file -> default it to --model
  177. if (params.hf_file.empty()) {
  178. if (params.model.empty()) {
  179. throw std::invalid_argument("error: --hf-repo requires either --hf-file or --model\n");
  180. }
  181. params.hf_file = params.model;
  182. } else if (params.model.empty()) {
  183. std::string cache_directory = fs_get_cache_directory();
  184. const bool success = fs_create_directory_with_parents(cache_directory);
  185. if (!success) {
  186. throw std::runtime_error("failed to create cache directory: " + cache_directory);
  187. }
  188. params.model = cache_directory + string_split(params.hf_file, '/').back();
  189. }
  190. } else if (!params.model_url.empty()) {
  191. if (params.model.empty()) {
  192. auto f = string_split(params.model_url, '#').front();
  193. f = string_split(f, '?').front();
  194. f = string_split(f, '/').back();
  195. params.model = "models/" + f;
  196. }
  197. } else if (params.model.empty()) {
  198. params.model = DEFAULT_MODEL_PATH;
  199. }
  200. }
  201. bool gpt_params_parse_ex(int argc, char ** argv, gpt_params & params) {
  202. bool invalid_param = false;
  203. std::string arg;
  204. const std::string arg_prefix = "--";
  205. llama_sampling_params & sparams = params.sparams;
  206. for (int i = 1; i < argc; i++) {
  207. arg = argv[i];
  208. if (arg.compare(0, arg_prefix.size(), arg_prefix) == 0) {
  209. std::replace(arg.begin(), arg.end(), '_', '-');
  210. }
  211. if (!gpt_params_find_arg(argc, argv, arg, params, i, invalid_param)) {
  212. throw std::invalid_argument("error: unknown argument: " + arg);
  213. }
  214. if (invalid_param) {
  215. throw std::invalid_argument("error: invalid parameter for argument: " + arg);
  216. }
  217. }
  218. if (params.prompt_cache_all && (params.interactive || params.interactive_first)) {
  219. throw std::invalid_argument("error: --prompt-cache-all not supported in interactive mode yet\n");
  220. }
  221. gpt_params_handle_model_default(params);
  222. if (params.escape) {
  223. string_process_escapes(params.prompt);
  224. string_process_escapes(params.input_prefix);
  225. string_process_escapes(params.input_suffix);
  226. string_process_escapes(sparams.cfg_negative_prompt);
  227. for (auto & antiprompt : params.antiprompt) {
  228. string_process_escapes(antiprompt);
  229. }
  230. }
  231. if (!params.kv_overrides.empty()) {
  232. params.kv_overrides.emplace_back();
  233. params.kv_overrides.back().key[0] = 0;
  234. }
  235. return true;
  236. }
  237. bool gpt_params_parse(int argc, char ** argv, gpt_params & params) {
  238. const auto params_org = params; // the example can modify the default params
  239. try {
  240. if (!gpt_params_parse_ex(argc, argv, params) || params.usage) {
  241. params = params_org;
  242. params.usage = true;
  243. return false;
  244. }
  245. } catch (const std::invalid_argument & ex) {
  246. fprintf(stderr, "%s\n", ex.what());
  247. params = params_org;
  248. return false;
  249. }
  250. return true;
  251. }
  252. bool gpt_params_find_arg(int argc, char ** argv, const std::string & arg, gpt_params & params, int & i, bool & invalid_param) {
  253. const char split_delim = ',';
  254. llama_sampling_params & sparams = params.sparams;
  255. if (arg == "-s" || arg == "--seed") {
  256. if (++i >= argc) {
  257. invalid_param = true;
  258. return true;
  259. }
  260. // TODO: this is temporary, in the future the sampling state will be moved fully to llama_sampling_context.
  261. params.seed = std::stoul(argv[i]);
  262. sparams.seed = std::stoul(argv[i]);
  263. return true;
  264. }
  265. if (arg == "-t" || arg == "--threads") {
  266. if (++i >= argc) {
  267. invalid_param = true;
  268. return true;
  269. }
  270. params.n_threads = std::stoi(argv[i]);
  271. if (params.n_threads <= 0) {
  272. params.n_threads = std::thread::hardware_concurrency();
  273. }
  274. return true;
  275. }
  276. if (arg == "-tb" || arg == "--threads-batch") {
  277. if (++i >= argc) {
  278. invalid_param = true;
  279. return true;
  280. }
  281. params.n_threads_batch = std::stoi(argv[i]);
  282. if (params.n_threads_batch <= 0) {
  283. params.n_threads_batch = std::thread::hardware_concurrency();
  284. }
  285. return true;
  286. }
  287. if (arg == "-td" || arg == "--threads-draft") {
  288. if (++i >= argc) {
  289. invalid_param = true;
  290. return true;
  291. }
  292. params.n_threads_draft = std::stoi(argv[i]);
  293. if (params.n_threads_draft <= 0) {
  294. params.n_threads_draft = std::thread::hardware_concurrency();
  295. }
  296. return true;
  297. }
  298. if (arg == "-tbd" || arg == "--threads-batch-draft") {
  299. if (++i >= argc) {
  300. invalid_param = true;
  301. return true;
  302. }
  303. params.n_threads_batch_draft = std::stoi(argv[i]);
  304. if (params.n_threads_batch_draft <= 0) {
  305. params.n_threads_batch_draft = std::thread::hardware_concurrency();
  306. }
  307. return true;
  308. }
  309. if (arg == "-p" || arg == "--prompt") {
  310. if (++i >= argc) {
  311. invalid_param = true;
  312. return true;
  313. }
  314. params.prompt = argv[i];
  315. return true;
  316. }
  317. if (arg == "-e" || arg == "--escape") {
  318. params.escape = true;
  319. return true;
  320. }
  321. if (arg == "--no-escape") {
  322. params.escape = false;
  323. return true;
  324. }
  325. if (arg == "--prompt-cache") {
  326. if (++i >= argc) {
  327. invalid_param = true;
  328. return true;
  329. }
  330. params.path_prompt_cache = argv[i];
  331. return true;
  332. }
  333. if (arg == "--prompt-cache-all") {
  334. params.prompt_cache_all = true;
  335. return true;
  336. }
  337. if (arg == "--prompt-cache-ro") {
  338. params.prompt_cache_ro = true;
  339. return true;
  340. }
  341. if (arg == "-bf" || arg == "--binary-file") {
  342. if (++i >= argc) {
  343. invalid_param = true;
  344. return true;
  345. }
  346. std::ifstream file(argv[i], std::ios::binary);
  347. if (!file) {
  348. fprintf(stderr, "error: failed to open file '%s'\n", argv[i]);
  349. invalid_param = true;
  350. return true;
  351. }
  352. // store the external file name in params
  353. params.prompt_file = argv[i];
  354. std::ostringstream ss;
  355. ss << file.rdbuf();
  356. params.prompt = ss.str();
  357. fprintf(stderr, "Read %zu bytes from binary file %s\n", params.prompt.size(), argv[i]);
  358. return true;
  359. }
  360. if (arg == "-f" || arg == "--file") {
  361. if (++i >= argc) {
  362. invalid_param = true;
  363. return true;
  364. }
  365. std::ifstream file(argv[i]);
  366. if (!file) {
  367. fprintf(stderr, "error: failed to open file '%s'\n", argv[i]);
  368. invalid_param = true;
  369. return true;
  370. }
  371. // store the external file name in params
  372. params.prompt_file = argv[i];
  373. std::copy(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>(), back_inserter(params.prompt));
  374. if (!params.prompt.empty() && params.prompt.back() == '\n') {
  375. params.prompt.pop_back();
  376. }
  377. return true;
  378. }
  379. if (arg == "--in-file") {
  380. if (++i >= argc) {
  381. invalid_param = true;
  382. return true;
  383. }
  384. std::ifstream file(argv[i]);
  385. if (!file) {
  386. fprintf(stderr, "error: failed to open file '%s'\n", argv[i]);
  387. invalid_param = true;
  388. return true;
  389. }
  390. params.in_files.push_back(argv[i]);
  391. return true;
  392. }
  393. if (arg == "-n" || arg == "--predict" || arg == "--n-predict") {
  394. if (++i >= argc) {
  395. invalid_param = true;
  396. return true;
  397. }
  398. params.n_predict = std::stoi(argv[i]);
  399. return true;
  400. }
  401. if (arg == "--top-k") {
  402. if (++i >= argc) {
  403. invalid_param = true;
  404. return true;
  405. }
  406. sparams.top_k = std::stoi(argv[i]);
  407. return true;
  408. }
  409. if (arg == "-c" || arg == "--ctx-size") {
  410. if (++i >= argc) {
  411. invalid_param = true;
  412. return true;
  413. }
  414. params.n_ctx = std::stoi(argv[i]);
  415. return true;
  416. }
  417. if (arg == "--grp-attn-n" || arg == "-gan") {
  418. if (++i >= argc) {
  419. invalid_param = true;
  420. return true;
  421. }
  422. params.grp_attn_n = std::stoi(argv[i]);
  423. return true;
  424. }
  425. if (arg == "--grp-attn-w" || arg == "-gaw") {
  426. if (++i >= argc) {
  427. invalid_param = true;
  428. return true;
  429. }
  430. params.grp_attn_w = std::stoi(argv[i]);
  431. return true;
  432. }
  433. if (arg == "--rope-freq-base") {
  434. if (++i >= argc) {
  435. invalid_param = true;
  436. return true;
  437. }
  438. params.rope_freq_base = std::stof(argv[i]);
  439. return true;
  440. }
  441. if (arg == "--rope-freq-scale") {
  442. if (++i >= argc) {
  443. invalid_param = true;
  444. return true;
  445. }
  446. params.rope_freq_scale = std::stof(argv[i]);
  447. return true;
  448. }
  449. if (arg == "--rope-scaling") {
  450. if (++i >= argc) {
  451. invalid_param = true;
  452. return true;
  453. }
  454. std::string value(argv[i]);
  455. /**/ if (value == "none") { params.rope_scaling_type = LLAMA_ROPE_SCALING_TYPE_NONE; }
  456. else if (value == "linear") { params.rope_scaling_type = LLAMA_ROPE_SCALING_TYPE_LINEAR; }
  457. else if (value == "yarn") { params.rope_scaling_type = LLAMA_ROPE_SCALING_TYPE_YARN; }
  458. else { invalid_param = true; }
  459. return true;
  460. }
  461. if (arg == "--rope-scale") {
  462. if (++i >= argc) {
  463. invalid_param = true;
  464. return true;
  465. }
  466. params.rope_freq_scale = 1.0f / std::stof(argv[i]);
  467. return true;
  468. }
  469. if (arg == "--yarn-orig-ctx") {
  470. if (++i >= argc) {
  471. invalid_param = true;
  472. return true;
  473. }
  474. params.yarn_orig_ctx = std::stoi(argv[i]);
  475. return true;
  476. }
  477. if (arg == "--yarn-ext-factor") {
  478. if (++i >= argc) {
  479. invalid_param = true;
  480. return true;
  481. }
  482. params.yarn_ext_factor = std::stof(argv[i]);
  483. return true;
  484. }
  485. if (arg == "--yarn-attn-factor") {
  486. if (++i >= argc) {
  487. invalid_param = true;
  488. return true;
  489. }
  490. params.yarn_attn_factor = std::stof(argv[i]);
  491. return true;
  492. }
  493. if (arg == "--yarn-beta-fast") {
  494. if (++i >= argc) {
  495. invalid_param = true;
  496. return true;
  497. }
  498. params.yarn_beta_fast = std::stof(argv[i]);
  499. return true;
  500. }
  501. if (arg == "--yarn-beta-slow") {
  502. if (++i >= argc) {
  503. invalid_param = true;
  504. return true;
  505. }
  506. params.yarn_beta_slow = std::stof(argv[i]);
  507. return true;
  508. }
  509. if (arg == "--pooling") {
  510. if (++i >= argc) {
  511. invalid_param = true;
  512. return true;
  513. }
  514. std::string value(argv[i]);
  515. /**/ if (value == "none") { params.pooling_type = LLAMA_POOLING_TYPE_NONE; }
  516. else if (value == "mean") { params.pooling_type = LLAMA_POOLING_TYPE_MEAN; }
  517. else if (value == "cls") { params.pooling_type = LLAMA_POOLING_TYPE_CLS; }
  518. else { invalid_param = true; }
  519. return true;
  520. }
  521. if (arg == "--defrag-thold" || arg == "-dt") {
  522. if (++i >= argc) {
  523. invalid_param = true;
  524. return true;
  525. }
  526. params.defrag_thold = std::stof(argv[i]);
  527. return true;
  528. }
  529. if (arg == "--samplers") {
  530. if (++i >= argc) {
  531. invalid_param = true;
  532. return true;
  533. }
  534. const auto sampler_names = string_split(argv[i], ';');
  535. sparams.samplers_sequence = llama_sampling_types_from_names(sampler_names, true);
  536. return true;
  537. }
  538. if (arg == "--sampling-seq") {
  539. if (++i >= argc) {
  540. invalid_param = true;
  541. return true;
  542. }
  543. sparams.samplers_sequence = llama_sampling_types_from_chars(argv[i]);
  544. return true;
  545. }
  546. if (arg == "--top-p") {
  547. if (++i >= argc) {
  548. invalid_param = true;
  549. return true;
  550. }
  551. sparams.top_p = std::stof(argv[i]);
  552. return true;
  553. }
  554. if (arg == "--min-p") {
  555. if (++i >= argc) {
  556. invalid_param = true;
  557. return true;
  558. }
  559. sparams.min_p = std::stof(argv[i]);
  560. return true;
  561. }
  562. if (arg == "--temp") {
  563. if (++i >= argc) {
  564. invalid_param = true;
  565. return true;
  566. }
  567. sparams.temp = std::stof(argv[i]);
  568. sparams.temp = std::max(sparams.temp, 0.0f);
  569. return true;
  570. }
  571. if (arg == "--tfs") {
  572. if (++i >= argc) {
  573. invalid_param = true;
  574. return true;
  575. }
  576. sparams.tfs_z = std::stof(argv[i]);
  577. return true;
  578. }
  579. if (arg == "--typical") {
  580. if (++i >= argc) {
  581. invalid_param = true;
  582. return true;
  583. }
  584. sparams.typical_p = std::stof(argv[i]);
  585. return true;
  586. }
  587. if (arg == "--repeat-last-n") {
  588. if (++i >= argc) {
  589. invalid_param = true;
  590. return true;
  591. }
  592. sparams.penalty_last_n = std::stoi(argv[i]);
  593. sparams.n_prev = std::max(sparams.n_prev, sparams.penalty_last_n);
  594. return true;
  595. }
  596. if (arg == "--repeat-penalty") {
  597. if (++i >= argc) {
  598. invalid_param = true;
  599. return true;
  600. }
  601. sparams.penalty_repeat = std::stof(argv[i]);
  602. return true;
  603. }
  604. if (arg == "--frequency-penalty") {
  605. if (++i >= argc) {
  606. invalid_param = true;
  607. return true;
  608. }
  609. sparams.penalty_freq = std::stof(argv[i]);
  610. return true;
  611. }
  612. if (arg == "--presence-penalty") {
  613. if (++i >= argc) {
  614. invalid_param = true;
  615. return true;
  616. }
  617. sparams.penalty_present = std::stof(argv[i]);
  618. return true;
  619. }
  620. if (arg == "--dynatemp-range") {
  621. if (++i >= argc) {
  622. invalid_param = true;
  623. return true;
  624. }
  625. sparams.dynatemp_range = std::stof(argv[i]);
  626. return true;
  627. }
  628. if (arg == "--dynatemp-exp") {
  629. if (++i >= argc) {
  630. invalid_param = true;
  631. return true;
  632. }
  633. sparams.dynatemp_exponent = std::stof(argv[i]);
  634. return true;
  635. }
  636. if (arg == "--mirostat") {
  637. if (++i >= argc) {
  638. invalid_param = true;
  639. return true;
  640. }
  641. sparams.mirostat = std::stoi(argv[i]);
  642. return true;
  643. }
  644. if (arg == "--mirostat-lr") {
  645. if (++i >= argc) {
  646. invalid_param = true;
  647. return true;
  648. }
  649. sparams.mirostat_eta = std::stof(argv[i]);
  650. return true;
  651. }
  652. if (arg == "--mirostat-ent") {
  653. if (++i >= argc) {
  654. invalid_param = true;
  655. return true;
  656. }
  657. sparams.mirostat_tau = std::stof(argv[i]);
  658. return true;
  659. }
  660. if (arg == "--cfg-negative-prompt") {
  661. if (++i >= argc) {
  662. invalid_param = true;
  663. return true;
  664. }
  665. sparams.cfg_negative_prompt = argv[i];
  666. return true;
  667. }
  668. if (arg == "--cfg-negative-prompt-file") {
  669. if (++i >= argc) {
  670. invalid_param = true;
  671. return true;
  672. }
  673. std::ifstream file(argv[i]);
  674. if (!file) {
  675. fprintf(stderr, "error: failed to open file '%s'\n", argv[i]);
  676. invalid_param = true;
  677. return true;
  678. }
  679. std::copy(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>(), back_inserter(sparams.cfg_negative_prompt));
  680. if (!sparams.cfg_negative_prompt.empty() && sparams.cfg_negative_prompt.back() == '\n') {
  681. sparams.cfg_negative_prompt.pop_back();
  682. }
  683. return true;
  684. }
  685. if (arg == "--cfg-scale") {
  686. if (++i >= argc) {
  687. invalid_param = true;
  688. return true;
  689. }
  690. sparams.cfg_scale = std::stof(argv[i]);
  691. return true;
  692. }
  693. if (arg == "-b" || arg == "--batch-size") {
  694. if (++i >= argc) {
  695. invalid_param = true;
  696. return true;
  697. }
  698. params.n_batch = std::stoi(argv[i]);
  699. return true;
  700. }
  701. if (arg == "-ub" || arg == "--ubatch-size") {
  702. if (++i >= argc) {
  703. invalid_param = true;
  704. return true;
  705. }
  706. params.n_ubatch = std::stoi(argv[i]);
  707. return true;
  708. }
  709. if (arg == "--keep") {
  710. if (++i >= argc) {
  711. invalid_param = true;
  712. return true;
  713. }
  714. params.n_keep = std::stoi(argv[i]);
  715. return true;
  716. }
  717. if (arg == "--draft") {
  718. if (++i >= argc) {
  719. invalid_param = true;
  720. return true;
  721. }
  722. params.n_draft = std::stoi(argv[i]);
  723. return true;
  724. }
  725. if (arg == "--chunks") {
  726. if (++i >= argc) {
  727. invalid_param = true;
  728. return true;
  729. }
  730. params.n_chunks = std::stoi(argv[i]);
  731. return true;
  732. }
  733. if (arg == "-np" || arg == "--parallel") {
  734. if (++i >= argc) {
  735. invalid_param = true;
  736. return true;
  737. }
  738. params.n_parallel = std::stoi(argv[i]);
  739. return true;
  740. }
  741. if (arg == "-ns" || arg == "--sequences") {
  742. if (++i >= argc) {
  743. invalid_param = true;
  744. return true;
  745. }
  746. params.n_sequences = std::stoi(argv[i]);
  747. return true;
  748. }
  749. if (arg == "--p-split" || arg == "-ps") {
  750. if (++i >= argc) {
  751. invalid_param = true;
  752. return true;
  753. }
  754. params.p_split = std::stof(argv[i]);
  755. return true;
  756. }
  757. if (arg == "-m" || arg == "--model") {
  758. if (++i >= argc) {
  759. invalid_param = true;
  760. return true;
  761. }
  762. params.model = argv[i];
  763. return true;
  764. }
  765. if (arg == "-md" || arg == "--model-draft") {
  766. if (++i >= argc) {
  767. invalid_param = true;
  768. return true;
  769. }
  770. params.model_draft = argv[i];
  771. return true;
  772. }
  773. if (arg == "-a" || arg == "--alias") {
  774. if (++i >= argc) {
  775. invalid_param = true;
  776. return true;
  777. }
  778. params.model_alias = argv[i];
  779. return true;
  780. }
  781. if (arg == "-mu" || arg == "--model-url") {
  782. if (++i >= argc) {
  783. invalid_param = true;
  784. return true;
  785. }
  786. params.model_url = argv[i];
  787. return true;
  788. }
  789. if (arg == "-hfr" || arg == "--hf-repo") {
  790. if (++i >= argc) {
  791. invalid_param = true;
  792. return true;
  793. }
  794. params.hf_repo = argv[i];
  795. return true;
  796. }
  797. if (arg == "-hff" || arg == "--hf-file") {
  798. if (++i >= argc) {
  799. invalid_param = true;
  800. return true;
  801. }
  802. params.hf_file = argv[i];
  803. return true;
  804. }
  805. if (arg == "--lora") {
  806. if (++i >= argc) {
  807. invalid_param = true;
  808. return true;
  809. }
  810. params.lora_adapter.emplace_back(argv[i], 1.0f);
  811. params.use_mmap = false;
  812. return true;
  813. }
  814. if (arg == "--lora-scaled") {
  815. if (++i >= argc) {
  816. invalid_param = true;
  817. return true;
  818. }
  819. const char* lora_adapter = argv[i];
  820. if (++i >= argc) {
  821. invalid_param = true;
  822. return true;
  823. }
  824. params.lora_adapter.emplace_back(lora_adapter, std::stof(argv[i]));
  825. params.use_mmap = false;
  826. return true;
  827. }
  828. if (arg == "--lora-base") {
  829. if (++i >= argc) {
  830. invalid_param = true;
  831. return true;
  832. }
  833. params.lora_base = argv[i];
  834. return true;
  835. }
  836. if (arg == "--control-vector") {
  837. if (++i >= argc) {
  838. invalid_param = true;
  839. return true;
  840. }
  841. params.control_vectors.push_back({ 1.0f, argv[i], });
  842. return true;
  843. }
  844. if (arg == "--control-vector-scaled") {
  845. if (++i >= argc) {
  846. invalid_param = true;
  847. return true;
  848. }
  849. const char* fname = argv[i];
  850. if (++i >= argc) {
  851. invalid_param = true;
  852. return true;
  853. }
  854. params.control_vectors.push_back({ std::stof(argv[i]), fname, });
  855. return true;
  856. }
  857. if (arg == "--control-vector-layer-range") {
  858. if (++i >= argc) {
  859. invalid_param = true;
  860. return true;
  861. }
  862. params.control_vector_layer_start = std::stoi(argv[i]);
  863. if (++i >= argc) {
  864. invalid_param = true;
  865. return true;
  866. }
  867. params.control_vector_layer_end = std::stoi(argv[i]);
  868. return true;
  869. }
  870. if (arg == "--mmproj") {
  871. if (++i >= argc) {
  872. invalid_param = true;
  873. return true;
  874. }
  875. params.mmproj = argv[i];
  876. return true;
  877. }
  878. if (arg == "--image") {
  879. if (++i >= argc) {
  880. invalid_param = true;
  881. return true;
  882. }
  883. params.image.emplace_back(argv[i]);
  884. return true;
  885. }
  886. if (arg == "-i" || arg == "--interactive") {
  887. params.interactive = true;
  888. return true;
  889. }
  890. if (arg == "-sp" || arg == "--special") {
  891. params.special = true;
  892. return true;
  893. }
  894. if (arg == "--embedding" || arg == "--embeddings") {
  895. params.embedding = true;
  896. return true;
  897. }
  898. if (arg == "-if" || arg == "--interactive-first") {
  899. params.interactive_first = true;
  900. return true;
  901. }
  902. if (arg == "-cnv" || arg == "--conversation") {
  903. params.conversation = true;
  904. return true;
  905. }
  906. if (arg == "--infill") {
  907. params.infill = true;
  908. return true;
  909. }
  910. if (arg == "-dkvc" || arg == "--dump-kv-cache") {
  911. params.dump_kv_cache = true;
  912. return true;
  913. }
  914. if (arg == "-nkvo" || arg == "--no-kv-offload") {
  915. params.no_kv_offload = true;
  916. return true;
  917. }
  918. if (arg == "-ctk" || arg == "--cache-type-k") {
  919. params.cache_type_k = argv[++i];
  920. return true;
  921. }
  922. if (arg == "-ctv" || arg == "--cache-type-v") {
  923. params.cache_type_v = argv[++i];
  924. return true;
  925. }
  926. if (arg == "--multiline-input") {
  927. params.multiline_input = true;
  928. return true;
  929. }
  930. if (arg == "--simple-io") {
  931. params.simple_io = true;
  932. return true;
  933. }
  934. if (arg == "-cb" || arg == "--cont-batching") {
  935. params.cont_batching = true;
  936. return true;
  937. }
  938. if (arg == "-fa" || arg == "--flash-attn") {
  939. params.flash_attn = true;
  940. return true;
  941. }
  942. if (arg == "-co" || arg == "--color") {
  943. params.use_color = true;
  944. return true;
  945. }
  946. if (arg == "--mlock") {
  947. params.use_mlock = true;
  948. return true;
  949. }
  950. if (arg == "-ngl" || arg == "--gpu-layers" || arg == "--n-gpu-layers") {
  951. if (++i >= argc) {
  952. invalid_param = true;
  953. return true;
  954. }
  955. params.n_gpu_layers = std::stoi(argv[i]);
  956. if (!llama_supports_gpu_offload()) {
  957. fprintf(stderr, "warning: not compiled with GPU offload support, --gpu-layers option will be ignored\n");
  958. fprintf(stderr, "warning: see main README.md for information on enabling GPU BLAS support\n");
  959. }
  960. return true;
  961. }
  962. if (arg == "-ngld" || arg == "--gpu-layers-draft" || arg == "--gpu-layers-draft") {
  963. if (++i >= argc) {
  964. invalid_param = true;
  965. return true;
  966. }
  967. params.n_gpu_layers_draft = std::stoi(argv[i]);
  968. if (!llama_supports_gpu_offload()) {
  969. fprintf(stderr, "warning: not compiled with GPU offload support, --gpu-layers-draft option will be ignored\n");
  970. fprintf(stderr, "warning: see main README.md for information on enabling GPU BLAS support\n");
  971. }
  972. return true;
  973. }
  974. if (arg == "--main-gpu" || arg == "-mg") {
  975. if (++i >= argc) {
  976. invalid_param = true;
  977. return true;
  978. }
  979. params.main_gpu = std::stoi(argv[i]);
  980. #ifndef GGML_USE_CUDA_SYCL_VULKAN
  981. fprintf(stderr, "warning: llama.cpp was compiled without CUDA/SYCL/Vulkan. Setting the main GPU has no effect.\n");
  982. #endif // GGML_USE_CUDA_SYCL_VULKAN
  983. return true;
  984. }
  985. if (arg == "--split-mode" || arg == "-sm") {
  986. if (++i >= argc) {
  987. invalid_param = true;
  988. return true;
  989. }
  990. std::string arg_next = argv[i];
  991. if (arg_next == "none") {
  992. params.split_mode = LLAMA_SPLIT_MODE_NONE;
  993. }
  994. else if (arg_next == "layer") {
  995. params.split_mode = LLAMA_SPLIT_MODE_LAYER;
  996. }
  997. else if (arg_next == "row") {
  998. #ifdef GGML_USE_SYCL
  999. fprintf(stderr, "warning: The split mode value:[row] is not supported by llama.cpp with SYCL. It's developing.\nExit!\n");
  1000. exit(1);
  1001. #endif // GGML_USE_SYCL
  1002. params.split_mode = LLAMA_SPLIT_MODE_ROW;
  1003. }
  1004. else {
  1005. invalid_param = true;
  1006. return true;
  1007. }
  1008. #ifndef GGML_USE_CUDA_SYCL_VULKAN
  1009. fprintf(stderr, "warning: llama.cpp was compiled without CUDA/SYCL/Vulkan. Setting the split mode has no effect.\n");
  1010. #endif // GGML_USE_CUDA_SYCL_VULKAN
  1011. return true;
  1012. }
  1013. if (arg == "--tensor-split" || arg == "-ts") {
  1014. if (++i >= argc) {
  1015. invalid_param = true;
  1016. return true;
  1017. }
  1018. std::string arg_next = argv[i];
  1019. // split string by , and /
  1020. const std::regex regex{ R"([,/]+)" };
  1021. std::sregex_token_iterator it{ arg_next.begin(), arg_next.end(), regex, -1 };
  1022. std::vector<std::string> split_arg{ it, {} };
  1023. if (split_arg.size() >= llama_max_devices()) {
  1024. invalid_param = true;
  1025. return true;
  1026. }
  1027. for (size_t i = 0; i < llama_max_devices(); ++i) {
  1028. if (i < split_arg.size()) {
  1029. params.tensor_split[i] = std::stof(split_arg[i]);
  1030. }
  1031. else {
  1032. params.tensor_split[i] = 0.0f;
  1033. }
  1034. }
  1035. #ifndef GGML_USE_CUDA_SYCL_VULKAN
  1036. fprintf(stderr, "warning: llama.cpp was compiled without CUDA/SYCL/Vulkan. Setting a tensor split has no effect.\n");
  1037. #endif // GGML_USE_CUDA_SYCL_VULKAN
  1038. return true;
  1039. }
  1040. if (arg == "--rpc") {
  1041. if (++i >= argc) {
  1042. invalid_param = true;
  1043. return true;
  1044. }
  1045. params.rpc_servers = argv[i];
  1046. return true;
  1047. }
  1048. if (arg == "--no-mmap") {
  1049. params.use_mmap = false;
  1050. return true;
  1051. }
  1052. if (arg == "--numa") {
  1053. if (++i >= argc) {
  1054. invalid_param = true;
  1055. return true;
  1056. }
  1057. std::string value(argv[i]);
  1058. /**/ if (value == "distribute" || value == "") { params.numa = GGML_NUMA_STRATEGY_DISTRIBUTE; }
  1059. else if (value == "isolate") { params.numa = GGML_NUMA_STRATEGY_ISOLATE; }
  1060. else if (value == "numactl") { params.numa = GGML_NUMA_STRATEGY_NUMACTL; }
  1061. else { invalid_param = true; }
  1062. return true;
  1063. }
  1064. if (arg == "-v" || arg == "--verbose") {
  1065. params.verbosity = 1;
  1066. return true;
  1067. }
  1068. if (arg == "--verbosity") {
  1069. if (++i >= argc) {
  1070. invalid_param = true;
  1071. return true;
  1072. }
  1073. params.verbosity = std::stoi(argv[i]);
  1074. return true;
  1075. }
  1076. if (arg == "--verbose-prompt") {
  1077. params.verbose_prompt = true;
  1078. return true;
  1079. }
  1080. if (arg == "--no-display-prompt") {
  1081. params.display_prompt = false;
  1082. return true;
  1083. }
  1084. if (arg == "-r" || arg == "--reverse-prompt") {
  1085. if (++i >= argc) {
  1086. invalid_param = true;
  1087. return true;
  1088. }
  1089. params.antiprompt.emplace_back(argv[i]);
  1090. return true;
  1091. }
  1092. if (arg == "-ld" || arg == "--logdir") {
  1093. if (++i >= argc) {
  1094. invalid_param = true;
  1095. return true;
  1096. }
  1097. params.logdir = argv[i];
  1098. if (params.logdir.back() != DIRECTORY_SEPARATOR) {
  1099. params.logdir += DIRECTORY_SEPARATOR;
  1100. }
  1101. return true;
  1102. }
  1103. if (arg == "-lcs" || arg == "--lookup-cache-static") {
  1104. if (++i >= argc) {
  1105. invalid_param = true;
  1106. return true;
  1107. }
  1108. params.lookup_cache_static = argv[i];
  1109. return true;
  1110. }
  1111. if (arg == "-lcd" || arg == "--lookup-cache-dynamic") {
  1112. if (++i >= argc) {
  1113. invalid_param = true;
  1114. return true;
  1115. }
  1116. params.lookup_cache_dynamic = argv[i];
  1117. return true;
  1118. }
  1119. if (arg == "--save-all-logits" || arg == "--kl-divergence-base") {
  1120. if (++i >= argc) {
  1121. invalid_param = true;
  1122. return true;
  1123. }
  1124. params.logits_file = argv[i];
  1125. return true;
  1126. }
  1127. if (arg == "--perplexity" || arg == "--all-logits") {
  1128. params.logits_all = true;
  1129. return true;
  1130. }
  1131. if (arg == "--ppl-stride") {
  1132. if (++i >= argc) {
  1133. invalid_param = true;
  1134. return true;
  1135. }
  1136. params.ppl_stride = std::stoi(argv[i]);
  1137. return true;
  1138. }
  1139. if (arg == "--ppl-output-type") {
  1140. if (++i >= argc) {
  1141. invalid_param = true;
  1142. return true;
  1143. }
  1144. params.ppl_output_type = std::stoi(argv[i]);
  1145. return true;
  1146. }
  1147. if (arg == "-ptc" || arg == "--print-token-count") {
  1148. if (++i >= argc) {
  1149. invalid_param = true;
  1150. return true;
  1151. }
  1152. params.n_print = std::stoi(argv[i]);
  1153. return true;
  1154. }
  1155. if (arg == "--check-tensors") {
  1156. params.check_tensors = true;
  1157. return true;
  1158. }
  1159. if (arg == "--hellaswag") {
  1160. params.hellaswag = true;
  1161. return true;
  1162. }
  1163. if (arg == "--hellaswag-tasks") {
  1164. if (++i >= argc) {
  1165. invalid_param = true;
  1166. return true;
  1167. }
  1168. params.hellaswag_tasks = std::stoi(argv[i]);
  1169. return true;
  1170. }
  1171. if (arg == "--winogrande") {
  1172. params.winogrande = true;
  1173. return true;
  1174. }
  1175. if (arg == "--winogrande-tasks") {
  1176. if (++i >= argc) {
  1177. invalid_param = true;
  1178. return true;
  1179. }
  1180. params.winogrande_tasks = std::stoi(argv[i]);
  1181. return true;
  1182. }
  1183. if (arg == "--multiple-choice") {
  1184. params.multiple_choice = true;
  1185. return true;
  1186. }
  1187. if (arg == "--multiple-choice-tasks") {
  1188. if (++i >= argc) {
  1189. invalid_param = true;
  1190. return true;
  1191. }
  1192. params.multiple_choice_tasks = std::stoi(argv[i]);
  1193. return true;
  1194. }
  1195. if (arg == "--kl-divergence") {
  1196. params.kl_divergence = true;
  1197. return true;
  1198. }
  1199. if (arg == "--ignore-eos") {
  1200. params.ignore_eos = true;
  1201. return true;
  1202. }
  1203. if (arg == "--penalize-nl") {
  1204. sparams.penalize_nl = true;
  1205. return true;
  1206. }
  1207. if (arg == "-l" || arg == "--logit-bias") {
  1208. if (++i >= argc) {
  1209. invalid_param = true;
  1210. return true;
  1211. }
  1212. std::stringstream ss(argv[i]);
  1213. llama_token key;
  1214. char sign;
  1215. std::string value_str;
  1216. try {
  1217. if (ss >> key && ss >> sign && std::getline(ss, value_str) && (sign == '+' || sign == '-')) {
  1218. sparams.logit_bias[key] = std::stof(value_str) * ((sign == '-') ? -1.0f : 1.0f);
  1219. }
  1220. else {
  1221. throw std::exception();
  1222. }
  1223. }
  1224. catch (const std::exception&) {
  1225. invalid_param = true;
  1226. return true;
  1227. }
  1228. return true;
  1229. }
  1230. if (arg == "-h" || arg == "--help" || arg == "--usage" ) {
  1231. params.usage = true;
  1232. return true;
  1233. }
  1234. if (arg == "--version") {
  1235. fprintf(stderr, "version: %d (%s)\n", LLAMA_BUILD_NUMBER, LLAMA_COMMIT);
  1236. fprintf(stderr, "built with %s for %s\n", LLAMA_COMPILER, LLAMA_BUILD_TARGET);
  1237. exit(0);
  1238. }
  1239. if (arg == "--in-prefix-bos") {
  1240. params.input_prefix_bos = true;
  1241. return true;
  1242. }
  1243. if (arg == "--in-prefix") {
  1244. if (++i >= argc) {
  1245. invalid_param = true;
  1246. return true;
  1247. }
  1248. params.input_prefix = argv[i];
  1249. return true;
  1250. }
  1251. if (arg == "--in-suffix") {
  1252. if (++i >= argc) {
  1253. invalid_param = true;
  1254. return true;
  1255. }
  1256. params.input_suffix = argv[i];
  1257. return true;
  1258. }
  1259. if (arg == "--grammar") {
  1260. if (++i >= argc) {
  1261. invalid_param = true;
  1262. return true;
  1263. }
  1264. sparams.grammar = argv[i];
  1265. return true;
  1266. }
  1267. if (arg == "--grammar-file") {
  1268. if (++i >= argc) {
  1269. invalid_param = true;
  1270. return true;
  1271. }
  1272. std::ifstream file(argv[i]);
  1273. if (!file) {
  1274. fprintf(stderr, "error: failed to open file '%s'\n", argv[i]);
  1275. invalid_param = true;
  1276. return true;
  1277. }
  1278. std::copy(
  1279. std::istreambuf_iterator<char>(file),
  1280. std::istreambuf_iterator<char>(),
  1281. std::back_inserter(sparams.grammar)
  1282. );
  1283. return true;
  1284. }
  1285. if (arg == "-j" || arg == "--json-schema") {
  1286. if (++i >= argc) {
  1287. invalid_param = true;
  1288. return true;
  1289. }
  1290. sparams.grammar = json_schema_to_grammar(json::parse(argv[i]));
  1291. return true;
  1292. }
  1293. if (arg == "--override-kv") {
  1294. if (++i >= argc) {
  1295. invalid_param = true;
  1296. return true;
  1297. }
  1298. if (!string_parse_kv_override(argv[i], params.kv_overrides)) {
  1299. fprintf(stderr, "error: Invalid type for KV override: %s\n", argv[i]);
  1300. invalid_param = true;
  1301. return true;
  1302. }
  1303. return true;
  1304. }
  1305. if (arg == "--host") {
  1306. if (++i >= argc) {
  1307. invalid_param = true;
  1308. return true;
  1309. }
  1310. params.hostname = argv[i];
  1311. return true;
  1312. }
  1313. if (arg == "--port") {
  1314. if (++i >= argc) {
  1315. invalid_param = true;
  1316. return true;
  1317. }
  1318. params.port = std::stoi(argv[i]);
  1319. return true;
  1320. }
  1321. if (arg == "--path") {
  1322. if (++i >= argc) {
  1323. invalid_param = true;
  1324. return true;
  1325. }
  1326. params.public_path = argv[i];
  1327. return true;
  1328. }
  1329. if (arg == "--api-key") {
  1330. if (++i >= argc) {
  1331. invalid_param = true;
  1332. return true;
  1333. }
  1334. params.api_keys.push_back(argv[i]);
  1335. return true;
  1336. }
  1337. if (arg == "--api-key-file") {
  1338. if (++i >= argc) {
  1339. invalid_param = true;
  1340. return true;
  1341. }
  1342. std::ifstream key_file(argv[i]);
  1343. if (!key_file) {
  1344. fprintf(stderr, "error: failed to open file '%s'\n", argv[i]);
  1345. invalid_param = true;
  1346. return true;
  1347. }
  1348. std::string key;
  1349. while (std::getline(key_file, key)) {
  1350. if (!key.empty()) {
  1351. params.api_keys.push_back(key);
  1352. }
  1353. }
  1354. key_file.close();
  1355. return true;
  1356. }
  1357. if (arg == "--ssl-key-file") {
  1358. if (++i >= argc) {
  1359. invalid_param = true;
  1360. return true;
  1361. }
  1362. params.ssl_file_key = argv[i];
  1363. return true;
  1364. }
  1365. if (arg == "--ssl-cert-file") {
  1366. if (++i >= argc) {
  1367. invalid_param = true;
  1368. return true;
  1369. }
  1370. params.ssl_file_cert = argv[i];
  1371. return true;
  1372. }
  1373. if (arg == "--timeout" || arg == "-to") {
  1374. if (++i >= argc) {
  1375. invalid_param = true;
  1376. return true;
  1377. }
  1378. params.timeout_read = std::stoi(argv[i]);
  1379. params.timeout_write = std::stoi(argv[i]);
  1380. return true;
  1381. }
  1382. if (arg == "--threads-http") {
  1383. if (++i >= argc) {
  1384. invalid_param = true;
  1385. return true;
  1386. }
  1387. params.n_threads_http = std::stoi(argv[i]);
  1388. return true;
  1389. }
  1390. if (arg == "-spf" || arg == "--system-prompt-file") {
  1391. if (++i >= argc) {
  1392. invalid_param = true;
  1393. return true;
  1394. }
  1395. std::ifstream file(argv[i]);
  1396. if (!file) {
  1397. fprintf(stderr, "error: failed to open file '%s'\n", argv[i]);
  1398. invalid_param = true;
  1399. return true;
  1400. }
  1401. std::string system_prompt;
  1402. std::copy(
  1403. std::istreambuf_iterator<char>(file),
  1404. std::istreambuf_iterator<char>(),
  1405. std::back_inserter(system_prompt)
  1406. );
  1407. params.system_prompt = system_prompt;
  1408. return true;
  1409. }
  1410. if (arg == "--log-format") {
  1411. if (++i >= argc) {
  1412. invalid_param = true;
  1413. return true;
  1414. }
  1415. if (std::strcmp(argv[i], "json") == 0) {
  1416. params.log_json = true;
  1417. } else if (std::strcmp(argv[i], "text") == 0) {
  1418. params.log_json = false;
  1419. } else {
  1420. invalid_param = true;
  1421. return true;
  1422. }
  1423. return true;
  1424. }
  1425. if (arg == "--no-slots") {
  1426. params.endpoint_slots = false;
  1427. return true;
  1428. }
  1429. if (arg == "--metrics") {
  1430. params.endpoint_metrics = true;
  1431. return true;
  1432. }
  1433. if (arg == "--slot-save-path") {
  1434. if (++i >= argc) {
  1435. invalid_param = true;
  1436. return true;
  1437. }
  1438. params.slot_save_path = argv[i];
  1439. // if doesn't end with DIRECTORY_SEPARATOR, add it
  1440. if (!params.slot_save_path.empty() && params.slot_save_path[params.slot_save_path.size() - 1] != DIRECTORY_SEPARATOR) {
  1441. params.slot_save_path += DIRECTORY_SEPARATOR;
  1442. }
  1443. return true;
  1444. }
  1445. if (arg == "--chat-template") {
  1446. if (++i >= argc) {
  1447. invalid_param = true;
  1448. return true;
  1449. }
  1450. if (!llama_chat_verify_template(argv[i])) {
  1451. fprintf(stderr, "error: the supplied chat template is not supported: %s\n", argv[i]);
  1452. fprintf(stderr, "note: llama.cpp does not use jinja parser, we only support commonly used templates\n");
  1453. invalid_param = true;
  1454. return true;
  1455. }
  1456. params.chat_template = argv[i];
  1457. return true;
  1458. }
  1459. if (arg == "-pps") {
  1460. params.is_pp_shared = true;
  1461. return true;
  1462. }
  1463. if (arg == "-npp") {
  1464. if (++i >= argc) {
  1465. invalid_param = true;
  1466. return true;
  1467. }
  1468. auto p = string_split<int>(argv[i], split_delim);
  1469. params.n_pp.insert(params.n_pp.end(), p.begin(), p.end());
  1470. return true;
  1471. }
  1472. if (arg == "-ntg") {
  1473. if (++i >= argc) {
  1474. invalid_param = true;
  1475. return true;
  1476. }
  1477. auto p = string_split<int>(argv[i], split_delim);
  1478. params.n_tg.insert(params.n_tg.end(), p.begin(), p.end());
  1479. return true;
  1480. }
  1481. if (arg == "-npl") {
  1482. if (++i >= argc) {
  1483. invalid_param = true;
  1484. return true;
  1485. }
  1486. auto p = string_split<int>(argv[i], split_delim);
  1487. params.n_pl.insert(params.n_pl.end(), p.begin(), p.end());
  1488. return true;
  1489. }
  1490. if (arg == "--context-file") {
  1491. if (++i >= argc) {
  1492. invalid_param = true;
  1493. return true;
  1494. }
  1495. std::ifstream file(argv[i], std::ios::binary);
  1496. if (!file) {
  1497. fprintf(stderr, "error: failed to open file '%s'\n", argv[i]);
  1498. invalid_param = true;
  1499. return true;
  1500. }
  1501. params.context_files.push_back(argv[i]);
  1502. return true;
  1503. }
  1504. if (arg == "--chunk-size") {
  1505. if (++i >= argc) {
  1506. invalid_param = true;
  1507. return true;
  1508. }
  1509. params.chunk_size = std::stoi(argv[i]);
  1510. return true;
  1511. }
  1512. if (arg == "--chunk-separator") {
  1513. if (++i >= argc) {
  1514. invalid_param = true;
  1515. return true;
  1516. }
  1517. params.chunk_separator = argv[i];
  1518. return true;
  1519. }
  1520. if (arg == "--junk") {
  1521. if (++i >= argc) {
  1522. invalid_param = true;
  1523. return true;
  1524. }
  1525. params.n_junk = std::stoi(argv[i]);
  1526. return true;
  1527. }
  1528. if (arg == "--pos") {
  1529. if (++i >= argc) {
  1530. invalid_param = true;
  1531. return true;
  1532. }
  1533. params.i_pos = std::stoi(argv[i]);
  1534. return true;
  1535. }
  1536. if (arg == "-o" || arg == "--output" || arg == "--output-file") {
  1537. if (++i >= argc) {
  1538. invalid_param = true;
  1539. return true;
  1540. }
  1541. params.out_file = argv[i];
  1542. return true;
  1543. }
  1544. if (arg == "-ofreq" || arg == "--output-frequency") {
  1545. if (++i >= argc) {
  1546. invalid_param = true;
  1547. return true;
  1548. }
  1549. params.n_out_freq = std::stoi(argv[i]);
  1550. return true;
  1551. }
  1552. if (arg == "--save-frequency") {
  1553. if (++i >= argc) {
  1554. invalid_param = true;
  1555. return true;
  1556. }
  1557. params.n_save_freq = std::stoi(argv[i]);
  1558. return true;
  1559. }
  1560. if (arg == "--process-output") {
  1561. params.process_output = true;
  1562. return true;
  1563. }
  1564. if (arg == "--no-ppl") {
  1565. params.compute_ppl = false;
  1566. return true;
  1567. }
  1568. if (arg == "--chunk" || arg == "--from-chunk") {
  1569. if (++i >= argc) {
  1570. invalid_param = true;
  1571. return true;
  1572. }
  1573. params.i_chunk = std::stoi(argv[i]);
  1574. return true;
  1575. }
  1576. #ifndef LOG_DISABLE_LOGS
  1577. // Parse args for logging parameters
  1578. if (log_param_single_parse(argv[i])) {
  1579. // Do nothing, log_param_single_parse automatically does it's thing
  1580. // and returns if a match was found and parsed.
  1581. return true;
  1582. }
  1583. if (log_param_pair_parse( /*check_but_dont_parse*/ true, argv[i])) {
  1584. // We have a matching known parameter requiring an argument,
  1585. // now we need to check if there is anything after this argv
  1586. // and flag invalid_param or parse it.
  1587. if (++i >= argc) {
  1588. invalid_param = true;
  1589. return true;
  1590. }
  1591. if (!log_param_pair_parse( /*check_but_dont_parse*/ false, argv[i - 1], argv[i])) {
  1592. invalid_param = true;
  1593. return true;
  1594. }
  1595. return true;
  1596. }
  1597. // End of Parse args for logging parameters
  1598. #endif // LOG_DISABLE_LOGS
  1599. return false;
  1600. }
  1601. #ifdef __GNUC__
  1602. #ifdef __MINGW32__
  1603. #define LLAMA_COMMON_ATTRIBUTE_FORMAT(...) __attribute__((format(gnu_printf, __VA_ARGS__)))
  1604. #else
  1605. #define LLAMA_COMMON_ATTRIBUTE_FORMAT(...) __attribute__((format(printf, __VA_ARGS__)))
  1606. #endif
  1607. #else
  1608. #define LLAMA_COMMON_ATTRIBUTE_FORMAT(...)
  1609. #endif
  1610. void gpt_params_print_usage(int /*argc*/, char ** argv, const gpt_params & params) {
  1611. const llama_sampling_params & sparams = params.sparams;
  1612. std::string sampler_type_chars;
  1613. std::string sampler_type_names;
  1614. for (const auto sampler_type : sparams.samplers_sequence) {
  1615. sampler_type_chars += static_cast<char>(sampler_type);
  1616. sampler_type_names += llama_sampling_type_to_str(sampler_type) + ";";
  1617. }
  1618. sampler_type_names.pop_back();
  1619. struct option_info {
  1620. LLAMA_COMMON_ATTRIBUTE_FORMAT(4, 5)
  1621. option_info(const std::string & tags, const char * args, const char * desc, ...) : tags(tags), args(args), desc(desc) {
  1622. va_list args_list;
  1623. va_start(args_list, desc);
  1624. char buffer[1024];
  1625. vsnprintf(buffer, sizeof(buffer), desc, args_list);
  1626. va_end(args_list);
  1627. this->desc = buffer;
  1628. }
  1629. option_info(const std::string & grp) : grp(grp) {}
  1630. std::string tags;
  1631. std::string args;
  1632. std::string desc;
  1633. std::string grp;
  1634. };
  1635. std::vector<option_info> options;
  1636. // TODO: filter by tags
  1637. options.push_back({ "general" });
  1638. options.push_back({ "*", "-h, --help, --usage", "print usage and exit" });
  1639. options.push_back({ "*", " --version", "show version and build info" });
  1640. options.push_back({ "*", "-v, --verbose", "print verbose information" });
  1641. options.push_back({ "*", " --verbosity N", "set specific verbosity level (default: %d)", params.verbosity });
  1642. options.push_back({ "*", " --verbose-prompt", "print a verbose prompt before generation (default: %s)", params.verbose_prompt ? "true" : "false" });
  1643. options.push_back({ "*", " --no-display-prompt", "don't print prompt at generation (default: %s)", !params.display_prompt ? "true" : "false" });
  1644. options.push_back({ "*", "-co, --color", "colorise output to distinguish prompt and user input from generations (default: %s)", params.use_color ? "true" : "false" });
  1645. options.push_back({ "*", "-s, --seed SEED", "RNG seed (default: %d, use random seed for < 0)", params.seed });
  1646. options.push_back({ "*", "-t, --threads N", "number of threads to use during generation (default: %d)", params.n_threads });
  1647. options.push_back({ "*", "-tb, --threads-batch N", "number of threads to use during batch and prompt processing (default: same as --threads)" });
  1648. options.push_back({ "speculative", "-td, --threads-draft N", "number of threads to use during generation (default: same as --threads)" });
  1649. options.push_back({ "speculative", "-tbd, --threads-batch-draft N",
  1650. "number of threads to use during batch and prompt processing (default: same as --threads-draft)" });
  1651. options.push_back({ "speculative", " --draft N", "number of tokens to draft for speculative decoding (default: %d)", params.n_draft });
  1652. options.push_back({ "speculative", "-ps, --p-split N", "speculative decoding split probability (default: %.1f)", (double)params.p_split });
  1653. options.push_back({ "*", "-lcs, --lookup-cache-static FNAME",
  1654. "path to static lookup cache to use for lookup decoding (not updated by generation)" });
  1655. options.push_back({ "*", "-lcd, --lookup-cache-dynamic FNAME",
  1656. "path to dynamic lookup cache to use for lookup decoding (updated by generation)" });
  1657. options.push_back({ "*", "-c, --ctx-size N", "size of the prompt context (default: %d, 0 = loaded from model)", params.n_ctx });
  1658. options.push_back({ "*", "-n, --predict N", "number of tokens to predict (default: %d, -1 = infinity, -2 = until context filled)", params.n_predict });
  1659. options.push_back({ "*", "-b, --batch-size N", "logical maximum batch size (default: %d)", params.n_batch });
  1660. options.push_back({ "*", "-ub, --ubatch-size N", "physical maximum batch size (default: %d)", params.n_ubatch });
  1661. options.push_back({ "*", " --keep N", "number of tokens to keep from the initial prompt (default: %d, -1 = all)", params.n_keep });
  1662. options.push_back({ "*", " --chunks N", "max number of chunks to process (default: %d, -1 = all)", params.n_chunks });
  1663. options.push_back({ "*", "-fa, --flash-attn", "enable Flash Attention (default: %s)", params.flash_attn ? "enabled" : "disabled" });
  1664. options.push_back({ "*", "-p, --prompt PROMPT", "prompt to start generation with (default: '%s')", params.prompt.c_str() });
  1665. options.push_back({ "*", "-f, --file FNAME", "a file containing the prompt (default: none)" });
  1666. options.push_back({ "*", " --in-file FNAME", "an input file (repeat to specify multiple files)" });
  1667. options.push_back({ "*", "-bf, --binary-file FNAME", "binary file containing the prompt (default: none)" });
  1668. options.push_back({ "*", "-e, --escape", "process escapes sequences (\\n, \\r, \\t, \\', \\\", \\\\) (default: %s)", params.escape ? "true" : "false" });
  1669. options.push_back({ "*", " --no-escape", "do not process escape sequences" });
  1670. options.push_back({ "main", "-ptc, --print-token-count N", "print token count every N tokens (default: %d)", params.n_print });
  1671. options.push_back({ "main", " --prompt-cache FNAME", "file to cache prompt state for faster startup (default: none)" });
  1672. options.push_back({ "main", " --prompt-cache-all", "if specified, saves user input and generations to cache as well\n"
  1673. "not supported with --interactive or other interactive options" });
  1674. options.push_back({ "main", " --prompt-cache-ro", "if specified, uses the prompt cache but does not update it" });
  1675. options.push_back({ "main", "-r, --reverse-prompt PROMPT",
  1676. "halt generation at PROMPT, return control in interactive mode\n"
  1677. "can be specified more than once for multiple prompts" });
  1678. options.push_back({ "main", "-sp, --special", "special tokens output enabled (default: %s)", params.special ? "true" : "false" });
  1679. options.push_back({ "main", "-cnv, --conversation", "run in conversation mode (does not print special tokens and suffix/prefix) (default: %s)", params.conversation ? "true" : "false" });
  1680. options.push_back({ "main infill", "-i, --interactive", "run in interactive mode (default: %s)", params.interactive ? "true" : "false" });
  1681. options.push_back({ "main infill", "-if, --interactive-first", "run in interactive mode and wait for input right away (default: %s)", params.interactive_first ? "true" : "false" });
  1682. options.push_back({ "main infill", "-mli, --multiline-input", "allows you to write or paste multiple lines without ending each in '\\'" });
  1683. options.push_back({ "main infill", " --in-prefix-bos", "prefix BOS to user inputs, preceding the `--in-prefix` string" });
  1684. options.push_back({ "main infill", " --in-prefix STRING", "string to prefix user inputs with (default: empty)" });
  1685. options.push_back({ "main infill", " --in-suffix STRING", "string to suffix after user inputs with (default: empty)" });
  1686. options.push_back({ "sampling" });
  1687. options.push_back({ "*", " --samplers SAMPLERS", "samplers that will be used for generation in the order, separated by \';\'\n"
  1688. "(default: %s)", sampler_type_names.c_str() });
  1689. options.push_back({ "*", " --sampling-seq SEQUENCE",
  1690. "simplified sequence for samplers that will be used (default: %s)", sampler_type_chars.c_str() });
  1691. options.push_back({ "*", " --ignore-eos", "ignore end of stream token and continue generating (implies --logit-bias EOS-inf)" });
  1692. options.push_back({ "*", " --penalize-nl", "penalize newline tokens (default: %s)", sparams.penalize_nl ? "true" : "false" });
  1693. options.push_back({ "*", " --temp N", "temperature (default: %.1f)", (double)sparams.temp });
  1694. options.push_back({ "*", " --top-k N", "top-k sampling (default: %d, 0 = disabled)", sparams.top_k });
  1695. options.push_back({ "*", " --top-p N", "top-p sampling (default: %.1f, 1.0 = disabled)", (double)sparams.top_p });
  1696. options.push_back({ "*", " --min-p N", "min-p sampling (default: %.1f, 0.0 = disabled)", (double)sparams.min_p });
  1697. options.push_back({ "*", " --tfs N", "tail free sampling, parameter z (default: %.1f, 1.0 = disabled)", (double)sparams.tfs_z });
  1698. options.push_back({ "*", " --typical N", "locally typical sampling, parameter p (default: %.1f, 1.0 = disabled)", (double)sparams.typical_p });
  1699. options.push_back({ "*", " --repeat-last-n N", "last n tokens to consider for penalize (default: %d, 0 = disabled, -1 = ctx_size)", sparams.penalty_last_n });
  1700. options.push_back({ "*", " --repeat-penalty N", "penalize repeat sequence of tokens (default: %.1f, 1.0 = disabled)", (double)sparams.penalty_repeat });
  1701. options.push_back({ "*", " --presence-penalty N", "repeat alpha presence penalty (default: %.1f, 0.0 = disabled)", (double)sparams.penalty_present });
  1702. options.push_back({ "*", " --frequency-penalty N", "repeat alpha frequency penalty (default: %.1f, 0.0 = disabled)", (double)sparams.penalty_freq });
  1703. options.push_back({ "*", " --dynatemp-range N", "dynamic temperature range (default: %.1f, 0.0 = disabled)", (double)sparams.dynatemp_range });
  1704. options.push_back({ "*", " --dynatemp-exp N", "dynamic temperature exponent (default: %.1f)", (double)sparams.dynatemp_exponent });
  1705. options.push_back({ "*", " --mirostat N", "use Mirostat sampling.\n"
  1706. "Top K, Nucleus, Tail Free and Locally Typical samplers are ignored if used.\n"
  1707. "(default: %d, 0 = disabled, 1 = Mirostat, 2 = Mirostat 2.0)", sparams.mirostat });
  1708. options.push_back({ "*", " --mirostat-lr N", "Mirostat learning rate, parameter eta (default: %.1f)", (double)sparams.mirostat_eta });
  1709. options.push_back({ "*", " --mirostat-ent N", "Mirostat target entropy, parameter tau (default: %.1f)", (double)sparams.mirostat_tau });
  1710. options.push_back({ "*", " -l TOKEN_ID(+/-)BIAS", "modifies the likelihood of token appearing in the completion,\n"
  1711. "i.e. `--logit-bias 15043+1` to increase likelihood of token ' Hello',\n"
  1712. "or `--logit-bias 15043-1` to decrease likelihood of token ' Hello'" });
  1713. options.push_back({ "main", " --cfg-negative-prompt PROMPT",
  1714. "negative prompt to use for guidance (default: '%s')", sparams.cfg_negative_prompt.c_str() });
  1715. options.push_back({ "main", " --cfg-negative-prompt-file FNAME",
  1716. "negative prompt file to use for guidance" });
  1717. options.push_back({ "main", " --cfg-scale N", "strength of guidance (default: %.1f, 1.0 = disable)", (double)sparams.cfg_scale });
  1718. options.push_back({ "grammar" });
  1719. options.push_back({ "*", " --grammar GRAMMAR", "BNF-like grammar to constrain generations (see samples in grammars/ dir) (default: '%s')", sparams.grammar.c_str() });
  1720. options.push_back({ "*", " --grammar-file FNAME", "file to read grammar from" });
  1721. options.push_back({ "*", "-j, --json-schema SCHEMA",
  1722. "JSON schema to constrain generations (https://json-schema.org/), e.g. `{}` for any JSON object\n"
  1723. "For schemas w/ external $refs, use --grammar + example/json_schema_to_grammar.py instead" });
  1724. options.push_back({ "embedding" });
  1725. options.push_back({ "embedding", " --pooling {none,mean,cls}",
  1726. "pooling type for embeddings, use model default if unspecified" });
  1727. options.push_back({ "context hacking" });
  1728. options.push_back({ "*", " --rope-scaling {none,linear,yarn}",
  1729. "RoPE frequency scaling method, defaults to linear unless specified by the model" });
  1730. options.push_back({ "*", " --rope-scale N", "RoPE context scaling factor, expands context by a factor of N" });
  1731. options.push_back({ "*", " --rope-freq-base N", "RoPE base frequency, used by NTK-aware scaling (default: loaded from model)" });
  1732. options.push_back({ "*", " --rope-freq-scale N", "RoPE frequency scaling factor, expands context by a factor of 1/N" });
  1733. options.push_back({ "*", " --yarn-orig-ctx N", "YaRN: original context size of model (default: %d = model training context size)", params.yarn_orig_ctx });
  1734. options.push_back({ "*", " --yarn-ext-factor N", "YaRN: extrapolation mix factor (default: %.1f, 0.0 = full interpolation)", (double)params.yarn_ext_factor });
  1735. options.push_back({ "*", " --yarn-attn-factor N", "YaRN: scale sqrt(t) or attention magnitude (default: %.1f)", (double)params.yarn_attn_factor });
  1736. options.push_back({ "*", " --yarn-beta-slow N", "YaRN: high correction dim or alpha (default: %.1f)", (double)params.yarn_beta_slow });
  1737. options.push_back({ "*", " --yarn-beta-fast N", "YaRN: low correction dim or beta (default: %.1f)", (double)params.yarn_beta_fast });
  1738. options.push_back({ "*", "-gan, --grp-attn-n N", "group-attention factor (default: %d)", params.grp_attn_n });
  1739. options.push_back({ "*", "-gaw, --grp-attn-w N", "group-attention width (default: %.1f)", (double)params.grp_attn_w });
  1740. options.push_back({ "*", "-dkvc, --dump-kv-cache", "verbose print of the KV cache" });
  1741. options.push_back({ "*", "-nkvo, --no-kv-offload", "disable KV offload" });
  1742. options.push_back({ "*", "-ctk, --cache-type-k TYPE", "KV cache data type for K (default: %s)", params.cache_type_k.c_str() });
  1743. options.push_back({ "*", "-ctv, --cache-type-v TYPE", "KV cache data type for V (default: %s)", params.cache_type_v.c_str() });
  1744. options.push_back({ "perplexity" });
  1745. options.push_back({ "perplexity", " --all-logits", "return logits for all tokens in the batch (default: %s)", params.logits_all ? "true" : "false" });
  1746. options.push_back({ "perplexity", " --hellaswag", "compute HellaSwag score over random tasks from datafile supplied with -f" });
  1747. options.push_back({ "perplexity", " --hellaswag-tasks N", "number of tasks to use when computing the HellaSwag score (default: %zu)", params.hellaswag_tasks });
  1748. options.push_back({ "perplexity", " --winogrande", "compute Winogrande score over random tasks from datafile supplied with -f" });
  1749. options.push_back({ "perplexity", " --winogrande-tasks N", "number of tasks to use when computing the Winogrande score (default: %zu)", params.winogrande_tasks });
  1750. options.push_back({ "perplexity", " --multiple-choice", "compute multiple choice score over random tasks from datafile supplied with -f" });
  1751. options.push_back({ "perplexity", " --multiple-choice-tasks N",
  1752. "number of tasks to use when computing the multiple choice score (default: %zu)", params.multiple_choice_tasks });
  1753. options.push_back({ "perplexity", " --kl-divergence", "computes KL-divergence to logits provided via --kl-divergence-base" });
  1754. options.push_back({ "perplexity", " --ppl-stride N", "stride for perplexity calculation (default: %d)", params.ppl_stride });
  1755. options.push_back({ "perplexity", " --ppl-output-type {0,1}",
  1756. "output type for perplexity calculation (default: %d)", params.ppl_output_type });
  1757. options.push_back({ "parallel" });
  1758. options.push_back({ "*", "-dt, --defrag-thold N", "KV cache defragmentation threshold (default: %.1f, < 0 - disabled)", (double)params.defrag_thold });
  1759. options.push_back({ "*", "-np, --parallel N", "number of parallel sequences to decode (default: %d)", params.n_parallel });
  1760. options.push_back({ "*", "-ns, --sequences N", "number of sequences to decode (default: %d)", params.n_sequences });
  1761. options.push_back({ "*", "-cb, --cont-batching", "enable continuous batching (a.k.a dynamic batching) (default: %s)", params.cont_batching ? "enabled" : "disabled" });
  1762. options.push_back({ "multi-modality" });
  1763. options.push_back({ "*", " --mmproj FILE", "path to a multimodal projector file for LLaVA. see examples/llava/README.md" });
  1764. options.push_back({ "*", " --image FILE", "path to an image file. use with multimodal models. Specify multiple times for batching" });
  1765. options.push_back({ "backend" });
  1766. options.push_back({ "*", " --rpc SERVERS", "comma separated list of RPC servers" });
  1767. if (llama_supports_mlock()) {
  1768. options.push_back({ "*", " --mlock", "force system to keep model in RAM rather than swapping or compressing" });
  1769. }
  1770. if (llama_supports_mmap()) {
  1771. options.push_back({ "*", " --no-mmap", "do not memory-map model (slower load but may reduce pageouts if not using mlock)" });
  1772. }
  1773. options.push_back({ "*", " --numa TYPE", "attempt optimizations that help on some NUMA systems\n"
  1774. " - distribute: spread execution evenly over all nodes\n"
  1775. " - isolate: only spawn threads on CPUs on the node that execution started on\n"
  1776. " - numactl: use the CPU map provided by numactl\n"
  1777. "if run without this previously, it is recommended to drop the system page cache before using this\n"
  1778. "see https://github.com/ggerganov/llama.cpp/issues/1437" });
  1779. if (llama_supports_gpu_offload()) {
  1780. options.push_back({ "*", "-ngl, --gpu-layers N",
  1781. "number of layers to store in VRAM" });
  1782. options.push_back({ "*", "-ngld, --gpu-layers-draft N",
  1783. "number of layers to store in VRAM for the draft model" });
  1784. options.push_back({ "*", "-sm, --split-mode SPLIT_MODE",
  1785. "how to split the model across multiple GPUs, one of:\n"
  1786. " - none: use one GPU only\n"
  1787. " - layer (default): split layers and KV across GPUs\n"
  1788. " - row: split rows across GPUs" });
  1789. options.push_back({ "*", "-ts, --tensor-split SPLIT",
  1790. "fraction of the model to offload to each GPU, comma-separated list of proportions, e.g. 3,1" });
  1791. options.push_back({ "*", "-mg, --main-gpu i", "the GPU to use for the model (with split-mode = none),\n"
  1792. "or for intermediate results and KV (with split-mode = row) (default: %d)", params.main_gpu });
  1793. }
  1794. options.push_back({ "model" });
  1795. options.push_back({ "*", " --check-tensors", "check model tensor data for invalid values (default: %s)", params.check_tensors ? "true" : "false" });
  1796. options.push_back({ "*", " --override-kv KEY=TYPE:VALUE",
  1797. "advanced option to override model metadata by key. may be specified multiple times.\n"
  1798. "types: int, float, bool, str. example: --override-kv tokenizer.ggml.add_bos_token=bool:false" });
  1799. options.push_back({ "*", " --lora FNAME", "apply LoRA adapter (implies --no-mmap)" });
  1800. options.push_back({ "*", " --lora-scaled FNAME S", "apply LoRA adapter with user defined scaling S (implies --no-mmap)" });
  1801. options.push_back({ "*", " --lora-base FNAME", "optional model to use as a base for the layers modified by the LoRA adapter" });
  1802. options.push_back({ "*", " --control-vector FNAME", "add a control vector" });
  1803. options.push_back({ "*", " --control-vector-scaled FNAME SCALE",
  1804. "add a control vector with user defined scaling SCALE" });
  1805. options.push_back({ "*", " --control-vector-layer-range START END",
  1806. "layer range to apply the control vector(s) to, start and end inclusive" });
  1807. options.push_back({ "*", "-m, --model FNAME", "model path (default: models/$filename with filename from --hf-file\n"
  1808. "or --model-url if set, otherwise %s)", DEFAULT_MODEL_PATH });
  1809. options.push_back({ "*", "-md, --model-draft FNAME", "draft model for speculative decoding (default: unused)" });
  1810. options.push_back({ "*", "-mu, --model-url MODEL_URL", "model download url (default: unused)" });
  1811. options.push_back({ "*", "-hfr, --hf-repo REPO", "Hugging Face model repository (default: unused)" });
  1812. options.push_back({ "*", "-hff, --hf-file FILE", "Hugging Face model file (default: unused)" });
  1813. options.push_back({ "retrieval" });
  1814. options.push_back({ "retrieval", " --context-file FNAME", "file to load context from (repeat to specify multiple files)" });
  1815. options.push_back({ "retrieval", " --chunk-size N", "minimum length of embedded text chunks (default: %d)", params.chunk_size });
  1816. options.push_back({ "retrieval", " --chunk-separator STRING",
  1817. "separator between chunks (default: '%s')", params.chunk_separator.c_str() });
  1818. options.push_back({ "passkey" });
  1819. options.push_back({ "passkey", " --junk N", "number of times to repeat the junk text (default: %d)", params.n_junk });
  1820. options.push_back({ "passkey", " --pos N", "position of the passkey in the junk text (default: %d)", params.i_pos });
  1821. options.push_back({ "imatrix" });
  1822. options.push_back({ "imatrix", "-o, --output FNAME", "output file (default: '%s')", params.out_file.c_str() });
  1823. options.push_back({ "imatrix", " --output-frequency N", "output the imatrix every N iterations (default: %d)", params.n_out_freq });
  1824. options.push_back({ "imatrix", " --save-frequency N", "save an imatrix copy every N iterations (default: %d)", params.n_save_freq });
  1825. options.push_back({ "imatrix", " --process-output", "collect data for the output tensor (default: %s)", params.process_output ? "true" : "false" });
  1826. options.push_back({ "imatrix", " --no-ppl", "do not compute perplexity (default: %s)", params.compute_ppl ? "true" : "false" });
  1827. options.push_back({ "imatrix", " --chunk N", "start processing the input from chunk N (default: %d)", params.i_chunk });
  1828. options.push_back({ "bench" });
  1829. options.push_back({ "bench", "-pps", "is the prompt shared across parallel sequences (default: %s)", params.is_pp_shared ? "true" : "false" });
  1830. options.push_back({ "bench", "-npp n0,n1,...", "number of prompt tokens" });
  1831. options.push_back({ "bench", "-ntg n0,n1,...", "number of text generation tokens" });
  1832. options.push_back({ "bench", "-npl n0,n1,...", "number of parallel prompts" });
  1833. options.push_back({ "server" });
  1834. options.push_back({ "server", " --host HOST", "ip address to listen (default: %s)", params.hostname.c_str() });
  1835. options.push_back({ "server", " --port PORT", "port to listen (default: %d)", params.port });
  1836. options.push_back({ "server", " --path PATH", "path to serve static files from (default: %s)", params.public_path.c_str() });
  1837. options.push_back({ "server", " --embedding(s)", "enable embedding endpoint (default: %s)", params.embedding ? "enabled" : "disabled" });
  1838. options.push_back({ "server", " --api-key KEY", "API key to use for authentication (default: none)" });
  1839. options.push_back({ "server", " --api-key-file FNAME", "path to file containing API keys (default: none)" });
  1840. options.push_back({ "server", " --ssl-key-file FNAME", "path to file a PEM-encoded SSL private key" });
  1841. options.push_back({ "server", " --ssl-cert-file FNAME", "path to file a PEM-encoded SSL certificate" });
  1842. options.push_back({ "server", " --timeout N", "server read/write timeout in seconds (default: %d)", params.timeout_read });
  1843. options.push_back({ "server", " --threads-http N", "number of threads used to process HTTP requests (default: %d)", params.n_threads_http });
  1844. options.push_back({ "server", " --system-prompt-file FNAME",
  1845. "set a file to load a system prompt (initial prompt of all slots), this is useful for chat applications" });
  1846. options.push_back({ "server", " --log-format {text,json}",
  1847. "log output format: json or text (default: json)" });
  1848. options.push_back({ "server", " --metrics", "enable prometheus compatible metrics endpoint (default: %s)", params.endpoint_metrics ? "enabled" : "disabled" });
  1849. options.push_back({ "server", " --no-slots", "disables slots monitoring endpoint (default: %s)", params.endpoint_slots ? "enabled" : "disabled" });
  1850. options.push_back({ "server", " --slot-save-path PATH", "path to save slot kv cache (default: disabled)" });
  1851. options.push_back({ "server", " --chat-template JINJA_TEMPLATE",
  1852. "set custom jinja chat template (default: template taken from model's metadata)\n"
  1853. "only commonly used templates are accepted:\n"
  1854. "https://github.com/ggerganov/llama.cpp/wiki/Templates-supported-by-llama_chat_apply_template" });
  1855. #ifndef LOG_DISABLE_LOGS
  1856. options.push_back({ "logging" });
  1857. options.push_back({ "*", " --simple-io", "use basic IO for better compatibility in subprocesses and limited consoles" });
  1858. options.push_back({ "*", "-ld, --logdir LOGDIR", "path under which to save YAML logs (no logging if unset)" });
  1859. options.push_back({ "logging", " --log-test", "Run simple logging test" });
  1860. options.push_back({ "logging", " --log-disable", "Disable trace logs" });
  1861. options.push_back({ "logging", " --log-enable", "Enable trace logs" });
  1862. options.push_back({ "logging", " --log-file FNAME", "Specify a log filename (without extension)" });
  1863. options.push_back({ "logging", " --log-new", "Create a separate new log file on start. "
  1864. "Each log file will have unique name: \"<name>.<ID>.log\"" });
  1865. options.push_back({ "logging", " --log-append", "Don't truncate the old log file." });
  1866. #endif // LOG_DISABLE_LOGS
  1867. printf("usage: %s [options]\n", argv[0]);
  1868. for (const auto & o : options) {
  1869. if (!o.grp.empty()) {
  1870. printf("\n%s:\n\n", o.grp.c_str());
  1871. continue;
  1872. }
  1873. printf(" %-32s", o.args.c_str());
  1874. if (o.args.length() > 30) {
  1875. printf("\n%34s", "");
  1876. }
  1877. const auto desc = o.desc;
  1878. size_t start = 0;
  1879. size_t end = desc.find('\n');
  1880. while (end != std::string::npos) {
  1881. printf("%s\n%34s", desc.substr(start, end - start).c_str(), "");
  1882. start = end + 1;
  1883. end = desc.find('\n', start);
  1884. }
  1885. printf("%s\n", desc.substr(start).c_str());
  1886. }
  1887. printf("\n");
  1888. }
  1889. std::string gpt_params_get_system_info(const gpt_params & params) {
  1890. std::ostringstream os;
  1891. os << "system_info: n_threads = " << params.n_threads;
  1892. if (params.n_threads_batch != -1) {
  1893. os << " (n_threads_batch = " << params.n_threads_batch << ")";
  1894. }
  1895. os << " / " << std::thread::hardware_concurrency() << " | " << llama_print_system_info();
  1896. return os.str();
  1897. }
  1898. //
  1899. // String utils
  1900. //
  1901. std::vector<std::string> string_split(std::string input, char separator) {
  1902. std::vector<std::string> parts;
  1903. size_t separator_pos = input.find(separator);
  1904. while (separator_pos != std::string::npos) {
  1905. std::string part = input.substr(0, separator_pos);
  1906. parts.emplace_back(part);
  1907. input = input.substr(separator_pos + 1);
  1908. separator_pos = input.find(separator);
  1909. }
  1910. parts.emplace_back(input);
  1911. return parts;
  1912. }
  1913. std::string string_strip(const std::string & str) {
  1914. size_t start = 0;
  1915. size_t end = str.size();
  1916. while (start < end && std::isspace(str[start])) {
  1917. start++;
  1918. }
  1919. while (end > start && std::isspace(str[end - 1])) {
  1920. end--;
  1921. }
  1922. return str.substr(start, end - start);
  1923. }
  1924. std::string string_get_sortable_timestamp() {
  1925. using clock = std::chrono::system_clock;
  1926. const clock::time_point current_time = clock::now();
  1927. const time_t as_time_t = clock::to_time_t(current_time);
  1928. char timestamp_no_ns[100];
  1929. std::strftime(timestamp_no_ns, 100, "%Y_%m_%d-%H_%M_%S", std::localtime(&as_time_t));
  1930. const int64_t ns = std::chrono::duration_cast<std::chrono::nanoseconds>(
  1931. current_time.time_since_epoch() % 1000000000).count();
  1932. char timestamp_ns[11];
  1933. snprintf(timestamp_ns, 11, "%09" PRId64, ns);
  1934. return std::string(timestamp_no_ns) + "." + std::string(timestamp_ns);
  1935. }
  1936. void string_process_escapes(std::string & input) {
  1937. std::size_t input_len = input.length();
  1938. std::size_t output_idx = 0;
  1939. for (std::size_t input_idx = 0; input_idx < input_len; ++input_idx) {
  1940. if (input[input_idx] == '\\' && input_idx + 1 < input_len) {
  1941. switch (input[++input_idx]) {
  1942. case 'n': input[output_idx++] = '\n'; break;
  1943. case 'r': input[output_idx++] = '\r'; break;
  1944. case 't': input[output_idx++] = '\t'; break;
  1945. case '\'': input[output_idx++] = '\''; break;
  1946. case '\"': input[output_idx++] = '\"'; break;
  1947. case '\\': input[output_idx++] = '\\'; break;
  1948. case 'x':
  1949. // Handle \x12, etc
  1950. if (input_idx + 2 < input_len) {
  1951. const char x[3] = { input[input_idx + 1], input[input_idx + 2], 0 };
  1952. char *err_p = nullptr;
  1953. const long val = std::strtol(x, &err_p, 16);
  1954. if (err_p == x + 2) {
  1955. input_idx += 2;
  1956. input[output_idx++] = char(val);
  1957. break;
  1958. }
  1959. }
  1960. // fall through
  1961. default: input[output_idx++] = '\\';
  1962. input[output_idx++] = input[input_idx]; break;
  1963. }
  1964. } else {
  1965. input[output_idx++] = input[input_idx];
  1966. }
  1967. }
  1968. input.resize(output_idx);
  1969. }
  1970. bool string_parse_kv_override(const char * data, std::vector<llama_model_kv_override> & overrides) {
  1971. const char * sep = strchr(data, '=');
  1972. if (sep == nullptr || sep - data >= 128) {
  1973. fprintf(stderr, "%s: malformed KV override '%s'\n", __func__, data);
  1974. return false;
  1975. }
  1976. llama_model_kv_override kvo;
  1977. std::strncpy(kvo.key, data, sep - data);
  1978. kvo.key[sep - data] = 0;
  1979. sep++;
  1980. if (strncmp(sep, "int:", 4) == 0) {
  1981. sep += 4;
  1982. kvo.tag = LLAMA_KV_OVERRIDE_TYPE_INT;
  1983. kvo.val_i64 = std::atol(sep);
  1984. } else if (strncmp(sep, "float:", 6) == 0) {
  1985. sep += 6;
  1986. kvo.tag = LLAMA_KV_OVERRIDE_TYPE_FLOAT;
  1987. kvo.val_f64 = std::atof(sep);
  1988. } else if (strncmp(sep, "bool:", 5) == 0) {
  1989. sep += 5;
  1990. kvo.tag = LLAMA_KV_OVERRIDE_TYPE_BOOL;
  1991. if (std::strcmp(sep, "true") == 0) {
  1992. kvo.val_bool = true;
  1993. } else if (std::strcmp(sep, "false") == 0) {
  1994. kvo.val_bool = false;
  1995. } else {
  1996. fprintf(stderr, "%s: invalid boolean value for KV override '%s'\n", __func__, data);
  1997. return false;
  1998. }
  1999. } else if (strncmp(sep, "str:", 4) == 0) {
  2000. sep += 4;
  2001. kvo.tag = LLAMA_KV_OVERRIDE_TYPE_STR;
  2002. if (strlen(sep) > 127) {
  2003. fprintf(stderr, "%s: malformed KV override '%s', value cannot exceed 127 chars\n", __func__, data);
  2004. return false;
  2005. }
  2006. strncpy(kvo.val_str, sep, 127);
  2007. kvo.val_str[127] = '\0';
  2008. } else {
  2009. fprintf(stderr, "%s: invalid type for KV override '%s'\n", __func__, data);
  2010. return false;
  2011. }
  2012. overrides.emplace_back(std::move(kvo));
  2013. return true;
  2014. }
  2015. //
  2016. // Filesystem utils
  2017. //
  2018. // Validate if a filename is safe to use
  2019. // To validate a full path, split the path by the OS-specific path separator, and validate each part with this function
  2020. bool fs_validate_filename(const std::string & filename) {
  2021. if (!filename.length()) {
  2022. // Empty filename invalid
  2023. return false;
  2024. }
  2025. if (filename.length() > 255) {
  2026. // Limit at common largest possible filename on Linux filesystems
  2027. // to avoid unnecessary further validation
  2028. // (On systems with smaller limits it will be caught by the OS)
  2029. return false;
  2030. }
  2031. std::u32string filename_utf32;
  2032. try {
  2033. std::wstring_convert<std::codecvt_utf8<char32_t>, char32_t> converter;
  2034. filename_utf32 = converter.from_bytes(filename);
  2035. // If the reverse conversion mismatches, it means overlong UTF-8 sequences were used,
  2036. // or invalid encodings were encountered. Reject such attempts
  2037. std::string filename_reencoded = converter.to_bytes(filename_utf32);
  2038. if (filename_reencoded != filename) {
  2039. return false;
  2040. }
  2041. } catch (const std::exception &) {
  2042. return false;
  2043. }
  2044. // Check for forbidden codepoints:
  2045. // - Control characters
  2046. // - Unicode equivalents of illegal characters
  2047. // - UTF-16 surrogate pairs
  2048. // - UTF-8 replacement character
  2049. // - Byte order mark (BOM)
  2050. // - Illegal characters: / \ : * ? " < > |
  2051. for (char32_t c : filename_utf32) {
  2052. if (c <= 0x1F // Control characters (C0)
  2053. || c == 0x7F // Control characters (DEL)
  2054. || (c >= 0x80 && c <= 0x9F) // Control characters (C1)
  2055. || c == 0xFF0E // Fullwidth Full Stop (period equivalent)
  2056. || c == 0x2215 // Division Slash (forward slash equivalent)
  2057. || c == 0x2216 // Set Minus (backslash equivalent)
  2058. || (c >= 0xD800 && c <= 0xDFFF) // UTF-16 surrogate pairs
  2059. || c == 0xFFFD // Replacement Character (UTF-8)
  2060. || c == 0xFEFF // Byte Order Mark (BOM)
  2061. || c == '/' || c == '\\' || c == ':' || c == '*' // Illegal characters
  2062. || c == '?' || c == '"' || c == '<' || c == '>' || c == '|') {
  2063. return false;
  2064. }
  2065. }
  2066. // Reject any leading or trailing ' ', or any trailing '.', these are stripped on Windows and will cause a different filename
  2067. // Unicode and other whitespace is not affected, only 0x20 space
  2068. if (filename.front() == ' ' || filename.back() == ' ' || filename.back() == '.') {
  2069. return false;
  2070. }
  2071. // Reject any ".." (currently stricter than necessary, it should be fine to just check for == ".." instead)
  2072. if (filename.find("..") != std::string::npos) {
  2073. return false;
  2074. }
  2075. // Reject "."
  2076. if (filename == ".") {
  2077. return false;
  2078. }
  2079. return true;
  2080. }
  2081. // returns true if successful, false otherwise
  2082. bool fs_create_directory_with_parents(const std::string & path) {
  2083. #ifdef _WIN32
  2084. std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;
  2085. std::wstring wpath = converter.from_bytes(path);
  2086. // if the path already exists, check whether it's a directory
  2087. const DWORD attributes = GetFileAttributesW(wpath.c_str());
  2088. if ((attributes != INVALID_FILE_ATTRIBUTES) && (attributes & FILE_ATTRIBUTE_DIRECTORY)) {
  2089. return true;
  2090. }
  2091. size_t pos_slash = 0;
  2092. // process path from front to back, procedurally creating directories
  2093. while ((pos_slash = path.find('\\', pos_slash)) != std::string::npos) {
  2094. const std::wstring subpath = wpath.substr(0, pos_slash);
  2095. const wchar_t * test = subpath.c_str();
  2096. const bool success = CreateDirectoryW(test, NULL);
  2097. if (!success) {
  2098. const DWORD error = GetLastError();
  2099. // if the path already exists, ensure that it's a directory
  2100. if (error == ERROR_ALREADY_EXISTS) {
  2101. const DWORD attributes = GetFileAttributesW(subpath.c_str());
  2102. if (attributes == INVALID_FILE_ATTRIBUTES || !(attributes & FILE_ATTRIBUTE_DIRECTORY)) {
  2103. return false;
  2104. }
  2105. } else {
  2106. return false;
  2107. }
  2108. }
  2109. pos_slash += 1;
  2110. }
  2111. return true;
  2112. #else
  2113. // if the path already exists, check whether it's a directory
  2114. struct stat info;
  2115. if (stat(path.c_str(), &info) == 0) {
  2116. return S_ISDIR(info.st_mode);
  2117. }
  2118. size_t pos_slash = 1; // skip leading slashes for directory creation
  2119. // process path from front to back, procedurally creating directories
  2120. while ((pos_slash = path.find('/', pos_slash)) != std::string::npos) {
  2121. const std::string subpath = path.substr(0, pos_slash);
  2122. struct stat info;
  2123. // if the path already exists, ensure that it's a directory
  2124. if (stat(subpath.c_str(), &info) == 0) {
  2125. if (!S_ISDIR(info.st_mode)) {
  2126. return false;
  2127. }
  2128. } else {
  2129. // create parent directories
  2130. const int ret = mkdir(subpath.c_str(), 0755);
  2131. if (ret != 0) {
  2132. return false;
  2133. }
  2134. }
  2135. pos_slash += 1;
  2136. }
  2137. return true;
  2138. #endif // _WIN32
  2139. }
  2140. std::string fs_get_cache_directory() {
  2141. std::string cache_directory = "";
  2142. auto ensure_trailing_slash = [](std::string p) {
  2143. // Make sure to add trailing slash
  2144. if (p.back() != DIRECTORY_SEPARATOR) {
  2145. p += DIRECTORY_SEPARATOR;
  2146. }
  2147. return p;
  2148. };
  2149. if (getenv("LLAMA_CACHE")) {
  2150. cache_directory = std::getenv("LLAMA_CACHE");
  2151. } else {
  2152. #ifdef __linux__
  2153. if (std::getenv("XDG_CACHE_HOME")) {
  2154. cache_directory = std::getenv("XDG_CACHE_HOME");
  2155. } else {
  2156. cache_directory = std::getenv("HOME") + std::string("/.cache/");
  2157. }
  2158. #elif defined(__APPLE__)
  2159. cache_directory = std::getenv("HOME") + std::string("/Library/Caches/");
  2160. #elif defined(_WIN32)
  2161. cache_directory = std::getenv("LOCALAPPDATA");
  2162. #endif // __linux__
  2163. cache_directory = ensure_trailing_slash(cache_directory);
  2164. cache_directory += "llama.cpp";
  2165. }
  2166. return ensure_trailing_slash(cache_directory);
  2167. }
  2168. //
  2169. // Model utils
  2170. //
  2171. std::tuple<struct llama_model *, struct llama_context *> llama_init_from_gpt_params(gpt_params & params) {
  2172. auto mparams = llama_model_params_from_gpt_params(params);
  2173. llama_model * model = nullptr;
  2174. if (!params.hf_repo.empty() && !params.hf_file.empty()) {
  2175. model = llama_load_model_from_hf(params.hf_repo.c_str(), params.hf_file.c_str(), params.model.c_str(), mparams);
  2176. } else if (!params.model_url.empty()) {
  2177. model = llama_load_model_from_url(params.model_url.c_str(), params.model.c_str(), mparams);
  2178. } else {
  2179. model = llama_load_model_from_file(params.model.c_str(), mparams);
  2180. }
  2181. if (model == NULL) {
  2182. fprintf(stderr, "%s: error: failed to load model '%s'\n", __func__, params.model.c_str());
  2183. return std::make_tuple(nullptr, nullptr);
  2184. }
  2185. auto cparams = llama_context_params_from_gpt_params(params);
  2186. llama_context * lctx = llama_new_context_with_model(model, cparams);
  2187. if (lctx == NULL) {
  2188. fprintf(stderr, "%s: error: failed to create context with model '%s'\n", __func__, params.model.c_str());
  2189. llama_free_model(model);
  2190. return std::make_tuple(nullptr, nullptr);
  2191. }
  2192. if (!params.control_vectors.empty()) {
  2193. if (params.control_vector_layer_start <= 0) params.control_vector_layer_start = 1;
  2194. if (params.control_vector_layer_end <= 0) params.control_vector_layer_end = llama_n_layer(model);
  2195. const auto cvec = llama_control_vector_load(params.control_vectors);
  2196. if (cvec.n_embd == -1) {
  2197. llama_free(lctx);
  2198. llama_free_model(model);
  2199. return std::make_tuple(nullptr, nullptr);
  2200. }
  2201. int err = llama_control_vector_apply(lctx,
  2202. cvec.data.data(),
  2203. cvec.data.size(),
  2204. cvec.n_embd,
  2205. params.control_vector_layer_start,
  2206. params.control_vector_layer_end);
  2207. if (err) {
  2208. llama_free(lctx);
  2209. llama_free_model(model);
  2210. return std::make_tuple(nullptr, nullptr);
  2211. }
  2212. }
  2213. for (unsigned int i = 0; i < params.lora_adapter.size(); ++i) {
  2214. const std::string & lora_adapter = std::get<0>(params.lora_adapter[i]);
  2215. float lora_scale = std::get<1>(params.lora_adapter[i]);
  2216. int err = llama_model_apply_lora_from_file(model,
  2217. lora_adapter.c_str(),
  2218. lora_scale,
  2219. ((i > 0) || params.lora_base.empty())
  2220. ? NULL
  2221. : params.lora_base.c_str(),
  2222. params.n_threads);
  2223. if (err != 0) {
  2224. fprintf(stderr, "%s: error: failed to apply lora adapter\n", __func__);
  2225. llama_free(lctx);
  2226. llama_free_model(model);
  2227. return std::make_tuple(nullptr, nullptr);
  2228. }
  2229. }
  2230. if (params.ignore_eos) {
  2231. params.sparams.logit_bias[llama_token_eos(model)] = -INFINITY;
  2232. }
  2233. if (params.warmup) {
  2234. LOG("warming up the model with an empty run\n");
  2235. std::vector<llama_token> tmp = { llama_token_bos(model), llama_token_eos(model), };
  2236. llama_decode(lctx, llama_batch_get_one(tmp.data(), std::min(tmp.size(), (size_t) params.n_batch), 0, 0));
  2237. llama_kv_cache_clear(lctx);
  2238. llama_synchronize(lctx);
  2239. llama_reset_timings(lctx);
  2240. }
  2241. return std::make_tuple(model, lctx);
  2242. }
  2243. struct llama_model_params llama_model_params_from_gpt_params(const gpt_params & params) {
  2244. auto mparams = llama_model_default_params();
  2245. if (params.n_gpu_layers != -1) {
  2246. mparams.n_gpu_layers = params.n_gpu_layers;
  2247. }
  2248. mparams.rpc_servers = params.rpc_servers.c_str();
  2249. mparams.main_gpu = params.main_gpu;
  2250. mparams.split_mode = params.split_mode;
  2251. mparams.tensor_split = params.tensor_split;
  2252. mparams.use_mmap = params.use_mmap;
  2253. mparams.use_mlock = params.use_mlock;
  2254. mparams.check_tensors = params.check_tensors;
  2255. if (params.kv_overrides.empty()) {
  2256. mparams.kv_overrides = NULL;
  2257. } else {
  2258. GGML_ASSERT(params.kv_overrides.back().key[0] == 0 && "KV overrides not terminated with empty key");
  2259. mparams.kv_overrides = params.kv_overrides.data();
  2260. }
  2261. return mparams;
  2262. }
  2263. static ggml_type kv_cache_type_from_str(const std::string & s) {
  2264. if (s == "f32") {
  2265. return GGML_TYPE_F32;
  2266. }
  2267. if (s == "f16") {
  2268. return GGML_TYPE_F16;
  2269. }
  2270. if (s == "q8_0") {
  2271. return GGML_TYPE_Q8_0;
  2272. }
  2273. if (s == "q4_0") {
  2274. return GGML_TYPE_Q4_0;
  2275. }
  2276. if (s == "q4_1") {
  2277. return GGML_TYPE_Q4_1;
  2278. }
  2279. if (s == "iq4_nl") {
  2280. return GGML_TYPE_IQ4_NL;
  2281. }
  2282. if (s == "q5_0") {
  2283. return GGML_TYPE_Q5_0;
  2284. }
  2285. if (s == "q5_1") {
  2286. return GGML_TYPE_Q5_1;
  2287. }
  2288. throw std::runtime_error("Invalid cache type: " + s);
  2289. }
  2290. struct llama_context_params llama_context_params_from_gpt_params(const gpt_params & params) {
  2291. auto cparams = llama_context_default_params();
  2292. cparams.n_ctx = params.n_ctx;
  2293. cparams.n_seq_max = params.n_parallel;
  2294. cparams.n_batch = params.n_batch;
  2295. cparams.n_ubatch = params.n_ubatch;
  2296. cparams.n_threads = params.n_threads;
  2297. cparams.n_threads_batch = params.n_threads_batch == -1 ? params.n_threads : params.n_threads_batch;
  2298. cparams.seed = params.seed;
  2299. cparams.logits_all = params.logits_all;
  2300. cparams.embeddings = params.embedding;
  2301. cparams.rope_scaling_type = params.rope_scaling_type;
  2302. cparams.rope_freq_base = params.rope_freq_base;
  2303. cparams.rope_freq_scale = params.rope_freq_scale;
  2304. cparams.yarn_ext_factor = params.yarn_ext_factor;
  2305. cparams.yarn_attn_factor = params.yarn_attn_factor;
  2306. cparams.yarn_beta_fast = params.yarn_beta_fast;
  2307. cparams.yarn_beta_slow = params.yarn_beta_slow;
  2308. cparams.yarn_orig_ctx = params.yarn_orig_ctx;
  2309. cparams.pooling_type = params.pooling_type;
  2310. cparams.defrag_thold = params.defrag_thold;
  2311. cparams.cb_eval = params.cb_eval;
  2312. cparams.cb_eval_user_data = params.cb_eval_user_data;
  2313. cparams.offload_kqv = !params.no_kv_offload;
  2314. cparams.flash_attn = params.flash_attn;
  2315. cparams.type_k = kv_cache_type_from_str(params.cache_type_k);
  2316. cparams.type_v = kv_cache_type_from_str(params.cache_type_v);
  2317. return cparams;
  2318. }
  2319. #ifdef LLAMA_USE_CURL
  2320. static bool starts_with(const std::string & str, const std::string & prefix) {
  2321. // While we wait for C++20's std::string::starts_with...
  2322. return str.rfind(prefix, 0) == 0;
  2323. }
  2324. static bool llama_download_file(const std::string & url, const std::string & path) {
  2325. // Initialize libcurl
  2326. std::unique_ptr<CURL, decltype(&curl_easy_cleanup)> curl(curl_easy_init(), &curl_easy_cleanup);
  2327. if (!curl) {
  2328. fprintf(stderr, "%s: error initializing libcurl\n", __func__);
  2329. return false;
  2330. }
  2331. bool force_download = false;
  2332. // Set the URL, allow to follow http redirection
  2333. curl_easy_setopt(curl.get(), CURLOPT_URL, url.c_str());
  2334. curl_easy_setopt(curl.get(), CURLOPT_FOLLOWLOCATION, 1L);
  2335. #if defined(_WIN32)
  2336. // CURLSSLOPT_NATIVE_CA tells libcurl to use standard certificate store of
  2337. // operating system. Currently implemented under MS-Windows.
  2338. curl_easy_setopt(curl.get(), CURLOPT_SSL_OPTIONS, CURLSSLOPT_NATIVE_CA);
  2339. #endif
  2340. // Check if the file already exists locally
  2341. struct stat model_file_info;
  2342. auto file_exists = (stat(path.c_str(), &model_file_info) == 0);
  2343. // If the file exists, check its JSON metadata companion file.
  2344. std::string metadata_path = path + ".json";
  2345. nlohmann::json metadata;
  2346. std::string etag;
  2347. std::string last_modified;
  2348. if (file_exists) {
  2349. // Try and read the JSON metadata file (note: stream autoclosed upon exiting this block).
  2350. std::ifstream metadata_in(metadata_path);
  2351. if (metadata_in.good()) {
  2352. try {
  2353. metadata_in >> metadata;
  2354. fprintf(stderr, "%s: previous metadata file found %s: %s\n", __func__, metadata_path.c_str(), metadata.dump().c_str());
  2355. if (metadata.contains("url") && metadata.at("url").is_string()) {
  2356. auto previous_url = metadata.at("url").get<std::string>();
  2357. if (previous_url != url) {
  2358. fprintf(stderr, "%s: Model URL mismatch: %s != %s\n", __func__, url.c_str(), previous_url.c_str());
  2359. return false;
  2360. }
  2361. }
  2362. if (metadata.contains("etag") && metadata.at("etag").is_string()) {
  2363. etag = metadata.at("etag");
  2364. }
  2365. if (metadata.contains("lastModified") && metadata.at("lastModified").is_string()) {
  2366. last_modified = metadata.at("lastModified");
  2367. }
  2368. } catch (const nlohmann::json::exception & e) {
  2369. fprintf(stderr, "%s: error reading metadata file %s: %s\n", __func__, metadata_path.c_str(), e.what());
  2370. return false;
  2371. }
  2372. }
  2373. } else {
  2374. fprintf(stderr, "%s: no previous model file found %s\n", __func__, path.c_str());
  2375. }
  2376. // Send a HEAD request to retrieve the etag and last-modified headers
  2377. struct llama_load_model_from_url_headers {
  2378. std::string etag;
  2379. std::string last_modified;
  2380. };
  2381. llama_load_model_from_url_headers headers;
  2382. {
  2383. typedef size_t(*CURLOPT_HEADERFUNCTION_PTR)(char *, size_t, size_t, void *);
  2384. auto header_callback = [](char * buffer, size_t /*size*/, size_t n_items, void * userdata) -> size_t {
  2385. llama_load_model_from_url_headers *headers = (llama_load_model_from_url_headers *) userdata;
  2386. static std::regex header_regex("([^:]+): (.*)\r\n");
  2387. static std::regex etag_regex("ETag", std::regex_constants::icase);
  2388. static std::regex last_modified_regex("Last-Modified", std::regex_constants::icase);
  2389. std::string header(buffer, n_items);
  2390. std::smatch match;
  2391. if (std::regex_match(header, match, header_regex)) {
  2392. const std::string & key = match[1];
  2393. const std::string & value = match[2];
  2394. if (std::regex_match(key, match, etag_regex)) {
  2395. headers->etag = value;
  2396. } else if (std::regex_match(key, match, last_modified_regex)) {
  2397. headers->last_modified = value;
  2398. }
  2399. }
  2400. return n_items;
  2401. };
  2402. curl_easy_setopt(curl.get(), CURLOPT_NOBODY, 1L); // will trigger the HEAD verb
  2403. curl_easy_setopt(curl.get(), CURLOPT_NOPROGRESS, 1L); // hide head request progress
  2404. curl_easy_setopt(curl.get(), CURLOPT_HEADERFUNCTION, static_cast<CURLOPT_HEADERFUNCTION_PTR>(header_callback));
  2405. curl_easy_setopt(curl.get(), CURLOPT_HEADERDATA, &headers);
  2406. CURLcode res = curl_easy_perform(curl.get());
  2407. if (res != CURLE_OK) {
  2408. fprintf(stderr, "%s: curl_easy_perform() failed: %s\n", __func__, curl_easy_strerror(res));
  2409. return false;
  2410. }
  2411. long http_code = 0;
  2412. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &http_code);
  2413. if (http_code != 200) {
  2414. // HEAD not supported, we don't know if the file has changed
  2415. // force trigger downloading
  2416. force_download = true;
  2417. fprintf(stderr, "%s: HEAD invalid http status code received: %ld\n", __func__, http_code);
  2418. }
  2419. }
  2420. bool should_download = !file_exists || force_download;
  2421. if (!should_download) {
  2422. if (!etag.empty() && etag != headers.etag) {
  2423. fprintf(stderr, "%s: ETag header is different (%s != %s): triggering a new download\n", __func__, etag.c_str(), headers.etag.c_str());
  2424. should_download = true;
  2425. } else if (!last_modified.empty() && last_modified != headers.last_modified) {
  2426. fprintf(stderr, "%s: Last-Modified header is different (%s != %s): triggering a new download\n", __func__, last_modified.c_str(), headers.last_modified.c_str());
  2427. should_download = true;
  2428. }
  2429. }
  2430. if (should_download) {
  2431. std::string path_temporary = path + ".downloadInProgress";
  2432. if (file_exists) {
  2433. fprintf(stderr, "%s: deleting previous downloaded file: %s\n", __func__, path.c_str());
  2434. if (remove(path.c_str()) != 0) {
  2435. fprintf(stderr, "%s: unable to delete file: %s\n", __func__, path.c_str());
  2436. return false;
  2437. }
  2438. }
  2439. // Set the output file
  2440. std::unique_ptr<FILE, decltype(&fclose)> outfile(fopen(path_temporary.c_str(), "wb"), fclose);
  2441. if (!outfile) {
  2442. fprintf(stderr, "%s: error opening local file for writing: %s\n", __func__, path.c_str());
  2443. return false;
  2444. }
  2445. typedef size_t(*CURLOPT_WRITEFUNCTION_PTR)(void * data, size_t size, size_t nmemb, void * fd);
  2446. auto write_callback = [](void * data, size_t size, size_t nmemb, void * fd) -> size_t {
  2447. return fwrite(data, size, nmemb, (FILE *)fd);
  2448. };
  2449. curl_easy_setopt(curl.get(), CURLOPT_NOBODY, 0L);
  2450. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, static_cast<CURLOPT_WRITEFUNCTION_PTR>(write_callback));
  2451. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, outfile.get());
  2452. // display download progress
  2453. curl_easy_setopt(curl.get(), CURLOPT_NOPROGRESS, 0L);
  2454. // helper function to hide password in URL
  2455. auto llama_download_hide_password_in_url = [](const std::string & url) -> std::string {
  2456. std::size_t protocol_pos = url.find("://");
  2457. if (protocol_pos == std::string::npos) {
  2458. return url; // Malformed URL
  2459. }
  2460. std::size_t at_pos = url.find('@', protocol_pos + 3);
  2461. if (at_pos == std::string::npos) {
  2462. return url; // No password in URL
  2463. }
  2464. return url.substr(0, protocol_pos + 3) + "********" + url.substr(at_pos);
  2465. };
  2466. // start the download
  2467. fprintf(stderr, "%s: downloading from %s to %s (server_etag:%s, server_last_modified:%s)...\n", __func__,
  2468. llama_download_hide_password_in_url(url).c_str(), path.c_str(), headers.etag.c_str(), headers.last_modified.c_str());
  2469. auto res = curl_easy_perform(curl.get());
  2470. if (res != CURLE_OK) {
  2471. fprintf(stderr, "%s: curl_easy_perform() failed: %s\n", __func__, curl_easy_strerror(res));
  2472. return false;
  2473. }
  2474. long http_code = 0;
  2475. curl_easy_getinfo (curl.get(), CURLINFO_RESPONSE_CODE, &http_code);
  2476. if (http_code < 200 || http_code >= 400) {
  2477. fprintf(stderr, "%s: invalid http status code received: %ld\n", __func__, http_code);
  2478. return false;
  2479. }
  2480. // Causes file to be closed explicitly here before we rename it.
  2481. outfile.reset();
  2482. // Write the updated JSON metadata file.
  2483. metadata.update({
  2484. {"url", url},
  2485. {"etag", headers.etag},
  2486. {"lastModified", headers.last_modified}
  2487. });
  2488. std::ofstream(metadata_path) << metadata.dump(4);
  2489. fprintf(stderr, "%s: file metadata saved: %s\n", __func__, metadata_path.c_str());
  2490. if (rename(path_temporary.c_str(), path.c_str()) != 0) {
  2491. fprintf(stderr, "%s: unable to rename file: %s to %s\n", __func__, path_temporary.c_str(), path.c_str());
  2492. return false;
  2493. }
  2494. }
  2495. return true;
  2496. }
  2497. struct llama_model * llama_load_model_from_url(
  2498. const char * model_url,
  2499. const char * path_model,
  2500. const struct llama_model_params & params) {
  2501. // Basic validation of the model_url
  2502. if (!model_url || strlen(model_url) == 0) {
  2503. fprintf(stderr, "%s: invalid model_url\n", __func__);
  2504. return NULL;
  2505. }
  2506. if (!llama_download_file(model_url, path_model)) {
  2507. return NULL;
  2508. }
  2509. // check for additional GGUFs split to download
  2510. int n_split = 0;
  2511. {
  2512. struct gguf_init_params gguf_params = {
  2513. /*.no_alloc = */ true,
  2514. /*.ctx = */ NULL,
  2515. };
  2516. auto * ctx_gguf = gguf_init_from_file(path_model, gguf_params);
  2517. if (!ctx_gguf) {
  2518. fprintf(stderr, "\n%s: failed to load input GGUF from %s\n", __func__, path_model);
  2519. return NULL;
  2520. }
  2521. auto key_n_split = gguf_find_key(ctx_gguf, LLM_KV_SPLIT_COUNT);
  2522. if (key_n_split >= 0) {
  2523. n_split = gguf_get_val_u16(ctx_gguf, key_n_split);
  2524. }
  2525. gguf_free(ctx_gguf);
  2526. }
  2527. if (n_split > 1) {
  2528. char split_prefix[PATH_MAX] = {0};
  2529. char split_url_prefix[LLAMA_CURL_MAX_URL_LENGTH] = {0};
  2530. // Verify the first split file format
  2531. // and extract split URL and PATH prefixes
  2532. {
  2533. if (!llama_split_prefix(split_prefix, sizeof(split_prefix), path_model, 0, n_split)) {
  2534. fprintf(stderr, "\n%s: unexpected model file name: %s"
  2535. " n_split=%d\n", __func__, path_model, n_split);
  2536. return NULL;
  2537. }
  2538. if (!llama_split_prefix(split_url_prefix, sizeof(split_url_prefix), model_url, 0, n_split)) {
  2539. fprintf(stderr, "\n%s: unexpected model url: %s"
  2540. " n_split=%d\n", __func__, model_url, n_split);
  2541. return NULL;
  2542. }
  2543. }
  2544. // Prepare download in parallel
  2545. std::vector<std::future<bool>> futures_download;
  2546. for (int idx = 1; idx < n_split; idx++) {
  2547. futures_download.push_back(std::async(std::launch::async, [&split_prefix, &split_url_prefix, &n_split](int download_idx) -> bool {
  2548. char split_path[PATH_MAX] = {0};
  2549. llama_split_path(split_path, sizeof(split_path), split_prefix, download_idx, n_split);
  2550. char split_url[LLAMA_CURL_MAX_URL_LENGTH] = {0};
  2551. llama_split_path(split_url, sizeof(split_url), split_url_prefix, download_idx, n_split);
  2552. return llama_download_file(split_url, split_path);
  2553. }, idx));
  2554. }
  2555. // Wait for all downloads to complete
  2556. for (auto & f : futures_download) {
  2557. if (!f.get()) {
  2558. return NULL;
  2559. }
  2560. }
  2561. }
  2562. return llama_load_model_from_file(path_model, params);
  2563. }
  2564. struct llama_model * llama_load_model_from_hf(
  2565. const char * repo,
  2566. const char * model,
  2567. const char * path_model,
  2568. const struct llama_model_params & params) {
  2569. // construct hugging face model url:
  2570. //
  2571. // --repo ggml-org/models --file tinyllama-1.1b/ggml-model-f16.gguf
  2572. // https://huggingface.co/ggml-org/models/resolve/main/tinyllama-1.1b/ggml-model-f16.gguf
  2573. //
  2574. // --repo TheBloke/Mixtral-8x7B-v0.1-GGUF --file mixtral-8x7b-v0.1.Q4_K_M.gguf
  2575. // https://huggingface.co/TheBloke/Mixtral-8x7B-v0.1-GGUF/resolve/main/mixtral-8x7b-v0.1.Q4_K_M.gguf
  2576. //
  2577. std::string model_url = "https://huggingface.co/";
  2578. model_url += repo;
  2579. model_url += "/resolve/main/";
  2580. model_url += model;
  2581. return llama_load_model_from_url(model_url.c_str(), path_model, params);
  2582. }
  2583. #else
  2584. struct llama_model * llama_load_model_from_url(
  2585. const char * /*model_url*/,
  2586. const char * /*path_model*/,
  2587. const struct llama_model_params & /*params*/) {
  2588. fprintf(stderr, "%s: llama.cpp built without libcurl, downloading from an url not supported.\n", __func__);
  2589. return nullptr;
  2590. }
  2591. struct llama_model * llama_load_model_from_hf(
  2592. const char * /*repo*/,
  2593. const char * /*model*/,
  2594. const char * /*path_model*/,
  2595. const struct llama_model_params & /*params*/) {
  2596. fprintf(stderr, "%s: llama.cpp built without libcurl, downloading from Hugging Face not supported.\n", __func__);
  2597. return nullptr;
  2598. }
  2599. #endif // LLAMA_USE_CURL
  2600. //
  2601. // Batch utils
  2602. //
  2603. void llama_batch_clear(struct llama_batch & batch) {
  2604. batch.n_tokens = 0;
  2605. }
  2606. void llama_batch_add(
  2607. struct llama_batch & batch,
  2608. llama_token id,
  2609. llama_pos pos,
  2610. const std::vector<llama_seq_id> & seq_ids,
  2611. bool logits) {
  2612. batch.token [batch.n_tokens] = id;
  2613. batch.pos [batch.n_tokens] = pos;
  2614. batch.n_seq_id[batch.n_tokens] = seq_ids.size();
  2615. for (size_t i = 0; i < seq_ids.size(); ++i) {
  2616. batch.seq_id[batch.n_tokens][i] = seq_ids[i];
  2617. }
  2618. batch.logits [batch.n_tokens] = logits;
  2619. batch.n_tokens++;
  2620. }
  2621. //
  2622. // Vocab utils
  2623. //
  2624. std::vector<llama_token> llama_tokenize(
  2625. const struct llama_context * ctx,
  2626. const std::string & text,
  2627. bool add_special,
  2628. bool parse_special) {
  2629. return llama_tokenize(llama_get_model(ctx), text, add_special, parse_special);
  2630. }
  2631. std::vector<llama_token> llama_tokenize(
  2632. const struct llama_model * model,
  2633. const std::string & text,
  2634. bool add_special,
  2635. bool parse_special) {
  2636. // upper limit for the number of tokens
  2637. int n_tokens = text.length() + 2 * add_special;
  2638. std::vector<llama_token> result(n_tokens);
  2639. n_tokens = llama_tokenize(model, text.data(), text.length(), result.data(), result.size(), add_special, parse_special);
  2640. if (n_tokens < 0) {
  2641. result.resize(-n_tokens);
  2642. int check = llama_tokenize(model, text.data(), text.length(), result.data(), result.size(), add_special, parse_special);
  2643. GGML_ASSERT(check == -n_tokens);
  2644. } else {
  2645. result.resize(n_tokens);
  2646. }
  2647. return result;
  2648. }
  2649. std::string llama_token_to_piece(const struct llama_context * ctx, llama_token token, bool special) {
  2650. std::vector<char> result(8, 0);
  2651. const int n_tokens = llama_token_to_piece(llama_get_model(ctx), token, result.data(), result.size(), special);
  2652. if (n_tokens < 0) {
  2653. result.resize(-n_tokens);
  2654. int check = llama_token_to_piece(llama_get_model(ctx), token, result.data(), result.size(), special);
  2655. GGML_ASSERT(check == -n_tokens);
  2656. } else {
  2657. result.resize(n_tokens);
  2658. }
  2659. return std::string(result.data(), result.size());
  2660. }
  2661. std::string llama_detokenize_spm(llama_context * ctx, const std::vector<llama_token> & tokens) {
  2662. const llama_token bos_id = llama_token_bos(llama_get_model(ctx));
  2663. std::string piece;
  2664. std::string result;
  2665. for (size_t i = 0; i < tokens.size(); ++i) {
  2666. piece = llama_token_to_piece(ctx, tokens[i]);
  2667. // remove the leading space of the first non-BOS token
  2668. if (((tokens[0] == bos_id && i == 1) || (tokens[0] != bos_id && i == 0)) && piece[0] == ' ') {
  2669. piece = piece.substr(1);
  2670. }
  2671. result += piece;
  2672. }
  2673. return result;
  2674. }
  2675. std::string llama_detokenize_bpe(llama_context * ctx, const std::vector<llama_token> & tokens) {
  2676. std::string piece;
  2677. std::string result;
  2678. for (size_t i = 0; i < tokens.size(); ++i) {
  2679. piece = llama_token_to_piece(ctx, tokens[i]);
  2680. result += piece;
  2681. }
  2682. // NOTE: the original tokenizer decodes bytes after collecting the pieces.
  2683. return result;
  2684. }
  2685. bool llama_should_add_bos_token(const llama_model * model) {
  2686. const int add_bos = llama_add_bos_token(model);
  2687. return add_bos != -1 ? bool(add_bos) : (llama_vocab_type(model) == LLAMA_VOCAB_TYPE_SPM);
  2688. }
  2689. bool llama_chat_verify_template(const std::string & tmpl) {
  2690. llama_chat_message chat[] = {{"user", "test"}};
  2691. int res = llama_chat_apply_template(nullptr, tmpl.c_str(), chat, 1, true, nullptr, 0);
  2692. return res >= 0;
  2693. }
  2694. //
  2695. // KV cache utils
  2696. //
  2697. void llama_kv_cache_dump_view(const llama_kv_cache_view & view, int row_size) {
  2698. static const char slot_chars[] = ".123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+";
  2699. printf("=== Dumping KV cache. total cells %d, max sequences per cell %d, populated cells %d, total tokens in cache %d, largest empty slot=%d @ %d",
  2700. view.n_cells, view.n_seq_max, view.used_cells, view.token_count, view.max_contiguous, view.max_contiguous_idx);
  2701. llama_kv_cache_view_cell * c_curr = view.cells;
  2702. llama_seq_id * cs_curr = view.cells_sequences;
  2703. for (int i = 0; i < view.n_cells; i++, c_curr++, cs_curr += view.n_seq_max) {
  2704. if (i % row_size == 0) {
  2705. printf("\n%5d: ", i);
  2706. }
  2707. int seq_count = 0;
  2708. for (int j = 0; j < view.n_seq_max; j++) {
  2709. if (cs_curr[j] >= 0) { seq_count++; }
  2710. }
  2711. putchar(slot_chars[std::min(sizeof(slot_chars) - 2, size_t(seq_count))]);
  2712. }
  2713. printf("\n=== Done dumping\n");
  2714. }
  2715. void llama_kv_cache_dump_view_seqs(const llama_kv_cache_view & view, int row_size) {
  2716. static const char slot_chars[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  2717. printf("=== Dumping KV cache. total cells %d, max sequences per cell %d, populated cells %d, total tokens in cache %d, largest empty slot=%d @ %d\n",
  2718. view.n_cells, view.n_seq_max, view.used_cells, view.token_count, view.max_contiguous, view.max_contiguous_idx);
  2719. std::unordered_map<llama_seq_id, size_t> seqs;
  2720. llama_kv_cache_view_cell * c_curr = view.cells;
  2721. llama_seq_id * cs_curr = view.cells_sequences;
  2722. for (int i = 0; i < view.n_cells; i++, c_curr++, cs_curr += view.n_seq_max) {
  2723. for (int j = 0; j < view.n_seq_max; j++) {
  2724. if (cs_curr[j] < 0) { continue; }
  2725. if (seqs.find(cs_curr[j]) == seqs.end()) {
  2726. if (seqs.size() + 1 >= sizeof(slot_chars)) { break; }
  2727. const size_t sz = seqs.size();
  2728. seqs[cs_curr[j]] = sz;
  2729. }
  2730. }
  2731. if (seqs.size() + 1 >= sizeof(slot_chars)) { break; }
  2732. }
  2733. printf("=== Sequence legend: ");
  2734. for (const auto & it : seqs) {
  2735. printf("%zu=%d, ", it.second, it.first);
  2736. }
  2737. printf("'+'=other sequence ids");
  2738. c_curr = view.cells;
  2739. cs_curr = view.cells_sequences;
  2740. for (int i = 0; i < view.n_cells; i++, c_curr++, cs_curr += view.n_seq_max) {
  2741. if (i % row_size == 0) {
  2742. printf("\n%5d: ", i);
  2743. }
  2744. for (int j = 0; j < view.n_seq_max; j++) {
  2745. if (cs_curr[j] >= 0) {
  2746. const auto & it = seqs.find(cs_curr[j]);
  2747. putchar(it != seqs.end() ? int(slot_chars[it->second]) : '+');
  2748. } else {
  2749. putchar('.');
  2750. }
  2751. }
  2752. putchar(' ');
  2753. }
  2754. printf("\n=== Done dumping\n");
  2755. }
  2756. //
  2757. // Embedding utils
  2758. //
  2759. void llama_embd_normalize(const float * inp, float * out, int n) {
  2760. double sum = 0.0;
  2761. for (int i = 0; i < n; i++) {
  2762. sum += inp[i] * inp[i];
  2763. }
  2764. sum = sqrt(sum);
  2765. const float norm = sum > 0.0 ? 1.0f / sum : 0.0f;
  2766. for (int i = 0; i < n; i++) {
  2767. out[i] = inp[i] * norm;
  2768. }
  2769. }
  2770. float llama_embd_similarity_cos(const float * embd1, const float * embd2, int n){
  2771. double sum = 0.0;
  2772. double sum1 = 0.0;
  2773. double sum2 = 0.0;
  2774. for (int i = 0; i < n; i++) {
  2775. sum += embd1[i] * embd2[i];
  2776. sum1 += embd1[i] * embd1[i];
  2777. sum2 += embd2[i] * embd2[i];
  2778. }
  2779. return sum / (sqrt(sum1) * sqrt(sum2));
  2780. }
  2781. //
  2782. // Control vector utils
  2783. //
  2784. static llama_control_vector_data llama_control_vector_load_one(const llama_control_vector_load_info & load_info) {
  2785. int32_t n_tensors;
  2786. size_t n_bytes = 0;
  2787. uint32_t max_direction_layer = 0;
  2788. llama_control_vector_data result = { -1, {} };
  2789. // calculate size of ctx needed for tensors, ensure tensors are f32, and find max layer
  2790. {
  2791. struct ggml_init_params meta_params = {
  2792. /* .mem_size = */ ggml_tensor_overhead() * 128 + ggml_graph_overhead(),
  2793. /* .mem_buffer = */ nullptr,
  2794. /* .no_alloc = */ true,
  2795. };
  2796. ggml_context * meta_ctx = ggml_init(meta_params);
  2797. struct gguf_init_params meta_gguf_params = {
  2798. /* .no_alloc = */ true,
  2799. /* .ctx = */ &meta_ctx,
  2800. };
  2801. struct gguf_context * meta_ctx_gguf = gguf_init_from_file(load_info.fname.c_str(), meta_gguf_params);
  2802. if (!meta_ctx_gguf) {
  2803. fprintf(stderr, "%s: failed to load control vector from %s\n", __func__, load_info.fname.c_str());
  2804. ggml_free(meta_ctx);
  2805. return result;
  2806. }
  2807. n_tensors = gguf_get_n_tensors(meta_ctx_gguf);
  2808. for (int i = 0; i < n_tensors; i++) {
  2809. std::string name = gguf_get_tensor_name(meta_ctx_gguf, i);
  2810. // split on '.'
  2811. size_t dotpos = name.find('.');
  2812. if (dotpos != std::string::npos && name.substr(0, dotpos) == "direction") {
  2813. try {
  2814. uint32_t layer = std::stoi(name.substr(dotpos + 1));
  2815. if (layer == 0) {
  2816. fprintf(stderr, "%s: direction tensor invalid in %s\n", __func__, load_info.fname.c_str());
  2817. ggml_free(meta_ctx);
  2818. gguf_free(meta_ctx_gguf);
  2819. return result;
  2820. }
  2821. if (layer > max_direction_layer) {
  2822. max_direction_layer = layer;
  2823. }
  2824. } catch (...) {
  2825. fprintf(stderr, "%s: direction tensor invalid in %s\n", __func__, load_info.fname.c_str());
  2826. ggml_free(meta_ctx);
  2827. gguf_free(meta_ctx_gguf);
  2828. return result;
  2829. }
  2830. }
  2831. struct ggml_tensor * tensor_meta = ggml_get_tensor(meta_ctx, name.c_str());
  2832. if (tensor_meta->type != GGML_TYPE_F32 || ggml_n_dims(tensor_meta) != 1) {
  2833. fprintf(stderr, "%s: direction tensor invalid in %s\n", __func__, load_info.fname.c_str());
  2834. ggml_free(meta_ctx);
  2835. gguf_free(meta_ctx_gguf);
  2836. return result;
  2837. }
  2838. if (result.n_embd == -1) {
  2839. result.n_embd = ggml_nelements(tensor_meta);
  2840. } else if (ggml_nelements(tensor_meta) != result.n_embd) {
  2841. fprintf(stderr, "%s: direction tensor sizes mismatched in %s\n", __func__, load_info.fname.c_str());
  2842. ggml_free(meta_ctx);
  2843. gguf_free(meta_ctx_gguf);
  2844. return result;
  2845. }
  2846. n_bytes += ggml_nbytes(tensor_meta);
  2847. }
  2848. ggml_free(meta_ctx);
  2849. gguf_free(meta_ctx_gguf);
  2850. }
  2851. if (n_tensors == 0) {
  2852. fprintf(stderr, "%s: no direction tensors found in %s\n", __func__, load_info.fname.c_str());
  2853. return result;
  2854. }
  2855. // load and scale tensors into final control vector context
  2856. struct ggml_init_params ggml_params = {
  2857. /* .mem_size = */ ggml_tensor_overhead() * n_tensors + n_bytes,
  2858. /* .mem_buffer = */ nullptr,
  2859. /* .no_alloc = */ false,
  2860. };
  2861. struct ggml_context * ctx = ggml_init(ggml_params);
  2862. struct gguf_init_params params = {
  2863. /*.no_alloc = */ false,
  2864. /*.ctx = */ &ctx,
  2865. };
  2866. struct gguf_context * ctx_gguf = gguf_init_from_file(load_info.fname.c_str(), params);
  2867. if (!ctx_gguf) {
  2868. fprintf(stderr, "%s: failed to load control vector from %s\n", __func__, load_info.fname.c_str());
  2869. ggml_free(ctx);
  2870. return result;
  2871. }
  2872. // do not store data for layer 0 (it's not used)
  2873. result.data.resize(result.n_embd * max_direction_layer);
  2874. for (uint32_t il = 1; il <= max_direction_layer; il++) {
  2875. const std::string name = "direction." + std::to_string(il);
  2876. const ggml_tensor * tensor = ggml_get_tensor(ctx, name.c_str());
  2877. float * dst = result.data.data() + result.n_embd * (il - 1);
  2878. if (tensor) {
  2879. const float * src = (const float *) tensor->data;
  2880. for (int j = 0; j < result.n_embd; j++) {
  2881. dst[j] = src[j] * load_info.strength;
  2882. }
  2883. } else {
  2884. for (int j = 0; j < result.n_embd; j++) {
  2885. dst[j] = 0.0f;
  2886. }
  2887. }
  2888. }
  2889. return result;
  2890. }
  2891. llama_control_vector_data llama_control_vector_load(const std::vector<llama_control_vector_load_info> & load_infos) {
  2892. llama_control_vector_data result = { -1, {} };
  2893. for (const auto & info : load_infos) {
  2894. auto cur = llama_control_vector_load_one(info);
  2895. if (cur.n_embd == -1) {
  2896. return result;
  2897. }
  2898. if (result.n_embd != -1 && (result.n_embd != cur.n_embd || result.data.size() != cur.data.size())) {
  2899. fprintf(stderr, "%s: control vector in %s does not match previous vector dimensions\n", __func__, info.fname.c_str());
  2900. return result;
  2901. }
  2902. if (result.n_embd == -1) {
  2903. result = std::move(cur);
  2904. } else {
  2905. for (size_t i = 0; i < cur.data.size(); i++) {
  2906. result.data[i] += cur.data[i];
  2907. }
  2908. }
  2909. }
  2910. if (result.n_embd == -1) {
  2911. fprintf(stderr, "%s: no vectors passed\n", __func__);
  2912. }
  2913. return result;
  2914. }
  2915. //
  2916. // YAML utils
  2917. //
  2918. void yaml_dump_vector_float(FILE * stream, const char * prop_name, const std::vector<float> & data) {
  2919. if (data.empty()) {
  2920. fprintf(stream, "%s:\n", prop_name);
  2921. return;
  2922. }
  2923. fprintf(stream, "%s: [", prop_name);
  2924. for (size_t i = 0; i < data.size() - 1; ++i) {
  2925. fprintf(stream, "%e, ", data[i]);
  2926. }
  2927. fprintf(stream, "%e]\n", data.back());
  2928. }
  2929. void yaml_dump_vector_int(FILE * stream, const char * prop_name, const std::vector<int> & data) {
  2930. if (data.empty()) {
  2931. fprintf(stream, "%s:\n", prop_name);
  2932. return;
  2933. }
  2934. fprintf(stream, "%s: [", prop_name);
  2935. for (size_t i = 0; i < data.size() - 1; ++i) {
  2936. fprintf(stream, "%d, ", data[i]);
  2937. }
  2938. fprintf(stream, "%d]\n", data.back());
  2939. }
  2940. void yaml_dump_string_multiline(FILE * stream, const char * prop_name, const char * data) {
  2941. std::string data_str(data == NULL ? "" : data);
  2942. if (data_str.empty()) {
  2943. fprintf(stream, "%s:\n", prop_name);
  2944. return;
  2945. }
  2946. size_t pos_start = 0;
  2947. size_t pos_found = 0;
  2948. if (std::isspace(data_str[0]) || std::isspace(data_str.back())) {
  2949. data_str = std::regex_replace(data_str, std::regex("\n"), "\\n");
  2950. data_str = std::regex_replace(data_str, std::regex("\""), "\\\"");
  2951. data_str = std::regex_replace(data_str, std::regex(R"(\\[^n"])"), R"(\$&)");
  2952. data_str = "\"" + data_str + "\"";
  2953. fprintf(stream, "%s: %s\n", prop_name, data_str.c_str());
  2954. return;
  2955. }
  2956. if (data_str.find('\n') == std::string::npos) {
  2957. fprintf(stream, "%s: %s\n", prop_name, data_str.c_str());
  2958. return;
  2959. }
  2960. fprintf(stream, "%s: |\n", prop_name);
  2961. while ((pos_found = data_str.find('\n', pos_start)) != std::string::npos) {
  2962. fprintf(stream, " %s\n", data_str.substr(pos_start, pos_found-pos_start).c_str());
  2963. pos_start = pos_found + 1;
  2964. }
  2965. }
  2966. void yaml_dump_non_result_info(FILE * stream, const gpt_params & params, const llama_context * lctx,
  2967. const std::string & timestamp, const std::vector<int> & prompt_tokens, const char * model_desc) {
  2968. const llama_sampling_params & sparams = params.sparams;
  2969. fprintf(stream, "build_commit: %s\n", LLAMA_COMMIT);
  2970. fprintf(stream, "build_number: %d\n", LLAMA_BUILD_NUMBER);
  2971. fprintf(stream, "cpu_has_arm_fma: %s\n", ggml_cpu_has_arm_fma() ? "true" : "false");
  2972. fprintf(stream, "cpu_has_avx: %s\n", ggml_cpu_has_avx() ? "true" : "false");
  2973. fprintf(stream, "cpu_has_avx_vnni: %s\n", ggml_cpu_has_avx_vnni() ? "true" : "false");
  2974. fprintf(stream, "cpu_has_avx2: %s\n", ggml_cpu_has_avx2() ? "true" : "false");
  2975. fprintf(stream, "cpu_has_avx512: %s\n", ggml_cpu_has_avx512() ? "true" : "false");
  2976. fprintf(stream, "cpu_has_avx512_vbmi: %s\n", ggml_cpu_has_avx512_vbmi() ? "true" : "false");
  2977. fprintf(stream, "cpu_has_avx512_vnni: %s\n", ggml_cpu_has_avx512_vnni() ? "true" : "false");
  2978. fprintf(stream, "cpu_has_cuda: %s\n", ggml_cpu_has_cuda() ? "true" : "false");
  2979. fprintf(stream, "cpu_has_vulkan: %s\n", ggml_cpu_has_vulkan() ? "true" : "false");
  2980. fprintf(stream, "cpu_has_kompute: %s\n", ggml_cpu_has_kompute() ? "true" : "false");
  2981. fprintf(stream, "cpu_has_fma: %s\n", ggml_cpu_has_fma() ? "true" : "false");
  2982. fprintf(stream, "cpu_has_gpublas: %s\n", ggml_cpu_has_gpublas() ? "true" : "false");
  2983. fprintf(stream, "cpu_has_neon: %s\n", ggml_cpu_has_neon() ? "true" : "false");
  2984. fprintf(stream, "cpu_has_sve: %s\n", ggml_cpu_has_sve() ? "true" : "false");
  2985. fprintf(stream, "cpu_has_f16c: %s\n", ggml_cpu_has_f16c() ? "true" : "false");
  2986. fprintf(stream, "cpu_has_fp16_va: %s\n", ggml_cpu_has_fp16_va() ? "true" : "false");
  2987. fprintf(stream, "cpu_has_wasm_simd: %s\n", ggml_cpu_has_wasm_simd() ? "true" : "false");
  2988. fprintf(stream, "cpu_has_blas: %s\n", ggml_cpu_has_blas() ? "true" : "false");
  2989. fprintf(stream, "cpu_has_sse3: %s\n", ggml_cpu_has_sse3() ? "true" : "false");
  2990. fprintf(stream, "cpu_has_vsx: %s\n", ggml_cpu_has_vsx() ? "true" : "false");
  2991. fprintf(stream, "cpu_has_matmul_int8: %s\n", ggml_cpu_has_matmul_int8() ? "true" : "false");
  2992. #ifdef NDEBUG
  2993. fprintf(stream, "debug: false\n");
  2994. #else
  2995. fprintf(stream, "debug: true\n");
  2996. #endif // NDEBUG
  2997. fprintf(stream, "model_desc: %s\n", model_desc);
  2998. fprintf(stream, "n_vocab: %d # output size of the final layer, 32001 for some models\n", llama_n_vocab(llama_get_model(lctx)));
  2999. #ifdef __OPTIMIZE__
  3000. fprintf(stream, "optimize: true\n");
  3001. #else
  3002. fprintf(stream, "optimize: false\n");
  3003. #endif // __OPTIMIZE__
  3004. fprintf(stream, "time: %s\n", timestamp.c_str());
  3005. fprintf(stream, "\n");
  3006. fprintf(stream, "###############\n");
  3007. fprintf(stream, "# User Inputs #\n");
  3008. fprintf(stream, "###############\n");
  3009. fprintf(stream, "\n");
  3010. fprintf(stream, "alias: %s # default: unknown\n", params.model_alias.c_str());
  3011. fprintf(stream, "batch_size: %d # default: 512\n", params.n_batch);
  3012. yaml_dump_string_multiline(stream, "cfg_negative_prompt", sparams.cfg_negative_prompt.c_str());
  3013. fprintf(stream, "cfg_scale: %f # default: 1.0\n", sparams.cfg_scale);
  3014. fprintf(stream, "chunks: %d # default: -1 (unlimited)\n", params.n_chunks);
  3015. fprintf(stream, "color: %s # default: false\n", params.use_color ? "true" : "false");
  3016. fprintf(stream, "ctx_size: %d # default: 512\n", params.n_ctx);
  3017. fprintf(stream, "escape: %s # default: false\n", params.escape ? "true" : "false");
  3018. fprintf(stream, "file: # never logged, see prompt instead. Can still be specified for input.\n");
  3019. fprintf(stream, "frequency_penalty: %f # default: 0.0 \n", sparams.penalty_freq);
  3020. yaml_dump_string_multiline(stream, "grammar", sparams.grammar.c_str());
  3021. fprintf(stream, "grammar-file: # never logged, see grammar instead. Can still be specified for input.\n");
  3022. fprintf(stream, "hellaswag: %s # default: false\n", params.hellaswag ? "true" : "false");
  3023. fprintf(stream, "hellaswag_tasks: %zu # default: 400\n", params.hellaswag_tasks);
  3024. const auto logit_bias_eos = sparams.logit_bias.find(llama_token_eos(llama_get_model(lctx)));
  3025. const bool ignore_eos = logit_bias_eos != sparams.logit_bias.end() && logit_bias_eos->second == -INFINITY;
  3026. fprintf(stream, "ignore_eos: %s # default: false\n", ignore_eos ? "true" : "false");
  3027. yaml_dump_string_multiline(stream, "in_prefix", params.input_prefix.c_str());
  3028. fprintf(stream, "in_prefix_bos: %s # default: false\n", params.input_prefix_bos ? "true" : "false");
  3029. yaml_dump_string_multiline(stream, "in_suffix", params.input_prefix.c_str());
  3030. fprintf(stream, "interactive: %s # default: false\n", params.interactive ? "true" : "false");
  3031. fprintf(stream, "interactive_first: %s # default: false\n", params.interactive_first ? "true" : "false");
  3032. fprintf(stream, "keep: %d # default: 0\n", params.n_keep);
  3033. fprintf(stream, "logdir: %s # default: unset (no logging)\n", params.logdir.c_str());
  3034. fprintf(stream, "logit_bias:\n");
  3035. for (std::pair<llama_token, float> lb : sparams.logit_bias) {
  3036. if (ignore_eos && lb.first == logit_bias_eos->first) {
  3037. continue;
  3038. }
  3039. fprintf(stream, " %d: %f", lb.first, lb.second);
  3040. }
  3041. fprintf(stream, "lora:\n");
  3042. for (std::tuple<std::string, float> la : params.lora_adapter) {
  3043. if (std::get<1>(la) != 1.0f) {
  3044. continue;
  3045. }
  3046. fprintf(stream, " - %s\n", std::get<0>(la).c_str());
  3047. }
  3048. fprintf(stream, "lora_scaled:\n");
  3049. for (std::tuple<std::string, float> la : params.lora_adapter) {
  3050. if (std::get<1>(la) == 1.0f) {
  3051. continue;
  3052. }
  3053. fprintf(stream, " - %s: %f\n", std::get<0>(la).c_str(), std::get<1>(la));
  3054. }
  3055. fprintf(stream, "lora_base: %s\n", params.lora_base.c_str());
  3056. fprintf(stream, "main_gpu: %d # default: 0\n", params.main_gpu);
  3057. fprintf(stream, "min_keep: %d # default: 0 (disabled)\n", sparams.min_keep);
  3058. fprintf(stream, "mirostat: %d # default: 0 (disabled)\n", sparams.mirostat);
  3059. fprintf(stream, "mirostat_ent: %f # default: 5.0\n", sparams.mirostat_tau);
  3060. fprintf(stream, "mirostat_lr: %f # default: 0.1\n", sparams.mirostat_eta);
  3061. fprintf(stream, "mlock: %s # default: false\n", params.use_mlock ? "true" : "false");
  3062. fprintf(stream, "model: %s # default: %s\n", params.model.c_str(), DEFAULT_MODEL_PATH);
  3063. fprintf(stream, "model_draft: %s # default:\n", params.model_draft.c_str());
  3064. fprintf(stream, "multiline_input: %s # default: false\n", params.multiline_input ? "true" : "false");
  3065. fprintf(stream, "n_gpu_layers: %d # default: -1\n", params.n_gpu_layers);
  3066. fprintf(stream, "n_predict: %d # default: -1 (unlimited)\n", params.n_predict);
  3067. fprintf(stream, "n_probs: %d # only used by server binary, default: 0\n", sparams.n_probs);
  3068. fprintf(stream, "no_mmap: %s # default: false\n", !params.use_mmap ? "true" : "false");
  3069. fprintf(stream, "penalize_nl: %s # default: false\n", sparams.penalize_nl ? "true" : "false");
  3070. fprintf(stream, "ppl_output_type: %d # default: 0\n", params.ppl_output_type);
  3071. fprintf(stream, "ppl_stride: %d # default: 0\n", params.ppl_stride);
  3072. fprintf(stream, "presence_penalty: %f # default: 0.0\n", sparams.penalty_present);
  3073. yaml_dump_string_multiline(stream, "prompt", params.prompt.c_str());
  3074. fprintf(stream, "prompt_cache: %s\n", params.path_prompt_cache.c_str());
  3075. fprintf(stream, "prompt_cache_all: %s # default: false\n", params.prompt_cache_all ? "true" : "false");
  3076. fprintf(stream, "prompt_cache_ro: %s # default: false\n", params.prompt_cache_ro ? "true" : "false");
  3077. yaml_dump_vector_int(stream, "prompt_tokens", prompt_tokens);
  3078. fprintf(stream, "repeat_penalty: %f # default: 1.1\n", sparams.penalty_repeat);
  3079. fprintf(stream, "reverse_prompt:\n");
  3080. for (std::string ap : params.antiprompt) {
  3081. size_t pos = 0;
  3082. while ((pos = ap.find('\n', pos)) != std::string::npos) {
  3083. ap.replace(pos, 1, "\\n");
  3084. pos += 1;
  3085. }
  3086. fprintf(stream, " - %s\n", ap.c_str());
  3087. }
  3088. fprintf(stream, "rope_freq_base: %f # default: 10000.0\n", params.rope_freq_base);
  3089. fprintf(stream, "rope_freq_scale: %f # default: 1.0\n", params.rope_freq_scale);
  3090. fprintf(stream, "seed: %u # default: -1 (random seed)\n", params.seed);
  3091. fprintf(stream, "simple_io: %s # default: false\n", params.simple_io ? "true" : "false");
  3092. fprintf(stream, "cont_batching: %s # default: false\n", params.cont_batching ? "true" : "false");
  3093. fprintf(stream, "flash_attn: %s # default: false\n", params.flash_attn ? "true" : "false");
  3094. fprintf(stream, "temp: %f # default: 0.8\n", sparams.temp);
  3095. const std::vector<float> tensor_split_vector(params.tensor_split, params.tensor_split + llama_max_devices());
  3096. yaml_dump_vector_float(stream, "tensor_split", tensor_split_vector);
  3097. fprintf(stream, "tfs: %f # default: 1.0\n", sparams.tfs_z);
  3098. fprintf(stream, "threads: %d # default: %u\n", params.n_threads, std::thread::hardware_concurrency());
  3099. fprintf(stream, "top_k: %d # default: 40\n", sparams.top_k);
  3100. fprintf(stream, "top_p: %f # default: 0.95\n", sparams.top_p);
  3101. fprintf(stream, "min_p: %f # default: 0.0\n", sparams.min_p);
  3102. fprintf(stream, "typical_p: %f # default: 1.0\n", sparams.typical_p);
  3103. fprintf(stream, "verbose_prompt: %s # default: false\n", params.verbose_prompt ? "true" : "false");
  3104. fprintf(stream, "display_prompt: %s # default: true\n", params.display_prompt ? "true" : "false");
  3105. }