common.cpp 98 KB

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