main.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  1. // Defines sigaction on msys:
  2. #ifndef _GNU_SOURCE
  3. #define _GNU_SOURCE
  4. #endif
  5. #include "common.h"
  6. #include "llama.h"
  7. #include <cassert>
  8. #include <cinttypes>
  9. #include <cmath>
  10. #include <cstdio>
  11. #include <cstring>
  12. #include <fstream>
  13. #include <iostream>
  14. #include <string>
  15. #include <vector>
  16. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
  17. #include <signal.h>
  18. #include <unistd.h>
  19. #elif defined (_WIN32)
  20. #include <signal.h>
  21. #endif
  22. static console_state con_st;
  23. static bool is_interacting = false;
  24. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__)) || defined (_WIN32)
  25. void sigint_handler(int signo) {
  26. set_console_color(con_st, CONSOLE_COLOR_DEFAULT);
  27. fflush(stdout);
  28. fflush(stderr);
  29. if (signo == SIGINT) {
  30. if (!is_interacting) {
  31. is_interacting=true;
  32. } else {
  33. _exit(130);
  34. }
  35. }
  36. }
  37. #endif
  38. int main(int argc, char ** argv) {
  39. gpt_params params;
  40. params.model = "models/llama-7B/ggml-model.bin";
  41. if (gpt_params_parse(argc, argv, params) == false) {
  42. return 1;
  43. }
  44. // save choice to use color for later
  45. // (note for later: this is a slightly awkward choice)
  46. con_st.use_color = params.use_color;
  47. #if defined (_WIN32)
  48. win32_console_init(params.use_color);
  49. #endif
  50. if (params.perplexity) {
  51. printf("\n************\n");
  52. printf("%s: please use the 'perplexity' tool for perplexity calculations\n", __func__);
  53. printf("************\n\n");
  54. return 0;
  55. }
  56. if (params.embedding) {
  57. printf("\n************\n");
  58. printf("%s: please use the 'embedding' tool for embedding calculations\n", __func__);
  59. printf("************\n\n");
  60. return 0;
  61. }
  62. if (params.n_ctx > 2048) {
  63. fprintf(stderr, "%s: warning: model does not support context sizes greater than 2048 tokens (%d specified);"
  64. "expect poor results\n", __func__, params.n_ctx);
  65. }
  66. if (params.seed <= 0) {
  67. params.seed = time(NULL);
  68. }
  69. fprintf(stderr, "%s: seed = %d\n", __func__, params.seed);
  70. std::mt19937 rng(params.seed);
  71. if (params.random_prompt) {
  72. params.prompt = gpt_random_prompt(rng);
  73. }
  74. bool instruct_mode = !params.instruct_prefix.empty() || !params.instruct_suffix.empty();
  75. // params.prompt = R"(// this function checks if the number n is prime
  76. //bool is_prime(int n) {)";
  77. llama_context * ctx;
  78. // load the model
  79. {
  80. auto lparams = llama_context_default_params();
  81. lparams.n_ctx = params.n_ctx;
  82. lparams.n_parts = params.n_parts;
  83. lparams.seed = params.seed;
  84. lparams.f16_kv = params.memory_f16;
  85. lparams.use_mmap = params.use_mmap;
  86. lparams.use_mlock = params.use_mlock;
  87. ctx = llama_init_from_file(params.model.c_str(), lparams);
  88. if (ctx == NULL) {
  89. fprintf(stderr, "%s: error: failed to load model '%s'\n", __func__, params.model.c_str());
  90. return 1;
  91. }
  92. }
  93. // print system information
  94. {
  95. fprintf(stderr, "\n");
  96. fprintf(stderr, "system_info: n_threads = %d / %d | %s\n",
  97. params.n_threads, std::thread::hardware_concurrency(), llama_print_system_info());
  98. }
  99. // determine the maximum memory usage needed to do inference for the given n_batch and n_predict parameters
  100. // uncomment the "used_mem" line in llama.cpp to see the results
  101. if (params.mem_test) {
  102. {
  103. const std::vector<llama_token> tmp(params.n_batch, 0);
  104. llama_eval(ctx, tmp.data(), tmp.size(), 0, params.n_threads);
  105. }
  106. {
  107. const std::vector<llama_token> tmp = { 0, };
  108. llama_eval(ctx, tmp.data(), tmp.size(), params.n_predict - 1, params.n_threads);
  109. }
  110. llama_print_timings(ctx);
  111. llama_free(ctx);
  112. return 0;
  113. }
  114. // Add a space in front of the first character to match OG llama tokenizer behavior
  115. params.prompt.insert(0, 1, ' ');
  116. // tokenize the prompt
  117. auto embd_inp = ::llama_tokenize(ctx, params.prompt, true);
  118. const int n_ctx = llama_n_ctx(ctx);
  119. if ((int) embd_inp.size() > n_ctx - 4) {
  120. fprintf(stderr, "%s: error: prompt is too long (%d tokens, max %d)\n", __func__, (int) embd_inp.size(), n_ctx - 4);
  121. return 1;
  122. }
  123. // number of tokens to keep when resetting context
  124. if (params.n_keep < 0 || params.n_keep > (int)embd_inp.size()) {
  125. params.n_keep = (int)embd_inp.size();
  126. }
  127. // prefix & suffix for instruct mode
  128. const auto inp_pfx = ::llama_tokenize(ctx, params.instruct_prefix, params.instruct_prefix_bos);
  129. std::string instruct_suffix = params.instruct_suffix;
  130. if (params.rm_trailing_space_workaround) {
  131. if (instruct_suffix.back() == ' ') { instruct_suffix.pop_back(); }
  132. }
  133. const auto inp_sfx = ::llama_tokenize(ctx, instruct_suffix, params.instruct_suffix_bos);
  134. // enable interactive mode if reverse prompt or interactive start is specified
  135. if (params.antiprompt.size() != 0 || params.stopprompt.size() != 0 || params.interactive_start) {
  136. params.interactive = true;
  137. }
  138. // determine newline token
  139. auto llama_token_newline = ::llama_tokenize(ctx, "\n", false);
  140. if (params.verbose_prompt) {
  141. fprintf(stderr, "\n");
  142. fprintf(stderr, "%s: prompt: '%s'\n", __func__, params.prompt.c_str());
  143. fprintf(stderr, "%s: number of tokens in prompt = %zu\n", __func__, embd_inp.size());
  144. for (int i = 0; i < (int) embd_inp.size(); i++) {
  145. fprintf(stderr, "%6d -> '%s'\n", embd_inp[i], llama_token_to_str(ctx, embd_inp[i]));
  146. }
  147. if (params.n_keep > 0) {
  148. fprintf(stderr, "%s: static prompt based on n_keep: '", __func__);
  149. for (int i = 0; i < params.n_keep; i++) {
  150. fprintf(stderr, "%s", llama_token_to_str(ctx, embd_inp[i]));
  151. }
  152. fprintf(stderr, "'\n");
  153. }
  154. fprintf(stderr, "\n");
  155. }
  156. if (params.interactive) {
  157. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
  158. struct sigaction sigint_action;
  159. sigint_action.sa_handler = sigint_handler;
  160. sigemptyset (&sigint_action.sa_mask);
  161. sigint_action.sa_flags = 0;
  162. sigaction(SIGINT, &sigint_action, NULL);
  163. #elif defined (_WIN32)
  164. signal(SIGINT, sigint_handler);
  165. #endif
  166. fprintf(stderr, "%s: interactive mode on.\n", __func__);
  167. if (params.antiprompt.size()) {
  168. for (auto antiprompt : params.antiprompt) {
  169. fprintf(stderr, "Reverse prompt: '%s'\n", antiprompt.c_str());
  170. }
  171. }
  172. if (params.stopprompt.size()) {
  173. for (auto stopprompt : params.stopprompt) {
  174. fprintf(stderr, "Stop prompt: '%s'\n", stopprompt.c_str());
  175. }
  176. }
  177. if (!params.input_prefix.empty()) {
  178. fprintf(stderr, "Input prefix: '%s'\n", params.input_prefix.c_str());
  179. }
  180. if (!params.instruct_prefix.empty()) {
  181. fprintf(stderr, "Instruct prefix %s: '%s'\n", params.instruct_prefix_bos ? "(with bos token)" : "", params.instruct_prefix.c_str());
  182. }
  183. if (!params.instruct_suffix.empty()) {
  184. fprintf(stderr, "Instruct suffix %s: '%s'\n", params.instruct_suffix_bos ? "(with bos token)" : "", params.instruct_suffix.c_str());
  185. }
  186. }
  187. fprintf(stderr, "sampling: temp = %f, top_k = %d, top_p = %f, repeat_last_n = %i, repeat_penalty = %f\n",
  188. params.temp, params.top_k, params.top_p, params.repeat_last_n, params.repeat_penalty);
  189. 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);
  190. fprintf(stderr, "\n\n");
  191. // TODO: replace with ring-buffer
  192. std::vector<llama_token> last_n_tokens(n_ctx);
  193. std::fill(last_n_tokens.begin(), last_n_tokens.end(), 0);
  194. if (params.interactive) {
  195. fprintf(stderr, "== Running in interactive mode. ==\n"
  196. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__)) || defined (_WIN32)
  197. " - Press Ctrl+C to interject at any time.\n"
  198. #endif
  199. );
  200. if (params.multiline_mode) {
  201. fprintf(stderr, " - Press Return to return control to LLaMa.\n"
  202. #if defined (_WIN32)
  203. " - [MULTILINE MODE] Press Ctrl+Z then Return (EOF) to toggle.\n\n");
  204. #else
  205. " - [MULTILINE MODE] Press Ctrl+D (EOF) to toggle.\n\n");
  206. #endif
  207. }
  208. else {
  209. fprintf(stderr, " - Press Return to return control to LLaMa.\n"
  210. " - If you want to submit another line, end your input in '\\'.\n\n");
  211. }
  212. is_interacting = params.interactive_start;
  213. }
  214. struct Antiprompt {
  215. bool any = false;
  216. bool trailing_space = false;
  217. size_t len;
  218. bool is_stop_prompt = false;
  219. } antiprompt;
  220. bool input_noecho = false;
  221. int n_past = 0;
  222. int n_remain = params.n_predict;
  223. int n_consumed = 0;
  224. // the first thing we will do is to output the prompt, so set color accordingly
  225. set_console_color(con_st, CONSOLE_COLOR_PROMPT);
  226. std::vector<llama_token> embd;
  227. while (n_remain != 0 || params.interactive) {
  228. // predict
  229. if (embd.size() > 0) {
  230. // infinite text generation via context swapping
  231. // if we run out of context:
  232. // - take the n_keep first tokens from the original prompt (via n_past)
  233. // - take half of the last (n_ctx - n_keep) tokens and recompute the logits in a batch
  234. if (n_past + (int) embd.size() > n_ctx) {
  235. const int n_left = n_past - params.n_keep;
  236. n_past = params.n_keep;
  237. // insert n_left/2 tokens at the start of embd from last_n_tokens
  238. embd.insert(embd.begin(), last_n_tokens.begin() + n_ctx - n_left/2 - embd.size(), last_n_tokens.end() - embd.size());
  239. //printf("\n---\n");
  240. //printf("resetting: '");
  241. //for (int i = 0; i < (int) embd.size(); i++) {
  242. // printf("%s", llama_token_to_str(ctx, embd[i]));
  243. //}
  244. //printf("'\n");
  245. //printf("\n---\n");
  246. }
  247. if (llama_eval(ctx, embd.data(), embd.size(), n_past, params.n_threads)) {
  248. fprintf(stderr, "%s : failed to eval\n", __func__);
  249. return 1;
  250. }
  251. }
  252. n_past += embd.size();
  253. embd.clear();
  254. if ((int) embd_inp.size() <= n_consumed && !is_interacting) {
  255. // out of user input, sample next token
  256. const int32_t top_k = params.top_k;
  257. const float top_p = params.top_p;
  258. const float temp = params.temp;
  259. const float repeat_penalty = params.repeat_penalty;
  260. llama_token id = 0;
  261. {
  262. auto logits = llama_get_logits(ctx);
  263. if (params.ignore_eos) {
  264. logits[llama_token_eos()] = 0;
  265. }
  266. id = llama_sample_top_p_top_k(ctx,
  267. last_n_tokens.data() + n_ctx - params.repeat_last_n,
  268. params.repeat_last_n, top_k, top_p, temp, repeat_penalty);
  269. last_n_tokens.erase(last_n_tokens.begin());
  270. last_n_tokens.push_back(id);
  271. }
  272. // replace end of text token with newline token when in interactive mode
  273. if (id == llama_token_eos() && params.interactive && !instruct_mode) {
  274. id = llama_token_newline.front();
  275. if (params.antiprompt.size() != 0) {
  276. // tokenize and inject first reverse prompt
  277. const auto first_antiprompt = ::llama_tokenize(ctx, params.antiprompt.front(), false);
  278. embd_inp.insert(embd_inp.end(), first_antiprompt.begin(), first_antiprompt.end());
  279. }
  280. }
  281. // add it to the context
  282. embd.push_back(id);
  283. // echo this to console
  284. input_noecho = false;
  285. // decrement remaining sampling budget
  286. --n_remain;
  287. } else {
  288. // some user input remains from prompt or interaction, forward it to processing
  289. while ((int) embd_inp.size() > n_consumed) {
  290. embd.push_back(embd_inp[n_consumed]);
  291. last_n_tokens.erase(last_n_tokens.begin());
  292. last_n_tokens.push_back(embd_inp[n_consumed]);
  293. ++n_consumed;
  294. if ((int) embd.size() >= params.n_batch) {
  295. break;
  296. }
  297. }
  298. }
  299. // display text
  300. if (!input_noecho) {
  301. for (auto id : embd) {
  302. printf("%s", llama_token_to_str(ctx, id));
  303. }
  304. fflush(stdout);
  305. }
  306. // reset color to default if we there is no pending user input
  307. if (!input_noecho && (int)embd_inp.size() == n_consumed) {
  308. set_console_color(con_st, CONSOLE_COLOR_DEFAULT);
  309. }
  310. // in interactive mode, and not currently processing queued inputs;
  311. // check if we should prompt the user for more
  312. if (params.interactive && (int) embd_inp.size() <= n_consumed) {
  313. // check for reverse prompt or stop prompt
  314. if (params.antiprompt.size() || params.stopprompt.size()) {
  315. std::string last_output;
  316. for (auto id : last_n_tokens) {
  317. last_output += llama_token_to_str(ctx, id);
  318. }
  319. antiprompt.any = false;
  320. antiprompt.is_stop_prompt = false;
  321. // Check if each of the reverse prompts appears at the end of the output.
  322. for (std::string & prompt : params.antiprompt) {
  323. if (params.rm_trailing_space_workaround) {
  324. antiprompt.trailing_space = prompt.back() == ' ';
  325. antiprompt.len = prompt.length() - (antiprompt.trailing_space ? 1 : 0);
  326. }
  327. if (last_output.find(prompt.c_str(), last_output.length() - antiprompt.len, antiprompt.len) != std::string::npos) {
  328. is_interacting = true;
  329. antiprompt.any = true;
  330. set_console_color(con_st, CONSOLE_COLOR_USER_INPUT);
  331. fflush(stdout);
  332. break;
  333. }
  334. }
  335. if (!antiprompt.any) {
  336. for (std::string & prompt : params.stopprompt) {
  337. if (params.rm_trailing_space_workaround) {
  338. antiprompt.trailing_space = prompt.back() == ' ';
  339. antiprompt.len = prompt.length() - (antiprompt.trailing_space ? 1 : 0);
  340. }
  341. if (last_output.find(prompt.c_str(), last_output.length() - antiprompt.len, antiprompt.len) != std::string::npos) {
  342. is_interacting = true;
  343. antiprompt.any = true;
  344. antiprompt.is_stop_prompt = true;
  345. set_console_color(con_st, CONSOLE_COLOR_USER_INPUT);
  346. fflush(stdout);
  347. break;
  348. }
  349. }
  350. }
  351. }
  352. if (n_past > 0 && is_interacting)
  353. {
  354. std::string buffer;
  355. if (!params.clean_interface && !params.instruct_prefix.empty() && !antiprompt.any) {
  356. // avoid printing again user's new line (TODO: try to revert enter press and print newline)
  357. int i = params.instruct_prefix.front() == '\n' ? 1 : 0;
  358. for (; i < inp_pfx.size(); i++) {
  359. printf("%s", llama_token_to_str(ctx, inp_pfx[i]));
  360. }
  361. fflush(stdout);
  362. }
  363. if (params.rm_trailing_space_workaround) {
  364. // add only if not stopprompt (as stopprompt could be used to pause
  365. // assistant and then continue without input - adding back trailing
  366. // space may mess it up.)
  367. if (!antiprompt.is_stop_prompt && antiprompt.any && antiprompt.trailing_space) {
  368. // add back removed trailing space to buffer(workaround)
  369. buffer += ' ';
  370. if (!params.clean_interface) {
  371. printf("%s", buffer.c_str());
  372. }
  373. fflush(stdout);
  374. }
  375. }
  376. // potentially set color to indicate we are taking user input
  377. set_console_color(con_st, CONSOLE_COLOR_USER_INPUT);
  378. #if defined (_WIN32)
  379. // Windows: must reactivate sigint handler after each signal
  380. signal(SIGINT, sigint_handler);
  381. #endif
  382. if (params.clean_interface) {
  383. printf("\n> ");
  384. }
  385. if (!params.input_prefix.empty()) {
  386. buffer += params.input_prefix;
  387. printf("%s", buffer.c_str());
  388. }
  389. if (!get_input_text(buffer, params.multiline_mode)) {
  390. // input stream is bad
  391. return 1;
  392. }
  393. if (!antiprompt.is_stop_prompt) {
  394. buffer += "\n";
  395. }
  396. // done taking input, reset color
  397. set_console_color(con_st, CONSOLE_COLOR_DEFAULT);
  398. if (!params.clean_interface && !params.instruct_suffix.empty() && !antiprompt.is_stop_prompt) {
  399. // avoid printing again user's new line (TODO: try to revert enter press and print newline)
  400. int i = params.instruct_suffix.front() == '\n' ? 1 : 0;
  401. for (; i < inp_sfx.size(); i++) {
  402. printf("%s", llama_token_to_str(ctx, inp_sfx[i]));
  403. }
  404. // if (remove trailing space workaround) {
  405. // We won't add back removed trailing space here, because assistant continues here,
  406. // and it may mess up it's output (remove trailing space workaround).
  407. // }
  408. fflush(stdout);
  409. }
  410. // Add tokens to embd only if the input buffer is non-empty
  411. // Entering a empty line lets the user pass control back
  412. if (buffer.length() > 1) {
  413. // insert input prefix
  414. if (!params.instruct_prefix.empty() && !antiprompt.any) {
  415. n_consumed = embd_inp.size();
  416. embd_inp.insert(embd_inp.end(), inp_pfx.begin(), inp_pfx.end());
  417. }
  418. auto line_inp = ::llama_tokenize(ctx, buffer, false);
  419. embd_inp.insert(embd_inp.end(), line_inp.begin(), line_inp.end());
  420. // insert response suffix
  421. if (!params.instruct_suffix.empty() && !antiprompt.is_stop_prompt) {
  422. embd_inp.insert(embd_inp.end(), inp_sfx.begin(), inp_sfx.end());
  423. }
  424. n_remain -= line_inp.size();
  425. }
  426. input_noecho = true; // do not echo this again
  427. }
  428. if (n_past > 0) {
  429. is_interacting = false;
  430. }
  431. }
  432. // end of text token
  433. if (!embd.empty() && embd.back() == llama_token_eos()) {
  434. if (instruct_mode) {
  435. is_interacting = true;
  436. } else {
  437. fprintf(stderr, " [end of text]\n");
  438. break;
  439. }
  440. }
  441. // In interactive mode, respect the maximum number of tokens and drop back to user input when reached.
  442. if (params.interactive && n_remain <= 0 && params.n_predict != -1) {
  443. n_remain = params.n_predict;
  444. is_interacting = true;
  445. }
  446. }
  447. #if defined (_WIN32)
  448. signal(SIGINT, SIG_DFL);
  449. #endif
  450. llama_print_timings(ctx);
  451. llama_free(ctx);
  452. set_console_color(con_st, CONSOLE_COLOR_DEFAULT);
  453. return 0;
  454. }