common.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927
  1. #include "common.h"
  2. #include <cassert>
  3. #include <iostream>
  4. #include <cstring>
  5. #include <fstream>
  6. #include <string>
  7. #include <iterator>
  8. #include <algorithm>
  9. #include <sstream>
  10. #include <unordered_set>
  11. #include <regex>
  12. #if defined(__APPLE__) && defined(__MACH__)
  13. #include <sys/types.h>
  14. #include <sys/sysctl.h>
  15. #endif
  16. #if defined(_WIN32)
  17. #define WIN32_LEAN_AND_MEAN
  18. #define NOMINMAX
  19. #include <windows.h>
  20. #include <fcntl.h>
  21. #include <io.h>
  22. #else
  23. #include <sys/ioctl.h>
  24. #include <unistd.h>
  25. #include <wchar.h>
  26. #endif
  27. int32_t get_num_physical_cores() {
  28. #ifdef __linux__
  29. // enumerate the set of thread siblings, num entries is num cores
  30. std::unordered_set<std::string> siblings;
  31. for (uint32_t cpu=0; cpu < UINT32_MAX; ++cpu) {
  32. std::ifstream thread_siblings("/sys/devices/system/cpu"
  33. + std::to_string(cpu) + "/topology/thread_siblings");
  34. if (!thread_siblings.is_open()) {
  35. break; // no more cpus
  36. }
  37. std::string line;
  38. if (std::getline(thread_siblings, line)) {
  39. siblings.insert(line);
  40. }
  41. }
  42. if (siblings.size() > 0) {
  43. return static_cast<int32_t>(siblings.size());
  44. }
  45. #elif defined(__APPLE__) && defined(__MACH__)
  46. int32_t num_physical_cores;
  47. size_t len = sizeof(num_physical_cores);
  48. int result = sysctlbyname("hw.perflevel0.physicalcpu", &num_physical_cores, &len, NULL, 0);
  49. if (result == 0) {
  50. return num_physical_cores;
  51. }
  52. result = sysctlbyname("hw.physicalcpu", &num_physical_cores, &len, NULL, 0);
  53. if (result == 0) {
  54. return num_physical_cores;
  55. }
  56. #elif defined(_WIN32)
  57. //TODO: Implement
  58. #endif
  59. unsigned int n_threads = std::thread::hardware_concurrency();
  60. return n_threads > 0 ? (n_threads <= 4 ? n_threads : n_threads / 2) : 4;
  61. }
  62. void process_escapes(std::string& input) {
  63. std::size_t input_len = input.length();
  64. std::size_t output_idx = 0;
  65. for (std::size_t input_idx = 0; input_idx < input_len; ++input_idx) {
  66. if (input[input_idx] == '\\' && input_idx + 1 < input_len) {
  67. switch (input[++input_idx]) {
  68. case 'n': input[output_idx++] = '\n'; break;
  69. case 'r': input[output_idx++] = '\r'; break;
  70. case 't': input[output_idx++] = '\t'; break;
  71. case '\'': input[output_idx++] = '\''; break;
  72. case '\"': input[output_idx++] = '\"'; break;
  73. case '\\': input[output_idx++] = '\\'; break;
  74. default: input[output_idx++] = '\\';
  75. input[output_idx++] = input[input_idx]; break;
  76. }
  77. } else {
  78. input[output_idx++] = input[input_idx];
  79. }
  80. }
  81. input.resize(output_idx);
  82. }
  83. bool gpt_params_parse(int argc, char ** argv, gpt_params & params) {
  84. bool invalid_param = false;
  85. bool escape_prompt = false;
  86. std::string arg;
  87. gpt_params default_params;
  88. const std::string arg_prefix = "--";
  89. for (int i = 1; i < argc; i++) {
  90. arg = argv[i];
  91. if (arg.compare(0, arg_prefix.size(), arg_prefix) == 0) {
  92. std::replace(arg.begin(), arg.end(), '_', '-');
  93. }
  94. if (arg == "-s" || arg == "--seed") {
  95. #if defined(GGML_USE_CUBLAS)
  96. fprintf(stderr, "WARNING: when using cuBLAS generation results are NOT guaranteed to be reproducible.\n");
  97. #endif
  98. if (++i >= argc) {
  99. invalid_param = true;
  100. break;
  101. }
  102. params.seed = std::stoi(argv[i]);
  103. } else if (arg == "-t" || arg == "--threads") {
  104. if (++i >= argc) {
  105. invalid_param = true;
  106. break;
  107. }
  108. params.n_threads = std::stoi(argv[i]);
  109. } else if (arg == "-p" || arg == "--prompt") {
  110. if (++i >= argc) {
  111. invalid_param = true;
  112. break;
  113. }
  114. params.prompt = argv[i];
  115. } else if (arg == "-e") {
  116. escape_prompt = true;
  117. } else if (arg == "--prompt-cache") {
  118. if (++i >= argc) {
  119. invalid_param = true;
  120. break;
  121. }
  122. params.path_prompt_cache = argv[i];
  123. } else if (arg == "--prompt-cache-all") {
  124. params.prompt_cache_all = true;
  125. } else if (arg == "--prompt-cache-ro") {
  126. params.prompt_cache_ro = true;
  127. } else if (arg == "-f" || arg == "--file") {
  128. if (++i >= argc) {
  129. invalid_param = true;
  130. break;
  131. }
  132. std::ifstream file(argv[i]);
  133. if (!file) {
  134. fprintf(stderr, "error: failed to open file '%s'\n", argv[i]);
  135. invalid_param = true;
  136. break;
  137. }
  138. std::copy(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>(), back_inserter(params.prompt));
  139. if (params.prompt.back() == '\n') {
  140. params.prompt.pop_back();
  141. }
  142. } else if (arg == "-n" || arg == "--n-predict") {
  143. if (++i >= argc) {
  144. invalid_param = true;
  145. break;
  146. }
  147. params.n_predict = std::stoi(argv[i]);
  148. } else if (arg == "--top-k") {
  149. if (++i >= argc) {
  150. invalid_param = true;
  151. break;
  152. }
  153. params.top_k = std::stoi(argv[i]);
  154. } else if (arg == "-c" || arg == "--ctx-size") {
  155. if (++i >= argc) {
  156. invalid_param = true;
  157. break;
  158. }
  159. params.n_ctx = std::stoi(argv[i]);
  160. } else if (arg == "--memory-f32") {
  161. params.memory_f16 = false;
  162. } else if (arg == "--top-p") {
  163. if (++i >= argc) {
  164. invalid_param = true;
  165. break;
  166. }
  167. params.top_p = std::stof(argv[i]);
  168. } else if (arg == "--temp") {
  169. if (++i >= argc) {
  170. invalid_param = true;
  171. break;
  172. }
  173. params.temp = std::stof(argv[i]);
  174. } else if (arg == "--tfs") {
  175. if (++i >= argc) {
  176. invalid_param = true;
  177. break;
  178. }
  179. params.tfs_z = std::stof(argv[i]);
  180. } else if (arg == "--typical") {
  181. if (++i >= argc) {
  182. invalid_param = true;
  183. break;
  184. }
  185. params.typical_p = std::stof(argv[i]);
  186. } else if (arg == "--repeat-last-n") {
  187. if (++i >= argc) {
  188. invalid_param = true;
  189. break;
  190. }
  191. params.repeat_last_n = std::stoi(argv[i]);
  192. } else if (arg == "--repeat-penalty") {
  193. if (++i >= argc) {
  194. invalid_param = true;
  195. break;
  196. }
  197. params.repeat_penalty = std::stof(argv[i]);
  198. } else if (arg == "--frequency-penalty") {
  199. if (++i >= argc) {
  200. invalid_param = true;
  201. break;
  202. }
  203. params.frequency_penalty = std::stof(argv[i]);
  204. } else if (arg == "--presence-penalty") {
  205. if (++i >= argc) {
  206. invalid_param = true;
  207. break;
  208. }
  209. params.presence_penalty = std::stof(argv[i]);
  210. } else if (arg == "--mirostat") {
  211. if (++i >= argc) {
  212. invalid_param = true;
  213. break;
  214. }
  215. params.mirostat = std::stoi(argv[i]);
  216. } else if (arg == "--mirostat-lr") {
  217. if (++i >= argc) {
  218. invalid_param = true;
  219. break;
  220. }
  221. params.mirostat_eta = std::stof(argv[i]);
  222. } else if (arg == "--mirostat-ent") {
  223. if (++i >= argc) {
  224. invalid_param = true;
  225. break;
  226. }
  227. params.mirostat_tau = std::stof(argv[i]);
  228. } else if (arg == "-b" || arg == "--batch-size") {
  229. if (++i >= argc) {
  230. invalid_param = true;
  231. break;
  232. }
  233. params.n_batch = std::stoi(argv[i]);
  234. params.n_batch = std::min(512, params.n_batch);
  235. } else if (arg == "--keep") {
  236. if (++i >= argc) {
  237. invalid_param = true;
  238. break;
  239. }
  240. params.n_keep = std::stoi(argv[i]);
  241. } else if (arg == "-m" || arg == "--model") {
  242. if (++i >= argc) {
  243. invalid_param = true;
  244. break;
  245. }
  246. params.model = argv[i];
  247. } else if (arg == "-a" || arg == "--alias") {
  248. if (++i >= argc) {
  249. invalid_param = true;
  250. break;
  251. }
  252. params.model_alias = argv[i];
  253. } else if (arg == "--lora") {
  254. if (++i >= argc) {
  255. invalid_param = true;
  256. break;
  257. }
  258. params.lora_adapter = argv[i];
  259. params.use_mmap = false;
  260. } else if (arg == "--lora-base") {
  261. if (++i >= argc) {
  262. invalid_param = true;
  263. break;
  264. }
  265. params.lora_base = argv[i];
  266. } else if (arg == "-i" || arg == "--interactive") {
  267. params.interactive = true;
  268. } else if (arg == "--embedding") {
  269. params.embedding = true;
  270. } else if (arg == "--interactive-first") {
  271. params.interactive_first = true;
  272. } else if (arg == "-ins" || arg == "--instruct") {
  273. params.instruct = true;
  274. } else if (arg == "--multiline-input") {
  275. params.multiline_input = true;
  276. } else if (arg == "--color") {
  277. params.use_color = true;
  278. } else if (arg == "--mlock") {
  279. params.use_mlock = true;
  280. } else if (arg == "--gpu-layers" || arg == "-ngl" || arg == "--n-gpu-layers") {
  281. if (++i >= argc) {
  282. invalid_param = true;
  283. break;
  284. }
  285. #ifdef LLAMA_SUPPORTS_GPU_OFFLOAD
  286. params.n_gpu_layers = std::stoi(argv[i]);
  287. #else
  288. fprintf(stderr, "warning: not compiled with GPU offload support, --n-gpu-layers option will be ignored\n");
  289. fprintf(stderr, "warning: see main README.md for information on enabling GPU BLAS support\n");
  290. #endif
  291. } else if (arg == "--main-gpu" || arg == "-mg") {
  292. if (++i >= argc) {
  293. invalid_param = true;
  294. break;
  295. }
  296. #ifdef GGML_USE_CUBLAS
  297. params.main_gpu = std::stoi(argv[i]);
  298. #else
  299. fprintf(stderr, "warning: llama.cpp was compiled without cuBLAS. It is not possible to set a main GPU.\n");
  300. #endif
  301. } else if (arg == "--tensor-split" || arg == "-ts") {
  302. if (++i >= argc) {
  303. invalid_param = true;
  304. break;
  305. }
  306. #ifdef GGML_USE_CUBLAS
  307. std::string arg_next = argv[i];
  308. // split string by , and /
  309. const std::regex regex{R"([,/]+)"};
  310. std::sregex_token_iterator it{arg_next.begin(), arg_next.end(), regex, -1};
  311. std::vector<std::string> split_arg{it, {}};
  312. GGML_ASSERT(split_arg.size() <= LLAMA_MAX_DEVICES);
  313. for (size_t i = 0; i < LLAMA_MAX_DEVICES; ++i) {
  314. if (i < split_arg.size()) {
  315. params.tensor_split[i] = std::stof(split_arg[i]);
  316. } else {
  317. params.tensor_split[i] = 0.0f;
  318. }
  319. }
  320. #else
  321. fprintf(stderr, "warning: llama.cpp was compiled without cuBLAS. It is not possible to set a tensor split.\n");
  322. #endif // GGML_USE_CUBLAS
  323. } else if (arg == "--no-mmap") {
  324. params.use_mmap = false;
  325. } else if (arg == "--mtest") {
  326. params.mem_test = true;
  327. } else if (arg == "--export") {
  328. params.export_cgraph = true;
  329. } else if (arg == "--verbose-prompt") {
  330. params.verbose_prompt = true;
  331. } else if (arg == "-r" || arg == "--reverse-prompt") {
  332. if (++i >= argc) {
  333. invalid_param = true;
  334. break;
  335. }
  336. params.antiprompt.push_back(argv[i]);
  337. } else if (arg == "--perplexity") {
  338. params.perplexity = true;
  339. } else if (arg == "--ignore-eos") {
  340. params.logit_bias[llama_token_eos()] = -INFINITY;
  341. } else if (arg == "--no-penalize-nl") {
  342. params.penalize_nl = false;
  343. } else if (arg == "-l" || arg == "--logit-bias") {
  344. if (++i >= argc) {
  345. invalid_param = true;
  346. break;
  347. }
  348. std::stringstream ss(argv[i]);
  349. llama_token key;
  350. char sign;
  351. std::string value_str;
  352. try {
  353. if (ss >> key && ss >> sign && std::getline(ss, value_str) && (sign == '+' || sign == '-')) {
  354. params.logit_bias[key] = std::stof(value_str) * ((sign == '-') ? -1.0f : 1.0f);
  355. } else {
  356. throw std::exception();
  357. }
  358. } catch (const std::exception &e) {
  359. invalid_param = true;
  360. break;
  361. }
  362. } else if (arg == "-h" || arg == "--help") {
  363. gpt_print_usage(argc, argv, default_params);
  364. exit(0);
  365. } else if (arg == "--random-prompt") {
  366. params.random_prompt = true;
  367. } else if (arg == "--in-prefix") {
  368. if (++i >= argc) {
  369. invalid_param = true;
  370. break;
  371. }
  372. params.input_prefix = argv[i];
  373. } else if (arg == "--in-suffix") {
  374. if (++i >= argc) {
  375. invalid_param = true;
  376. break;
  377. }
  378. params.input_suffix = argv[i];
  379. } else {
  380. fprintf(stderr, "error: unknown argument: %s\n", arg.c_str());
  381. gpt_print_usage(argc, argv, default_params);
  382. exit(1);
  383. }
  384. }
  385. if (invalid_param) {
  386. fprintf(stderr, "error: invalid parameter for argument: %s\n", arg.c_str());
  387. gpt_print_usage(argc, argv, default_params);
  388. exit(1);
  389. }
  390. if (params.prompt_cache_all &&
  391. (params.interactive || params.interactive_first ||
  392. params.instruct)) {
  393. fprintf(stderr, "error: --prompt-cache-all not supported in interactive mode yet\n");
  394. gpt_print_usage(argc, argv, default_params);
  395. exit(1);
  396. }
  397. if (escape_prompt) {
  398. process_escapes(params.prompt);
  399. }
  400. return true;
  401. }
  402. void gpt_print_usage(int /*argc*/, char ** argv, const gpt_params & params) {
  403. fprintf(stderr, "usage: %s [options]\n", argv[0]);
  404. fprintf(stderr, "\n");
  405. fprintf(stderr, "options:\n");
  406. fprintf(stderr, " -h, --help show this help message and exit\n");
  407. fprintf(stderr, " -i, --interactive run in interactive mode\n");
  408. fprintf(stderr, " --interactive-first run in interactive mode and wait for input right away\n");
  409. fprintf(stderr, " -ins, --instruct run in instruction mode (use with Alpaca models)\n");
  410. fprintf(stderr, " --multiline-input allows you to write or paste multiple lines without ending each in '\\'\n");
  411. fprintf(stderr, " -r PROMPT, --reverse-prompt PROMPT\n");
  412. fprintf(stderr, " halt generation at PROMPT, return control in interactive mode\n");
  413. fprintf(stderr, " (can be specified more than once for multiple prompts).\n");
  414. fprintf(stderr, " --color colorise output to distinguish prompt and user input from generations\n");
  415. fprintf(stderr, " -s SEED, --seed SEED RNG seed (default: -1, use random seed for < 0)\n");
  416. fprintf(stderr, " -t N, --threads N number of threads to use during computation (default: %d)\n", params.n_threads);
  417. fprintf(stderr, " -p PROMPT, --prompt PROMPT\n");
  418. fprintf(stderr, " prompt to start generation with (default: empty)\n");
  419. fprintf(stderr, " -e process prompt escapes sequences (\\n, \\r, \\t, \\', \\\", \\\\)\n");
  420. fprintf(stderr, " --prompt-cache FNAME file to cache prompt state for faster startup (default: none)\n");
  421. fprintf(stderr, " --prompt-cache-all if specified, saves user input and generations to cache as well.\n");
  422. fprintf(stderr, " not supported with --interactive or other interactive options\n");
  423. fprintf(stderr, " --prompt-cache-ro if specified, uses the prompt cache but does not update it.\n");
  424. fprintf(stderr, " --random-prompt start with a randomized prompt.\n");
  425. fprintf(stderr, " --in-prefix STRING string to prefix user inputs with (default: empty)\n");
  426. fprintf(stderr, " --in-suffix STRING string to suffix after user inputs with (default: empty)\n");
  427. fprintf(stderr, " -f FNAME, --file FNAME\n");
  428. fprintf(stderr, " prompt file to start generation.\n");
  429. fprintf(stderr, " -n N, --n-predict N number of tokens to predict (default: %d, -1 = infinity)\n", params.n_predict);
  430. fprintf(stderr, " --top-k N top-k sampling (default: %d, 0 = disabled)\n", params.top_k);
  431. fprintf(stderr, " --top-p N top-p sampling (default: %.1f, 1.0 = disabled)\n", (double)params.top_p);
  432. fprintf(stderr, " --tfs N tail free sampling, parameter z (default: %.1f, 1.0 = disabled)\n", (double)params.tfs_z);
  433. fprintf(stderr, " --typical N locally typical sampling, parameter p (default: %.1f, 1.0 = disabled)\n", (double)params.typical_p);
  434. fprintf(stderr, " --repeat-last-n N last n tokens to consider for penalize (default: %d, 0 = disabled, -1 = ctx_size)\n", params.repeat_last_n);
  435. fprintf(stderr, " --repeat-penalty N penalize repeat sequence of tokens (default: %.1f, 1.0 = disabled)\n", (double)params.repeat_penalty);
  436. fprintf(stderr, " --presence-penalty N repeat alpha presence penalty (default: %.1f, 0.0 = disabled)\n", (double)params.presence_penalty);
  437. fprintf(stderr, " --frequency-penalty N repeat alpha frequency penalty (default: %.1f, 0.0 = disabled)\n", (double)params.frequency_penalty);
  438. fprintf(stderr, " --mirostat N use Mirostat sampling.\n");
  439. fprintf(stderr, " Top K, Nucleus, Tail Free and Locally Typical samplers are ignored if used.\n");
  440. fprintf(stderr, " (default: %d, 0 = disabled, 1 = Mirostat, 2 = Mirostat 2.0)\n", params.mirostat);
  441. fprintf(stderr, " --mirostat-lr N Mirostat learning rate, parameter eta (default: %.1f)\n", (double)params.mirostat_eta);
  442. fprintf(stderr, " --mirostat-ent N Mirostat target entropy, parameter tau (default: %.1f)\n", (double)params.mirostat_tau);
  443. fprintf(stderr, " -l TOKEN_ID(+/-)BIAS, --logit-bias TOKEN_ID(+/-)BIAS\n");
  444. fprintf(stderr, " modifies the likelihood of token appearing in the completion,\n");
  445. fprintf(stderr, " i.e. `--logit-bias 15043+1` to increase likelihood of token ' Hello',\n");
  446. fprintf(stderr, " or `--logit-bias 15043-1` to decrease likelihood of token ' Hello'\n");
  447. fprintf(stderr, " -c N, --ctx-size N size of the prompt context (default: %d)\n", params.n_ctx);
  448. fprintf(stderr, " --ignore-eos ignore end of stream token and continue generating (implies --logit-bias 2-inf)\n");
  449. fprintf(stderr, " --no-penalize-nl do not penalize newline token\n");
  450. fprintf(stderr, " --memory-f32 use f32 instead of f16 for memory key+value (default: disabled)\n");
  451. fprintf(stderr, " not recommended: doubles context memory required and no measurable increase in quality\n");
  452. fprintf(stderr, " --temp N temperature (default: %.1f)\n", (double)params.temp);
  453. fprintf(stderr, " -b N, --batch-size N batch size for prompt processing (default: %d)\n", params.n_batch);
  454. fprintf(stderr, " --perplexity compute perplexity over the prompt\n");
  455. fprintf(stderr, " --keep number of tokens to keep from the initial prompt (default: %d, -1 = all)\n", params.n_keep);
  456. if (llama_mlock_supported()) {
  457. fprintf(stderr, " --mlock force system to keep model in RAM rather than swapping or compressing\n");
  458. }
  459. if (llama_mmap_supported()) {
  460. fprintf(stderr, " --no-mmap do not memory-map model (slower load but may reduce pageouts if not using mlock)\n");
  461. }
  462. #ifdef LLAMA_SUPPORTS_GPU_OFFLOAD
  463. fprintf(stderr, " -ngl N, --n-gpu-layers N\n");
  464. fprintf(stderr, " number of layers to store in VRAM\n");
  465. fprintf(stderr, " -ts SPLIT --tensor-split SPLIT\n");
  466. fprintf(stderr, " how to split tensors across multiple GPUs, comma-separated list of proportions, e.g. 3,1\n");
  467. fprintf(stderr, " -mg i, --main-gpu i the GPU to use for scratch and small tensors\n" );
  468. #endif
  469. fprintf(stderr, " --mtest compute maximum memory usage\n");
  470. fprintf(stderr, " --export export the computation graph to 'llama.ggml'\n");
  471. fprintf(stderr, " --verbose-prompt print prompt before generation\n");
  472. fprintf(stderr, " --lora FNAME apply LoRA adapter (implies --no-mmap)\n");
  473. fprintf(stderr, " --lora-base FNAME optional model to use as a base for the layers modified by the LoRA adapter\n");
  474. fprintf(stderr, " -m FNAME, --model FNAME\n");
  475. fprintf(stderr, " model path (default: %s)\n", params.model.c_str());
  476. fprintf(stderr, "\n");
  477. }
  478. std::string gpt_random_prompt(std::mt19937 & rng) {
  479. const int r = rng() % 10;
  480. switch (r) {
  481. case 0: return "So";
  482. case 1: return "Once upon a time";
  483. case 2: return "When";
  484. case 3: return "The";
  485. case 4: return "After";
  486. case 5: return "If";
  487. case 6: return "import";
  488. case 7: return "He";
  489. case 8: return "She";
  490. case 9: return "They";
  491. default: return "To";
  492. }
  493. return "The";
  494. }
  495. // TODO: not great allocating this every time
  496. std::vector<llama_token> llama_tokenize(struct llama_context * ctx, const std::string & text, bool add_bos) {
  497. // initialize to prompt numer of chars, since n_tokens <= n_prompt_chars
  498. std::vector<llama_token> res(text.size() + (int) add_bos);
  499. const int n = llama_tokenize(ctx, text.c_str(), res.data(), res.size(), add_bos);
  500. assert(n >= 0);
  501. res.resize(n);
  502. return res;
  503. }
  504. struct llama_context * llama_init_from_gpt_params(const gpt_params & params) {
  505. auto lparams = llama_context_default_params();
  506. lparams.n_ctx = params.n_ctx;
  507. lparams.n_batch = params.n_batch;
  508. lparams.n_gpu_layers = params.n_gpu_layers;
  509. lparams.main_gpu = params.main_gpu;
  510. memcpy(lparams.tensor_split, params.tensor_split, LLAMA_MAX_DEVICES*sizeof(float));
  511. lparams.seed = params.seed;
  512. lparams.f16_kv = params.memory_f16;
  513. lparams.use_mmap = params.use_mmap;
  514. lparams.use_mlock = params.use_mlock;
  515. lparams.logits_all = params.perplexity;
  516. lparams.embedding = params.embedding;
  517. llama_context * lctx = llama_init_from_file(params.model.c_str(), lparams);
  518. if (lctx == NULL) {
  519. fprintf(stderr, "%s: error: failed to load model '%s'\n", __func__, params.model.c_str());
  520. return NULL;
  521. }
  522. if (!params.lora_adapter.empty()) {
  523. int err = llama_apply_lora_from_file(lctx,
  524. params.lora_adapter.c_str(),
  525. params.lora_base.empty() ? NULL : params.lora_base.c_str(),
  526. params.n_threads);
  527. if (err != 0) {
  528. fprintf(stderr, "%s: error: failed to apply lora adapter\n", __func__);
  529. return NULL;
  530. }
  531. }
  532. return lctx;
  533. }
  534. void console_init(console_state & con_st) {
  535. #if defined(_WIN32)
  536. // Windows-specific console initialization
  537. DWORD dwMode = 0;
  538. con_st.hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
  539. if (con_st.hConsole == INVALID_HANDLE_VALUE || !GetConsoleMode(con_st.hConsole, &dwMode)) {
  540. con_st.hConsole = GetStdHandle(STD_ERROR_HANDLE);
  541. if (con_st.hConsole != INVALID_HANDLE_VALUE && (!GetConsoleMode(con_st.hConsole, &dwMode))) {
  542. con_st.hConsole = NULL;
  543. }
  544. }
  545. if (con_st.hConsole) {
  546. // Enable ANSI colors on Windows 10+
  547. if (con_st.use_color && !(dwMode & ENABLE_VIRTUAL_TERMINAL_PROCESSING)) {
  548. SetConsoleMode(con_st.hConsole, dwMode | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
  549. }
  550. // Set console output codepage to UTF8
  551. SetConsoleOutputCP(CP_UTF8);
  552. }
  553. HANDLE hConIn = GetStdHandle(STD_INPUT_HANDLE);
  554. if (hConIn != INVALID_HANDLE_VALUE && GetConsoleMode(hConIn, &dwMode)) {
  555. // Set console input codepage to UTF16
  556. _setmode(_fileno(stdin), _O_WTEXT);
  557. // Turn off ICANON (ENABLE_LINE_INPUT) and ECHO (ENABLE_ECHO_INPUT)
  558. dwMode &= ~(ENABLE_LINE_INPUT | ENABLE_ECHO_INPUT);
  559. SetConsoleMode(hConIn, dwMode);
  560. }
  561. #else
  562. // POSIX-specific console initialization
  563. struct termios new_termios;
  564. tcgetattr(STDIN_FILENO, &con_st.prev_state);
  565. new_termios = con_st.prev_state;
  566. new_termios.c_lflag &= ~(ICANON | ECHO);
  567. new_termios.c_cc[VMIN] = 1;
  568. new_termios.c_cc[VTIME] = 0;
  569. tcsetattr(STDIN_FILENO, TCSANOW, &new_termios);
  570. con_st.tty = fopen("/dev/tty", "w+");
  571. if (con_st.tty != nullptr) {
  572. con_st.out = con_st.tty;
  573. }
  574. setlocale(LC_ALL, "");
  575. #endif
  576. }
  577. void console_cleanup(console_state & con_st) {
  578. // Reset console color
  579. console_set_color(con_st, CONSOLE_COLOR_DEFAULT);
  580. #if !defined(_WIN32)
  581. if (con_st.tty != nullptr) {
  582. con_st.out = stdout;
  583. fclose(con_st.tty);
  584. con_st.tty = nullptr;
  585. }
  586. // Restore the terminal settings on POSIX systems
  587. tcsetattr(STDIN_FILENO, TCSANOW, &con_st.prev_state);
  588. #endif
  589. }
  590. /* Keep track of current color of output, and emit ANSI code if it changes. */
  591. void console_set_color(console_state & con_st, console_color_t color) {
  592. if (con_st.use_color && con_st.color != color) {
  593. fflush(stdout);
  594. switch(color) {
  595. case CONSOLE_COLOR_DEFAULT:
  596. fprintf(con_st.out, ANSI_COLOR_RESET);
  597. break;
  598. case CONSOLE_COLOR_PROMPT:
  599. fprintf(con_st.out, ANSI_COLOR_YELLOW);
  600. break;
  601. case CONSOLE_COLOR_USER_INPUT:
  602. fprintf(con_st.out, ANSI_BOLD ANSI_COLOR_GREEN);
  603. break;
  604. }
  605. con_st.color = color;
  606. fflush(con_st.out);
  607. }
  608. }
  609. char32_t getchar32() {
  610. #if defined(_WIN32)
  611. HANDLE hConsole = GetStdHandle(STD_INPUT_HANDLE);
  612. wchar_t high_surrogate = 0;
  613. while (true) {
  614. INPUT_RECORD record;
  615. DWORD count;
  616. if (!ReadConsoleInputW(hConsole, &record, 1, &count) || count == 0) {
  617. return WEOF;
  618. }
  619. if (record.EventType == KEY_EVENT && record.Event.KeyEvent.bKeyDown) {
  620. wchar_t wc = record.Event.KeyEvent.uChar.UnicodeChar;
  621. if (wc == 0) {
  622. continue;
  623. }
  624. if ((wc >= 0xD800) && (wc <= 0xDBFF)) { // Check if wc is a high surrogate
  625. high_surrogate = wc;
  626. continue;
  627. } else if ((wc >= 0xDC00) && (wc <= 0xDFFF)) { // Check if wc is a low surrogate
  628. if (high_surrogate != 0) { // Check if we have a high surrogate
  629. return ((high_surrogate - 0xD800) << 10) + (wc - 0xDC00) + 0x10000;
  630. }
  631. }
  632. high_surrogate = 0; // Reset the high surrogate
  633. return static_cast<char32_t>(wc);
  634. }
  635. }
  636. #else
  637. wchar_t wc = getwchar();
  638. if (static_cast<wint_t>(wc) == WEOF) {
  639. return WEOF;
  640. }
  641. #if WCHAR_MAX == 0xFFFF
  642. if ((wc >= 0xD800) && (wc <= 0xDBFF)) { // Check if wc is a high surrogate
  643. wchar_t low_surrogate = getwchar();
  644. if ((low_surrogate >= 0xDC00) && (low_surrogate <= 0xDFFF)) { // Check if the next wchar is a low surrogate
  645. return (static_cast<char32_t>(wc & 0x03FF) << 10) + (low_surrogate & 0x03FF) + 0x10000;
  646. }
  647. }
  648. if ((wc >= 0xD800) && (wc <= 0xDFFF)) { // Invalid surrogate pair
  649. return 0xFFFD; // Return the replacement character U+FFFD
  650. }
  651. #endif
  652. return static_cast<char32_t>(wc);
  653. #endif
  654. }
  655. void pop_cursor(console_state & con_st) {
  656. #if defined(_WIN32)
  657. if (con_st.hConsole != NULL) {
  658. CONSOLE_SCREEN_BUFFER_INFO bufferInfo;
  659. GetConsoleScreenBufferInfo(con_st.hConsole, &bufferInfo);
  660. COORD newCursorPosition = bufferInfo.dwCursorPosition;
  661. if (newCursorPosition.X == 0) {
  662. newCursorPosition.X = bufferInfo.dwSize.X - 1;
  663. newCursorPosition.Y -= 1;
  664. } else {
  665. newCursorPosition.X -= 1;
  666. }
  667. SetConsoleCursorPosition(con_st.hConsole, newCursorPosition);
  668. return;
  669. }
  670. #endif
  671. putc('\b', con_st.out);
  672. }
  673. int estimateWidth(char32_t codepoint) {
  674. #if defined(_WIN32)
  675. return 1;
  676. #else
  677. return wcwidth(codepoint);
  678. #endif
  679. }
  680. int put_codepoint(console_state & con_st, const char* utf8_codepoint, size_t length, int expectedWidth) {
  681. #if defined(_WIN32)
  682. CONSOLE_SCREEN_BUFFER_INFO bufferInfo;
  683. if (!GetConsoleScreenBufferInfo(con_st.hConsole, &bufferInfo)) {
  684. // go with the default
  685. return expectedWidth;
  686. }
  687. COORD initialPosition = bufferInfo.dwCursorPosition;
  688. DWORD nNumberOfChars = length;
  689. WriteConsole(con_st.hConsole, utf8_codepoint, nNumberOfChars, &nNumberOfChars, NULL);
  690. CONSOLE_SCREEN_BUFFER_INFO newBufferInfo;
  691. GetConsoleScreenBufferInfo(con_st.hConsole, &newBufferInfo);
  692. // Figure out our real position if we're in the last column
  693. if (utf8_codepoint[0] != 0x09 && initialPosition.X == newBufferInfo.dwSize.X - 1) {
  694. DWORD nNumberOfChars;
  695. WriteConsole(con_st.hConsole, &" \b", 2, &nNumberOfChars, NULL);
  696. GetConsoleScreenBufferInfo(con_st.hConsole, &newBufferInfo);
  697. }
  698. int width = newBufferInfo.dwCursorPosition.X - initialPosition.X;
  699. if (width < 0) {
  700. width += newBufferInfo.dwSize.X;
  701. }
  702. return width;
  703. #else
  704. // we can trust expectedWidth if we've got one
  705. if (expectedWidth >= 0 || con_st.tty == nullptr) {
  706. fwrite(utf8_codepoint, length, 1, con_st.out);
  707. return expectedWidth;
  708. }
  709. fputs("\033[6n", con_st.tty); // Query cursor position
  710. int x1, x2, y1, y2;
  711. int results = 0;
  712. results = fscanf(con_st.tty, "\033[%d;%dR", &y1, &x1);
  713. fwrite(utf8_codepoint, length, 1, con_st.tty);
  714. fputs("\033[6n", con_st.tty); // Query cursor position
  715. results += fscanf(con_st.tty, "\033[%d;%dR", &y2, &x2);
  716. if (results != 4) {
  717. return expectedWidth;
  718. }
  719. int width = x2 - x1;
  720. if (width < 0) {
  721. // Calculate the width considering text wrapping
  722. struct winsize w;
  723. ioctl(STDOUT_FILENO, TIOCGWINSZ, &w);
  724. width += w.ws_col;
  725. }
  726. return width;
  727. #endif
  728. }
  729. void replace_last(console_state & con_st, char ch) {
  730. #if defined(_WIN32)
  731. pop_cursor(con_st);
  732. put_codepoint(con_st, &ch, 1, 1);
  733. #else
  734. fprintf(con_st.out, "\b%c", ch);
  735. #endif
  736. }
  737. void append_utf8(char32_t ch, std::string & out) {
  738. if (ch <= 0x7F) {
  739. out.push_back(static_cast<unsigned char>(ch));
  740. } else if (ch <= 0x7FF) {
  741. out.push_back(static_cast<unsigned char>(0xC0 | ((ch >> 6) & 0x1F)));
  742. out.push_back(static_cast<unsigned char>(0x80 | (ch & 0x3F)));
  743. } else if (ch <= 0xFFFF) {
  744. out.push_back(static_cast<unsigned char>(0xE0 | ((ch >> 12) & 0x0F)));
  745. out.push_back(static_cast<unsigned char>(0x80 | ((ch >> 6) & 0x3F)));
  746. out.push_back(static_cast<unsigned char>(0x80 | (ch & 0x3F)));
  747. } else if (ch <= 0x10FFFF) {
  748. out.push_back(static_cast<unsigned char>(0xF0 | ((ch >> 18) & 0x07)));
  749. out.push_back(static_cast<unsigned char>(0x80 | ((ch >> 12) & 0x3F)));
  750. out.push_back(static_cast<unsigned char>(0x80 | ((ch >> 6) & 0x3F)));
  751. out.push_back(static_cast<unsigned char>(0x80 | (ch & 0x3F)));
  752. } else {
  753. // Invalid Unicode code point
  754. }
  755. }
  756. // Helper function to remove the last UTF-8 character from a string
  757. void pop_back_utf8_char(std::string & line) {
  758. if (line.empty()) {
  759. return;
  760. }
  761. size_t pos = line.length() - 1;
  762. // Find the start of the last UTF-8 character (checking up to 4 bytes back)
  763. for (size_t i = 0; i < 3 && pos > 0; ++i, --pos) {
  764. if ((line[pos] & 0xC0) != 0x80) break; // Found the start of the character
  765. }
  766. line.erase(pos);
  767. }
  768. bool console_readline(console_state & con_st, std::string & line) {
  769. console_set_color(con_st, CONSOLE_COLOR_USER_INPUT);
  770. if (con_st.out != stdout) {
  771. fflush(stdout);
  772. }
  773. line.clear();
  774. std::vector<int> widths;
  775. bool is_special_char = false;
  776. bool end_of_stream = false;
  777. char32_t input_char;
  778. while (true) {
  779. fflush(con_st.out); // Ensure all output is displayed before waiting for input
  780. input_char = getchar32();
  781. if (input_char == '\r' || input_char == '\n') {
  782. break;
  783. }
  784. if (input_char == (char32_t) WEOF || input_char == 0x04 /* Ctrl+D*/) {
  785. end_of_stream = true;
  786. break;
  787. }
  788. if (is_special_char) {
  789. console_set_color(con_st, CONSOLE_COLOR_USER_INPUT);
  790. replace_last(con_st, line.back());
  791. is_special_char = false;
  792. }
  793. if (input_char == '\033') { // Escape sequence
  794. char32_t code = getchar32();
  795. if (code == '[' || code == 0x1B) {
  796. // Discard the rest of the escape sequence
  797. while ((code = getchar32()) != (char32_t) WEOF) {
  798. if ((code >= 'A' && code <= 'Z') || (code >= 'a' && code <= 'z') || code == '~') {
  799. break;
  800. }
  801. }
  802. }
  803. } else if (input_char == 0x08 || input_char == 0x7F) { // Backspace
  804. if (!widths.empty()) {
  805. int count;
  806. do {
  807. count = widths.back();
  808. widths.pop_back();
  809. // Move cursor back, print space, and move cursor back again
  810. for (int i = 0; i < count; i++) {
  811. replace_last(con_st, ' ');
  812. pop_cursor(con_st);
  813. }
  814. pop_back_utf8_char(line);
  815. } while (count == 0 && !widths.empty());
  816. }
  817. } else {
  818. int offset = line.length();
  819. append_utf8(input_char, line);
  820. int width = put_codepoint(con_st, line.c_str() + offset, line.length() - offset, estimateWidth(input_char));
  821. if (width < 0) {
  822. width = 0;
  823. }
  824. widths.push_back(width);
  825. }
  826. if (!line.empty() && (line.back() == '\\' || line.back() == '/')) {
  827. console_set_color(con_st, CONSOLE_COLOR_PROMPT);
  828. replace_last(con_st, line.back());
  829. is_special_char = true;
  830. }
  831. }
  832. bool has_more = con_st.multiline_input;
  833. if (is_special_char) {
  834. replace_last(con_st, ' ');
  835. pop_cursor(con_st);
  836. char last = line.back();
  837. line.pop_back();
  838. if (last == '\\') {
  839. line += '\n';
  840. fputc('\n', con_st.out);
  841. has_more = !has_more;
  842. } else {
  843. // llama will just eat the single space, it won't act as a space
  844. if (line.length() == 1 && line.back() == ' ') {
  845. line.clear();
  846. pop_cursor(con_st);
  847. }
  848. has_more = false;
  849. }
  850. } else {
  851. if (end_of_stream) {
  852. has_more = false;
  853. } else {
  854. line += '\n';
  855. fputc('\n', con_st.out);
  856. }
  857. }
  858. fflush(con_st.out);
  859. return has_more;
  860. }