common.cpp 132 KB

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