common.cpp 135 KB

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