common.cpp 129 KB

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