1
0

common.cpp 100 KB

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