main.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. #include "common.h"
  2. #include "llama.h"
  3. #include <cassert>
  4. #include <cinttypes>
  5. #include <cmath>
  6. #include <cstdio>
  7. #include <cstring>
  8. #include <fstream>
  9. #include <iostream>
  10. #include <string>
  11. #include <vector>
  12. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
  13. #include <signal.h>
  14. #include <unistd.h>
  15. #elif defined (_WIN32)
  16. #include <signal.h>
  17. #endif
  18. #if defined (_WIN32)
  19. #pragma comment(lib,"kernel32.lib")
  20. extern "C" __declspec(dllimport) void* __stdcall GetStdHandle(unsigned long nStdHandle);
  21. extern "C" __declspec(dllimport) int __stdcall GetConsoleMode(void* hConsoleHandle, unsigned long* lpMode);
  22. extern "C" __declspec(dllimport) int __stdcall SetConsoleMode(void* hConsoleHandle, unsigned long dwMode);
  23. #endif
  24. #define ANSI_COLOR_RED "\x1b[31m"
  25. #define ANSI_COLOR_GREEN "\x1b[32m"
  26. #define ANSI_COLOR_YELLOW "\x1b[33m"
  27. #define ANSI_COLOR_BLUE "\x1b[34m"
  28. #define ANSI_COLOR_MAGENTA "\x1b[35m"
  29. #define ANSI_COLOR_CYAN "\x1b[36m"
  30. #define ANSI_COLOR_RESET "\x1b[0m"
  31. #define ANSI_BOLD "\x1b[1m"
  32. /* Keep track of current color of output, and emit ANSI code if it changes. */
  33. enum console_state {
  34. CONSOLE_STATE_DEFAULT=0,
  35. CONSOLE_STATE_PROMPT,
  36. CONSOLE_STATE_USER_INPUT
  37. };
  38. static console_state con_st = CONSOLE_STATE_DEFAULT;
  39. static bool con_use_color = false;
  40. void set_console_state(console_state new_st)
  41. {
  42. if (!con_use_color) return;
  43. // only emit color code if state changed
  44. if (new_st != con_st) {
  45. con_st = new_st;
  46. switch(con_st) {
  47. case CONSOLE_STATE_DEFAULT:
  48. printf(ANSI_COLOR_RESET);
  49. return;
  50. case CONSOLE_STATE_PROMPT:
  51. printf(ANSI_COLOR_YELLOW);
  52. return;
  53. case CONSOLE_STATE_USER_INPUT:
  54. printf(ANSI_BOLD ANSI_COLOR_GREEN);
  55. return;
  56. }
  57. }
  58. }
  59. static bool is_interacting = false;
  60. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__)) || defined (_WIN32)
  61. void sigint_handler(int signo) {
  62. set_console_state(CONSOLE_STATE_DEFAULT);
  63. printf("\n"); // this also force flush stdout.
  64. if (signo == SIGINT) {
  65. if (!is_interacting) {
  66. is_interacting=true;
  67. } else {
  68. _exit(130);
  69. }
  70. }
  71. }
  72. #endif
  73. int main(int argc, char ** argv) {
  74. gpt_params params;
  75. params.model = "models/llama-7B/ggml-model.bin";
  76. if (gpt_params_parse(argc, argv, params) == false) {
  77. return 1;
  78. }
  79. if (params.perplexity) {
  80. printf("\n************\n");
  81. printf("%s: please use the 'perplexity' tool for perplexity calculations\n", __func__);
  82. printf("************\n\n");
  83. return 0;
  84. }
  85. if (params.n_ctx > 2048) {
  86. fprintf(stderr, "%s: warning: model does not support context sizes greater than 2048 tokens (%d specified);"
  87. "expect poor results\n", __func__, params.n_ctx);
  88. }
  89. if (params.seed <= 0) {
  90. params.seed = time(NULL);
  91. }
  92. fprintf(stderr, "%s: seed = %d\n", __func__, params.seed);
  93. std::mt19937 rng(params.seed);
  94. if (params.random_prompt) {
  95. params.prompt = gpt_random_prompt(rng);
  96. }
  97. // save choice to use color for later
  98. // (note for later: this is a slightly awkward choice)
  99. con_use_color = params.use_color;
  100. // params.prompt = R"(// this function checks if the number n is prime
  101. //bool is_prime(int n) {)";
  102. llama_context * ctx;
  103. // load the model
  104. {
  105. auto lparams = llama_context_default_params();
  106. lparams.n_ctx = params.n_ctx;
  107. lparams.n_parts = params.n_parts;
  108. lparams.seed = params.seed;
  109. lparams.f16_kv = params.memory_f16;
  110. lparams.use_mlock = params.use_mlock;
  111. ctx = llama_init_from_file(params.model.c_str(), lparams);
  112. if (ctx == NULL) {
  113. fprintf(stderr, "%s: error: failed to load model '%s'\n", __func__, params.model.c_str());
  114. return 1;
  115. }
  116. }
  117. // print system information
  118. {
  119. fprintf(stderr, "\n");
  120. fprintf(stderr, "system_info: n_threads = %d / %d | %s\n",
  121. params.n_threads, std::thread::hardware_concurrency(), llama_print_system_info());
  122. }
  123. // determine the maximum memory usage needed to do inference for the given n_batch and n_predict parameters
  124. // uncomment the "used_mem" line in llama.cpp to see the results
  125. if (params.mem_test) {
  126. {
  127. const std::vector<llama_token> tmp(params.n_batch, 0);
  128. llama_eval(ctx, tmp.data(), tmp.size(), 0, params.n_threads);
  129. }
  130. {
  131. const std::vector<llama_token> tmp = { 0, };
  132. llama_eval(ctx, tmp.data(), tmp.size(), params.n_predict - 1, params.n_threads);
  133. }
  134. llama_print_timings(ctx);
  135. llama_free(ctx);
  136. return 0;
  137. }
  138. int n_past = 0;
  139. // Add a space in front of the first character to match OG llama tokenizer behavior
  140. params.prompt.insert(0, 1, ' ');
  141. // tokenize the prompt
  142. auto embd_inp = ::llama_tokenize(ctx, params.prompt, true);
  143. const int n_ctx = llama_n_ctx(ctx);
  144. params.n_predict = std::min(params.n_predict, n_ctx - (int) embd_inp.size());
  145. // prefix & suffix for instruct mode
  146. const auto inp_pfx = ::llama_tokenize(ctx, "\n\n### Instruction:\n\n", true);
  147. const auto inp_sfx = ::llama_tokenize(ctx, "\n\n### Response:\n\n", false);
  148. // in instruct mode, we inject a prefix and a suffix to each input by the user
  149. if (params.instruct) {
  150. params.interactive = true;
  151. params.antiprompt.push_back("### Instruction:\n\n");
  152. }
  153. // enable interactive mode if reverse prompt is specified
  154. if (params.antiprompt.size() != 0) {
  155. params.interactive = true;
  156. }
  157. if (params.interactive_start) {
  158. params.interactive = true;
  159. }
  160. // determine newline token
  161. auto llama_token_newline = ::llama_tokenize(ctx, "\n", false);
  162. if (params.verbose_prompt) {
  163. fprintf(stderr, "\n");
  164. fprintf(stderr, "%s: prompt: '%s'\n", __func__, params.prompt.c_str());
  165. fprintf(stderr, "%s: number of tokens in prompt = %zu\n", __func__, embd_inp.size());
  166. for (int i = 0; i < (int) embd_inp.size(); i++) {
  167. fprintf(stderr, "%6d -> '%s'\n", embd_inp[i], llama_token_to_str(ctx, embd_inp[i]));
  168. }
  169. fprintf(stderr, "\n");
  170. }
  171. if (params.interactive) {
  172. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
  173. struct sigaction sigint_action;
  174. sigint_action.sa_handler = sigint_handler;
  175. sigemptyset (&sigint_action.sa_mask);
  176. sigint_action.sa_flags = 0;
  177. sigaction(SIGINT, &sigint_action, NULL);
  178. #elif defined (_WIN32)
  179. signal(SIGINT, sigint_handler);
  180. #endif
  181. fprintf(stderr, "%s: interactive mode on.\n", __func__);
  182. if(params.antiprompt.size()) {
  183. for (auto antiprompt : params.antiprompt) {
  184. fprintf(stderr, "Reverse prompt: '%s'\n", antiprompt.c_str());
  185. }
  186. }
  187. if (!params.input_prefix.empty()) {
  188. fprintf(stderr, "Input prefix: '%s'\n", params.input_prefix.c_str());
  189. }
  190. }
  191. fprintf(stderr, "sampling parameters: temp = %f, top_k = %d, top_p = %f, repeat_last_n = %i, repeat_penalty = %f\n", params.temp, params.top_k, params.top_p, params.repeat_last_n, params.repeat_penalty);
  192. fprintf(stderr, "\n\n");
  193. std::vector<llama_token> embd;
  194. int last_n_size = params.repeat_last_n;
  195. std::vector<llama_token> last_n_tokens(last_n_size);
  196. std::fill(last_n_tokens.begin(), last_n_tokens.end(), 0);
  197. if (params.interactive) {
  198. fprintf(stderr, "== Running in interactive mode. ==\n"
  199. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__)) || defined (_WIN32)
  200. " - Press Ctrl+C to interject at any time.\n"
  201. #endif
  202. " - Press Return to return control to LLaMa.\n"
  203. " - If you want to submit another line, end your input in '\\'.\n\n");
  204. is_interacting = params.interactive_start || params.instruct;
  205. }
  206. int input_consumed = 0;
  207. bool input_noecho = false;
  208. int remaining_tokens = params.n_predict;
  209. #if defined (_WIN32)
  210. if (params.use_color) {
  211. // Enable ANSI colors on Windows 10+
  212. unsigned long dwMode = 0;
  213. void* hConOut = GetStdHandle((unsigned long)-11); // STD_OUTPUT_HANDLE (-11)
  214. if (hConOut && hConOut != (void*)-1 && GetConsoleMode(hConOut, &dwMode) && !(dwMode & 0x4)) {
  215. SetConsoleMode(hConOut, dwMode | 0x4); // ENABLE_VIRTUAL_TERMINAL_PROCESSING (0x4)
  216. }
  217. }
  218. #endif
  219. // the first thing we will do is to output the prompt, so set color accordingly
  220. set_console_state(CONSOLE_STATE_PROMPT);
  221. while (remaining_tokens > 0 || params.interactive) {
  222. // predict
  223. if (embd.size() > 0) {
  224. if (llama_eval(ctx, embd.data(), embd.size(), n_past, params.n_threads)) {
  225. fprintf(stderr, "%s : failed to eval\n", __func__);
  226. return 1;
  227. }
  228. }
  229. n_past += embd.size();
  230. embd.clear();
  231. if ((int) embd_inp.size() <= input_consumed && !is_interacting) {
  232. // out of user input, sample next token
  233. const float top_k = params.top_k;
  234. const float top_p = params.top_p;
  235. const float temp = params.temp;
  236. const float repeat_penalty = params.repeat_penalty;
  237. llama_token id = 0;
  238. {
  239. auto logits = llama_get_logits(ctx);
  240. if (params.ignore_eos) {
  241. logits[llama_token_eos()] = 0;
  242. }
  243. id = llama_sample_top_p_top_k(ctx, last_n_tokens.data(), last_n_tokens.size(), top_k, top_p, temp, repeat_penalty);
  244. last_n_tokens.erase(last_n_tokens.begin());
  245. last_n_tokens.push_back(id);
  246. }
  247. // replace end of text token with newline token when in interactive mode
  248. if (id == llama_token_eos() && params.interactive && !params.instruct) {
  249. id = llama_token_newline.front();
  250. if (params.antiprompt.size() != 0) {
  251. // tokenize and inject first reverse prompt
  252. const auto first_antiprompt = ::llama_tokenize(ctx, params.antiprompt.front(), false);
  253. embd_inp.insert(embd_inp.end(), first_antiprompt.begin(), first_antiprompt.end());
  254. }
  255. }
  256. // add it to the context
  257. embd.push_back(id);
  258. // echo this to console
  259. input_noecho = false;
  260. // decrement remaining sampling budget
  261. --remaining_tokens;
  262. } else {
  263. // some user input remains from prompt or interaction, forward it to processing
  264. while ((int) embd_inp.size() > input_consumed) {
  265. embd.push_back(embd_inp[input_consumed]);
  266. last_n_tokens.erase(last_n_tokens.begin());
  267. last_n_tokens.push_back(embd_inp[input_consumed]);
  268. ++input_consumed;
  269. if ((int) embd.size() >= params.n_batch) {
  270. break;
  271. }
  272. }
  273. }
  274. // display text
  275. if (!input_noecho) {
  276. for (auto id : embd) {
  277. printf("%s", llama_token_to_str(ctx, id));
  278. }
  279. fflush(stdout);
  280. }
  281. // reset color to default if we there is no pending user input
  282. if (!input_noecho && (int)embd_inp.size() == input_consumed) {
  283. set_console_state(CONSOLE_STATE_DEFAULT);
  284. }
  285. // in interactive mode, and not currently processing queued inputs;
  286. // check if we should prompt the user for more
  287. if (params.interactive && (int) embd_inp.size() <= input_consumed) {
  288. // check for reverse prompt
  289. std::string last_output;
  290. for (auto id : last_n_tokens) {
  291. last_output += llama_token_to_str(ctx, id);
  292. }
  293. // Check if each of the reverse prompts appears at the end of the output.
  294. for (std::string & antiprompt : params.antiprompt) {
  295. if (last_output.find(antiprompt.c_str(), last_output.length() - antiprompt.length(), antiprompt.length()) != std::string::npos) {
  296. is_interacting = true;
  297. set_console_state(CONSOLE_STATE_USER_INPUT);
  298. fflush(stdout);
  299. break;
  300. }
  301. }
  302. if (n_past > 0 && is_interacting) {
  303. // potentially set color to indicate we are taking user input
  304. set_console_state(CONSOLE_STATE_USER_INPUT);
  305. if (params.instruct) {
  306. input_consumed = embd_inp.size();
  307. embd_inp.insert(embd_inp.end(), inp_pfx.begin(), inp_pfx.end());
  308. printf("\n> ");
  309. }
  310. std::string buffer;
  311. if (!params.input_prefix.empty()) {
  312. buffer += params.input_prefix;
  313. printf("%s", buffer.c_str());
  314. }
  315. std::string line;
  316. bool another_line = true;
  317. do {
  318. std::getline(std::cin, line);
  319. if (line.empty() || line.back() != '\\') {
  320. another_line = false;
  321. } else {
  322. line.pop_back(); // Remove the continue character
  323. }
  324. buffer += line + '\n'; // Append the line to the result
  325. } while (another_line);
  326. // done taking input, reset color
  327. set_console_state(CONSOLE_STATE_DEFAULT);
  328. auto line_inp = ::llama_tokenize(ctx, buffer, false);
  329. embd_inp.insert(embd_inp.end(), line_inp.begin(), line_inp.end());
  330. if (params.instruct) {
  331. embd_inp.insert(embd_inp.end(), inp_sfx.begin(), inp_sfx.end());
  332. }
  333. remaining_tokens -= line_inp.size();
  334. input_noecho = true; // do not echo this again
  335. }
  336. if (n_past > 0) {
  337. is_interacting = false;
  338. }
  339. }
  340. // end of text token
  341. if (embd.back() == llama_token_eos()) {
  342. if (params.instruct) {
  343. is_interacting = true;
  344. } else {
  345. fprintf(stderr, " [end of text]\n");
  346. break;
  347. }
  348. }
  349. // In interactive mode, respect the maximum number of tokens and drop back to user input when reached.
  350. if (params.interactive && remaining_tokens <= 0) {
  351. remaining_tokens = params.n_predict;
  352. is_interacting = true;
  353. }
  354. }
  355. #if defined (_WIN32)
  356. signal(SIGINT, SIG_DFL);
  357. #endif
  358. llama_print_timings(ctx);
  359. llama_free(ctx);
  360. set_console_state(CONSOLE_STATE_DEFAULT);
  361. return 0;
  362. }