common.cpp 92 KB

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