common.cpp 58 KB

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