common.cpp 148 KB

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