1
0

common.cpp 57 KB

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