common.cpp 139 KB

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