main.cpp 17 KB

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