common.cpp 150 KB

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