common.cpp 148 KB

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