common.cpp 140 KB

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