common.cpp 136 KB

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