common.cpp 112 KB

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