main.cpp 17 KB

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