common.cpp 98 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596
  1. #include "common.h"
  2. #include "llama.h"
  3. #include <algorithm>
  4. #include <cassert>
  5. #include <cmath>
  6. #include <cstring>
  7. #include <ctime>
  8. #include <fstream>
  9. #include <iterator>
  10. #include <iostream>
  11. #include <regex>
  12. #include <sstream>
  13. #include <string>
  14. #include <unordered_map>
  15. #include <unordered_set>
  16. #include <vector>
  17. #include <cinttypes>
  18. #if defined(__APPLE__) && defined(__MACH__)
  19. #include <sys/types.h>
  20. #include <sys/sysctl.h>
  21. #endif
  22. #if defined(_WIN32)
  23. #define WIN32_LEAN_AND_MEAN
  24. #ifndef NOMINMAX
  25. # define NOMINMAX
  26. #endif
  27. #include <codecvt>
  28. #include <locale>
  29. #include <windows.h>
  30. #include <fcntl.h>
  31. #include <io.h>
  32. #else
  33. #include <sys/ioctl.h>
  34. #include <sys/stat.h>
  35. #include <unistd.h>
  36. #endif
  37. #if defined(LLAMA_USE_CURL)
  38. #include <curl/curl.h>
  39. #endif
  40. #if defined(_MSC_VER)
  41. #pragma warning(disable: 4244 4267) // possible loss of data
  42. #endif
  43. #if (defined(GGML_USE_CUBLAS) || defined(GGML_USE_SYCL))
  44. #define GGML_USE_CUBLAS_SYCL
  45. #endif
  46. #if (defined(GGML_USE_CUBLAS) || defined(GGML_USE_SYCL)) || defined(GGML_USE_VULKAN)
  47. #define GGML_USE_CUBLAS_SYCL_VULKAN
  48. #endif
  49. #if defined(LLAMA_USE_CURL)
  50. #ifdef __linux__
  51. #include <linux/limits.h>
  52. #elif defined(_WIN32)
  53. #define PATH_MAX MAX_PATH
  54. #else
  55. #include <sys/syslimits.h>
  56. #endif
  57. #define LLAMA_CURL_MAX_PATH_LENGTH PATH_MAX
  58. #define LLAMA_CURL_MAX_HEADER_LENGTH 256
  59. #endif // LLAMA_USE_CURL
  60. int32_t get_num_physical_cores() {
  61. #ifdef __linux__
  62. // enumerate the set of thread siblings, num entries is num cores
  63. std::unordered_set<std::string> siblings;
  64. for (uint32_t cpu=0; cpu < UINT32_MAX; ++cpu) {
  65. std::ifstream thread_siblings("/sys/devices/system/cpu"
  66. + std::to_string(cpu) + "/topology/thread_siblings");
  67. if (!thread_siblings.is_open()) {
  68. break; // no more cpus
  69. }
  70. std::string line;
  71. if (std::getline(thread_siblings, line)) {
  72. siblings.insert(line);
  73. }
  74. }
  75. if (!siblings.empty()) {
  76. return static_cast<int32_t>(siblings.size());
  77. }
  78. #elif defined(__APPLE__) && defined(__MACH__)
  79. int32_t num_physical_cores;
  80. size_t len = sizeof(num_physical_cores);
  81. int result = sysctlbyname("hw.perflevel0.physicalcpu", &num_physical_cores, &len, NULL, 0);
  82. if (result == 0) {
  83. return num_physical_cores;
  84. }
  85. result = sysctlbyname("hw.physicalcpu", &num_physical_cores, &len, NULL, 0);
  86. if (result == 0) {
  87. return num_physical_cores;
  88. }
  89. #elif defined(_WIN32)
  90. //TODO: Implement
  91. #endif
  92. unsigned int n_threads = std::thread::hardware_concurrency();
  93. return n_threads > 0 ? (n_threads <= 4 ? n_threads : n_threads / 2) : 4;
  94. }
  95. void process_escapes(std::string & input) {
  96. std::size_t input_len = input.length();
  97. std::size_t output_idx = 0;
  98. for (std::size_t input_idx = 0; input_idx < input_len; ++input_idx) {
  99. if (input[input_idx] == '\\' && input_idx + 1 < input_len) {
  100. switch (input[++input_idx]) {
  101. case 'n': input[output_idx++] = '\n'; break;
  102. case 'r': input[output_idx++] = '\r'; break;
  103. case 't': input[output_idx++] = '\t'; break;
  104. case '\'': input[output_idx++] = '\''; break;
  105. case '\"': input[output_idx++] = '\"'; break;
  106. case '\\': input[output_idx++] = '\\'; break;
  107. case 'x':
  108. // Handle \x12, etc
  109. if (input_idx + 2 < input_len) {
  110. const char x[3] = { input[input_idx + 1], input[input_idx + 2], 0 };
  111. char *err_p = nullptr;
  112. const long val = std::strtol(x, &err_p, 16);
  113. if (err_p == x + 2) {
  114. input_idx += 2;
  115. input[output_idx++] = char(val);
  116. break;
  117. }
  118. }
  119. // fall through
  120. default: input[output_idx++] = '\\';
  121. input[output_idx++] = input[input_idx]; break;
  122. }
  123. } else {
  124. input[output_idx++] = input[input_idx];
  125. }
  126. }
  127. input.resize(output_idx);
  128. }
  129. bool gpt_params_parse(int argc, char ** argv, gpt_params & params) {
  130. bool result = true;
  131. try {
  132. if (!gpt_params_parse_ex(argc, argv, params)) {
  133. gpt_print_usage(argc, argv, gpt_params());
  134. exit(0);
  135. }
  136. }
  137. catch (const std::invalid_argument & ex) {
  138. fprintf(stderr, "%s\n", ex.what());
  139. gpt_print_usage(argc, argv, gpt_params());
  140. exit(1);
  141. }
  142. return result;
  143. }
  144. static bool gpt_params_find_arg(int argc, char ** argv, const std::string & arg, gpt_params & params, int & i, bool & invalid_param) {
  145. llama_sampling_params& sparams = params.sparams;
  146. if (arg == "-s" || arg == "--seed") {
  147. if (++i >= argc) {
  148. invalid_param = true;
  149. return true;
  150. }
  151. params.seed = std::stoul(argv[i]);
  152. return true;
  153. }
  154. if (arg == "-t" || arg == "--threads") {
  155. if (++i >= argc) {
  156. invalid_param = true;
  157. return true;
  158. }
  159. params.n_threads = std::stoi(argv[i]);
  160. if (params.n_threads <= 0) {
  161. params.n_threads = std::thread::hardware_concurrency();
  162. }
  163. return true;
  164. }
  165. if (arg == "-tb" || arg == "--threads-batch") {
  166. if (++i >= argc) {
  167. invalid_param = true;
  168. return true;
  169. }
  170. params.n_threads_batch = std::stoi(argv[i]);
  171. if (params.n_threads_batch <= 0) {
  172. params.n_threads_batch = std::thread::hardware_concurrency();
  173. }
  174. return true;
  175. }
  176. if (arg == "-td" || arg == "--threads-draft") {
  177. if (++i >= argc) {
  178. invalid_param = true;
  179. return true;
  180. }
  181. params.n_threads_draft = std::stoi(argv[i]);
  182. if (params.n_threads_draft <= 0) {
  183. params.n_threads_draft = std::thread::hardware_concurrency();
  184. }
  185. return true;
  186. }
  187. if (arg == "-tbd" || arg == "--threads-batch-draft") {
  188. if (++i >= argc) {
  189. invalid_param = true;
  190. return true;
  191. }
  192. params.n_threads_batch_draft = std::stoi(argv[i]);
  193. if (params.n_threads_batch_draft <= 0) {
  194. params.n_threads_batch_draft = std::thread::hardware_concurrency();
  195. }
  196. return true;
  197. }
  198. if (arg == "-p" || arg == "--prompt") {
  199. if (++i >= argc) {
  200. invalid_param = true;
  201. return true;
  202. }
  203. params.prompt = argv[i];
  204. return true;
  205. }
  206. if (arg == "-e" || arg == "--escape") {
  207. params.escape = true;
  208. return true;
  209. }
  210. if (arg == "--prompt-cache") {
  211. if (++i >= argc) {
  212. invalid_param = true;
  213. return true;
  214. }
  215. params.path_prompt_cache = argv[i];
  216. return true;
  217. }
  218. if (arg == "--prompt-cache-all") {
  219. params.prompt_cache_all = true;
  220. return true;
  221. }
  222. if (arg == "--prompt-cache-ro") {
  223. params.prompt_cache_ro = true;
  224. return true;
  225. }
  226. if (arg == "-bf" || arg == "--binary-file") {
  227. if (++i >= argc) {
  228. invalid_param = true;
  229. return true;
  230. }
  231. std::ifstream file(argv[i], std::ios::binary);
  232. if (!file) {
  233. fprintf(stderr, "error: failed to open file '%s'\n", argv[i]);
  234. invalid_param = true;
  235. return true;
  236. }
  237. // store the external file name in params
  238. params.prompt_file = argv[i];
  239. std::ostringstream ss;
  240. ss << file.rdbuf();
  241. params.prompt = ss.str();
  242. fprintf(stderr, "Read %zu bytes from binary file %s\n", params.prompt.size(), argv[i]);
  243. return true;
  244. }
  245. if (arg == "-f" || arg == "--file") {
  246. if (++i >= argc) {
  247. invalid_param = true;
  248. return true;
  249. }
  250. std::ifstream file(argv[i]);
  251. if (!file) {
  252. fprintf(stderr, "error: failed to open file '%s'\n", argv[i]);
  253. invalid_param = true;
  254. return true;
  255. }
  256. // store the external file name in params
  257. params.prompt_file = argv[i];
  258. std::copy(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>(), back_inserter(params.prompt));
  259. if (!params.prompt.empty() && params.prompt.back() == '\n') {
  260. params.prompt.pop_back();
  261. }
  262. return true;
  263. }
  264. if (arg == "-n" || arg == "--n-predict") {
  265. if (++i >= argc) {
  266. invalid_param = true;
  267. return true;
  268. }
  269. params.n_predict = std::stoi(argv[i]);
  270. return true;
  271. }
  272. if (arg == "--top-k") {
  273. if (++i >= argc) {
  274. invalid_param = true;
  275. return true;
  276. }
  277. sparams.top_k = std::stoi(argv[i]);
  278. return true;
  279. }
  280. if (arg == "-c" || arg == "--ctx-size") {
  281. if (++i >= argc) {
  282. invalid_param = true;
  283. return true;
  284. }
  285. params.n_ctx = std::stoi(argv[i]);
  286. return true;
  287. }
  288. if (arg == "--grp-attn-n" || arg == "-gan") {
  289. if (++i >= argc) {
  290. invalid_param = true;
  291. return true;
  292. }
  293. params.grp_attn_n = std::stoi(argv[i]);
  294. return true;
  295. }
  296. if (arg == "--grp-attn-w" || arg == "-gaw") {
  297. if (++i >= argc) {
  298. invalid_param = true;
  299. return true;
  300. }
  301. params.grp_attn_w = std::stoi(argv[i]);
  302. return true;
  303. }
  304. if (arg == "--rope-freq-base") {
  305. if (++i >= argc) {
  306. invalid_param = true;
  307. return true;
  308. }
  309. params.rope_freq_base = std::stof(argv[i]);
  310. return true;
  311. }
  312. if (arg == "--rope-freq-scale") {
  313. if (++i >= argc) {
  314. invalid_param = true;
  315. return true;
  316. }
  317. params.rope_freq_scale = std::stof(argv[i]);
  318. return true;
  319. }
  320. if (arg == "--rope-scaling") {
  321. if (++i >= argc) {
  322. invalid_param = true;
  323. return true;
  324. }
  325. std::string value(argv[i]);
  326. /**/ if (value == "none") { params.rope_scaling_type = LLAMA_ROPE_SCALING_TYPE_NONE; }
  327. else if (value == "linear") { params.rope_scaling_type = LLAMA_ROPE_SCALING_TYPE_LINEAR; }
  328. else if (value == "yarn") { params.rope_scaling_type = LLAMA_ROPE_SCALING_TYPE_YARN; }
  329. else { invalid_param = true; }
  330. return true;
  331. }
  332. if (arg == "--rope-scale") {
  333. if (++i >= argc) {
  334. invalid_param = true;
  335. return true;
  336. }
  337. params.rope_freq_scale = 1.0f / std::stof(argv[i]);
  338. return true;
  339. }
  340. if (arg == "--yarn-orig-ctx") {
  341. if (++i >= argc) {
  342. invalid_param = true;
  343. return true;
  344. }
  345. params.yarn_orig_ctx = std::stoi(argv[i]);
  346. return true;
  347. }
  348. if (arg == "--yarn-ext-factor") {
  349. if (++i >= argc) {
  350. invalid_param = true;
  351. return true;
  352. }
  353. params.yarn_ext_factor = std::stof(argv[i]);
  354. return true;
  355. }
  356. if (arg == "--yarn-attn-factor") {
  357. if (++i >= argc) {
  358. invalid_param = true;
  359. return true;
  360. }
  361. params.yarn_attn_factor = std::stof(argv[i]);
  362. return true;
  363. }
  364. if (arg == "--yarn-beta-fast") {
  365. if (++i >= argc) {
  366. invalid_param = true;
  367. return true;
  368. }
  369. params.yarn_beta_fast = std::stof(argv[i]);
  370. return true;
  371. }
  372. if (arg == "--yarn-beta-slow") {
  373. if (++i >= argc) {
  374. invalid_param = true;
  375. return true;
  376. }
  377. params.yarn_beta_slow = std::stof(argv[i]);
  378. return true;
  379. }
  380. if (arg == "--pooling") {
  381. if (++i >= argc) {
  382. invalid_param = true;
  383. return true;
  384. }
  385. std::string value(argv[i]);
  386. /**/ if (value == "none") { params.pooling_type = LLAMA_POOLING_TYPE_NONE; }
  387. else if (value == "mean") { params.pooling_type = LLAMA_POOLING_TYPE_MEAN; }
  388. else if (value == "cls") { params.pooling_type = LLAMA_POOLING_TYPE_CLS; }
  389. else { invalid_param = true; }
  390. return true;
  391. }
  392. if (arg == "--defrag-thold" || arg == "-dt") {
  393. if (++i >= argc) {
  394. invalid_param = true;
  395. return true;
  396. }
  397. params.defrag_thold = std::stof(argv[i]);
  398. return true;
  399. }
  400. if (arg == "--samplers") {
  401. if (++i >= argc) {
  402. invalid_param = true;
  403. return true;
  404. }
  405. const auto sampler_names = string_split(argv[i], ';');
  406. sparams.samplers_sequence = sampler_types_from_names(sampler_names, true);
  407. return true;
  408. }
  409. if (arg == "--sampling-seq") {
  410. if (++i >= argc) {
  411. invalid_param = true;
  412. return true;
  413. }
  414. sparams.samplers_sequence = sampler_types_from_chars(argv[i]);
  415. return true;
  416. }
  417. if (arg == "--top-p") {
  418. if (++i >= argc) {
  419. invalid_param = true;
  420. return true;
  421. }
  422. sparams.top_p = std::stof(argv[i]);
  423. return true;
  424. }
  425. if (arg == "--min-p") {
  426. if (++i >= argc) {
  427. invalid_param = true;
  428. return true;
  429. }
  430. sparams.min_p = std::stof(argv[i]);
  431. return true;
  432. }
  433. if (arg == "--temp") {
  434. if (++i >= argc) {
  435. invalid_param = true;
  436. return true;
  437. }
  438. sparams.temp = std::stof(argv[i]);
  439. sparams.temp = std::max(sparams.temp, 0.0f);
  440. return true;
  441. }
  442. if (arg == "--tfs") {
  443. if (++i >= argc) {
  444. invalid_param = true;
  445. return true;
  446. }
  447. sparams.tfs_z = std::stof(argv[i]);
  448. return true;
  449. }
  450. if (arg == "--typical") {
  451. if (++i >= argc) {
  452. invalid_param = true;
  453. return true;
  454. }
  455. sparams.typical_p = std::stof(argv[i]);
  456. return true;
  457. }
  458. if (arg == "--repeat-last-n") {
  459. if (++i >= argc) {
  460. invalid_param = true;
  461. return true;
  462. }
  463. sparams.penalty_last_n = std::stoi(argv[i]);
  464. sparams.n_prev = std::max(sparams.n_prev, sparams.penalty_last_n);
  465. return true;
  466. }
  467. if (arg == "--repeat-penalty") {
  468. if (++i >= argc) {
  469. invalid_param = true;
  470. return true;
  471. }
  472. sparams.penalty_repeat = std::stof(argv[i]);
  473. return true;
  474. }
  475. if (arg == "--frequency-penalty") {
  476. if (++i >= argc) {
  477. invalid_param = true;
  478. return true;
  479. }
  480. sparams.penalty_freq = std::stof(argv[i]);
  481. return true;
  482. }
  483. if (arg == "--presence-penalty") {
  484. if (++i >= argc) {
  485. invalid_param = true;
  486. return true;
  487. }
  488. sparams.penalty_present = std::stof(argv[i]);
  489. return true;
  490. }
  491. if (arg == "--dynatemp-range") {
  492. if (++i >= argc) {
  493. invalid_param = true;
  494. return true;
  495. }
  496. sparams.dynatemp_range = std::stof(argv[i]);
  497. return true;
  498. }
  499. if (arg == "--dynatemp-exp") {
  500. if (++i >= argc) {
  501. invalid_param = true;
  502. return true;
  503. }
  504. sparams.dynatemp_exponent = std::stof(argv[i]);
  505. return true;
  506. }
  507. if (arg == "--mirostat") {
  508. if (++i >= argc) {
  509. invalid_param = true;
  510. return true;
  511. }
  512. sparams.mirostat = std::stoi(argv[i]);
  513. return true;
  514. }
  515. if (arg == "--mirostat-lr") {
  516. if (++i >= argc) {
  517. invalid_param = true;
  518. return true;
  519. }
  520. sparams.mirostat_eta = std::stof(argv[i]);
  521. return true;
  522. }
  523. if (arg == "--mirostat-ent") {
  524. if (++i >= argc) {
  525. invalid_param = true;
  526. return true;
  527. }
  528. sparams.mirostat_tau = std::stof(argv[i]);
  529. return true;
  530. }
  531. if (arg == "--cfg-negative-prompt") {
  532. if (++i >= argc) {
  533. invalid_param = true;
  534. return true;
  535. }
  536. sparams.cfg_negative_prompt = argv[i];
  537. return true;
  538. }
  539. if (arg == "--cfg-negative-prompt-file") {
  540. if (++i >= argc) {
  541. invalid_param = true;
  542. return true;
  543. }
  544. std::ifstream file(argv[i]);
  545. if (!file) {
  546. fprintf(stderr, "error: failed to open file '%s'\n", argv[i]);
  547. invalid_param = true;
  548. return true;
  549. }
  550. std::copy(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>(), back_inserter(sparams.cfg_negative_prompt));
  551. if (!sparams.cfg_negative_prompt.empty() && sparams.cfg_negative_prompt.back() == '\n') {
  552. sparams.cfg_negative_prompt.pop_back();
  553. }
  554. return true;
  555. }
  556. if (arg == "--cfg-scale") {
  557. if (++i >= argc) {
  558. invalid_param = true;
  559. return true;
  560. }
  561. sparams.cfg_scale = std::stof(argv[i]);
  562. return true;
  563. }
  564. if (arg == "-b" || arg == "--batch-size") {
  565. if (++i >= argc) {
  566. invalid_param = true;
  567. return true;
  568. }
  569. params.n_batch = std::stoi(argv[i]);
  570. return true;
  571. }
  572. if (arg == "-ub" || arg == "--ubatch-size") {
  573. if (++i >= argc) {
  574. invalid_param = true;
  575. return true;
  576. }
  577. params.n_ubatch = std::stoi(argv[i]);
  578. return true;
  579. }
  580. if (arg == "--keep") {
  581. if (++i >= argc) {
  582. invalid_param = true;
  583. return true;
  584. }
  585. params.n_keep = std::stoi(argv[i]);
  586. return true;
  587. }
  588. if (arg == "--draft") {
  589. if (++i >= argc) {
  590. invalid_param = true;
  591. return true;
  592. }
  593. params.n_draft = std::stoi(argv[i]);
  594. return true;
  595. }
  596. if (arg == "--chunks") {
  597. if (++i >= argc) {
  598. invalid_param = true;
  599. return true;
  600. }
  601. params.n_chunks = std::stoi(argv[i]);
  602. return true;
  603. }
  604. if (arg == "-np" || arg == "--parallel") {
  605. if (++i >= argc) {
  606. invalid_param = true;
  607. return true;
  608. }
  609. params.n_parallel = std::stoi(argv[i]);
  610. return true;
  611. }
  612. if (arg == "-ns" || arg == "--sequences") {
  613. if (++i >= argc) {
  614. invalid_param = true;
  615. return true;
  616. }
  617. params.n_sequences = std::stoi(argv[i]);
  618. return true;
  619. }
  620. if (arg == "--p-split" || arg == "-ps") {
  621. if (++i >= argc) {
  622. invalid_param = true;
  623. return true;
  624. }
  625. params.p_split = std::stof(argv[i]);
  626. return true;
  627. }
  628. if (arg == "-m" || arg == "--model") {
  629. if (++i >= argc) {
  630. invalid_param = true;
  631. return true;
  632. }
  633. params.model = argv[i];
  634. return true;
  635. }
  636. if (arg == "-mu" || arg == "--model-url") {
  637. if (++i >= argc) {
  638. invalid_param = true;
  639. return true;
  640. }
  641. params.model_url = argv[i];
  642. return true;
  643. }
  644. if (arg == "-md" || arg == "--model-draft") {
  645. if (++i >= argc) {
  646. invalid_param = true;
  647. return true;
  648. }
  649. params.model_draft = argv[i];
  650. return true;
  651. }
  652. if (arg == "-a" || arg == "--alias") {
  653. if (++i >= argc) {
  654. invalid_param = true;
  655. return true;
  656. }
  657. params.model_alias = argv[i];
  658. return true;
  659. }
  660. if (arg == "--lora") {
  661. if (++i >= argc) {
  662. invalid_param = true;
  663. return true;
  664. }
  665. params.lora_adapter.emplace_back(argv[i], 1.0f);
  666. params.use_mmap = false;
  667. return true;
  668. }
  669. if (arg == "--lora-scaled") {
  670. if (++i >= argc) {
  671. invalid_param = true;
  672. return true;
  673. }
  674. const char* lora_adapter = argv[i];
  675. if (++i >= argc) {
  676. invalid_param = true;
  677. return true;
  678. }
  679. params.lora_adapter.emplace_back(lora_adapter, std::stof(argv[i]));
  680. params.use_mmap = false;
  681. return true;
  682. }
  683. if (arg == "--lora-base") {
  684. if (++i >= argc) {
  685. invalid_param = true;
  686. return true;
  687. }
  688. params.lora_base = argv[i];
  689. return true;
  690. }
  691. if (arg == "--control-vector") {
  692. if (++i >= argc) {
  693. invalid_param = true;
  694. return true;
  695. }
  696. params.control_vectors.push_back({ 1.0f, argv[i], });
  697. return true;
  698. }
  699. if (arg == "--control-vector-scaled") {
  700. if (++i >= argc) {
  701. invalid_param = true;
  702. return true;
  703. }
  704. const char* fname = argv[i];
  705. if (++i >= argc) {
  706. invalid_param = true;
  707. return true;
  708. }
  709. params.control_vectors.push_back({ std::stof(argv[i]), fname, });
  710. return true;
  711. }
  712. if (arg == "--control-vector-layer-range") {
  713. if (++i >= argc) {
  714. invalid_param = true;
  715. return true;
  716. }
  717. params.control_vector_layer_start = std::stoi(argv[i]);
  718. if (++i >= argc) {
  719. invalid_param = true;
  720. return true;
  721. }
  722. params.control_vector_layer_end = std::stoi(argv[i]);
  723. return true;
  724. }
  725. if (arg == "--mmproj") {
  726. if (++i >= argc) {
  727. invalid_param = true;
  728. return true;
  729. }
  730. params.mmproj = argv[i];
  731. return true;
  732. }
  733. if (arg == "--image") {
  734. if (++i >= argc) {
  735. invalid_param = true;
  736. return true;
  737. }
  738. params.image = argv[i];
  739. return true;
  740. }
  741. if (arg == "-i" || arg == "--interactive") {
  742. params.interactive = true;
  743. return true;
  744. }
  745. if (arg == "--embedding") {
  746. params.embedding = true;
  747. return true;
  748. }
  749. if (arg == "--interactive-first") {
  750. params.interactive_first = true;
  751. return true;
  752. }
  753. if (arg == "-ins" || arg == "--instruct") {
  754. params.instruct = true;
  755. return true;
  756. }
  757. if (arg == "-cml" || arg == "--chatml") {
  758. params.chatml = true;
  759. return true;
  760. }
  761. if (arg == "--infill") {
  762. params.infill = true;
  763. return true;
  764. }
  765. if (arg == "-dkvc" || arg == "--dump-kv-cache") {
  766. params.dump_kv_cache = true;
  767. return true;
  768. }
  769. if (arg == "-nkvo" || arg == "--no-kv-offload") {
  770. params.no_kv_offload = true;
  771. return true;
  772. }
  773. if (arg == "-ctk" || arg == "--cache-type-k") {
  774. params.cache_type_k = argv[++i];
  775. return true;
  776. }
  777. if (arg == "-ctv" || arg == "--cache-type-v") {
  778. params.cache_type_v = argv[++i];
  779. return true;
  780. }
  781. if (arg == "--multiline-input") {
  782. params.multiline_input = true;
  783. return true;
  784. }
  785. if (arg == "--simple-io") {
  786. params.simple_io = true;
  787. return true;
  788. }
  789. if (arg == "-cb" || arg == "--cont-batching") {
  790. params.cont_batching = true;
  791. return true;
  792. }
  793. if (arg == "--color") {
  794. params.use_color = true;
  795. return true;
  796. }
  797. if (arg == "--mlock") {
  798. params.use_mlock = true;
  799. return true;
  800. }
  801. if (arg == "--gpu-layers" || arg == "-ngl" || arg == "--n-gpu-layers") {
  802. if (++i >= argc) {
  803. invalid_param = true;
  804. return true;
  805. }
  806. params.n_gpu_layers = std::stoi(argv[i]);
  807. if (!llama_supports_gpu_offload()) {
  808. fprintf(stderr, "warning: not compiled with GPU offload support, --n-gpu-layers option will be ignored\n");
  809. fprintf(stderr, "warning: see main README.md for information on enabling GPU BLAS support\n");
  810. }
  811. return true;
  812. }
  813. if (arg == "--gpu-layers-draft" || arg == "-ngld" || arg == "--n-gpu-layers-draft") {
  814. if (++i >= argc) {
  815. invalid_param = true;
  816. return true;
  817. }
  818. params.n_gpu_layers_draft = std::stoi(argv[i]);
  819. if (!llama_supports_gpu_offload()) {
  820. fprintf(stderr, "warning: not compiled with GPU offload support, --n-gpu-layers-draft option will be ignored\n");
  821. fprintf(stderr, "warning: see main README.md for information on enabling GPU BLAS support\n");
  822. }
  823. return true;
  824. }
  825. if (arg == "--main-gpu" || arg == "-mg") {
  826. if (++i >= argc) {
  827. invalid_param = true;
  828. return true;
  829. }
  830. params.main_gpu = std::stoi(argv[i]);
  831. #ifndef GGML_USE_CUBLAS_SYCL
  832. fprintf(stderr, "warning: llama.cpp was compiled without cuBLAS/SYCL. Setting the main GPU has no effect.\n");
  833. #endif // GGML_USE_CUBLAS_SYCL
  834. return true;
  835. }
  836. if (arg == "--split-mode" || arg == "-sm") {
  837. if (++i >= argc) {
  838. invalid_param = true;
  839. return true;
  840. }
  841. std::string arg_next = argv[i];
  842. if (arg_next == "none") {
  843. params.split_mode = LLAMA_SPLIT_MODE_NONE;
  844. }
  845. else if (arg_next == "layer") {
  846. params.split_mode = LLAMA_SPLIT_MODE_LAYER;
  847. }
  848. else if (arg_next == "row") {
  849. #ifdef GGML_USE_SYCL
  850. fprintf(stderr, "warning: The split mode value:[row] is not supported by llama.cpp with SYCL. It's developing.\nExit!\n");
  851. exit(1);
  852. #endif // GGML_USE_SYCL
  853. params.split_mode = LLAMA_SPLIT_MODE_ROW;
  854. }
  855. else {
  856. invalid_param = true;
  857. return true;
  858. }
  859. #ifndef GGML_USE_CUBLAS_SYCL
  860. fprintf(stderr, "warning: llama.cpp was compiled without cuBLAS/SYCL. Setting the split mode has no effect.\n");
  861. #endif // GGML_USE_CUBLAS_SYCL
  862. return true;
  863. }
  864. if (arg == "--tensor-split" || arg == "-ts") {
  865. if (++i >= argc) {
  866. invalid_param = true;
  867. return true;
  868. }
  869. std::string arg_next = argv[i];
  870. // split string by , and /
  871. const std::regex regex{ R"([,/]+)" };
  872. std::sregex_token_iterator it{ arg_next.begin(), arg_next.end(), regex, -1 };
  873. std::vector<std::string> split_arg{ it, {} };
  874. if (split_arg.size() >= llama_max_devices()) {
  875. invalid_param = true;
  876. return true;
  877. }
  878. for (size_t i = 0; i < llama_max_devices(); ++i) {
  879. if (i < split_arg.size()) {
  880. params.tensor_split[i] = std::stof(split_arg[i]);
  881. }
  882. else {
  883. params.tensor_split[i] = 0.0f;
  884. }
  885. }
  886. #ifndef GGML_USE_CUBLAS_SYCL_VULKAN
  887. fprintf(stderr, "warning: llama.cpp was compiled without cuBLAS/SYCL/Vulkan. Setting a tensor split has no effect.\n");
  888. #endif // GGML_USE_CUBLAS_SYCL
  889. return true;
  890. }
  891. if (arg == "--no-mmap") {
  892. params.use_mmap = false;
  893. return true;
  894. }
  895. if (arg == "--numa") {
  896. if (++i >= argc) {
  897. invalid_param = true;
  898. return true;
  899. }
  900. std::string value(argv[i]);
  901. /**/ if (value == "distribute" || value == "") { params.numa = GGML_NUMA_STRATEGY_DISTRIBUTE; }
  902. else if (value == "isolate") { params.numa = GGML_NUMA_STRATEGY_ISOLATE; }
  903. else if (value == "numactl") { params.numa = GGML_NUMA_STRATEGY_NUMACTL; }
  904. else { invalid_param = true; }
  905. return true;
  906. }
  907. if (arg == "--verbose-prompt") {
  908. params.verbose_prompt = true;
  909. return true;
  910. }
  911. if (arg == "--no-display-prompt") {
  912. params.display_prompt = false;
  913. return true;
  914. }
  915. if (arg == "-r" || arg == "--reverse-prompt") {
  916. if (++i >= argc) {
  917. invalid_param = true;
  918. return true;
  919. }
  920. params.antiprompt.emplace_back(argv[i]);
  921. return true;
  922. }
  923. if (arg == "-ld" || arg == "--logdir") {
  924. if (++i >= argc) {
  925. invalid_param = true;
  926. return true;
  927. }
  928. params.logdir = argv[i];
  929. if (params.logdir.back() != DIRECTORY_SEPARATOR) {
  930. params.logdir += DIRECTORY_SEPARATOR;
  931. }
  932. return true;
  933. }
  934. if (arg == "--save-all-logits" || arg == "--kl-divergence-base") {
  935. if (++i >= argc) {
  936. invalid_param = true;
  937. return true;
  938. }
  939. params.logits_file = argv[i];
  940. return true;
  941. }
  942. if (arg == "--perplexity" || arg == "--all-logits") {
  943. params.logits_all = true;
  944. return true;
  945. }
  946. if (arg == "--ppl-stride") {
  947. if (++i >= argc) {
  948. invalid_param = true;
  949. return true;
  950. }
  951. params.ppl_stride = std::stoi(argv[i]);
  952. return true;
  953. }
  954. if (arg == "-ptc" || arg == "--print-token-count") {
  955. if (++i >= argc) {
  956. invalid_param = true;
  957. return true;
  958. }
  959. params.n_print = std::stoi(argv[i]);
  960. return true;
  961. }
  962. if (arg == "--ppl-output-type") {
  963. if (++i >= argc) {
  964. invalid_param = true;
  965. return true;
  966. }
  967. params.ppl_output_type = std::stoi(argv[i]);
  968. return true;
  969. }
  970. if (arg == "--hellaswag") {
  971. params.hellaswag = true;
  972. return true;
  973. }
  974. if (arg == "--hellaswag-tasks") {
  975. if (++i >= argc) {
  976. invalid_param = true;
  977. return true;
  978. }
  979. params.hellaswag_tasks = std::stoi(argv[i]);
  980. return true;
  981. }
  982. if (arg == "--winogrande") {
  983. params.winogrande = true;
  984. return true;
  985. }
  986. if (arg == "--winogrande-tasks") {
  987. if (++i >= argc) {
  988. invalid_param = true;
  989. return true;
  990. }
  991. params.winogrande_tasks = std::stoi(argv[i]);
  992. return true;
  993. }
  994. if (arg == "--multiple-choice") {
  995. params.multiple_choice = true;
  996. return true;
  997. }
  998. if (arg == "--multiple-choice-tasks") {
  999. if (++i >= argc) {
  1000. invalid_param = true;
  1001. return true;
  1002. }
  1003. params.multiple_choice_tasks = std::stoi(argv[i]);
  1004. return true;
  1005. }
  1006. if (arg == "--kl-divergence") {
  1007. params.kl_divergence = true;
  1008. return true;
  1009. }
  1010. if (arg == "--ignore-eos") {
  1011. params.ignore_eos = true;
  1012. return true;
  1013. }
  1014. if (arg == "--no-penalize-nl") {
  1015. sparams.penalize_nl = false;
  1016. return true;
  1017. }
  1018. if (arg == "-l" || arg == "--logit-bias") {
  1019. if (++i >= argc) {
  1020. invalid_param = true;
  1021. return true;
  1022. }
  1023. std::stringstream ss(argv[i]);
  1024. llama_token key;
  1025. char sign;
  1026. std::string value_str;
  1027. try {
  1028. if (ss >> key && ss >> sign && std::getline(ss, value_str) && (sign == '+' || sign == '-')) {
  1029. sparams.logit_bias[key] = std::stof(value_str) * ((sign == '-') ? -1.0f : 1.0f);
  1030. }
  1031. else {
  1032. throw std::exception();
  1033. }
  1034. }
  1035. catch (const std::exception&) {
  1036. invalid_param = true;
  1037. return true;
  1038. }
  1039. return true;
  1040. }
  1041. if (arg == "-h" || arg == "--help") {
  1042. gpt_print_usage(argc, argv, gpt_params());
  1043. exit(0);
  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, arg, 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 == "iq4_nl") {
  1548. return GGML_TYPE_IQ4_NL;
  1549. }
  1550. if (s == "q5_0") {
  1551. return GGML_TYPE_Q5_0;
  1552. }
  1553. if (s == "q5_1") {
  1554. return GGML_TYPE_Q5_1;
  1555. }
  1556. throw std::runtime_error("Invalid cache type: " + s);
  1557. }
  1558. struct llama_context_params llama_context_params_from_gpt_params(const gpt_params & params) {
  1559. auto cparams = llama_context_default_params();
  1560. cparams.n_ctx = params.n_ctx;
  1561. cparams.n_seq_max = params.n_parallel;
  1562. cparams.n_batch = params.n_batch;
  1563. cparams.n_ubatch = params.n_ubatch;
  1564. cparams.n_threads = params.n_threads;
  1565. cparams.n_threads_batch = params.n_threads_batch == -1 ? params.n_threads : params.n_threads_batch;
  1566. cparams.seed = params.seed;
  1567. cparams.logits_all = params.logits_all;
  1568. cparams.embeddings = params.embedding;
  1569. cparams.rope_scaling_type = params.rope_scaling_type;
  1570. cparams.rope_freq_base = params.rope_freq_base;
  1571. cparams.rope_freq_scale = params.rope_freq_scale;
  1572. cparams.yarn_ext_factor = params.yarn_ext_factor;
  1573. cparams.yarn_attn_factor = params.yarn_attn_factor;
  1574. cparams.yarn_beta_fast = params.yarn_beta_fast;
  1575. cparams.yarn_beta_slow = params.yarn_beta_slow;
  1576. cparams.yarn_orig_ctx = params.yarn_orig_ctx;
  1577. cparams.pooling_type = params.pooling_type;
  1578. cparams.defrag_thold = params.defrag_thold;
  1579. cparams.offload_kqv = !params.no_kv_offload;
  1580. cparams.type_k = kv_cache_type_from_str(params.cache_type_k);
  1581. cparams.type_v = kv_cache_type_from_str(params.cache_type_v);
  1582. return cparams;
  1583. }
  1584. void llama_batch_clear(struct llama_batch & batch) {
  1585. batch.n_tokens = 0;
  1586. }
  1587. void llama_batch_add(
  1588. struct llama_batch & batch,
  1589. llama_token id,
  1590. llama_pos pos,
  1591. const std::vector<llama_seq_id> & seq_ids,
  1592. bool logits) {
  1593. batch.token [batch.n_tokens] = id;
  1594. batch.pos [batch.n_tokens] = pos;
  1595. batch.n_seq_id[batch.n_tokens] = seq_ids.size();
  1596. for (size_t i = 0; i < seq_ids.size(); ++i) {
  1597. batch.seq_id[batch.n_tokens][i] = seq_ids[i];
  1598. }
  1599. batch.logits [batch.n_tokens] = logits;
  1600. batch.n_tokens++;
  1601. }
  1602. #ifdef LLAMA_USE_CURL
  1603. struct llama_model * llama_load_model_from_url(const char * model_url, const char * path_model,
  1604. struct llama_model_params params) {
  1605. // Basic validation of the model_url
  1606. if (!model_url || strlen(model_url) == 0) {
  1607. fprintf(stderr, "%s: invalid model_url\n", __func__);
  1608. return NULL;
  1609. }
  1610. // Initialize libcurl globally
  1611. auto curl = curl_easy_init();
  1612. if (!curl) {
  1613. fprintf(stderr, "%s: error initializing libcurl\n", __func__);
  1614. return NULL;
  1615. }
  1616. // Set the URL, allow to follow http redirection
  1617. curl_easy_setopt(curl, CURLOPT_URL, model_url);
  1618. curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
  1619. #if defined(_WIN32)
  1620. // CURLSSLOPT_NATIVE_CA tells libcurl to use standard certificate store of
  1621. // operating system. Currently implemented under MS-Windows.
  1622. curl_easy_setopt(curl, CURLOPT_SSL_OPTIONS, CURLSSLOPT_NATIVE_CA);
  1623. #endif
  1624. // Check if the file already exists locally
  1625. struct stat model_file_info;
  1626. auto file_exists = (stat(path_model, &model_file_info) == 0);
  1627. // If the file exists, check for ${path_model}.etag or ${path_model}.lastModified files
  1628. char etag[LLAMA_CURL_MAX_HEADER_LENGTH] = {0};
  1629. char etag_path[LLAMA_CURL_MAX_PATH_LENGTH] = {0};
  1630. snprintf(etag_path, sizeof(etag_path), "%s.etag", path_model);
  1631. char last_modified[LLAMA_CURL_MAX_HEADER_LENGTH] = {0};
  1632. char last_modified_path[LLAMA_CURL_MAX_PATH_LENGTH] = {0};
  1633. snprintf(last_modified_path, sizeof(last_modified_path), "%s.lastModified", path_model);
  1634. if (file_exists) {
  1635. auto * f_etag = fopen(etag_path, "r");
  1636. if (f_etag) {
  1637. if (!fgets(etag, sizeof(etag), f_etag)) {
  1638. fprintf(stderr, "%s: unable to read file %s\n", __func__, etag_path);
  1639. } else {
  1640. fprintf(stderr, "%s: previous model file found %s: %s\n", __func__, etag_path, etag);
  1641. }
  1642. fclose(f_etag);
  1643. }
  1644. auto * f_last_modified = fopen(last_modified_path, "r");
  1645. if (f_last_modified) {
  1646. if (!fgets(last_modified, sizeof(last_modified), f_last_modified)) {
  1647. fprintf(stderr, "%s: unable to read file %s\n", __func__, last_modified_path);
  1648. } else {
  1649. fprintf(stderr, "%s: previous model file found %s: %s\n", __func__, last_modified_path,
  1650. last_modified);
  1651. }
  1652. fclose(f_last_modified);
  1653. }
  1654. }
  1655. // Send a HEAD request to retrieve the etag and last-modified headers
  1656. struct llama_load_model_from_url_headers {
  1657. char etag[LLAMA_CURL_MAX_HEADER_LENGTH] = {0};
  1658. char last_modified[LLAMA_CURL_MAX_HEADER_LENGTH] = {0};
  1659. };
  1660. llama_load_model_from_url_headers headers;
  1661. {
  1662. typedef size_t(*CURLOPT_HEADERFUNCTION_PTR)(char *, size_t, size_t, void *);
  1663. auto header_callback = [](char * buffer, size_t /*size*/, size_t n_items, void * userdata) -> size_t {
  1664. llama_load_model_from_url_headers *headers = (llama_load_model_from_url_headers *) userdata;
  1665. const char * etag_prefix = "etag: ";
  1666. if (strncmp(buffer, etag_prefix, strlen(etag_prefix)) == 0) {
  1667. strncpy(headers->etag, buffer + strlen(etag_prefix), n_items - strlen(etag_prefix) - 2); // Remove CRLF
  1668. }
  1669. const char * last_modified_prefix = "last-modified: ";
  1670. if (strncmp(buffer, last_modified_prefix, strlen(last_modified_prefix)) == 0) {
  1671. strncpy(headers->last_modified, buffer + strlen(last_modified_prefix),
  1672. n_items - strlen(last_modified_prefix) - 2); // Remove CRLF
  1673. }
  1674. return n_items;
  1675. };
  1676. curl_easy_setopt(curl, CURLOPT_NOBODY, 1L); // will trigger the HEAD verb
  1677. curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 1L); // hide head request progress
  1678. curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, static_cast<CURLOPT_HEADERFUNCTION_PTR>(header_callback));
  1679. curl_easy_setopt(curl, CURLOPT_HEADERDATA, &headers);
  1680. CURLcode res = curl_easy_perform(curl);
  1681. if (res != CURLE_OK) {
  1682. curl_easy_cleanup(curl);
  1683. fprintf(stderr, "%s: curl_easy_perform() failed: %s\n", __func__, curl_easy_strerror(res));
  1684. return NULL;
  1685. }
  1686. long http_code = 0;
  1687. curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code);
  1688. if (http_code != 200) {
  1689. // HEAD not supported, we don't know if the file has changed
  1690. // force trigger downloading
  1691. file_exists = false;
  1692. fprintf(stderr, "%s: HEAD invalid http status code received: %ld\n", __func__, http_code);
  1693. }
  1694. }
  1695. // If the ETag or the Last-Modified headers are different: trigger a new download
  1696. if (!file_exists || strcmp(etag, headers.etag) != 0 || strcmp(last_modified, headers.last_modified) != 0) {
  1697. char path_model_temporary[LLAMA_CURL_MAX_PATH_LENGTH] = {0};
  1698. snprintf(path_model_temporary, sizeof(path_model_temporary), "%s.downloadInProgress", path_model);
  1699. if (file_exists) {
  1700. fprintf(stderr, "%s: deleting previous downloaded model file: %s\n", __func__, path_model);
  1701. if (remove(path_model) != 0) {
  1702. curl_easy_cleanup(curl);
  1703. fprintf(stderr, "%s: unable to delete file: %s\n", __func__, path_model);
  1704. return NULL;
  1705. }
  1706. }
  1707. // Set the output file
  1708. auto * outfile = fopen(path_model_temporary, "wb");
  1709. if (!outfile) {
  1710. curl_easy_cleanup(curl);
  1711. fprintf(stderr, "%s: error opening local file for writing: %s\n", __func__, path_model);
  1712. return NULL;
  1713. }
  1714. typedef size_t(*CURLOPT_WRITEFUNCTION_PTR)(void * data, size_t size, size_t nmemb, void * fd);
  1715. auto write_callback = [](void * data, size_t size, size_t nmemb, void * fd) -> size_t {
  1716. return fwrite(data, size, nmemb, (FILE *)fd);
  1717. };
  1718. curl_easy_setopt(curl, CURLOPT_NOBODY, 0L);
  1719. curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, static_cast<CURLOPT_WRITEFUNCTION_PTR>(write_callback));
  1720. curl_easy_setopt(curl, CURLOPT_WRITEDATA, outfile);
  1721. // display download progress
  1722. curl_easy_setopt(curl, CURLOPT_NOPROGRESS, 0L);
  1723. // start the download
  1724. fprintf(stderr, "%s: downloading model from %s to %s (server_etag:%s, server_last_modified:%s)...\n", __func__,
  1725. model_url, path_model, headers.etag, headers.last_modified);
  1726. auto res = curl_easy_perform(curl);
  1727. if (res != CURLE_OK) {
  1728. fclose(outfile);
  1729. curl_easy_cleanup(curl);
  1730. fprintf(stderr, "%s: curl_easy_perform() failed: %s\n", __func__, curl_easy_strerror(res));
  1731. return NULL;
  1732. }
  1733. long http_code = 0;
  1734. curl_easy_getinfo (curl, CURLINFO_RESPONSE_CODE, &http_code);
  1735. if (http_code < 200 || http_code >= 400) {
  1736. fclose(outfile);
  1737. curl_easy_cleanup(curl);
  1738. fprintf(stderr, "%s: invalid http status code received: %ld\n", __func__, http_code);
  1739. return NULL;
  1740. }
  1741. // Clean up
  1742. fclose(outfile);
  1743. // Write the new ETag to the .etag file
  1744. if (strlen(headers.etag) > 0) {
  1745. auto * etag_file = fopen(etag_path, "w");
  1746. if (etag_file) {
  1747. fputs(headers.etag, etag_file);
  1748. fclose(etag_file);
  1749. fprintf(stderr, "%s: model etag saved %s: %s\n", __func__, etag_path, headers.etag);
  1750. }
  1751. }
  1752. // Write the new lastModified to the .etag file
  1753. if (strlen(headers.last_modified) > 0) {
  1754. auto * last_modified_file = fopen(last_modified_path, "w");
  1755. if (last_modified_file) {
  1756. fputs(headers.last_modified, last_modified_file);
  1757. fclose(last_modified_file);
  1758. fprintf(stderr, "%s: model last modified saved %s: %s\n", __func__, last_modified_path,
  1759. headers.last_modified);
  1760. }
  1761. }
  1762. if (rename(path_model_temporary, path_model) != 0) {
  1763. curl_easy_cleanup(curl);
  1764. fprintf(stderr, "%s: unable to rename file: %s to %s\n", __func__, path_model_temporary, path_model);
  1765. return NULL;
  1766. }
  1767. }
  1768. curl_easy_cleanup(curl);
  1769. return llama_load_model_from_file(path_model, params);
  1770. }
  1771. #else
  1772. struct llama_model * llama_load_model_from_url(const char * /*model_url*/, const char * /*path_model*/,
  1773. struct llama_model_params /*params*/) {
  1774. fprintf(stderr, "%s: llama.cpp built without libcurl, downloading from an url not supported.\n", __func__);
  1775. return nullptr;
  1776. }
  1777. #endif // LLAMA_USE_CURL
  1778. std::tuple<struct llama_model *, struct llama_context *> llama_init_from_gpt_params(gpt_params & params) {
  1779. auto mparams = llama_model_params_from_gpt_params(params);
  1780. llama_model * model = nullptr;
  1781. if (!params.model_url.empty()) {
  1782. model = llama_load_model_from_url(params.model_url.c_str(), params.model.c_str(), mparams);
  1783. } else {
  1784. model = llama_load_model_from_file(params.model.c_str(), mparams);
  1785. }
  1786. if (model == NULL) {
  1787. fprintf(stderr, "%s: error: failed to load model '%s'\n", __func__, params.model.c_str());
  1788. return std::make_tuple(nullptr, nullptr);
  1789. }
  1790. auto cparams = llama_context_params_from_gpt_params(params);
  1791. llama_context * lctx = llama_new_context_with_model(model, cparams);
  1792. if (lctx == NULL) {
  1793. fprintf(stderr, "%s: error: failed to create context with model '%s'\n", __func__, params.model.c_str());
  1794. llama_free_model(model);
  1795. return std::make_tuple(nullptr, nullptr);
  1796. }
  1797. if (!params.control_vectors.empty()) {
  1798. if (params.control_vector_layer_start <= 0) params.control_vector_layer_start = 1;
  1799. if (params.control_vector_layer_end <= 0) params.control_vector_layer_end = llama_n_layer(model);
  1800. const auto cvec = llama_control_vector_load(params.control_vectors);
  1801. if (cvec.n_embd == -1) {
  1802. llama_free(lctx);
  1803. llama_free_model(model);
  1804. return std::make_tuple(nullptr, nullptr);
  1805. }
  1806. int err = llama_control_vector_apply(lctx,
  1807. cvec.data.data(),
  1808. cvec.data.size(),
  1809. cvec.n_embd,
  1810. params.control_vector_layer_start,
  1811. params.control_vector_layer_end);
  1812. if (err) {
  1813. llama_free(lctx);
  1814. llama_free_model(model);
  1815. return std::make_tuple(nullptr, nullptr);
  1816. }
  1817. }
  1818. for (unsigned int i = 0; i < params.lora_adapter.size(); ++i) {
  1819. const std::string& lora_adapter = std::get<0>(params.lora_adapter[i]);
  1820. float lora_scale = std::get<1>(params.lora_adapter[i]);
  1821. int err = llama_model_apply_lora_from_file(model,
  1822. lora_adapter.c_str(),
  1823. lora_scale,
  1824. ((i > 0) || params.lora_base.empty())
  1825. ? NULL
  1826. : params.lora_base.c_str(),
  1827. params.n_threads);
  1828. if (err != 0) {
  1829. fprintf(stderr, "%s: error: failed to apply lora adapter\n", __func__);
  1830. llama_free(lctx);
  1831. llama_free_model(model);
  1832. return std::make_tuple(nullptr, nullptr);
  1833. }
  1834. }
  1835. if (params.ignore_eos) {
  1836. params.sparams.logit_bias[llama_token_eos(model)] = -INFINITY;
  1837. }
  1838. {
  1839. LOG("warming up the model with an empty run\n");
  1840. std::vector<llama_token> tmp = { llama_token_bos(model), llama_token_eos(model), };
  1841. llama_decode(lctx, llama_batch_get_one(tmp.data(), std::min(tmp.size(), (size_t) params.n_batch), 0, 0));
  1842. llama_kv_cache_clear(lctx);
  1843. llama_synchronize(lctx);
  1844. llama_reset_timings(lctx);
  1845. }
  1846. return std::make_tuple(model, lctx);
  1847. }
  1848. //
  1849. // Vocab utils
  1850. //
  1851. std::vector<llama_token> llama_tokenize(
  1852. const struct llama_context * ctx,
  1853. const std::string & text,
  1854. bool add_bos,
  1855. bool special) {
  1856. return llama_tokenize(llama_get_model(ctx), text, add_bos, special);
  1857. }
  1858. std::vector<llama_token> llama_tokenize(
  1859. const struct llama_model * model,
  1860. const std::string & text,
  1861. bool add_bos,
  1862. bool special) {
  1863. // upper limit for the number of tokens
  1864. int n_tokens = text.length() + add_bos;
  1865. std::vector<llama_token> result(n_tokens);
  1866. n_tokens = llama_tokenize(model, text.data(), text.length(), result.data(), result.size(), add_bos, special);
  1867. if (n_tokens < 0) {
  1868. result.resize(-n_tokens);
  1869. int check = llama_tokenize(model, text.data(), text.length(), result.data(), result.size(), add_bos, special);
  1870. GGML_ASSERT(check == -n_tokens);
  1871. } else {
  1872. result.resize(n_tokens);
  1873. }
  1874. return result;
  1875. }
  1876. std::string llama_token_to_piece(const struct llama_context * ctx, llama_token token) {
  1877. std::vector<char> result(8, 0);
  1878. const int n_tokens = llama_token_to_piece(llama_get_model(ctx), token, result.data(), result.size());
  1879. if (n_tokens < 0) {
  1880. result.resize(-n_tokens);
  1881. int check = llama_token_to_piece(llama_get_model(ctx), token, result.data(), result.size());
  1882. GGML_ASSERT(check == -n_tokens);
  1883. } else {
  1884. result.resize(n_tokens);
  1885. }
  1886. return std::string(result.data(), result.size());
  1887. }
  1888. std::string llama_detokenize_spm(llama_context * ctx, const std::vector<llama_token> & tokens) {
  1889. const llama_token bos_id = llama_token_bos(llama_get_model(ctx));
  1890. std::string piece;
  1891. std::string result;
  1892. for (size_t i = 0; i < tokens.size(); ++i) {
  1893. piece = llama_token_to_piece(ctx, tokens[i]);
  1894. // remove the leading space of the first non-BOS token
  1895. if (((tokens[0] == bos_id && i == 1) || (tokens[0] != bos_id && i == 0)) && piece[0] == ' ') {
  1896. piece = piece.substr(1);
  1897. }
  1898. result += piece;
  1899. }
  1900. return result;
  1901. }
  1902. std::string llama_detokenize_bpe(llama_context * ctx, const std::vector<llama_token> & tokens) {
  1903. std::string piece;
  1904. std::string result;
  1905. for (size_t i = 0; i < tokens.size(); ++i) {
  1906. piece = llama_token_to_piece(ctx, tokens[i]);
  1907. result += piece;
  1908. }
  1909. // NOTE: the original tokenizer decodes bytes after collecting the pieces.
  1910. return result;
  1911. }
  1912. bool llama_should_add_bos_token(const llama_model * model) {
  1913. const int add_bos = llama_add_bos_token(model);
  1914. return add_bos != -1 ? bool(add_bos) : (llama_vocab_type(model) == LLAMA_VOCAB_TYPE_SPM);
  1915. }
  1916. //
  1917. // YAML utils
  1918. //
  1919. // returns true if successful, false otherwise
  1920. bool create_directory_with_parents(const std::string & path) {
  1921. #ifdef _WIN32
  1922. std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;
  1923. std::wstring wpath = converter.from_bytes(path);
  1924. // if the path already exists, check whether it's a directory
  1925. const DWORD attributes = GetFileAttributesW(wpath.c_str());
  1926. if ((attributes != INVALID_FILE_ATTRIBUTES) && (attributes & FILE_ATTRIBUTE_DIRECTORY)) {
  1927. return true;
  1928. }
  1929. size_t pos_slash = 0;
  1930. // process path from front to back, procedurally creating directories
  1931. while ((pos_slash = path.find('\\', pos_slash)) != std::string::npos) {
  1932. const std::wstring subpath = wpath.substr(0, pos_slash);
  1933. const wchar_t * test = subpath.c_str();
  1934. const bool success = CreateDirectoryW(test, NULL);
  1935. if (!success) {
  1936. const DWORD error = GetLastError();
  1937. // if the path already exists, ensure that it's a directory
  1938. if (error == ERROR_ALREADY_EXISTS) {
  1939. const DWORD attributes = GetFileAttributesW(subpath.c_str());
  1940. if (attributes == INVALID_FILE_ATTRIBUTES || !(attributes & FILE_ATTRIBUTE_DIRECTORY)) {
  1941. return false;
  1942. }
  1943. } else {
  1944. return false;
  1945. }
  1946. }
  1947. pos_slash += 1;
  1948. }
  1949. return true;
  1950. #else
  1951. // if the path already exists, check whether it's a directory
  1952. struct stat info;
  1953. if (stat(path.c_str(), &info) == 0) {
  1954. return S_ISDIR(info.st_mode);
  1955. }
  1956. size_t pos_slash = 1; // skip leading slashes for directory creation
  1957. // process path from front to back, procedurally creating directories
  1958. while ((pos_slash = path.find('/', pos_slash)) != std::string::npos) {
  1959. const std::string subpath = path.substr(0, pos_slash);
  1960. struct stat info;
  1961. // if the path already exists, ensure that it's a directory
  1962. if (stat(subpath.c_str(), &info) == 0) {
  1963. if (!S_ISDIR(info.st_mode)) {
  1964. return false;
  1965. }
  1966. } else {
  1967. // create parent directories
  1968. const int ret = mkdir(subpath.c_str(), 0755);
  1969. if (ret != 0) {
  1970. return false;
  1971. }
  1972. }
  1973. pos_slash += 1;
  1974. }
  1975. return true;
  1976. #endif // _WIN32
  1977. }
  1978. void dump_vector_float_yaml(FILE * stream, const char * prop_name, const std::vector<float> & data) {
  1979. if (data.empty()) {
  1980. fprintf(stream, "%s:\n", prop_name);
  1981. return;
  1982. }
  1983. fprintf(stream, "%s: [", prop_name);
  1984. for (size_t i = 0; i < data.size() - 1; ++i) {
  1985. fprintf(stream, "%e, ", data[i]);
  1986. }
  1987. fprintf(stream, "%e]\n", data.back());
  1988. }
  1989. void dump_vector_int_yaml(FILE * stream, const char * prop_name, const std::vector<int> & data) {
  1990. if (data.empty()) {
  1991. fprintf(stream, "%s:\n", prop_name);
  1992. return;
  1993. }
  1994. fprintf(stream, "%s: [", prop_name);
  1995. for (size_t i = 0; i < data.size() - 1; ++i) {
  1996. fprintf(stream, "%d, ", data[i]);
  1997. }
  1998. fprintf(stream, "%d]\n", data.back());
  1999. }
  2000. void dump_string_yaml_multiline(FILE * stream, const char * prop_name, const char * data) {
  2001. std::string data_str(data == NULL ? "" : data);
  2002. if (data_str.empty()) {
  2003. fprintf(stream, "%s:\n", prop_name);
  2004. return;
  2005. }
  2006. size_t pos_start = 0;
  2007. size_t pos_found = 0;
  2008. if (!data_str.empty() && (std::isspace(data_str[0]) || std::isspace(data_str.back()))) {
  2009. data_str = std::regex_replace(data_str, std::regex("\n"), "\\n");
  2010. data_str = std::regex_replace(data_str, std::regex("\""), "\\\"");
  2011. data_str = std::regex_replace(data_str, std::regex(R"(\\[^n"])"), R"(\$&)");
  2012. data_str = "\"" + data_str + "\"";
  2013. fprintf(stream, "%s: %s\n", prop_name, data_str.c_str());
  2014. return;
  2015. }
  2016. if (data_str.find('\n') == std::string::npos) {
  2017. fprintf(stream, "%s: %s\n", prop_name, data_str.c_str());
  2018. return;
  2019. }
  2020. fprintf(stream, "%s: |\n", prop_name);
  2021. while ((pos_found = data_str.find('\n', pos_start)) != std::string::npos) {
  2022. fprintf(stream, " %s\n", data_str.substr(pos_start, pos_found-pos_start).c_str());
  2023. pos_start = pos_found + 1;
  2024. }
  2025. }
  2026. std::string get_sortable_timestamp() {
  2027. using clock = std::chrono::system_clock;
  2028. const clock::time_point current_time = clock::now();
  2029. const time_t as_time_t = clock::to_time_t(current_time);
  2030. char timestamp_no_ns[100];
  2031. std::strftime(timestamp_no_ns, 100, "%Y_%m_%d-%H_%M_%S", std::localtime(&as_time_t));
  2032. const int64_t ns = std::chrono::duration_cast<std::chrono::nanoseconds>(
  2033. current_time.time_since_epoch() % 1000000000).count();
  2034. char timestamp_ns[11];
  2035. snprintf(timestamp_ns, 11, "%09" PRId64, ns);
  2036. return std::string(timestamp_no_ns) + "." + std::string(timestamp_ns);
  2037. }
  2038. void dump_non_result_info_yaml(FILE * stream, const gpt_params & params, const llama_context * lctx,
  2039. const std::string & timestamp, const std::vector<int> & prompt_tokens, const char * model_desc) {
  2040. const llama_sampling_params & sparams = params.sparams;
  2041. fprintf(stream, "build_commit: %s\n", LLAMA_COMMIT);
  2042. fprintf(stream, "build_number: %d\n", LLAMA_BUILD_NUMBER);
  2043. fprintf(stream, "cpu_has_arm_fma: %s\n", ggml_cpu_has_arm_fma() ? "true" : "false");
  2044. fprintf(stream, "cpu_has_avx: %s\n", ggml_cpu_has_avx() ? "true" : "false");
  2045. fprintf(stream, "cpu_has_avx_vnni: %s\n", ggml_cpu_has_avx_vnni() ? "true" : "false");
  2046. fprintf(stream, "cpu_has_avx2: %s\n", ggml_cpu_has_avx2() ? "true" : "false");
  2047. fprintf(stream, "cpu_has_avx512: %s\n", ggml_cpu_has_avx512() ? "true" : "false");
  2048. fprintf(stream, "cpu_has_avx512_vbmi: %s\n", ggml_cpu_has_avx512_vbmi() ? "true" : "false");
  2049. fprintf(stream, "cpu_has_avx512_vnni: %s\n", ggml_cpu_has_avx512_vnni() ? "true" : "false");
  2050. fprintf(stream, "cpu_has_cublas: %s\n", ggml_cpu_has_cublas() ? "true" : "false");
  2051. fprintf(stream, "cpu_has_vulkan: %s\n", ggml_cpu_has_vulkan() ? "true" : "false");
  2052. fprintf(stream, "cpu_has_clblast: %s\n", ggml_cpu_has_clblast() ? "true" : "false");
  2053. fprintf(stream, "cpu_has_kompute: %s\n", ggml_cpu_has_kompute() ? "true" : "false");
  2054. fprintf(stream, "cpu_has_fma: %s\n", ggml_cpu_has_fma() ? "true" : "false");
  2055. fprintf(stream, "cpu_has_gpublas: %s\n", ggml_cpu_has_gpublas() ? "true" : "false");
  2056. fprintf(stream, "cpu_has_neon: %s\n", ggml_cpu_has_neon() ? "true" : "false");
  2057. fprintf(stream, "cpu_has_f16c: %s\n", ggml_cpu_has_f16c() ? "true" : "false");
  2058. fprintf(stream, "cpu_has_fp16_va: %s\n", ggml_cpu_has_fp16_va() ? "true" : "false");
  2059. fprintf(stream, "cpu_has_wasm_simd: %s\n", ggml_cpu_has_wasm_simd() ? "true" : "false");
  2060. fprintf(stream, "cpu_has_blas: %s\n", ggml_cpu_has_blas() ? "true" : "false");
  2061. fprintf(stream, "cpu_has_sse3: %s\n", ggml_cpu_has_sse3() ? "true" : "false");
  2062. fprintf(stream, "cpu_has_vsx: %s\n", ggml_cpu_has_vsx() ? "true" : "false");
  2063. fprintf(stream, "cpu_has_matmul_int8: %s\n", ggml_cpu_has_matmul_int8() ? "true" : "false");
  2064. #ifdef NDEBUG
  2065. fprintf(stream, "debug: false\n");
  2066. #else
  2067. fprintf(stream, "debug: true\n");
  2068. #endif // NDEBUG
  2069. fprintf(stream, "model_desc: %s\n", model_desc);
  2070. fprintf(stream, "n_vocab: %d # output size of the final layer, 32001 for some models\n", llama_n_vocab(llama_get_model(lctx)));
  2071. #ifdef __OPTIMIZE__
  2072. fprintf(stream, "optimize: true\n");
  2073. #else
  2074. fprintf(stream, "optimize: false\n");
  2075. #endif // __OPTIMIZE__
  2076. fprintf(stream, "time: %s\n", timestamp.c_str());
  2077. fprintf(stream, "\n");
  2078. fprintf(stream, "###############\n");
  2079. fprintf(stream, "# User Inputs #\n");
  2080. fprintf(stream, "###############\n");
  2081. fprintf(stream, "\n");
  2082. fprintf(stream, "alias: %s # default: unknown\n", params.model_alias.c_str());
  2083. fprintf(stream, "batch_size: %d # default: 512\n", params.n_batch);
  2084. dump_string_yaml_multiline(stream, "cfg_negative_prompt", sparams.cfg_negative_prompt.c_str());
  2085. fprintf(stream, "cfg_scale: %f # default: 1.0\n", sparams.cfg_scale);
  2086. fprintf(stream, "chunks: %d # default: -1 (unlimited)\n", params.n_chunks);
  2087. fprintf(stream, "color: %s # default: false\n", params.use_color ? "true" : "false");
  2088. fprintf(stream, "ctx_size: %d # default: 512\n", params.n_ctx);
  2089. fprintf(stream, "escape: %s # default: false\n", params.escape ? "true" : "false");
  2090. fprintf(stream, "file: # never logged, see prompt instead. Can still be specified for input.\n");
  2091. fprintf(stream, "frequency_penalty: %f # default: 0.0 \n", sparams.penalty_freq);
  2092. dump_string_yaml_multiline(stream, "grammar", sparams.grammar.c_str());
  2093. fprintf(stream, "grammar-file: # never logged, see grammar instead. Can still be specified for input.\n");
  2094. fprintf(stream, "hellaswag: %s # default: false\n", params.hellaswag ? "true" : "false");
  2095. fprintf(stream, "hellaswag_tasks: %zu # default: 400\n", params.hellaswag_tasks);
  2096. const auto logit_bias_eos = sparams.logit_bias.find(llama_token_eos(llama_get_model(lctx)));
  2097. const bool ignore_eos = logit_bias_eos != sparams.logit_bias.end() && logit_bias_eos->second == -INFINITY;
  2098. fprintf(stream, "ignore_eos: %s # default: false\n", ignore_eos ? "true" : "false");
  2099. dump_string_yaml_multiline(stream, "in_prefix", params.input_prefix.c_str());
  2100. fprintf(stream, "in_prefix_bos: %s # default: false\n", params.input_prefix_bos ? "true" : "false");
  2101. dump_string_yaml_multiline(stream, "in_suffix", params.input_prefix.c_str());
  2102. fprintf(stream, "instruct: %s # default: false\n", params.instruct ? "true" : "false");
  2103. fprintf(stream, "interactive: %s # default: false\n", params.interactive ? "true" : "false");
  2104. fprintf(stream, "interactive_first: %s # default: false\n", params.interactive_first ? "true" : "false");
  2105. fprintf(stream, "keep: %d # default: 0\n", params.n_keep);
  2106. fprintf(stream, "logdir: %s # default: unset (no logging)\n", params.logdir.c_str());
  2107. fprintf(stream, "logit_bias:\n");
  2108. for (std::pair<llama_token, float> lb : sparams.logit_bias) {
  2109. if (ignore_eos && lb.first == logit_bias_eos->first) {
  2110. continue;
  2111. }
  2112. fprintf(stream, " %d: %f", lb.first, lb.second);
  2113. }
  2114. fprintf(stream, "lora:\n");
  2115. for (std::tuple<std::string, float> la : params.lora_adapter) {
  2116. if (std::get<1>(la) != 1.0f) {
  2117. continue;
  2118. }
  2119. fprintf(stream, " - %s\n", std::get<0>(la).c_str());
  2120. }
  2121. fprintf(stream, "lora_scaled:\n");
  2122. for (std::tuple<std::string, float> la : params.lora_adapter) {
  2123. if (std::get<1>(la) == 1.0f) {
  2124. continue;
  2125. }
  2126. fprintf(stream, " - %s: %f\n", std::get<0>(la).c_str(), std::get<1>(la));
  2127. }
  2128. fprintf(stream, "lora_base: %s\n", params.lora_base.c_str());
  2129. fprintf(stream, "main_gpu: %d # default: 0\n", params.main_gpu);
  2130. fprintf(stream, "min_keep: %d # default: 0 (disabled)\n", sparams.min_keep);
  2131. fprintf(stream, "mirostat: %d # default: 0 (disabled)\n", sparams.mirostat);
  2132. fprintf(stream, "mirostat_ent: %f # default: 5.0\n", sparams.mirostat_tau);
  2133. fprintf(stream, "mirostat_lr: %f # default: 0.1\n", sparams.mirostat_eta);
  2134. fprintf(stream, "mlock: %s # default: false\n", params.use_mlock ? "true" : "false");
  2135. fprintf(stream, "model: %s # default: models/7B/ggml-model.bin\n", params.model.c_str());
  2136. fprintf(stream, "model_draft: %s # default:\n", params.model_draft.c_str());
  2137. fprintf(stream, "multiline_input: %s # default: false\n", params.multiline_input ? "true" : "false");
  2138. fprintf(stream, "n_gpu_layers: %d # default: -1\n", params.n_gpu_layers);
  2139. fprintf(stream, "n_predict: %d # default: -1 (unlimited)\n", params.n_predict);
  2140. fprintf(stream, "n_probs: %d # only used by server binary, default: 0\n", sparams.n_probs);
  2141. fprintf(stream, "no_mmap: %s # default: false\n", !params.use_mmap ? "true" : "false");
  2142. fprintf(stream, "no_penalize_nl: %s # default: false\n", !sparams.penalize_nl ? "true" : "false");
  2143. fprintf(stream, "ppl_output_type: %d # default: 0\n", params.ppl_output_type);
  2144. fprintf(stream, "ppl_stride: %d # default: 0\n", params.ppl_stride);
  2145. fprintf(stream, "presence_penalty: %f # default: 0.0\n", sparams.penalty_present);
  2146. dump_string_yaml_multiline(stream, "prompt", params.prompt.c_str());
  2147. fprintf(stream, "prompt_cache: %s\n", params.path_prompt_cache.c_str());
  2148. fprintf(stream, "prompt_cache_all: %s # default: false\n", params.prompt_cache_all ? "true" : "false");
  2149. fprintf(stream, "prompt_cache_ro: %s # default: false\n", params.prompt_cache_ro ? "true" : "false");
  2150. dump_vector_int_yaml(stream, "prompt_tokens", prompt_tokens);
  2151. fprintf(stream, "random_prompt: %s # default: false\n", params.random_prompt ? "true" : "false");
  2152. fprintf(stream, "repeat_penalty: %f # default: 1.1\n", sparams.penalty_repeat);
  2153. fprintf(stream, "reverse_prompt:\n");
  2154. for (std::string ap : params.antiprompt) {
  2155. size_t pos = 0;
  2156. while ((pos = ap.find('\n', pos)) != std::string::npos) {
  2157. ap.replace(pos, 1, "\\n");
  2158. pos += 1;
  2159. }
  2160. fprintf(stream, " - %s\n", ap.c_str());
  2161. }
  2162. fprintf(stream, "rope_freq_base: %f # default: 10000.0\n", params.rope_freq_base);
  2163. fprintf(stream, "rope_freq_scale: %f # default: 1.0\n", params.rope_freq_scale);
  2164. fprintf(stream, "seed: %u # default: -1 (random seed)\n", params.seed);
  2165. fprintf(stream, "simple_io: %s # default: false\n", params.simple_io ? "true" : "false");
  2166. fprintf(stream, "cont_batching: %s # default: false\n", params.cont_batching ? "true" : "false");
  2167. fprintf(stream, "temp: %f # default: 0.8\n", sparams.temp);
  2168. const std::vector<float> tensor_split_vector(params.tensor_split, params.tensor_split + llama_max_devices());
  2169. dump_vector_float_yaml(stream, "tensor_split", tensor_split_vector);
  2170. fprintf(stream, "tfs: %f # default: 1.0\n", sparams.tfs_z);
  2171. fprintf(stream, "threads: %d # default: %u\n", params.n_threads, std::thread::hardware_concurrency());
  2172. fprintf(stream, "top_k: %d # default: 40\n", sparams.top_k);
  2173. fprintf(stream, "top_p: %f # default: 0.95\n", sparams.top_p);
  2174. fprintf(stream, "min_p: %f # default: 0.0\n", sparams.min_p);
  2175. fprintf(stream, "typical_p: %f # default: 1.0\n", sparams.typical_p);
  2176. fprintf(stream, "verbose_prompt: %s # default: false\n", params.verbose_prompt ? "true" : "false");
  2177. fprintf(stream, "display_prompt: %s # default: true\n", params.display_prompt ? "true" : "false");
  2178. }
  2179. //
  2180. // KV cache utils
  2181. //
  2182. void dump_kv_cache_view(const llama_kv_cache_view & view, int row_size) {
  2183. static const char slot_chars[] = ".123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+";
  2184. 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",
  2185. view.n_cells, view.n_seq_max, view.used_cells, view.token_count, view.max_contiguous, view.max_contiguous_idx);
  2186. llama_kv_cache_view_cell * c_curr = view.cells;
  2187. llama_seq_id * cs_curr = view.cells_sequences;
  2188. for (int i = 0; i < view.n_cells; i++, c_curr++, cs_curr += view.n_seq_max) {
  2189. if (i % row_size == 0) {
  2190. printf("\n%5d: ", i);
  2191. }
  2192. int seq_count = 0;
  2193. for (int j = 0; j < view.n_seq_max; j++) {
  2194. if (cs_curr[j] >= 0) { seq_count++; }
  2195. }
  2196. putchar(slot_chars[std::min(sizeof(slot_chars) - 2, size_t(seq_count))]);
  2197. }
  2198. printf("\n=== Done dumping\n");
  2199. }
  2200. void dump_kv_cache_view_seqs(const llama_kv_cache_view & view, int row_size) {
  2201. static const char slot_chars[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  2202. 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",
  2203. view.n_cells, view.n_seq_max, view.used_cells, view.token_count, view.max_contiguous, view.max_contiguous_idx);
  2204. std::unordered_map<llama_seq_id, size_t> seqs;
  2205. llama_kv_cache_view_cell * c_curr = view.cells;
  2206. llama_seq_id * cs_curr = view.cells_sequences;
  2207. for (int i = 0; i < view.n_cells; i++, c_curr++, cs_curr += view.n_seq_max) {
  2208. for (int j = 0; j < view.n_seq_max; j++) {
  2209. if (cs_curr[j] < 0) { continue; }
  2210. if (seqs.find(cs_curr[j]) == seqs.end()) {
  2211. if (seqs.size() + 1 >= sizeof(slot_chars)) { break; }
  2212. const size_t sz = seqs.size();
  2213. seqs[cs_curr[j]] = sz;
  2214. }
  2215. }
  2216. if (seqs.size() + 1 >= sizeof(slot_chars)) { break; }
  2217. }
  2218. printf("=== Sequence legend: ");
  2219. for (const auto & it : seqs) {
  2220. printf("%zu=%d, ", it.second, it.first);
  2221. }
  2222. printf("'+'=other sequence ids");
  2223. c_curr = view.cells;
  2224. cs_curr = view.cells_sequences;
  2225. for (int i = 0; i < view.n_cells; i++, c_curr++, cs_curr += view.n_seq_max) {
  2226. if (i % row_size == 0) {
  2227. printf("\n%5d: ", i);
  2228. }
  2229. for (int j = 0; j < view.n_seq_max; j++) {
  2230. if (cs_curr[j] >= 0) {
  2231. const auto & it = seqs.find(cs_curr[j]);
  2232. putchar(it != seqs.end() ? int(slot_chars[it->second]) : '+');
  2233. } else {
  2234. putchar('.');
  2235. }
  2236. }
  2237. putchar(' ');
  2238. }
  2239. printf("\n=== Done dumping\n");
  2240. }
  2241. void llama_embd_normalize(const float * inp, float * out, int n) {
  2242. double sum = 0.0;
  2243. for (int i = 0; i < n; i++) {
  2244. sum += inp[i] * inp[i];
  2245. }
  2246. sum = sqrt(sum);
  2247. const float norm = sum > 0.0 ? 1.0f / sum : 0.0f;
  2248. for (int i = 0; i < n; i++) {
  2249. out[i] = inp[i] * norm;
  2250. }
  2251. }
  2252. float llama_embd_similarity_cos(const float * embd1, const float * embd2, int n){
  2253. double sum = 0.0;
  2254. double sum1 = 0.0;
  2255. double sum2 = 0.0;
  2256. for (int i = 0; i < n; i++) {
  2257. sum += embd1[i] * embd2[i];
  2258. sum1 += embd1[i] * embd1[i];
  2259. sum2 += embd2[i] * embd2[i];
  2260. }
  2261. return sum / (sqrt(sum1) * sqrt(sum2));
  2262. }
  2263. //
  2264. // Control vector utils
  2265. //
  2266. static llama_control_vector_data llama_control_vector_load_one(const llama_control_vector_load_info & load_info) {
  2267. int32_t n_tensors;
  2268. size_t n_bytes = 0;
  2269. uint32_t max_direction_layer = 0;
  2270. llama_control_vector_data result = { -1, {} };
  2271. // calculate size of ctx needed for tensors, ensure tensors are f32, and find max layer
  2272. {
  2273. struct ggml_init_params meta_params = {
  2274. /* .mem_size = */ ggml_tensor_overhead() * 128 + ggml_graph_overhead(),
  2275. /* .mem_buffer = */ nullptr,
  2276. /* .no_alloc = */ true,
  2277. };
  2278. ggml_context * meta_ctx = ggml_init(meta_params);
  2279. struct gguf_init_params meta_gguf_params = {
  2280. /* .no_alloc = */ true,
  2281. /* .ctx = */ &meta_ctx,
  2282. };
  2283. struct gguf_context * meta_ctx_gguf = gguf_init_from_file(load_info.fname.c_str(), meta_gguf_params);
  2284. if (!meta_ctx_gguf) {
  2285. fprintf(stderr, "%s: failed to load control vector from %s\n", __func__, load_info.fname.c_str());
  2286. ggml_free(meta_ctx);
  2287. return result;
  2288. }
  2289. n_tensors = gguf_get_n_tensors(meta_ctx_gguf);
  2290. for (int i = 0; i < n_tensors; i++) {
  2291. std::string name = gguf_get_tensor_name(meta_ctx_gguf, i);
  2292. // split on '.'
  2293. size_t dotpos = name.find('.');
  2294. if (dotpos != std::string::npos && name.substr(0, dotpos) == "direction") {
  2295. try {
  2296. uint32_t layer = std::stoi(name.substr(dotpos + 1));
  2297. if (layer == 0) {
  2298. fprintf(stderr, "%s: direction tensor invalid in %s\n", __func__, load_info.fname.c_str());
  2299. ggml_free(meta_ctx);
  2300. gguf_free(meta_ctx_gguf);
  2301. return result;
  2302. }
  2303. if (layer > max_direction_layer) {
  2304. max_direction_layer = layer;
  2305. }
  2306. } catch (...) {
  2307. fprintf(stderr, "%s: direction tensor invalid in %s\n", __func__, load_info.fname.c_str());
  2308. ggml_free(meta_ctx);
  2309. gguf_free(meta_ctx_gguf);
  2310. return result;
  2311. }
  2312. }
  2313. struct ggml_tensor * tensor_meta = ggml_get_tensor(meta_ctx, name.c_str());
  2314. if (tensor_meta->type != GGML_TYPE_F32 || ggml_n_dims(tensor_meta) != 1) {
  2315. fprintf(stderr, "%s: direction tensor invalid in %s\n", __func__, load_info.fname.c_str());
  2316. ggml_free(meta_ctx);
  2317. gguf_free(meta_ctx_gguf);
  2318. return result;
  2319. }
  2320. if (result.n_embd == -1) {
  2321. result.n_embd = ggml_nelements(tensor_meta);
  2322. } else if (ggml_nelements(tensor_meta) != result.n_embd) {
  2323. fprintf(stderr, "%s: direction tensor sizes mismatched in %s\n", __func__, load_info.fname.c_str());
  2324. ggml_free(meta_ctx);
  2325. gguf_free(meta_ctx_gguf);
  2326. return result;
  2327. }
  2328. n_bytes += ggml_nbytes(tensor_meta);
  2329. }
  2330. ggml_free(meta_ctx);
  2331. gguf_free(meta_ctx_gguf);
  2332. }
  2333. if (n_tensors == 0) {
  2334. fprintf(stderr, "%s: no direction tensors found in %s\n", __func__, load_info.fname.c_str());
  2335. return result;
  2336. }
  2337. // load and scale tensors into final control vector context
  2338. struct ggml_init_params ggml_params = {
  2339. /* .mem_size = */ ggml_tensor_overhead() * n_tensors + n_bytes,
  2340. /* .mem_buffer = */ nullptr,
  2341. /* .no_alloc = */ false,
  2342. };
  2343. struct ggml_context * ctx = ggml_init(ggml_params);
  2344. struct gguf_init_params params = {
  2345. /*.no_alloc = */ false,
  2346. /*.ctx = */ &ctx,
  2347. };
  2348. struct gguf_context * ctx_gguf = gguf_init_from_file(load_info.fname.c_str(), params);
  2349. if (!ctx_gguf) {
  2350. fprintf(stderr, "%s: failed to load control vector from %s\n", __func__, load_info.fname.c_str());
  2351. ggml_free(ctx);
  2352. return result;
  2353. }
  2354. // do not store data for layer 0 (it's not used)
  2355. result.data.resize(result.n_embd * max_direction_layer);
  2356. for (uint32_t il = 1; il <= max_direction_layer; il++) {
  2357. const std::string name = "direction." + std::to_string(il);
  2358. const ggml_tensor * tensor = ggml_get_tensor(ctx, name.c_str());
  2359. float * dst = result.data.data() + result.n_embd * (il - 1);
  2360. if (tensor) {
  2361. const float * src = (const float *) tensor->data;
  2362. for (int j = 0; j < result.n_embd; j++) {
  2363. dst[j] = src[j] * load_info.strength;
  2364. }
  2365. } else {
  2366. for (int j = 0; j < result.n_embd; j++) {
  2367. dst[j] = 0.0f;
  2368. }
  2369. }
  2370. }
  2371. return result;
  2372. }
  2373. llama_control_vector_data llama_control_vector_load(const std::vector<llama_control_vector_load_info> & load_infos) {
  2374. llama_control_vector_data result = { -1, {} };
  2375. for (const auto & info : load_infos) {
  2376. auto cur = llama_control_vector_load_one(info);
  2377. if (cur.n_embd == -1) {
  2378. return result;
  2379. }
  2380. if (result.n_embd != -1 && (result.n_embd != cur.n_embd || result.data.size() != cur.data.size())) {
  2381. fprintf(stderr, "%s: control vector in %s does not match previous vector dimensions\n", __func__, info.fname.c_str());
  2382. return result;
  2383. }
  2384. if (result.n_embd == -1) {
  2385. result = std::move(cur);
  2386. } else {
  2387. for (size_t i = 0; i < cur.data.size(); i++) {
  2388. result.data[i] += cur.data[i];
  2389. }
  2390. }
  2391. }
  2392. if (result.n_embd == -1) {
  2393. fprintf(stderr, "%s: no vectors passed\n", __func__);
  2394. }
  2395. return result;
  2396. }