common.cpp 54 KB

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