common.cpp 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467
  1. #include "common.h"
  2. #include "llama.h"
  3. #include <algorithm>
  4. #include <cassert>
  5. #include <cmath>
  6. #include <cstring>
  7. #include <ctime>
  8. #include <fstream>
  9. #include <iterator>
  10. #include <iostream>
  11. #include <regex>
  12. #include <sstream>
  13. #include <string>
  14. #include <unordered_map>
  15. #include <unordered_set>
  16. #include <vector>
  17. #include <cinttypes>
  18. #if defined(__APPLE__) && defined(__MACH__)
  19. #include <sys/types.h>
  20. #include <sys/sysctl.h>
  21. #endif
  22. #if defined(_WIN32)
  23. #define WIN32_LEAN_AND_MEAN
  24. #ifndef NOMINMAX
  25. # define NOMINMAX
  26. #endif
  27. #include <codecvt>
  28. #include <locale>
  29. #include <windows.h>
  30. #include <fcntl.h>
  31. #include <io.h>
  32. #else
  33. #include <sys/ioctl.h>
  34. #include <sys/stat.h>
  35. #include <unistd.h>
  36. #endif
  37. #if defined(_MSC_VER)
  38. #pragma warning(disable: 4244 4267) // possible loss of data
  39. #endif
  40. int32_t get_num_physical_cores() {
  41. #ifdef __linux__
  42. // enumerate the set of thread siblings, num entries is num cores
  43. std::unordered_set<std::string> siblings;
  44. for (uint32_t cpu=0; cpu < UINT32_MAX; ++cpu) {
  45. std::ifstream thread_siblings("/sys/devices/system/cpu"
  46. + std::to_string(cpu) + "/topology/thread_siblings");
  47. if (!thread_siblings.is_open()) {
  48. break; // no more cpus
  49. }
  50. std::string line;
  51. if (std::getline(thread_siblings, line)) {
  52. siblings.insert(line);
  53. }
  54. }
  55. if (!siblings.empty()) {
  56. return static_cast<int32_t>(siblings.size());
  57. }
  58. #elif defined(__APPLE__) && defined(__MACH__)
  59. int32_t num_physical_cores;
  60. size_t len = sizeof(num_physical_cores);
  61. int result = sysctlbyname("hw.perflevel0.physicalcpu", &num_physical_cores, &len, NULL, 0);
  62. if (result == 0) {
  63. return num_physical_cores;
  64. }
  65. result = sysctlbyname("hw.physicalcpu", &num_physical_cores, &len, NULL, 0);
  66. if (result == 0) {
  67. return num_physical_cores;
  68. }
  69. #elif defined(_WIN32)
  70. //TODO: Implement
  71. #endif
  72. unsigned int n_threads = std::thread::hardware_concurrency();
  73. return n_threads > 0 ? (n_threads <= 4 ? n_threads : n_threads / 2) : 4;
  74. }
  75. void process_escapes(std::string& input) {
  76. std::size_t input_len = input.length();
  77. std::size_t output_idx = 0;
  78. for (std::size_t input_idx = 0; input_idx < input_len; ++input_idx) {
  79. if (input[input_idx] == '\\' && input_idx + 1 < input_len) {
  80. switch (input[++input_idx]) {
  81. case 'n': input[output_idx++] = '\n'; break;
  82. case 'r': input[output_idx++] = '\r'; break;
  83. case 't': input[output_idx++] = '\t'; break;
  84. case '\'': input[output_idx++] = '\''; break;
  85. case '\"': input[output_idx++] = '\"'; break;
  86. case '\\': input[output_idx++] = '\\'; break;
  87. case 'x':
  88. // Handle \x12, etc
  89. if (input_idx + 2 < input_len) {
  90. const char x[3] = { input[input_idx + 1], input[input_idx + 2], 0 };
  91. char *err_p = nullptr;
  92. const long val = std::strtol(x, &err_p, 16);
  93. if (err_p == x + 2) {
  94. input_idx += 2;
  95. input[output_idx++] = char(val);
  96. break;
  97. }
  98. }
  99. // fall through
  100. default: input[output_idx++] = '\\';
  101. input[output_idx++] = input[input_idx]; break;
  102. }
  103. } else {
  104. input[output_idx++] = input[input_idx];
  105. }
  106. }
  107. input.resize(output_idx);
  108. }
  109. bool gpt_params_parse(int argc, char ** argv, gpt_params & params) {
  110. bool result = true;
  111. try {
  112. if (!gpt_params_parse_ex(argc, argv, params)) {
  113. gpt_print_usage(argc, argv, gpt_params());
  114. exit(0);
  115. }
  116. }
  117. catch (const std::invalid_argument & ex) {
  118. fprintf(stderr, "%s\n", ex.what());
  119. gpt_print_usage(argc, argv, gpt_params());
  120. exit(1);
  121. }
  122. return result;
  123. }
  124. bool gpt_params_parse_ex(int argc, char ** argv, gpt_params & params) {
  125. bool invalid_param = false;
  126. std::string arg;
  127. const std::string arg_prefix = "--";
  128. llama_sampling_params & sparams = params.sparams;
  129. for (int i = 1; i < argc; i++) {
  130. arg = argv[i];
  131. if (arg.compare(0, arg_prefix.size(), arg_prefix) == 0) {
  132. std::replace(arg.begin(), arg.end(), '_', '-');
  133. }
  134. if (arg == "-s" || arg == "--seed") {
  135. if (++i >= argc) {
  136. invalid_param = true;
  137. break;
  138. }
  139. params.seed = std::stoul(argv[i]);
  140. } else if (arg == "-t" || arg == "--threads") {
  141. if (++i >= argc) {
  142. invalid_param = true;
  143. break;
  144. }
  145. params.n_threads = std::stoi(argv[i]);
  146. if (params.n_threads <= 0) {
  147. params.n_threads = std::thread::hardware_concurrency();
  148. }
  149. } else if (arg == "-tb" || arg == "--threads-batch") {
  150. if (++i >= argc) {
  151. invalid_param = true;
  152. break;
  153. }
  154. params.n_threads_batch = std::stoi(argv[i]);
  155. if (params.n_threads_batch <= 0) {
  156. params.n_threads_batch = std::thread::hardware_concurrency();
  157. }
  158. } else if (arg == "-p" || arg == "--prompt") {
  159. if (++i >= argc) {
  160. invalid_param = true;
  161. break;
  162. }
  163. params.prompt = argv[i];
  164. } else if (arg == "-e" || arg == "--escape") {
  165. params.escape = true;
  166. } else if (arg == "--prompt-cache") {
  167. if (++i >= argc) {
  168. invalid_param = true;
  169. break;
  170. }
  171. params.path_prompt_cache = argv[i];
  172. } else if (arg == "--prompt-cache-all") {
  173. params.prompt_cache_all = true;
  174. } else if (arg == "--prompt-cache-ro") {
  175. params.prompt_cache_ro = true;
  176. } else if (arg == "-f" || arg == "--file") {
  177. if (++i >= argc) {
  178. invalid_param = true;
  179. break;
  180. }
  181. std::ifstream file(argv[i]);
  182. if (!file) {
  183. fprintf(stderr, "error: failed to open file '%s'\n", argv[i]);
  184. invalid_param = true;
  185. break;
  186. }
  187. // store the external file name in params
  188. params.prompt_file = argv[i];
  189. std::copy(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>(), back_inserter(params.prompt));
  190. if (!params.prompt.empty() && params.prompt.back() == '\n') {
  191. params.prompt.pop_back();
  192. }
  193. } else if (arg == "-n" || arg == "--n-predict") {
  194. if (++i >= argc) {
  195. invalid_param = true;
  196. break;
  197. }
  198. params.n_predict = std::stoi(argv[i]);
  199. } else if (arg == "--top-k") {
  200. if (++i >= argc) {
  201. invalid_param = true;
  202. break;
  203. }
  204. sparams.top_k = std::stoi(argv[i]);
  205. } else if (arg == "-c" || arg == "--ctx-size") {
  206. if (++i >= argc) {
  207. invalid_param = true;
  208. break;
  209. }
  210. params.n_ctx = std::stoi(argv[i]);
  211. } else if (arg == "--rope-freq-base") {
  212. if (++i >= argc) {
  213. invalid_param = true;
  214. break;
  215. }
  216. params.rope_freq_base = std::stof(argv[i]);
  217. } else if (arg == "--rope-freq-scale") {
  218. if (++i >= argc) {
  219. invalid_param = true;
  220. break;
  221. }
  222. params.rope_freq_scale = std::stof(argv[i]);
  223. } else if (arg == "--rope-scaling") {
  224. if (++i >= argc) {
  225. invalid_param = true;
  226. break;
  227. }
  228. std::string value(argv[i]);
  229. /**/ if (value == "none") { params.rope_scaling_type = LLAMA_ROPE_SCALING_NONE; }
  230. else if (value == "linear") { params.rope_scaling_type = LLAMA_ROPE_SCALING_LINEAR; }
  231. else if (value == "yarn") { params.rope_scaling_type = LLAMA_ROPE_SCALING_YARN; }
  232. else { invalid_param = true; break; }
  233. } else if (arg == "--rope-scale") {
  234. if (++i >= argc) {
  235. invalid_param = true;
  236. break;
  237. }
  238. params.rope_freq_scale = 1.0f/std::stof(argv[i]);
  239. } else if (arg == "--yarn-orig-ctx") {
  240. if (++i >= argc) {
  241. invalid_param = true;
  242. break;
  243. }
  244. params.yarn_orig_ctx = std::stoi(argv[i]);
  245. } else if (arg == "--yarn-ext-factor") {
  246. if (++i >= argc) {
  247. invalid_param = true;
  248. break;
  249. }
  250. params.yarn_ext_factor = std::stof(argv[i]);
  251. } else if (arg == "--yarn-attn-factor") {
  252. if (++i >= argc) {
  253. invalid_param = true;
  254. break;
  255. }
  256. params.yarn_attn_factor = std::stof(argv[i]);
  257. } else if (arg == "--yarn-beta-fast") {
  258. if (++i >= argc) {
  259. invalid_param = true;
  260. break;
  261. }
  262. params.yarn_beta_fast = std::stof(argv[i]);
  263. } else if (arg == "--yarn-beta-slow") {
  264. if (++i >= argc) {
  265. invalid_param = true;
  266. break;
  267. }
  268. params.yarn_beta_slow = std::stof(argv[i]);
  269. } else if (arg == "--memory-f32") {
  270. params.memory_f16 = false;
  271. } else if (arg == "--top-p") {
  272. if (++i >= argc) {
  273. invalid_param = true;
  274. break;
  275. }
  276. sparams.top_p = std::stof(argv[i]);
  277. } else if (arg == "--min-p") {
  278. if (++i >= argc) {
  279. invalid_param = true;
  280. break;
  281. }
  282. sparams.min_p = std::stof(argv[i]);
  283. } else if (arg == "--temp") {
  284. if (++i >= argc) {
  285. invalid_param = true;
  286. break;
  287. }
  288. sparams.temp = std::stof(argv[i]);
  289. sparams.temp = std::max(sparams.temp, 0.0f);
  290. } else if (arg == "--tfs") {
  291. if (++i >= argc) {
  292. invalid_param = true;
  293. break;
  294. }
  295. sparams.tfs_z = std::stof(argv[i]);
  296. } else if (arg == "--typical") {
  297. if (++i >= argc) {
  298. invalid_param = true;
  299. break;
  300. }
  301. sparams.typical_p = std::stof(argv[i]);
  302. } else if (arg == "--repeat-last-n") {
  303. if (++i >= argc) {
  304. invalid_param = true;
  305. break;
  306. }
  307. sparams.penalty_last_n = std::stoi(argv[i]);
  308. sparams.n_prev = std::max(sparams.n_prev, sparams.penalty_last_n);
  309. } else if (arg == "--repeat-penalty") {
  310. if (++i >= argc) {
  311. invalid_param = true;
  312. break;
  313. }
  314. sparams.penalty_repeat = std::stof(argv[i]);
  315. } else if (arg == "--frequency-penalty") {
  316. if (++i >= argc) {
  317. invalid_param = true;
  318. break;
  319. }
  320. sparams.penalty_freq = std::stof(argv[i]);
  321. } else if (arg == "--presence-penalty") {
  322. if (++i >= argc) {
  323. invalid_param = true;
  324. break;
  325. }
  326. sparams.penalty_present = std::stof(argv[i]);
  327. } else if (arg == "--mirostat") {
  328. if (++i >= argc) {
  329. invalid_param = true;
  330. break;
  331. }
  332. sparams.mirostat = std::stoi(argv[i]);
  333. } else if (arg == "--mirostat-lr") {
  334. if (++i >= argc) {
  335. invalid_param = true;
  336. break;
  337. }
  338. sparams.mirostat_eta = std::stof(argv[i]);
  339. } else if (arg == "--mirostat-ent") {
  340. if (++i >= argc) {
  341. invalid_param = true;
  342. break;
  343. }
  344. sparams.mirostat_tau = std::stof(argv[i]);
  345. } else if (arg == "--cfg-negative-prompt") {
  346. if (++i >= argc) {
  347. invalid_param = true;
  348. break;
  349. }
  350. sparams.cfg_negative_prompt = argv[i];
  351. } else if (arg == "--cfg-negative-prompt-file") {
  352. if (++i >= argc) {
  353. invalid_param = true;
  354. break;
  355. }
  356. std::ifstream file(argv[i]);
  357. if (!file) {
  358. fprintf(stderr, "error: failed to open file '%s'\n", argv[i]);
  359. invalid_param = true;
  360. break;
  361. }
  362. std::copy(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>(), back_inserter(sparams.cfg_negative_prompt));
  363. if (!sparams.cfg_negative_prompt.empty() && sparams.cfg_negative_prompt.back() == '\n') {
  364. sparams.cfg_negative_prompt.pop_back();
  365. }
  366. } else if (arg == "--cfg-scale") {
  367. if (++i >= argc) {
  368. invalid_param = true;
  369. break;
  370. }
  371. sparams.cfg_scale = std::stof(argv[i]);
  372. } else if (arg == "-b" || arg == "--batch-size") {
  373. if (++i >= argc) {
  374. invalid_param = true;
  375. break;
  376. }
  377. params.n_batch = std::stoi(argv[i]);
  378. } else if (arg == "--keep") {
  379. if (++i >= argc) {
  380. invalid_param = true;
  381. break;
  382. }
  383. params.n_keep = std::stoi(argv[i]);
  384. } else if (arg == "--draft") {
  385. if (++i >= argc) {
  386. invalid_param = true;
  387. break;
  388. }
  389. params.n_draft = std::stoi(argv[i]);
  390. } else if (arg == "--chunks") {
  391. if (++i >= argc) {
  392. invalid_param = true;
  393. break;
  394. }
  395. params.n_chunks = std::stoi(argv[i]);
  396. } else if (arg == "-np" || arg == "--parallel") {
  397. if (++i >= argc) {
  398. invalid_param = true;
  399. break;
  400. }
  401. params.n_parallel = std::stoi(argv[i]);
  402. } else if (arg == "-ns" || arg == "--sequences") {
  403. if (++i >= argc) {
  404. invalid_param = true;
  405. break;
  406. }
  407. params.n_sequences = std::stoi(argv[i]);
  408. } else if (arg == "--p-accept" || arg == "-pa") {
  409. if (++i >= argc) {
  410. invalid_param = true;
  411. break;
  412. }
  413. params.p_accept = std::stof(argv[i]);
  414. } else if (arg == "--p-split" || arg == "-ps") {
  415. if (++i >= argc) {
  416. invalid_param = true;
  417. break;
  418. }
  419. params.p_split = std::stof(argv[i]);
  420. } else if (arg == "-m" || arg == "--model") {
  421. if (++i >= argc) {
  422. invalid_param = true;
  423. break;
  424. }
  425. params.model = argv[i];
  426. } else if (arg == "-md" || arg == "--model-draft") {
  427. if (++i >= argc) {
  428. invalid_param = true;
  429. break;
  430. }
  431. params.model_draft = argv[i];
  432. } else if (arg == "-a" || arg == "--alias") {
  433. if (++i >= argc) {
  434. invalid_param = true;
  435. break;
  436. }
  437. params.model_alias = argv[i];
  438. } else if (arg == "--lora") {
  439. if (++i >= argc) {
  440. invalid_param = true;
  441. break;
  442. }
  443. params.lora_adapter.push_back(std::make_tuple(argv[i], 1.0f));
  444. params.use_mmap = false;
  445. } else if (arg == "--lora-scaled") {
  446. if (++i >= argc) {
  447. invalid_param = true;
  448. break;
  449. }
  450. const char * lora_adapter = argv[i];
  451. if (++i >= argc) {
  452. invalid_param = true;
  453. break;
  454. }
  455. params.lora_adapter.push_back(std::make_tuple(lora_adapter, std::stof(argv[i])));
  456. params.use_mmap = false;
  457. } else if (arg == "--lora-base") {
  458. if (++i >= argc) {
  459. invalid_param = true;
  460. break;
  461. }
  462. params.lora_base = argv[i];
  463. } else if (arg == "--mmproj") {
  464. if (++i >= argc) {
  465. invalid_param = true;
  466. break;
  467. }
  468. params.mmproj = argv[i];
  469. } else if (arg == "--image") {
  470. if (++i >= argc) {
  471. invalid_param = true;
  472. break;
  473. }
  474. params.image = argv[i];
  475. } else if (arg == "-i" || arg == "--interactive") {
  476. params.interactive = true;
  477. } else if (arg == "--embedding") {
  478. params.embedding = true;
  479. } else if (arg == "--interactive-first") {
  480. params.interactive_first = true;
  481. } else if (arg == "-ins" || arg == "--instruct") {
  482. params.instruct = true;
  483. } else if (arg == "-cml" || arg == "--chatml") {
  484. params.chatml = true;
  485. } else if (arg == "--infill") {
  486. params.infill = true;
  487. } else if (arg == "-dkvc" || arg == "--dump-kv-cache") {
  488. params.dump_kv_cache = true;
  489. } else if (arg == "--multiline-input") {
  490. params.multiline_input = true;
  491. } else if (arg == "--simple-io") {
  492. params.simple_io = true;
  493. } else if (arg == "-cb" || arg == "--cont-batching") {
  494. params.cont_batching = true;
  495. } else if (arg == "--color") {
  496. params.use_color = true;
  497. } else if (arg == "--mlock") {
  498. params.use_mlock = true;
  499. } else if (arg == "--gpu-layers" || arg == "-ngl" || arg == "--n-gpu-layers") {
  500. if (++i >= argc) {
  501. invalid_param = true;
  502. break;
  503. }
  504. #ifdef LLAMA_SUPPORTS_GPU_OFFLOAD
  505. params.n_gpu_layers = std::stoi(argv[i]);
  506. #else
  507. fprintf(stderr, "warning: not compiled with GPU offload support, --n-gpu-layers option will be ignored\n");
  508. fprintf(stderr, "warning: see main README.md for information on enabling GPU BLAS support\n");
  509. #endif
  510. } else if (arg == "--gpu-layers-draft" || arg == "-ngld" || arg == "--n-gpu-layers-draft") {
  511. if (++i >= argc) {
  512. invalid_param = true;
  513. break;
  514. }
  515. #ifdef LLAMA_SUPPORTS_GPU_OFFLOAD
  516. params.n_gpu_layers_draft = std::stoi(argv[i]);
  517. #else
  518. fprintf(stderr, "warning: not compiled with GPU offload support, --n-gpu-layers-draft option will be ignored\n");
  519. fprintf(stderr, "warning: see main README.md for information on enabling GPU BLAS support\n");
  520. #endif
  521. } else if (arg == "--main-gpu" || arg == "-mg") {
  522. if (++i >= argc) {
  523. invalid_param = true;
  524. break;
  525. }
  526. #ifdef GGML_USE_CUBLAS
  527. params.main_gpu = std::stoi(argv[i]);
  528. #else
  529. fprintf(stderr, "warning: llama.cpp was compiled without cuBLAS. It is not possible to set a main GPU.\n");
  530. #endif
  531. } else if (arg == "--tensor-split" || arg == "-ts") {
  532. if (++i >= argc) {
  533. invalid_param = true;
  534. break;
  535. }
  536. #ifdef GGML_USE_CUBLAS
  537. std::string arg_next = argv[i];
  538. // split string by , and /
  539. const std::regex regex{R"([,/]+)"};
  540. std::sregex_token_iterator it{arg_next.begin(), arg_next.end(), regex, -1};
  541. std::vector<std::string> split_arg{it, {}};
  542. GGML_ASSERT(split_arg.size() <= LLAMA_MAX_DEVICES);
  543. for (size_t i = 0; i < LLAMA_MAX_DEVICES; ++i) {
  544. if (i < split_arg.size()) {
  545. params.tensor_split[i] = std::stof(split_arg[i]);
  546. } else {
  547. params.tensor_split[i] = 0.0f;
  548. }
  549. }
  550. #else
  551. fprintf(stderr, "warning: llama.cpp was compiled without cuBLAS. It is not possible to set a tensor split.\n");
  552. #endif // GGML_USE_CUBLAS
  553. } else if (arg == "--no-mul-mat-q" || arg == "-nommq") {
  554. #ifdef GGML_USE_CUBLAS
  555. params.mul_mat_q = false;
  556. #else
  557. fprintf(stderr, "warning: llama.cpp was compiled without cuBLAS. Disabling mul_mat_q kernels has no effect.\n");
  558. #endif // GGML_USE_CUBLAS
  559. } else if (arg == "--no-mmap") {
  560. params.use_mmap = false;
  561. } else if (arg == "--numa") {
  562. params.numa = true;
  563. } else if (arg == "--verbose-prompt") {
  564. params.verbose_prompt = true;
  565. } else if (arg == "-r" || arg == "--reverse-prompt") {
  566. if (++i >= argc) {
  567. invalid_param = true;
  568. break;
  569. }
  570. params.antiprompt.push_back(argv[i]);
  571. } else if (arg == "-ld" || arg == "--logdir") {
  572. if (++i >= argc) {
  573. invalid_param = true;
  574. break;
  575. }
  576. params.logdir = argv[i];
  577. if (params.logdir.back() != DIRECTORY_SEPARATOR) {
  578. params.logdir += DIRECTORY_SEPARATOR;
  579. }
  580. } else if (arg == "--perplexity" || arg == "--all-logits") {
  581. params.logits_all = true;
  582. } else if (arg == "--ppl-stride") {
  583. if (++i >= argc) {
  584. invalid_param = true;
  585. break;
  586. }
  587. params.ppl_stride = std::stoi(argv[i]);
  588. } else if (arg == "--ppl-output-type") {
  589. if (++i >= argc) {
  590. invalid_param = true;
  591. break;
  592. }
  593. params.ppl_output_type = std::stoi(argv[i]);
  594. } else if (arg == "--hellaswag") {
  595. params.hellaswag = true;
  596. } else if (arg == "--hellaswag-tasks") {
  597. if (++i >= argc) {
  598. invalid_param = true;
  599. break;
  600. }
  601. params.hellaswag_tasks = std::stoi(argv[i]);
  602. } else if (arg == "--ignore-eos") {
  603. params.ignore_eos = true;
  604. } else if (arg == "--no-penalize-nl") {
  605. sparams.penalize_nl = false;
  606. } else if (arg == "-l" || arg == "--logit-bias") {
  607. if (++i >= argc) {
  608. invalid_param = true;
  609. break;
  610. }
  611. std::stringstream ss(argv[i]);
  612. llama_token key;
  613. char sign;
  614. std::string value_str;
  615. try {
  616. if (ss >> key && ss >> sign && std::getline(ss, value_str) && (sign == '+' || sign == '-')) {
  617. sparams.logit_bias[key] = std::stof(value_str) * ((sign == '-') ? -1.0f : 1.0f);
  618. } else {
  619. throw std::exception();
  620. }
  621. } catch (const std::exception&) {
  622. invalid_param = true;
  623. break;
  624. }
  625. } else if (arg == "-h" || arg == "--help") {
  626. return false;
  627. } else if (arg == "--random-prompt") {
  628. params.random_prompt = true;
  629. } else if (arg == "--in-prefix-bos") {
  630. params.input_prefix_bos = true;
  631. } else if (arg == "--in-prefix") {
  632. if (++i >= argc) {
  633. invalid_param = true;
  634. break;
  635. }
  636. params.input_prefix = argv[i];
  637. } else if (arg == "--in-suffix") {
  638. if (++i >= argc) {
  639. invalid_param = true;
  640. break;
  641. }
  642. params.input_suffix = argv[i];
  643. } else if (arg == "--grammar") {
  644. if (++i >= argc) {
  645. invalid_param = true;
  646. break;
  647. }
  648. sparams.grammar = argv[i];
  649. } else if (arg == "--grammar-file") {
  650. if (++i >= argc) {
  651. invalid_param = true;
  652. break;
  653. }
  654. std::ifstream file(argv[i]);
  655. if (!file) {
  656. fprintf(stderr, "error: failed to open file '%s'\n", argv[i]);
  657. invalid_param = true;
  658. break;
  659. }
  660. std::copy(
  661. std::istreambuf_iterator<char>(file),
  662. std::istreambuf_iterator<char>(),
  663. std::back_inserter(sparams.grammar)
  664. );
  665. #ifndef LOG_DISABLE_LOGS
  666. // Parse args for logging parameters
  667. } else if ( log_param_single_parse( argv[i] ) ) {
  668. // Do nothing, log_param_single_parse automatically does it's thing
  669. // and returns if a match was found and parsed.
  670. } else if ( log_param_pair_parse( /*check_but_dont_parse*/ true, argv[i] ) ) {
  671. // We have a matching known parameter requiring an argument,
  672. // now we need to check if there is anything after this argv
  673. // and flag invalid_param or parse it.
  674. if (++i >= argc) {
  675. invalid_param = true;
  676. break;
  677. }
  678. if( !log_param_pair_parse( /*check_but_dont_parse*/ false, argv[i-1], argv[i]) ) {
  679. invalid_param = true;
  680. break;
  681. }
  682. // End of Parse args for logging parameters
  683. #endif // LOG_DISABLE_LOGS
  684. } else {
  685. throw std::invalid_argument("error: unknown argument: " + arg);
  686. }
  687. }
  688. if (invalid_param) {
  689. throw std::invalid_argument("error: invalid parameter for argument: " + arg);
  690. }
  691. if (params.prompt_cache_all &&
  692. (params.interactive || params.interactive_first ||
  693. params.instruct)) {
  694. throw std::invalid_argument("error: --prompt-cache-all not supported in interactive mode yet\n");
  695. }
  696. if (params.escape) {
  697. process_escapes(params.prompt);
  698. process_escapes(params.input_prefix);
  699. process_escapes(params.input_suffix);
  700. process_escapes(sparams.cfg_negative_prompt);
  701. for (auto & antiprompt : params.antiprompt) {
  702. process_escapes(antiprompt);
  703. }
  704. }
  705. return true;
  706. }
  707. void gpt_print_usage(int /*argc*/, char ** argv, const gpt_params & params) {
  708. const llama_sampling_params & sparams = params.sparams;
  709. printf("\n");
  710. printf("usage: %s [options]\n", argv[0]);
  711. printf("\n");
  712. printf("options:\n");
  713. printf(" -h, --help show this help message and exit\n");
  714. printf(" -i, --interactive run in interactive mode\n");
  715. printf(" --interactive-first run in interactive mode and wait for input right away\n");
  716. printf(" -ins, --instruct run in instruction mode (use with Alpaca models)\n");
  717. printf(" -cml, --chatml run in chatml mode (use with ChatML-compatible models)\n");
  718. printf(" --multiline-input allows you to write or paste multiple lines without ending each in '\\'\n");
  719. printf(" -r PROMPT, --reverse-prompt PROMPT\n");
  720. printf(" halt generation at PROMPT, return control in interactive mode\n");
  721. printf(" (can be specified more than once for multiple prompts).\n");
  722. printf(" --color colorise output to distinguish prompt and user input from generations\n");
  723. printf(" -s SEED, --seed SEED RNG seed (default: -1, use random seed for < 0)\n");
  724. printf(" -t N, --threads N number of threads to use during generation (default: %d)\n", params.n_threads);
  725. printf(" -tb N, --threads-batch N\n");
  726. printf(" number of threads to use during batch and prompt processing (default: same as --threads)\n");
  727. printf(" -p PROMPT, --prompt PROMPT\n");
  728. printf(" prompt to start generation with (default: empty)\n");
  729. printf(" -e, --escape process prompt escapes sequences (\\n, \\r, \\t, \\', \\\", \\\\)\n");
  730. printf(" --prompt-cache FNAME file to cache prompt state for faster startup (default: none)\n");
  731. printf(" --prompt-cache-all if specified, saves user input and generations to cache as well.\n");
  732. printf(" not supported with --interactive or other interactive options\n");
  733. printf(" --prompt-cache-ro if specified, uses the prompt cache but does not update it.\n");
  734. printf(" --random-prompt start with a randomized prompt.\n");
  735. printf(" --in-prefix-bos prefix BOS to user inputs, preceding the `--in-prefix` string\n");
  736. printf(" --in-prefix STRING string to prefix user inputs with (default: empty)\n");
  737. printf(" --in-suffix STRING string to suffix after user inputs with (default: empty)\n");
  738. printf(" -f FNAME, --file FNAME\n");
  739. printf(" prompt file to start generation.\n");
  740. printf(" -n N, --n-predict N number of tokens to predict (default: %d, -1 = infinity, -2 = until context filled)\n", params.n_predict);
  741. printf(" -c N, --ctx-size N size of the prompt context (default: %d, 0 = loaded from model)\n", params.n_ctx);
  742. printf(" -b N, --batch-size N batch size for prompt processing (default: %d)\n", params.n_batch);
  743. printf(" --top-k N top-k sampling (default: %d, 0 = disabled)\n", sparams.top_k);
  744. printf(" --top-p N top-p sampling (default: %.1f, 1.0 = disabled)\n", (double)sparams.top_p);
  745. printf(" --min-p N min-p sampling (default: %.1f, 0.0 = disabled)\n", (double)sparams.min_p);
  746. printf(" --tfs N tail free sampling, parameter z (default: %.1f, 1.0 = disabled)\n", (double)sparams.tfs_z);
  747. printf(" --typical N locally typical sampling, parameter p (default: %.1f, 1.0 = disabled)\n", (double)sparams.typical_p);
  748. printf(" --repeat-last-n N last n tokens to consider for penalize (default: %d, 0 = disabled, -1 = ctx_size)\n", sparams.penalty_last_n);
  749. printf(" --repeat-penalty N penalize repeat sequence of tokens (default: %.1f, 1.0 = disabled)\n", (double)sparams.penalty_repeat);
  750. printf(" --presence-penalty N repeat alpha presence penalty (default: %.1f, 0.0 = disabled)\n", (double)sparams.penalty_present);
  751. printf(" --frequency-penalty N repeat alpha frequency penalty (default: %.1f, 0.0 = disabled)\n", (double)sparams.penalty_freq);
  752. printf(" --mirostat N use Mirostat sampling.\n");
  753. printf(" Top K, Nucleus, Tail Free and Locally Typical samplers are ignored if used.\n");
  754. printf(" (default: %d, 0 = disabled, 1 = Mirostat, 2 = Mirostat 2.0)\n", sparams.mirostat);
  755. printf(" --mirostat-lr N Mirostat learning rate, parameter eta (default: %.1f)\n", (double)sparams.mirostat_eta);
  756. printf(" --mirostat-ent N Mirostat target entropy, parameter tau (default: %.1f)\n", (double)sparams.mirostat_tau);
  757. printf(" -l TOKEN_ID(+/-)BIAS, --logit-bias TOKEN_ID(+/-)BIAS\n");
  758. printf(" modifies the likelihood of token appearing in the completion,\n");
  759. printf(" i.e. `--logit-bias 15043+1` to increase likelihood of token ' Hello',\n");
  760. printf(" or `--logit-bias 15043-1` to decrease likelihood of token ' Hello'\n");
  761. printf(" --grammar GRAMMAR BNF-like grammar to constrain generations (see samples in grammars/ dir)\n");
  762. printf(" --grammar-file FNAME file to read grammar from\n");
  763. printf(" --cfg-negative-prompt PROMPT\n");
  764. printf(" negative prompt to use for guidance. (default: empty)\n");
  765. printf(" --cfg-negative-prompt-file FNAME\n");
  766. printf(" negative prompt file to use for guidance. (default: empty)\n");
  767. printf(" --cfg-scale N strength of guidance (default: %f, 1.0 = disable)\n", sparams.cfg_scale);
  768. printf(" --rope-scaling {none,linear,yarn}\n");
  769. printf(" RoPE frequency scaling method, defaults to linear unless specified by the model\n");
  770. printf(" --rope-scale N RoPE context scaling factor, expands context by a factor of N\n");
  771. printf(" --rope-freq-base N RoPE base frequency, used by NTK-aware scaling (default: loaded from model)\n");
  772. printf(" --rope-freq-scale N RoPE frequency scaling factor, expands context by a factor of 1/N\n");
  773. printf(" --yarn-orig-ctx N YaRN: original context size of model (default: 0 = model training context size)\n");
  774. printf(" --yarn-ext-factor N YaRN: extrapolation mix factor (default: 1.0, 0.0 = full interpolation)\n");
  775. printf(" --yarn-attn-factor N YaRN: scale sqrt(t) or attention magnitude (default: 1.0)\n");
  776. printf(" --yarn-beta-slow N YaRN: high correction dim or alpha (default: %.1f)\n", params.yarn_beta_slow);
  777. printf(" --yarn-beta-fast N YaRN: low correction dim or beta (default: %.1f)\n", params.yarn_beta_fast);
  778. printf(" --ignore-eos ignore end of stream token and continue generating (implies --logit-bias 2-inf)\n");
  779. printf(" --no-penalize-nl do not penalize newline token\n");
  780. printf(" --memory-f32 use f32 instead of f16 for memory key+value (default: disabled)\n");
  781. printf(" not recommended: doubles context memory required and no measurable increase in quality\n");
  782. printf(" --temp N temperature (default: %.1f)\n", (double)sparams.temp);
  783. printf(" --logits-all return logits for all tokens in the batch (default: disabled)\n");
  784. printf(" --hellaswag compute HellaSwag score over random tasks from datafile supplied with -f\n");
  785. printf(" --hellaswag-tasks N number of tasks to use when computing the HellaSwag score (default: %zu)\n", params.hellaswag_tasks);
  786. printf(" --keep N number of tokens to keep from the initial prompt (default: %d, -1 = all)\n", params.n_keep);
  787. printf(" --draft N number of tokens to draft for speculative decoding (default: %d)\n", params.n_draft);
  788. printf(" --chunks N max number of chunks to process (default: %d, -1 = all)\n", params.n_chunks);
  789. printf(" -np N, --parallel N number of parallel sequences to decode (default: %d)\n", params.n_parallel);
  790. printf(" -ns N, --sequences N number of sequences to decode (default: %d)\n", params.n_sequences);
  791. printf(" -pa N, --p-accept N speculative decoding accept probability (default: %.1f)\n", (double)params.p_accept);
  792. printf(" -ps N, --p-split N speculative decoding split probability (default: %.1f)\n", (double)params.p_split);
  793. printf(" -cb, --cont-batching enable continuous batching (a.k.a dynamic batching) (default: disabled)\n");
  794. printf(" --mmproj MMPROJ_FILE path to a multimodal projector file for LLaVA. see examples/llava/README.md\n");
  795. printf(" --image IMAGE_FILE path to an image file. use with multimodal models\n");
  796. if (llama_mlock_supported()) {
  797. printf(" --mlock force system to keep model in RAM rather than swapping or compressing\n");
  798. }
  799. if (llama_mmap_supported()) {
  800. printf(" --no-mmap do not memory-map model (slower load but may reduce pageouts if not using mlock)\n");
  801. }
  802. printf(" --numa attempt optimizations that help on some NUMA systems\n");
  803. printf(" if run without this previously, it is recommended to drop the system page cache before using this\n");
  804. printf(" see https://github.com/ggerganov/llama.cpp/issues/1437\n");
  805. #ifdef LLAMA_SUPPORTS_GPU_OFFLOAD
  806. printf(" -ngl N, --n-gpu-layers N\n");
  807. printf(" number of layers to store in VRAM\n");
  808. printf(" -ngld N, --n-gpu-layers-draft N\n");
  809. printf(" number of layers to store in VRAM for the draft model\n");
  810. printf(" -ts SPLIT --tensor-split SPLIT\n");
  811. printf(" how to split tensors across multiple GPUs, comma-separated list of proportions, e.g. 3,1\n");
  812. printf(" -mg i, --main-gpu i the GPU to use for scratch and small tensors\n");
  813. #ifdef GGML_USE_CUBLAS
  814. printf(" -nommq, --no-mul-mat-q\n");
  815. printf(" use " GGML_CUBLAS_NAME " instead of custom mul_mat_q " GGML_CUDA_NAME " kernels.\n");
  816. printf(" Not recommended since this is both slower and uses more VRAM.\n");
  817. #endif // GGML_USE_CUBLAS
  818. #endif
  819. printf(" --verbose-prompt print prompt before generation\n");
  820. printf(" -dkvc, --dump-kv-cache\n");
  821. printf(" verbose print of the KV cache\n");
  822. printf(" --simple-io use basic IO for better compatibility in subprocesses and limited consoles\n");
  823. printf(" --lora FNAME apply LoRA adapter (implies --no-mmap)\n");
  824. printf(" --lora-scaled FNAME S apply LoRA adapter with user defined scaling S (implies --no-mmap)\n");
  825. printf(" --lora-base FNAME optional model to use as a base for the layers modified by the LoRA adapter\n");
  826. printf(" -m FNAME, --model FNAME\n");
  827. printf(" model path (default: %s)\n", params.model.c_str());
  828. printf(" -md FNAME, --model-draft FNAME\n");
  829. printf(" draft model for speculative decoding (default: %s)\n", params.model.c_str());
  830. printf(" -ld LOGDIR, --logdir LOGDIR\n");
  831. printf(" path under which to save YAML logs (no logging if unset)\n");
  832. printf("\n");
  833. #ifndef LOG_DISABLE_LOGS
  834. log_print_usage();
  835. #endif // LOG_DISABLE_LOGS
  836. }
  837. std::string get_system_info(const gpt_params & params) {
  838. std::ostringstream os;
  839. os << "system_info: n_threads = " << params.n_threads;
  840. if (params.n_threads_batch != -1) {
  841. os << " (n_threads_batch = " << params.n_threads_batch << ")";
  842. }
  843. os << " / " << std::thread::hardware_concurrency() << " | " << llama_print_system_info();
  844. return os.str();
  845. }
  846. std::string gpt_random_prompt(std::mt19937 & rng) {
  847. const int r = rng() % 10;
  848. switch (r) {
  849. case 0: return "So";
  850. case 1: return "Once upon a time";
  851. case 2: return "When";
  852. case 3: return "The";
  853. case 4: return "After";
  854. case 5: return "If";
  855. case 6: return "import";
  856. case 7: return "He";
  857. case 8: return "She";
  858. case 9: return "They";
  859. }
  860. GGML_UNREACHABLE();
  861. }
  862. //
  863. // Model utils
  864. //
  865. struct llama_model_params llama_model_params_from_gpt_params(const gpt_params & params) {
  866. auto mparams = llama_model_default_params();
  867. if (params.n_gpu_layers != -1) {
  868. mparams.n_gpu_layers = params.n_gpu_layers;
  869. }
  870. mparams.main_gpu = params.main_gpu;
  871. mparams.tensor_split = params.tensor_split;
  872. mparams.use_mmap = params.use_mmap;
  873. mparams.use_mlock = params.use_mlock;
  874. return mparams;
  875. }
  876. struct llama_context_params llama_context_params_from_gpt_params(const gpt_params & params) {
  877. auto cparams = llama_context_default_params();
  878. cparams.n_ctx = params.n_ctx;
  879. cparams.n_batch = params.n_batch;
  880. cparams.n_threads = params.n_threads;
  881. cparams.n_threads_batch = params.n_threads_batch == -1 ? params.n_threads : params.n_threads_batch;
  882. cparams.mul_mat_q = params.mul_mat_q;
  883. cparams.seed = params.seed;
  884. cparams.f16_kv = params.memory_f16;
  885. cparams.logits_all = params.logits_all;
  886. cparams.embedding = params.embedding;
  887. cparams.rope_scaling_type = params.rope_scaling_type;
  888. cparams.rope_freq_base = params.rope_freq_base;
  889. cparams.rope_freq_scale = params.rope_freq_scale;
  890. cparams.yarn_ext_factor = params.yarn_ext_factor;
  891. cparams.yarn_attn_factor = params.yarn_attn_factor;
  892. cparams.yarn_beta_fast = params.yarn_beta_fast;
  893. cparams.yarn_beta_slow = params.yarn_beta_slow;
  894. cparams.yarn_orig_ctx = params.yarn_orig_ctx;
  895. return cparams;
  896. }
  897. void llama_batch_clear(struct llama_batch & batch) {
  898. batch.n_tokens = 0;
  899. }
  900. void llama_batch_add(
  901. struct llama_batch & batch,
  902. llama_token id,
  903. llama_pos pos,
  904. const std::vector<llama_seq_id> & seq_ids,
  905. bool logits) {
  906. batch.token [batch.n_tokens] = id;
  907. batch.pos [batch.n_tokens] = pos;
  908. batch.n_seq_id[batch.n_tokens] = seq_ids.size();
  909. for (size_t i = 0; i < seq_ids.size(); ++i) {
  910. batch.seq_id[batch.n_tokens][i] = seq_ids[i];
  911. }
  912. batch.logits [batch.n_tokens] = logits;
  913. batch.n_tokens++;
  914. }
  915. std::tuple<struct llama_model *, struct llama_context *> llama_init_from_gpt_params(gpt_params & params) {
  916. auto mparams = llama_model_params_from_gpt_params(params);
  917. llama_model * model = llama_load_model_from_file(params.model.c_str(), mparams);
  918. if (model == NULL) {
  919. fprintf(stderr, "%s: error: failed to load model '%s'\n", __func__, params.model.c_str());
  920. return std::make_tuple(nullptr, nullptr);
  921. }
  922. auto cparams = llama_context_params_from_gpt_params(params);
  923. llama_context * lctx = llama_new_context_with_model(model, cparams);
  924. if (lctx == NULL) {
  925. fprintf(stderr, "%s: error: failed to create context with model '%s'\n", __func__, params.model.c_str());
  926. llama_free_model(model);
  927. return std::make_tuple(nullptr, nullptr);
  928. }
  929. for (unsigned int i = 0; i < params.lora_adapter.size(); ++i) {
  930. const std::string& lora_adapter = std::get<0>(params.lora_adapter[i]);
  931. float lora_scale = std::get<1>(params.lora_adapter[i]);
  932. int err = llama_model_apply_lora_from_file(model,
  933. lora_adapter.c_str(),
  934. lora_scale,
  935. ((i > 0) || params.lora_base.empty())
  936. ? NULL
  937. : params.lora_base.c_str(),
  938. params.n_threads);
  939. if (err != 0) {
  940. fprintf(stderr, "%s: error: failed to apply lora adapter\n", __func__);
  941. llama_free(lctx);
  942. llama_free_model(model);
  943. return std::make_tuple(nullptr, nullptr);
  944. }
  945. }
  946. if (params.ignore_eos) {
  947. params.sparams.logit_bias[llama_token_eos(model)] = -INFINITY;
  948. }
  949. {
  950. LOG("warming up the model with an empty run\n");
  951. std::vector<llama_token> tmp = { llama_token_bos(model), llama_token_eos(model), };
  952. llama_decode(lctx, llama_batch_get_one(tmp.data(), std::min(tmp.size(), (size_t) params.n_batch), 0, 0));
  953. llama_kv_cache_clear(lctx);
  954. llama_reset_timings(lctx);
  955. }
  956. return std::make_tuple(model, lctx);
  957. }
  958. //
  959. // Vocab utils
  960. //
  961. std::vector<llama_token> llama_tokenize(
  962. const struct llama_context * ctx,
  963. const std::string & text,
  964. bool add_bos,
  965. bool special) {
  966. return llama_tokenize(llama_get_model(ctx), text, add_bos, special);
  967. }
  968. std::vector<llama_token> llama_tokenize(
  969. const struct llama_model * model,
  970. const std::string & text,
  971. bool add_bos,
  972. bool special) {
  973. // upper limit for the number of tokens
  974. int n_tokens = text.length() + add_bos;
  975. std::vector<llama_token> result(n_tokens);
  976. n_tokens = llama_tokenize(model, text.data(), text.length(), result.data(), result.size(), add_bos, special);
  977. if (n_tokens < 0) {
  978. result.resize(-n_tokens);
  979. int check = llama_tokenize(model, text.data(), text.length(), result.data(), result.size(), add_bos, special);
  980. GGML_ASSERT(check == -n_tokens);
  981. } else {
  982. result.resize(n_tokens);
  983. }
  984. return result;
  985. }
  986. std::string llama_token_to_piece(const struct llama_context * ctx, llama_token token) {
  987. std::vector<char> result(8, 0);
  988. const int n_tokens = llama_token_to_piece(llama_get_model(ctx), token, result.data(), result.size());
  989. if (n_tokens < 0) {
  990. result.resize(-n_tokens);
  991. int check = llama_token_to_piece(llama_get_model(ctx), token, result.data(), result.size());
  992. GGML_ASSERT(check == -n_tokens);
  993. } else {
  994. result.resize(n_tokens);
  995. }
  996. return std::string(result.data(), result.size());
  997. }
  998. std::string llama_detokenize_spm(llama_context * ctx, const std::vector<llama_token> & tokens) {
  999. const llama_token bos_id = llama_token_bos(llama_get_model(ctx));
  1000. std::string piece;
  1001. std::string result;
  1002. for (size_t i = 0; i < tokens.size(); ++i) {
  1003. piece = llama_token_to_piece(ctx, tokens[i]);
  1004. // remove the leading space of the first non-BOS token
  1005. if (((tokens[0] == bos_id && i == 1) || (tokens[0] != bos_id && i == 0)) && piece[0] == ' ') {
  1006. piece = piece.substr(1);
  1007. }
  1008. result += piece;
  1009. }
  1010. return result;
  1011. }
  1012. std::string llama_detokenize_bpe(llama_context * ctx, const std::vector<llama_token> & tokens) {
  1013. std::string piece;
  1014. std::string result;
  1015. for (size_t i = 0; i < tokens.size(); ++i) {
  1016. piece = llama_token_to_piece(ctx, tokens[i]);
  1017. result += piece;
  1018. }
  1019. // NOTE: the original tokenizer decodes bytes after collecting the pieces.
  1020. return result;
  1021. }
  1022. bool llama_should_add_bos_token(const llama_model * model) {
  1023. const int add_bos = llama_add_bos_token(model);
  1024. return add_bos != -1 ? bool(add_bos) : (llama_vocab_type(model) == LLAMA_VOCAB_TYPE_SPM);
  1025. }
  1026. //
  1027. // YAML utils
  1028. //
  1029. // returns true if successful, false otherwise
  1030. bool create_directory_with_parents(const std::string & path) {
  1031. #ifdef _WIN32
  1032. std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;
  1033. std::wstring wpath = converter.from_bytes(path);
  1034. // if the path already exists, check whether it's a directory
  1035. const DWORD attributes = GetFileAttributesW(wpath.c_str());
  1036. if ((attributes != INVALID_FILE_ATTRIBUTES) && (attributes & FILE_ATTRIBUTE_DIRECTORY)) {
  1037. return true;
  1038. }
  1039. size_t pos_slash = 0;
  1040. // process path from front to back, procedurally creating directories
  1041. while ((pos_slash = path.find('\\', pos_slash)) != std::string::npos) {
  1042. const std::wstring subpath = wpath.substr(0, pos_slash);
  1043. const wchar_t * test = subpath.c_str();
  1044. const bool success = CreateDirectoryW(test, NULL);
  1045. if (!success) {
  1046. const DWORD error = GetLastError();
  1047. // if the path already exists, ensure that it's a directory
  1048. if (error == ERROR_ALREADY_EXISTS) {
  1049. const DWORD attributes = GetFileAttributesW(subpath.c_str());
  1050. if (attributes == INVALID_FILE_ATTRIBUTES || !(attributes & FILE_ATTRIBUTE_DIRECTORY)) {
  1051. return false;
  1052. }
  1053. } else {
  1054. return false;
  1055. }
  1056. }
  1057. pos_slash += 1;
  1058. }
  1059. return true;
  1060. #else
  1061. // if the path already exists, check whether it's a directory
  1062. struct stat info;
  1063. if (stat(path.c_str(), &info) == 0) {
  1064. return S_ISDIR(info.st_mode);
  1065. }
  1066. size_t pos_slash = 1; // skip leading slashes for directory creation
  1067. // process path from front to back, procedurally creating directories
  1068. while ((pos_slash = path.find('/', pos_slash)) != std::string::npos) {
  1069. const std::string subpath = path.substr(0, pos_slash);
  1070. struct stat info;
  1071. // if the path already exists, ensure that it's a directory
  1072. if (stat(subpath.c_str(), &info) == 0) {
  1073. if (!S_ISDIR(info.st_mode)) {
  1074. return false;
  1075. }
  1076. } else {
  1077. // create parent directories
  1078. const int ret = mkdir(subpath.c_str(), 0755);
  1079. if (ret != 0) {
  1080. return false;
  1081. }
  1082. }
  1083. pos_slash += 1;
  1084. }
  1085. return true;
  1086. #endif // _WIN32
  1087. }
  1088. void dump_vector_float_yaml(FILE * stream, const char * prop_name, const std::vector<float> & data) {
  1089. if (data.empty()) {
  1090. fprintf(stream, "%s:\n", prop_name);
  1091. return;
  1092. }
  1093. fprintf(stream, "%s: [", prop_name);
  1094. for (size_t i = 0; i < data.size() - 1; ++i) {
  1095. fprintf(stream, "%e, ", data[i]);
  1096. }
  1097. fprintf(stream, "%e]\n", data.back());
  1098. }
  1099. void dump_vector_int_yaml(FILE * stream, const char * prop_name, const std::vector<int> & data) {
  1100. if (data.empty()) {
  1101. fprintf(stream, "%s:\n", prop_name);
  1102. return;
  1103. }
  1104. fprintf(stream, "%s: [", prop_name);
  1105. for (size_t i = 0; i < data.size() - 1; ++i) {
  1106. fprintf(stream, "%d, ", data[i]);
  1107. }
  1108. fprintf(stream, "%d]\n", data.back());
  1109. }
  1110. void dump_string_yaml_multiline(FILE * stream, const char * prop_name, const char * data) {
  1111. std::string data_str(data == NULL ? "" : data);
  1112. if (data_str.empty()) {
  1113. fprintf(stream, "%s:\n", prop_name);
  1114. return;
  1115. }
  1116. size_t pos_start = 0;
  1117. size_t pos_found = 0;
  1118. if (!data_str.empty() && (std::isspace(data_str[0]) || std::isspace(data_str.back()))) {
  1119. data_str = std::regex_replace(data_str, std::regex("\n"), "\\n");
  1120. data_str = std::regex_replace(data_str, std::regex("\""), "\\\"");
  1121. data_str = std::regex_replace(data_str, std::regex(R"(\\[^n"])"), R"(\$&)");
  1122. data_str = "\"" + data_str + "\"";
  1123. fprintf(stream, "%s: %s\n", prop_name, data_str.c_str());
  1124. return;
  1125. }
  1126. if (data_str.find('\n') == std::string::npos) {
  1127. fprintf(stream, "%s: %s\n", prop_name, data_str.c_str());
  1128. return;
  1129. }
  1130. fprintf(stream, "%s: |\n", prop_name);
  1131. while ((pos_found = data_str.find('\n', pos_start)) != std::string::npos) {
  1132. fprintf(stream, " %s\n", data_str.substr(pos_start, pos_found-pos_start).c_str());
  1133. pos_start = pos_found + 1;
  1134. }
  1135. }
  1136. std::string get_sortable_timestamp() {
  1137. using clock = std::chrono::system_clock;
  1138. const clock::time_point current_time = clock::now();
  1139. const time_t as_time_t = clock::to_time_t(current_time);
  1140. char timestamp_no_ns[100];
  1141. std::strftime(timestamp_no_ns, 100, "%Y_%m_%d-%H_%M_%S", std::localtime(&as_time_t));
  1142. const int64_t ns = std::chrono::duration_cast<std::chrono::nanoseconds>(
  1143. current_time.time_since_epoch() % 1000000000).count();
  1144. char timestamp_ns[11];
  1145. snprintf(timestamp_ns, 11, "%09" PRId64, ns);
  1146. return std::string(timestamp_no_ns) + "." + std::string(timestamp_ns);
  1147. }
  1148. void dump_non_result_info_yaml(FILE * stream, const gpt_params & params, const llama_context * lctx,
  1149. const std::string & timestamp, const std::vector<int> & prompt_tokens, const char * model_desc) {
  1150. const llama_sampling_params & sparams = params.sparams;
  1151. fprintf(stream, "build_commit: %s\n", LLAMA_COMMIT);
  1152. fprintf(stream, "build_number: %d\n", LLAMA_BUILD_NUMBER);
  1153. fprintf(stream, "cpu_has_arm_fma: %s\n", ggml_cpu_has_arm_fma() ? "true" : "false");
  1154. fprintf(stream, "cpu_has_avx: %s\n", ggml_cpu_has_avx() ? "true" : "false");
  1155. fprintf(stream, "cpu_has_avx2: %s\n", ggml_cpu_has_avx2() ? "true" : "false");
  1156. fprintf(stream, "cpu_has_avx512: %s\n", ggml_cpu_has_avx512() ? "true" : "false");
  1157. fprintf(stream, "cpu_has_avx512_vbmi: %s\n", ggml_cpu_has_avx512_vbmi() ? "true" : "false");
  1158. fprintf(stream, "cpu_has_avx512_vnni: %s\n", ggml_cpu_has_avx512_vnni() ? "true" : "false");
  1159. fprintf(stream, "cpu_has_blas: %s\n", ggml_cpu_has_blas() ? "true" : "false");
  1160. fprintf(stream, "cpu_has_cublas: %s\n", ggml_cpu_has_cublas() ? "true" : "false");
  1161. fprintf(stream, "cpu_has_clblast: %s\n", ggml_cpu_has_clblast() ? "true" : "false");
  1162. fprintf(stream, "cpu_has_fma: %s\n", ggml_cpu_has_fma() ? "true" : "false");
  1163. fprintf(stream, "cpu_has_gpublas: %s\n", ggml_cpu_has_gpublas() ? "true" : "false");
  1164. fprintf(stream, "cpu_has_neon: %s\n", ggml_cpu_has_neon() ? "true" : "false");
  1165. fprintf(stream, "cpu_has_f16c: %s\n", ggml_cpu_has_f16c() ? "true" : "false");
  1166. fprintf(stream, "cpu_has_fp16_va: %s\n", ggml_cpu_has_fp16_va() ? "true" : "false");
  1167. fprintf(stream, "cpu_has_wasm_simd: %s\n", ggml_cpu_has_wasm_simd() ? "true" : "false");
  1168. fprintf(stream, "cpu_has_blas: %s\n", ggml_cpu_has_blas() ? "true" : "false");
  1169. fprintf(stream, "cpu_has_sse3: %s\n", ggml_cpu_has_sse3() ? "true" : "false");
  1170. fprintf(stream, "cpu_has_vsx: %s\n", ggml_cpu_has_vsx() ? "true" : "false");
  1171. #ifdef NDEBUG
  1172. fprintf(stream, "debug: false\n");
  1173. #else
  1174. fprintf(stream, "debug: true\n");
  1175. #endif // NDEBUG
  1176. fprintf(stream, "model_desc: %s\n", model_desc);
  1177. fprintf(stream, "n_vocab: %d # output size of the final layer, 32001 for some models\n", llama_n_vocab(llama_get_model(lctx)));
  1178. #ifdef __OPTIMIZE__
  1179. fprintf(stream, "optimize: true\n");
  1180. #else
  1181. fprintf(stream, "optimize: false\n");
  1182. #endif // __OPTIMIZE__
  1183. fprintf(stream, "time: %s\n", timestamp.c_str());
  1184. fprintf(stream, "\n");
  1185. fprintf(stream, "###############\n");
  1186. fprintf(stream, "# User Inputs #\n");
  1187. fprintf(stream, "###############\n");
  1188. fprintf(stream, "\n");
  1189. fprintf(stream, "alias: %s # default: unknown\n", params.model_alias.c_str());
  1190. fprintf(stream, "batch_size: %d # default: 512\n", params.n_batch);
  1191. dump_string_yaml_multiline(stream, "cfg_negative_prompt", sparams.cfg_negative_prompt.c_str());
  1192. fprintf(stream, "cfg_scale: %f # default: 1.0\n", sparams.cfg_scale);
  1193. fprintf(stream, "chunks: %d # default: -1 (unlimited)\n", params.n_chunks);
  1194. fprintf(stream, "color: %s # default: false\n", params.use_color ? "true" : "false");
  1195. fprintf(stream, "ctx_size: %d # default: 512\n", params.n_ctx);
  1196. fprintf(stream, "escape: %s # default: false\n", params.escape ? "true" : "false");
  1197. fprintf(stream, "file: # never logged, see prompt instead. Can still be specified for input.\n");
  1198. fprintf(stream, "frequency_penalty: %f # default: 0.0 \n", sparams.penalty_freq);
  1199. dump_string_yaml_multiline(stream, "grammar", sparams.grammar.c_str());
  1200. fprintf(stream, "grammar-file: # never logged, see grammar instead. Can still be specified for input.\n");
  1201. fprintf(stream, "hellaswag: %s # default: false\n", params.hellaswag ? "true" : "false");
  1202. fprintf(stream, "hellaswag_tasks: %zu # default: 400\n", params.hellaswag_tasks);
  1203. const auto logit_bias_eos = sparams.logit_bias.find(llama_token_eos(llama_get_model(lctx)));
  1204. const bool ignore_eos = logit_bias_eos != sparams.logit_bias.end() && logit_bias_eos->second == -INFINITY;
  1205. fprintf(stream, "ignore_eos: %s # default: false\n", ignore_eos ? "true" : "false");
  1206. dump_string_yaml_multiline(stream, "in_prefix", params.input_prefix.c_str());
  1207. fprintf(stream, "in_prefix_bos: %s # default: false\n", params.input_prefix_bos ? "true" : "false");
  1208. dump_string_yaml_multiline(stream, "in_suffix", params.input_prefix.c_str());
  1209. fprintf(stream, "instruct: %s # default: false\n", params.instruct ? "true" : "false");
  1210. fprintf(stream, "interactive: %s # default: false\n", params.interactive ? "true" : "false");
  1211. fprintf(stream, "interactive_first: %s # default: false\n", params.interactive_first ? "true" : "false");
  1212. fprintf(stream, "keep: %d # default: 0\n", params.n_keep);
  1213. fprintf(stream, "logdir: %s # default: unset (no logging)\n", params.logdir.c_str());
  1214. fprintf(stream, "logit_bias:\n");
  1215. for (std::pair<llama_token, float> lb : sparams.logit_bias) {
  1216. if (ignore_eos && lb.first == logit_bias_eos->first) {
  1217. continue;
  1218. }
  1219. fprintf(stream, " %d: %f", lb.first, lb.second);
  1220. }
  1221. fprintf(stream, "lora:\n");
  1222. for (std::tuple<std::string, float> la : params.lora_adapter) {
  1223. if (std::get<1>(la) != 1.0f) {
  1224. continue;
  1225. }
  1226. fprintf(stream, " - %s\n", std::get<0>(la).c_str());
  1227. }
  1228. fprintf(stream, "lora_scaled:\n");
  1229. for (std::tuple<std::string, float> la : params.lora_adapter) {
  1230. if (std::get<1>(la) == 1.0f) {
  1231. continue;
  1232. }
  1233. fprintf(stream, " - %s: %f\n", std::get<0>(la).c_str(), std::get<1>(la));
  1234. }
  1235. fprintf(stream, "lora_base: %s\n", params.lora_base.c_str());
  1236. fprintf(stream, "main_gpu: %d # default: 0\n", params.main_gpu);
  1237. fprintf(stream, "memory_f32: %s # default: false\n", !params.memory_f16 ? "true" : "false");
  1238. fprintf(stream, "mirostat: %d # default: 0 (disabled)\n", sparams.mirostat);
  1239. fprintf(stream, "mirostat_ent: %f # default: 5.0\n", sparams.mirostat_tau);
  1240. fprintf(stream, "mirostat_lr: %f # default: 0.1\n", sparams.mirostat_eta);
  1241. fprintf(stream, "mlock: %s # default: false\n", params.use_mlock ? "true" : "false");
  1242. fprintf(stream, "model: %s # default: models/7B/ggml-model.bin\n", params.model.c_str());
  1243. fprintf(stream, "model_draft: %s # default:\n", params.model_draft.c_str());
  1244. fprintf(stream, "multiline_input: %s # default: false\n", params.multiline_input ? "true" : "false");
  1245. fprintf(stream, "n_gpu_layers: %d # default: -1\n", params.n_gpu_layers);
  1246. fprintf(stream, "n_predict: %d # default: -1 (unlimited)\n", params.n_predict);
  1247. fprintf(stream, "n_probs: %d # only used by server binary, default: 0\n", sparams.n_probs);
  1248. fprintf(stream, "no_mmap: %s # default: false\n", !params.use_mmap ? "true" : "false");
  1249. fprintf(stream, "no_mul_mat_q: %s # default: false\n", !params.mul_mat_q ? "true" : "false");
  1250. fprintf(stream, "no_penalize_nl: %s # default: false\n", !sparams.penalize_nl ? "true" : "false");
  1251. fprintf(stream, "numa: %s # default: false\n", params.numa ? "true" : "false");
  1252. fprintf(stream, "ppl_output_type: %d # default: 0\n", params.ppl_output_type);
  1253. fprintf(stream, "ppl_stride: %d # default: 0\n", params.ppl_stride);
  1254. fprintf(stream, "presence_penalty: %f # default: 0.0\n", sparams.penalty_present);
  1255. dump_string_yaml_multiline(stream, "prompt", params.prompt.c_str());
  1256. fprintf(stream, "prompt_cache: %s\n", params.path_prompt_cache.c_str());
  1257. fprintf(stream, "prompt_cache_all: %s # default: false\n", params.prompt_cache_all ? "true" : "false");
  1258. fprintf(stream, "prompt_cache_ro: %s # default: false\n", params.prompt_cache_ro ? "true" : "false");
  1259. dump_vector_int_yaml(stream, "prompt_tokens", prompt_tokens);
  1260. fprintf(stream, "random_prompt: %s # default: false\n", params.random_prompt ? "true" : "false");
  1261. fprintf(stream, "repeat_penalty: %f # default: 1.1\n", sparams.penalty_repeat);
  1262. fprintf(stream, "reverse_prompt:\n");
  1263. for (std::string ap : params.antiprompt) {
  1264. size_t pos = 0;
  1265. while ((pos = ap.find('\n', pos)) != std::string::npos) {
  1266. ap.replace(pos, 1, "\\n");
  1267. pos += 1;
  1268. }
  1269. fprintf(stream, " - %s\n", ap.c_str());
  1270. }
  1271. fprintf(stream, "rope_freq_base: %f # default: 10000.0\n", params.rope_freq_base);
  1272. fprintf(stream, "rope_freq_scale: %f # default: 1.0\n", params.rope_freq_scale);
  1273. fprintf(stream, "seed: %d # default: -1 (random seed)\n", params.seed);
  1274. fprintf(stream, "simple_io: %s # default: false\n", params.simple_io ? "true" : "false");
  1275. fprintf(stream, "cont_batching: %s # default: false\n", params.cont_batching ? "true" : "false");
  1276. fprintf(stream, "temp: %f # default: 0.8\n", sparams.temp);
  1277. const std::vector<float> tensor_split_vector(params.tensor_split, params.tensor_split + LLAMA_MAX_DEVICES);
  1278. dump_vector_float_yaml(stream, "tensor_split", tensor_split_vector);
  1279. fprintf(stream, "tfs: %f # default: 1.0\n", sparams.tfs_z);
  1280. fprintf(stream, "threads: %d # default: %d\n", params.n_threads, std::thread::hardware_concurrency());
  1281. fprintf(stream, "top_k: %d # default: 40\n", sparams.top_k);
  1282. fprintf(stream, "top_p: %f # default: 0.95\n", sparams.top_p);
  1283. fprintf(stream, "min_p: %f # default: 0.0\n", sparams.min_p);
  1284. fprintf(stream, "typical_p: %f # default: 1.0\n", sparams.typical_p);
  1285. fprintf(stream, "verbose_prompt: %s # default: false\n", params.verbose_prompt ? "true" : "false");
  1286. }
  1287. //
  1288. // KV cache utils
  1289. //
  1290. void dump_kv_cache_view(const llama_kv_cache_view & view, int row_size) {
  1291. static const char slot_chars[] = ".123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+";
  1292. 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",
  1293. view.n_cells, view.n_max_seq, view.used_cells, view.token_count, view.max_contiguous, view.max_contiguous_idx);
  1294. llama_kv_cache_view_cell * c_curr = view.cells;
  1295. llama_seq_id * cs_curr = view.cells_sequences;
  1296. for (int i = 0; i < view.n_cells; i++, c_curr++, cs_curr += view.n_max_seq) {
  1297. if (i % row_size == 0) {
  1298. printf("\n%5d: ", i);
  1299. }
  1300. int seq_count = 0;
  1301. for (int j = 0; j < view.n_max_seq; j++) {
  1302. if (cs_curr[j] >= 0) { seq_count++; }
  1303. }
  1304. putchar(slot_chars[std::min(sizeof(slot_chars) - 2, size_t(seq_count))]);
  1305. }
  1306. printf("\n=== Done dumping\n");
  1307. }
  1308. void dump_kv_cache_view_seqs(const llama_kv_cache_view & view, int row_size) {
  1309. static const char slot_chars[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  1310. 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",
  1311. view.n_cells, view.n_max_seq, view.used_cells, view.token_count, view.max_contiguous, view.max_contiguous_idx);
  1312. std::unordered_map<llama_seq_id, size_t> seqs;
  1313. llama_kv_cache_view_cell * c_curr = view.cells;
  1314. llama_seq_id * cs_curr = view.cells_sequences;
  1315. for (int i = 0; i < view.n_cells; i++, c_curr++, cs_curr += view.n_max_seq) {
  1316. for (int j = 0; j < view.n_max_seq; j++) {
  1317. if (cs_curr[j] < 0) { continue; }
  1318. if (seqs.find(cs_curr[j]) == seqs.end()) {
  1319. if (seqs.size() + 1 >= sizeof(slot_chars)) { break; }
  1320. seqs[cs_curr[j]] = seqs.size();
  1321. }
  1322. }
  1323. if (seqs.size() + 1 >= sizeof(slot_chars)) { break; }
  1324. }
  1325. printf("=== Sequence legend: ");
  1326. for (const auto & it : seqs) {
  1327. printf("%zu=%d, ", it.second, it.first);
  1328. }
  1329. printf("'+'=other sequence ids");
  1330. c_curr = view.cells;
  1331. cs_curr = view.cells_sequences;
  1332. for (int i = 0; i < view.n_cells; i++, c_curr++, cs_curr += view.n_max_seq) {
  1333. if (i % row_size == 0) {
  1334. printf("\n%5d: ", i);
  1335. }
  1336. for (int j = 0; j < view.n_max_seq; j++) {
  1337. if (cs_curr[j] >= 0) {
  1338. const auto & it = seqs.find(cs_curr[j]);
  1339. putchar(it != seqs.end() ? int(slot_chars[it->second]) : '+');
  1340. } else {
  1341. putchar('.');
  1342. }
  1343. }
  1344. putchar(' ');
  1345. }
  1346. printf("\n=== Done dumping\n");
  1347. }