common.cpp 152 KB

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