common.cpp 110 KB

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