common.cpp 137 KB

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