main.cpp 16 KB

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