common.cpp 57 KB

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