common.cpp 135 KB

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