common.cpp 56 KB

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