common.cpp 88 KB

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