1
0

common.cpp 101 KB

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