common.cpp 153 KB

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