main.cpp 16 KB

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