common.cpp 136 KB

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