common.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. #include "common.h"
  2. #include "ggml.h"
  3. #include <cassert>
  4. #include <cstring>
  5. #include <fstream>
  6. #include <string>
  7. #include <iterator>
  8. #include <algorithm>
  9. #if defined(_MSC_VER) || defined(__MINGW32__)
  10. #include <malloc.h> // using malloc.h with MSC/MINGW
  11. #elif !defined(__FreeBSD__) && !defined(__NetBSD__) && !defined(__OpenBSD__)
  12. #include <alloca.h>
  13. #endif
  14. #if defined (_WIN32)
  15. #pragma comment(lib,"kernel32.lib")
  16. extern "C" __declspec(dllimport) void* __stdcall GetStdHandle(unsigned long nStdHandle);
  17. extern "C" __declspec(dllimport) int __stdcall GetConsoleMode(void* hConsoleHandle, unsigned long* lpMode);
  18. extern "C" __declspec(dllimport) int __stdcall SetConsoleMode(void* hConsoleHandle, unsigned long dwMode);
  19. extern "C" __declspec(dllimport) int __stdcall SetConsoleCP(unsigned int wCodePageID);
  20. extern "C" __declspec(dllimport) int __stdcall SetConsoleOutputCP(unsigned int wCodePageID);
  21. #endif
  22. bool gpt_params_parse(int argc, char ** argv, gpt_params & params) {
  23. // determine sensible default number of threads.
  24. // std::thread::hardware_concurrency may not be equal to the number of cores, or may return 0.
  25. #ifdef __linux__
  26. std::ifstream cpuinfo("/proc/cpuinfo");
  27. params.n_threads = std::count(std::istream_iterator<std::string>(cpuinfo),
  28. std::istream_iterator<std::string>(),
  29. std::string("processor"));
  30. #endif
  31. if (params.n_threads == 0) {
  32. params.n_threads = std::max(1, (int32_t) std::thread::hardware_concurrency());
  33. }
  34. bool invalid_param = false;
  35. std::string arg;
  36. for (int i = 1; i < argc; i++) {
  37. arg = argv[i];
  38. if (arg == "-s" || arg == "--seed") {
  39. if (++i >= argc) {
  40. invalid_param = true;
  41. break;
  42. }
  43. params.seed = std::stoi(argv[i]);
  44. } else if (arg == "-t" || arg == "--threads") {
  45. if (++i >= argc) {
  46. invalid_param = true;
  47. break;
  48. }
  49. params.n_threads = std::stoi(argv[i]);
  50. } else if (arg == "-p" || arg == "--prompt") {
  51. if (++i >= argc) {
  52. invalid_param = true;
  53. break;
  54. }
  55. params.prompt = argv[i];
  56. } else if (arg == "-f" || arg == "--file") {
  57. if (++i >= argc) {
  58. invalid_param = true;
  59. break;
  60. }
  61. std::ifstream file(argv[i]);
  62. if (!file) {
  63. fprintf(stderr, "error: failed to open file '%s'\n", argv[i]);
  64. invalid_param = true;
  65. break;
  66. }
  67. std::copy(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>(), back_inserter(params.prompt));
  68. if (params.prompt.back() == '\n') {
  69. params.prompt.pop_back();
  70. }
  71. } else if (arg == "-n" || arg == "--n_predict") {
  72. if (++i >= argc) {
  73. invalid_param = true;
  74. break;
  75. }
  76. params.n_predict = std::stoi(argv[i]);
  77. } else if (arg == "--top_k") {
  78. if (++i >= argc) {
  79. invalid_param = true;
  80. break;
  81. }
  82. params.top_k = std::stoi(argv[i]);
  83. } else if (arg == "-c" || arg == "--ctx_size") {
  84. if (++i >= argc) {
  85. invalid_param = true;
  86. break;
  87. }
  88. params.n_ctx = std::stoi(argv[i]);
  89. } else if (arg == "--memory_f32") {
  90. params.memory_f16 = false;
  91. } else if (arg == "--top_p") {
  92. if (++i >= argc) {
  93. invalid_param = true;
  94. break;
  95. }
  96. params.top_p = std::stof(argv[i]);
  97. } else if (arg == "--temp") {
  98. if (++i >= argc) {
  99. invalid_param = true;
  100. break;
  101. }
  102. params.temp = std::stof(argv[i]);
  103. } else if (arg == "--repeat_last_n") {
  104. if (++i >= argc) {
  105. invalid_param = true;
  106. break;
  107. }
  108. params.repeat_last_n = std::stoi(argv[i]);
  109. } else if (arg == "--repeat_penalty") {
  110. if (++i >= argc) {
  111. invalid_param = true;
  112. break;
  113. }
  114. params.repeat_penalty = std::stof(argv[i]);
  115. } else if (arg == "-b" || arg == "--batch_size") {
  116. if (++i >= argc) {
  117. invalid_param = true;
  118. break;
  119. }
  120. params.n_batch = std::stoi(argv[i]);
  121. params.n_batch = std::min(512, params.n_batch);
  122. } else if (arg == "--keep") {
  123. if (++i >= argc) {
  124. invalid_param = true;
  125. break;
  126. }
  127. params.n_keep = std::stoi(argv[i]);
  128. } else if (arg == "-m" || arg == "--model") {
  129. if (++i >= argc) {
  130. invalid_param = true;
  131. break;
  132. }
  133. params.model = argv[i];
  134. } else if (arg == "-i" || arg == "--interactive") {
  135. params.interactive = true;
  136. } else if (arg == "--embedding") {
  137. params.embedding = true;
  138. } else if (arg == "--interactive-start") {
  139. params.interactive = true;
  140. } else if (arg == "--interactive-first") {
  141. params.interactive_start = true;
  142. } else if (arg == "-ins" || arg == "--instruct") {
  143. params.instruct = true;
  144. } else if (arg == "--color") {
  145. params.use_color = true;
  146. } else if (arg == "--mlock") {
  147. params.use_mlock = true;
  148. } else if (arg == "--mtest") {
  149. params.mem_test = true;
  150. } else if (arg == "--verbose-prompt") {
  151. params.verbose_prompt = true;
  152. } else if (arg == "-r" || arg == "--reverse-prompt") {
  153. if (++i >= argc) {
  154. invalid_param = true;
  155. break;
  156. }
  157. params.antiprompt.push_back(argv[i]);
  158. } else if (arg == "--perplexity") {
  159. params.perplexity = true;
  160. } else if (arg == "--ignore-eos") {
  161. params.ignore_eos = true;
  162. } else if (arg == "--n_parts") {
  163. if (++i >= argc) {
  164. invalid_param = true;
  165. break;
  166. }
  167. params.n_parts = std::stoi(argv[i]);
  168. } else if (arg == "-h" || arg == "--help") {
  169. gpt_print_usage(argc, argv, params);
  170. exit(0);
  171. } else if (arg == "--random-prompt") {
  172. params.random_prompt = true;
  173. } else if (arg == "--in-prefix") {
  174. if (++i >= argc) {
  175. invalid_param = true;
  176. break;
  177. }
  178. params.input_prefix = argv[i];
  179. } else {
  180. fprintf(stderr, "error: unknown argument: %s\n", arg.c_str());
  181. gpt_print_usage(argc, argv, params);
  182. exit(1);
  183. }
  184. }
  185. if (invalid_param) {
  186. fprintf(stderr, "error: invalid parameter for argument: %s\n", arg.c_str());
  187. gpt_print_usage(argc, argv, params);
  188. exit(1);
  189. }
  190. return true;
  191. }
  192. void gpt_print_usage(int /*argc*/, char ** argv, const gpt_params & params) {
  193. fprintf(stderr, "usage: %s [options]\n", argv[0]);
  194. fprintf(stderr, "\n");
  195. fprintf(stderr, "options:\n");
  196. fprintf(stderr, " -h, --help show this help message and exit\n");
  197. fprintf(stderr, " -i, --interactive run in interactive mode\n");
  198. fprintf(stderr, " --interactive-first run in interactive mode and wait for input right away\n");
  199. fprintf(stderr, " -ins, --instruct run in instruction mode (use with Alpaca models)\n");
  200. fprintf(stderr, " -r PROMPT, --reverse-prompt PROMPT\n");
  201. fprintf(stderr, " run in interactive mode and poll user input upon seeing PROMPT (can be\n");
  202. fprintf(stderr, " specified more than once for multiple prompts).\n");
  203. fprintf(stderr, " --color colorise output to distinguish prompt and user input from generations\n");
  204. fprintf(stderr, " -s SEED, --seed SEED RNG seed (default: -1, use random seed for <= 0)\n");
  205. fprintf(stderr, " -t N, --threads N number of threads to use during computation (default: %d)\n", params.n_threads);
  206. fprintf(stderr, " -p PROMPT, --prompt PROMPT\n");
  207. fprintf(stderr, " prompt to start generation with (default: empty)\n");
  208. fprintf(stderr, " --random-prompt start with a randomized prompt.\n");
  209. fprintf(stderr, " --in-prefix STRING string to prefix user inputs with (default: empty)\n");
  210. fprintf(stderr, " -f FNAME, --file FNAME\n");
  211. fprintf(stderr, " prompt file to start generation.\n");
  212. fprintf(stderr, " -n N, --n_predict N number of tokens to predict (default: %d, -1 = infinity)\n", params.n_predict);
  213. fprintf(stderr, " --top_k N top-k sampling (default: %d)\n", params.top_k);
  214. fprintf(stderr, " --top_p N top-p sampling (default: %.1f)\n", (double)params.top_p);
  215. fprintf(stderr, " --repeat_last_n N last n tokens to consider for penalize (default: %d)\n", params.repeat_last_n);
  216. fprintf(stderr, " --repeat_penalty N penalize repeat sequence of tokens (default: %.1f)\n", (double)params.repeat_penalty);
  217. fprintf(stderr, " -c N, --ctx_size N size of the prompt context (default: %d)\n", params.n_ctx);
  218. fprintf(stderr, " --ignore-eos ignore end of stream token and continue generating\n");
  219. fprintf(stderr, " --memory_f32 use f32 instead of f16 for memory key+value\n");
  220. fprintf(stderr, " --temp N temperature (default: %.1f)\n", (double)params.temp);
  221. fprintf(stderr, " --n_parts N number of model parts (default: -1 = determine from dimensions)\n");
  222. fprintf(stderr, " -b N, --batch_size N batch size for prompt processing (default: %d)\n", params.n_batch);
  223. fprintf(stderr, " --perplexity compute perplexity over the prompt\n");
  224. fprintf(stderr, " --keep number of tokens to keep from the initial prompt (default: %d, -1 = all)\n", params.n_keep);
  225. if (ggml_mlock_supported()) {
  226. fprintf(stderr, " --mlock force system to keep model in RAM rather than swapping or compressing\n");
  227. }
  228. fprintf(stderr, " --mtest compute maximum memory usage\n");
  229. fprintf(stderr, " --verbose-prompt print prompt before generation\n");
  230. fprintf(stderr, " -m FNAME, --model FNAME\n");
  231. fprintf(stderr, " model path (default: %s)\n", params.model.c_str());
  232. fprintf(stderr, "\n");
  233. }
  234. std::string gpt_random_prompt(std::mt19937 & rng) {
  235. const int r = rng() % 10;
  236. switch (r) {
  237. case 0: return "So";
  238. case 1: return "Once upon a time";
  239. case 2: return "When";
  240. case 3: return "The";
  241. case 4: return "After";
  242. case 5: return "If";
  243. case 6: return "import";
  244. case 7: return "He";
  245. case 8: return "She";
  246. case 9: return "They";
  247. default: return "To";
  248. }
  249. return "The";
  250. }
  251. // TODO: not great allocating this every time
  252. std::vector<llama_token> llama_tokenize(struct llama_context * ctx, const std::string & text, bool add_bos) {
  253. // initialize to prompt numer of chars, since n_tokens <= n_prompt_chars
  254. std::vector<llama_token> res(text.size() + (int)add_bos);
  255. int n = llama_tokenize(ctx, text.c_str(), res.data(), res.size(), add_bos);
  256. assert(n >= 0);
  257. res.resize(n);
  258. return res;
  259. }
  260. /* Keep track of current color of output, and emit ANSI code if it changes. */
  261. void set_console_color(console_state & con_st, console_color_t color) {
  262. if (con_st.use_color && con_st.color != color) {
  263. switch(color) {
  264. case CONSOLE_COLOR_DEFAULT:
  265. printf(ANSI_COLOR_RESET);
  266. break;
  267. case CONSOLE_COLOR_PROMPT:
  268. printf(ANSI_COLOR_YELLOW);
  269. break;
  270. case CONSOLE_COLOR_USER_INPUT:
  271. printf(ANSI_BOLD ANSI_COLOR_GREEN);
  272. break;
  273. }
  274. con_st.color = color;
  275. }
  276. }
  277. #if defined (_WIN32)
  278. void win32_console_init(bool enable_color) {
  279. unsigned long dwMode = 0;
  280. void* hConOut = GetStdHandle((unsigned long)-11); // STD_OUTPUT_HANDLE (-11)
  281. if (!hConOut || hConOut == (void*)-1 || !GetConsoleMode(hConOut, &dwMode)) {
  282. hConOut = GetStdHandle((unsigned long)-12); // STD_ERROR_HANDLE (-12)
  283. if (hConOut && (hConOut == (void*)-1 || !GetConsoleMode(hConOut, &dwMode))) {
  284. hConOut = 0;
  285. }
  286. }
  287. if (hConOut) {
  288. // Enable ANSI colors on Windows 10+
  289. if (enable_color && !(dwMode & 0x4)) {
  290. SetConsoleMode(hConOut, dwMode | 0x4); // ENABLE_VIRTUAL_TERMINAL_PROCESSING (0x4)
  291. }
  292. // Set console output codepage to UTF8
  293. SetConsoleOutputCP(65001); // CP_UTF8
  294. }
  295. void* hConIn = GetStdHandle((unsigned long)-10); // STD_INPUT_HANDLE (-10)
  296. if (hConIn && hConIn != (void*)-1 && GetConsoleMode(hConIn, &dwMode)) {
  297. // Set console input codepage to UTF8
  298. SetConsoleCP(65001); // CP_UTF8
  299. }
  300. }
  301. #endif