common.cpp 13 KB

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