main.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669
  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 "build-info.h"
  8. #include <cassert>
  9. #include <cinttypes>
  10. #include <cmath>
  11. #include <cstdio>
  12. #include <cstring>
  13. #include <ctime>
  14. #include <fstream>
  15. #include <iostream>
  16. #include <string>
  17. #include <vector>
  18. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
  19. #include <signal.h>
  20. #include <unistd.h>
  21. #elif defined (_WIN32)
  22. #define WIN32_LEAN_AND_MEAN
  23. #define NOMINMAX
  24. #include <windows.h>
  25. #include <signal.h>
  26. #endif
  27. #if defined(_MSC_VER)
  28. #pragma warning(disable: 4244 4267) // possible loss of data
  29. #endif
  30. static console_state con_st;
  31. static llama_context ** g_ctx;
  32. static bool is_interacting = false;
  33. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__)) || defined (_WIN32)
  34. void sigint_handler(int signo) {
  35. if (signo == SIGINT) {
  36. if (!is_interacting) {
  37. is_interacting=true;
  38. } else {
  39. console_cleanup(con_st);
  40. printf("\n");
  41. llama_print_timings(*g_ctx);
  42. _exit(130);
  43. }
  44. }
  45. }
  46. #endif
  47. int main(int argc, char ** argv) {
  48. gpt_params params;
  49. if (gpt_params_parse(argc, argv, params) == false) {
  50. return 1;
  51. }
  52. // save choice to use color for later
  53. // (note for later: this is a slightly awkward choice)
  54. con_st.use_color = params.use_color;
  55. con_st.multiline_input = params.multiline_input;
  56. console_init(con_st);
  57. atexit([]() { console_cleanup(con_st); });
  58. if (params.perplexity) {
  59. printf("\n************\n");
  60. printf("%s: please use the 'perplexity' tool for perplexity calculations\n", __func__);
  61. printf("************\n\n");
  62. return 0;
  63. }
  64. if (params.embedding) {
  65. printf("\n************\n");
  66. printf("%s: please use the 'embedding' tool for embedding calculations\n", __func__);
  67. printf("************\n\n");
  68. return 0;
  69. }
  70. if (params.n_ctx > 2048) {
  71. fprintf(stderr, "%s: warning: model does not support context sizes greater than 2048 tokens (%d specified);"
  72. "expect poor results\n", __func__, params.n_ctx);
  73. } else if (params.n_ctx < 8) {
  74. fprintf(stderr, "%s: warning: minimum context size is 8, using minimum size.\n", __func__);
  75. params.n_ctx = 8;
  76. }
  77. fprintf(stderr, "%s: build = %d (%s)\n", __func__, BUILD_NUMBER, BUILD_COMMIT);
  78. if (params.seed < 0) {
  79. params.seed = time(NULL);
  80. }
  81. fprintf(stderr, "%s: seed = %d\n", __func__, params.seed);
  82. std::mt19937 rng(params.seed);
  83. if (params.random_prompt) {
  84. params.prompt = gpt_random_prompt(rng);
  85. }
  86. llama_init_backend();
  87. llama_context * ctx;
  88. g_ctx = &ctx;
  89. // load the model and apply lora adapter, if any
  90. ctx = llama_init_from_gpt_params(params);
  91. if (ctx == NULL) {
  92. fprintf(stderr, "%s: error: unable to load model\n", __func__);
  93. return 1;
  94. }
  95. // print system information
  96. {
  97. fprintf(stderr, "\n");
  98. fprintf(stderr, "system_info: n_threads = %d / %d | %s\n",
  99. params.n_threads, std::thread::hardware_concurrency(), llama_print_system_info());
  100. }
  101. // determine the maximum memory usage needed to do inference for the given n_batch and n_predict parameters
  102. // uncomment the "used_mem" line in llama.cpp to see the results
  103. if (params.mem_test) {
  104. {
  105. const std::vector<llama_token> tmp(params.n_batch, llama_token_bos());
  106. llama_eval(ctx, tmp.data(), tmp.size(), 0, params.n_threads);
  107. }
  108. {
  109. const std::vector<llama_token> tmp = { 0, };
  110. llama_eval(ctx, tmp.data(), tmp.size(), params.n_predict - 1, params.n_threads);
  111. }
  112. llama_print_timings(ctx);
  113. llama_free(ctx);
  114. return 0;
  115. }
  116. // export the cgraph and exit
  117. if (params.export_cgraph) {
  118. llama_eval_export(ctx, "llama.ggml");
  119. llama_free(ctx);
  120. return 0;
  121. }
  122. std::string path_session = params.path_prompt_cache;
  123. std::vector<llama_token> session_tokens;
  124. if (!path_session.empty()) {
  125. fprintf(stderr, "%s: attempting to load saved session from '%s'\n", __func__, path_session.c_str());
  126. // fopen to check for existing session
  127. FILE * fp = std::fopen(path_session.c_str(), "rb");
  128. if (fp != NULL) {
  129. std::fclose(fp);
  130. session_tokens.resize(params.n_ctx);
  131. size_t n_token_count_out = 0;
  132. if (!llama_load_session_file(ctx, path_session.c_str(), session_tokens.data(), session_tokens.capacity(), &n_token_count_out)) {
  133. fprintf(stderr, "%s: error: failed to load session file '%s'\n", __func__, path_session.c_str());
  134. return 1;
  135. }
  136. session_tokens.resize(n_token_count_out);
  137. llama_set_rng_seed(ctx, params.seed);
  138. fprintf(stderr, "%s: loaded a session with prompt size of %d tokens\n", __func__, (int) session_tokens.size());
  139. } else {
  140. fprintf(stderr, "%s: session file does not exist, will create\n", __func__);
  141. }
  142. }
  143. // tokenize the prompt
  144. std::vector<llama_token> embd_inp;
  145. if (params.interactive_first || params.instruct || !params.prompt.empty() || session_tokens.empty()) {
  146. // Add a space in front of the first character to match OG llama tokenizer behavior
  147. params.prompt.insert(0, 1, ' ');
  148. embd_inp = ::llama_tokenize(ctx, params.prompt, true);
  149. } else {
  150. embd_inp = session_tokens;
  151. }
  152. const int n_ctx = llama_n_ctx(ctx);
  153. if ((int) embd_inp.size() > n_ctx - 4) {
  154. fprintf(stderr, "%s: error: prompt is too long (%d tokens, max %d)\n", __func__, (int) embd_inp.size(), n_ctx - 4);
  155. return 1;
  156. }
  157. // debug message about similarity of saved session, if applicable
  158. size_t n_matching_session_tokens = 0;
  159. if (session_tokens.size()) {
  160. for (llama_token id : session_tokens) {
  161. if (n_matching_session_tokens >= embd_inp.size() || id != embd_inp[n_matching_session_tokens]) {
  162. break;
  163. }
  164. n_matching_session_tokens++;
  165. }
  166. if (params.prompt.empty() && n_matching_session_tokens == embd_inp.size()) {
  167. fprintf(stderr, "%s: using full prompt from session file\n", __func__);
  168. } else if (n_matching_session_tokens >= embd_inp.size()) {
  169. fprintf(stderr, "%s: session file has exact match for prompt!\n", __func__);
  170. } else if (n_matching_session_tokens < (embd_inp.size() / 2)) {
  171. fprintf(stderr, "%s: warning: session file has low similarity to prompt (%zu / %zu tokens); will mostly be reevaluated\n",
  172. __func__, n_matching_session_tokens, embd_inp.size());
  173. } else {
  174. fprintf(stderr, "%s: session file matches %zu / %zu tokens of prompt\n",
  175. __func__, n_matching_session_tokens, embd_inp.size());
  176. }
  177. }
  178. // if we will use the cache for the full prompt without reaching the end of the cache, force
  179. // reevaluation of the last token token to recalculate the cached logits
  180. if (!embd_inp.empty() && n_matching_session_tokens == embd_inp.size() &&
  181. session_tokens.size() > embd_inp.size()) {
  182. session_tokens.resize(embd_inp.size() - 1);
  183. }
  184. // number of tokens to keep when resetting context
  185. if (params.n_keep < 0 || params.n_keep > (int) embd_inp.size() || params.instruct) {
  186. params.n_keep = (int)embd_inp.size();
  187. }
  188. // prefix & suffix for instruct mode
  189. const auto inp_pfx = ::llama_tokenize(ctx, "\n\n### Instruction:\n\n", true);
  190. const auto inp_sfx = ::llama_tokenize(ctx, "\n\n### Response:\n\n", false);
  191. // in instruct mode, we inject a prefix and a suffix to each input by the user
  192. if (params.instruct) {
  193. params.interactive_first = true;
  194. params.antiprompt.push_back("### Instruction:\n\n");
  195. }
  196. // enable interactive mode if interactive start is specified
  197. if (params.interactive_first) {
  198. params.interactive = true;
  199. }
  200. // determine newline token
  201. auto llama_token_newline = ::llama_tokenize(ctx, "\n", false);
  202. if (params.verbose_prompt) {
  203. fprintf(stderr, "\n");
  204. fprintf(stderr, "%s: prompt: '%s'\n", __func__, params.prompt.c_str());
  205. fprintf(stderr, "%s: number of tokens in prompt = %zu\n", __func__, embd_inp.size());
  206. for (int i = 0; i < (int) embd_inp.size(); i++) {
  207. fprintf(stderr, "%6d -> '%s'\n", embd_inp[i], llama_token_to_str(ctx, embd_inp[i]));
  208. }
  209. if (params.n_keep > 0) {
  210. fprintf(stderr, "%s: static prompt based on n_keep: '", __func__);
  211. for (int i = 0; i < params.n_keep; i++) {
  212. fprintf(stderr, "%s", llama_token_to_str(ctx, embd_inp[i]));
  213. }
  214. fprintf(stderr, "'\n");
  215. }
  216. fprintf(stderr, "\n");
  217. }
  218. if (params.interactive) {
  219. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
  220. struct sigaction sigint_action;
  221. sigint_action.sa_handler = sigint_handler;
  222. sigemptyset (&sigint_action.sa_mask);
  223. sigint_action.sa_flags = 0;
  224. sigaction(SIGINT, &sigint_action, NULL);
  225. #elif defined (_WIN32)
  226. auto console_ctrl_handler = +[](DWORD ctrl_type) -> BOOL {
  227. return (ctrl_type == CTRL_C_EVENT) ? (sigint_handler(SIGINT), true) : false;
  228. };
  229. SetConsoleCtrlHandler(static_cast<PHANDLER_ROUTINE>(console_ctrl_handler), true);
  230. #endif
  231. fprintf(stderr, "%s: interactive mode on.\n", __func__);
  232. if (params.antiprompt.size()) {
  233. for (auto antiprompt : params.antiprompt) {
  234. fprintf(stderr, "Reverse prompt: '%s'\n", antiprompt.c_str());
  235. }
  236. }
  237. if (!params.input_prefix.empty()) {
  238. fprintf(stderr, "Input prefix: '%s'\n", params.input_prefix.c_str());
  239. }
  240. if (!params.input_suffix.empty()) {
  241. fprintf(stderr, "Input suffix: '%s'\n", params.input_suffix.c_str());
  242. }
  243. }
  244. fprintf(stderr, "sampling: repeat_last_n = %d, repeat_penalty = %f, presence_penalty = %f, frequency_penalty = %f, top_k = %d, tfs_z = %f, top_p = %f, typical_p = %f, temp = %f, mirostat = %d, mirostat_lr = %f, mirostat_ent = %f\n",
  245. params.repeat_last_n, params.repeat_penalty, params.presence_penalty, params.frequency_penalty, params.top_k, params.tfs_z, params.top_p, params.typical_p, params.temp, params.mirostat, params.mirostat_eta, params.mirostat_tau);
  246. 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);
  247. fprintf(stderr, "\n\n");
  248. // TODO: replace with ring-buffer
  249. std::vector<llama_token> last_n_tokens(n_ctx);
  250. std::fill(last_n_tokens.begin(), last_n_tokens.end(), 0);
  251. if (params.interactive) {
  252. const char *control_message;
  253. if (con_st.multiline_input) {
  254. control_message = " - To return control to LLaMa, end your input with '\\'.\n"
  255. " - To return control without starting a new line, end your input with '/'.\n";
  256. } else {
  257. control_message = " - Press Return to return control to LLaMa.\n"
  258. " - To return control without starting a new line, end your input with '/'.\n"
  259. " - If you want to submit another line, end your input with '\\'.\n";
  260. }
  261. fprintf(stderr, "== Running in interactive mode. ==\n"
  262. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__)) || defined (_WIN32)
  263. " - Press Ctrl+C to interject at any time.\n"
  264. #endif
  265. "%s\n", control_message);
  266. is_interacting = params.interactive_first;
  267. }
  268. bool is_antiprompt = false;
  269. bool input_echo = true;
  270. bool need_to_save_session = !path_session.empty() && n_matching_session_tokens < embd_inp.size();
  271. int n_past = 0;
  272. int n_remain = params.n_predict;
  273. int n_consumed = 0;
  274. int n_session_consumed = 0;
  275. // the first thing we will do is to output the prompt, so set color accordingly
  276. console_set_color(con_st, CONSOLE_COLOR_PROMPT);
  277. std::vector<llama_token> embd;
  278. // do one empty run to warm up the model
  279. {
  280. const std::vector<llama_token> tmp = { llama_token_bos(), };
  281. llama_eval(ctx, tmp.data(), tmp.size(), 0, params.n_threads);
  282. llama_reset_timings(ctx);
  283. }
  284. while ((n_remain != 0 && !is_antiprompt) || params.interactive) {
  285. // predict
  286. if (embd.size() > 0) {
  287. // Note: n_ctx - 4 here is to match the logic for commandline prompt handling via
  288. // --prompt or --file which uses the same value.
  289. auto max_embd_size = n_ctx - 4;
  290. // Ensure the input doesn't exceed the context size by truncating embd if necessary.
  291. if ((int)embd.size() > max_embd_size) {
  292. auto skipped_tokens = embd.size() - max_embd_size;
  293. console_set_color(con_st, CONSOLE_COLOR_ERROR);
  294. printf("<<input too long: skipped %" PRIu64 " token%s>>", skipped_tokens, skipped_tokens != 1 ? "s" : "");
  295. console_set_color(con_st, CONSOLE_COLOR_DEFAULT);
  296. fflush(stdout);
  297. embd.resize(max_embd_size);
  298. }
  299. // infinite text generation via context swapping
  300. // if we run out of context:
  301. // - take the n_keep first tokens from the original prompt (via n_past)
  302. // - take half of the last (n_ctx - n_keep) tokens and recompute the logits in batches
  303. if (n_past + (int) embd.size() > n_ctx) {
  304. const int n_left = n_past - params.n_keep;
  305. // always keep the first token - BOS
  306. n_past = std::max(1, params.n_keep);
  307. // insert n_left/2 tokens at the start of embd from last_n_tokens
  308. embd.insert(embd.begin(), last_n_tokens.begin() + n_ctx - n_left/2 - embd.size(), last_n_tokens.end() - embd.size());
  309. // stop saving session if we run out of context
  310. path_session.clear();
  311. //printf("\n---\n");
  312. //printf("resetting: '");
  313. //for (int i = 0; i < (int) embd.size(); i++) {
  314. // printf("%s", llama_token_to_str(ctx, embd[i]));
  315. //}
  316. //printf("'\n");
  317. //printf("\n---\n");
  318. }
  319. // try to reuse a matching prefix from the loaded session instead of re-eval (via n_past)
  320. if (n_session_consumed < (int) session_tokens.size()) {
  321. size_t i = 0;
  322. for ( ; i < embd.size(); i++) {
  323. if (embd[i] != session_tokens[n_session_consumed]) {
  324. session_tokens.resize(n_session_consumed);
  325. break;
  326. }
  327. n_past++;
  328. n_session_consumed++;
  329. if (n_session_consumed >= (int) session_tokens.size()) {
  330. ++i;
  331. break;
  332. }
  333. }
  334. if (i > 0) {
  335. embd.erase(embd.begin(), embd.begin() + i);
  336. }
  337. }
  338. // evaluate tokens in batches
  339. // embd is typically prepared beforehand to fit within a batch, but not always
  340. for (int i = 0; i < (int) embd.size(); i += params.n_batch) {
  341. int n_eval = (int) embd.size() - i;
  342. if (n_eval > params.n_batch) {
  343. n_eval = params.n_batch;
  344. }
  345. if (llama_eval(ctx, &embd[i], n_eval, n_past, params.n_threads)) {
  346. fprintf(stderr, "%s : failed to eval\n", __func__);
  347. return 1;
  348. }
  349. n_past += n_eval;
  350. }
  351. if (embd.size() > 0 && !path_session.empty()) {
  352. session_tokens.insert(session_tokens.end(), embd.begin(), embd.end());
  353. n_session_consumed = session_tokens.size();
  354. }
  355. }
  356. embd.clear();
  357. if ((int) embd_inp.size() <= n_consumed && !is_interacting) {
  358. // out of user input, sample next token
  359. const float temp = params.temp;
  360. const int32_t top_k = params.top_k <= 0 ? llama_n_vocab(ctx) : params.top_k;
  361. const float top_p = params.top_p;
  362. const float tfs_z = params.tfs_z;
  363. const float typical_p = params.typical_p;
  364. const int32_t repeat_last_n = params.repeat_last_n < 0 ? n_ctx : params.repeat_last_n;
  365. const float repeat_penalty = params.repeat_penalty;
  366. const float alpha_presence = params.presence_penalty;
  367. const float alpha_frequency = params.frequency_penalty;
  368. const int mirostat = params.mirostat;
  369. const float mirostat_tau = params.mirostat_tau;
  370. const float mirostat_eta = params.mirostat_eta;
  371. const bool penalize_nl = params.penalize_nl;
  372. // optionally save the session on first sample (for faster prompt loading next time)
  373. if (!path_session.empty() && need_to_save_session && !params.prompt_cache_ro) {
  374. need_to_save_session = false;
  375. llama_save_session_file(ctx, path_session.c_str(), session_tokens.data(), session_tokens.size());
  376. }
  377. llama_token id = 0;
  378. {
  379. auto logits = llama_get_logits(ctx);
  380. auto n_vocab = llama_n_vocab(ctx);
  381. // Apply params.logit_bias map
  382. for (auto it = params.logit_bias.begin(); it != params.logit_bias.end(); it++) {
  383. logits[it->first] += it->second;
  384. }
  385. std::vector<llama_token_data> candidates;
  386. candidates.reserve(n_vocab);
  387. for (llama_token token_id = 0; token_id < n_vocab; token_id++) {
  388. candidates.emplace_back(llama_token_data{token_id, logits[token_id], 0.0f});
  389. }
  390. llama_token_data_array candidates_p = { candidates.data(), candidates.size(), false };
  391. // Apply penalties
  392. float nl_logit = logits[llama_token_nl()];
  393. auto last_n_repeat = std::min(std::min((int)last_n_tokens.size(), repeat_last_n), n_ctx);
  394. llama_sample_repetition_penalty(ctx, &candidates_p,
  395. last_n_tokens.data() + last_n_tokens.size() - last_n_repeat,
  396. last_n_repeat, repeat_penalty);
  397. llama_sample_frequency_and_presence_penalties(ctx, &candidates_p,
  398. last_n_tokens.data() + last_n_tokens.size() - last_n_repeat,
  399. last_n_repeat, alpha_frequency, alpha_presence);
  400. if (!penalize_nl) {
  401. logits[llama_token_nl()] = nl_logit;
  402. }
  403. if (temp <= 0) {
  404. // Greedy sampling
  405. id = llama_sample_token_greedy(ctx, &candidates_p);
  406. } else {
  407. if (mirostat == 1) {
  408. static float mirostat_mu = 2.0f * mirostat_tau;
  409. const int mirostat_m = 100;
  410. llama_sample_temperature(ctx, &candidates_p, temp);
  411. id = llama_sample_token_mirostat(ctx, &candidates_p, mirostat_tau, mirostat_eta, mirostat_m, &mirostat_mu);
  412. } else if (mirostat == 2) {
  413. static float mirostat_mu = 2.0f * mirostat_tau;
  414. llama_sample_temperature(ctx, &candidates_p, temp);
  415. id = llama_sample_token_mirostat_v2(ctx, &candidates_p, mirostat_tau, mirostat_eta, &mirostat_mu);
  416. } else {
  417. // Temperature sampling
  418. llama_sample_top_k(ctx, &candidates_p, top_k, 1);
  419. llama_sample_tail_free(ctx, &candidates_p, tfs_z, 1);
  420. llama_sample_typical(ctx, &candidates_p, typical_p, 1);
  421. llama_sample_top_p(ctx, &candidates_p, top_p, 1);
  422. llama_sample_temperature(ctx, &candidates_p, temp);
  423. id = llama_sample_token(ctx, &candidates_p);
  424. }
  425. }
  426. // printf("`%d`", candidates_p.size);
  427. last_n_tokens.erase(last_n_tokens.begin());
  428. last_n_tokens.push_back(id);
  429. }
  430. // replace end of text token with newline token when in interactive mode
  431. if (id == llama_token_eos() && params.interactive && !params.instruct) {
  432. id = llama_token_newline.front();
  433. if (params.antiprompt.size() != 0) {
  434. // tokenize and inject first reverse prompt
  435. const auto first_antiprompt = ::llama_tokenize(ctx, params.antiprompt.front(), false);
  436. embd_inp.insert(embd_inp.end(), first_antiprompt.begin(), first_antiprompt.end());
  437. }
  438. }
  439. // add it to the context
  440. embd.push_back(id);
  441. // echo this to console
  442. input_echo = true;
  443. // decrement remaining sampling budget
  444. --n_remain;
  445. } else {
  446. // some user input remains from prompt or interaction, forward it to processing
  447. while ((int) embd_inp.size() > n_consumed) {
  448. embd.push_back(embd_inp[n_consumed]);
  449. last_n_tokens.erase(last_n_tokens.begin());
  450. last_n_tokens.push_back(embd_inp[n_consumed]);
  451. ++n_consumed;
  452. if ((int) embd.size() >= params.n_batch) {
  453. break;
  454. }
  455. }
  456. }
  457. // display text
  458. if (input_echo) {
  459. for (auto id : embd) {
  460. printf("%s", llama_token_to_str(ctx, id));
  461. }
  462. fflush(stdout);
  463. }
  464. // reset color to default if we there is no pending user input
  465. if (input_echo && (int)embd_inp.size() == n_consumed) {
  466. console_set_color(con_st, CONSOLE_COLOR_DEFAULT);
  467. }
  468. // if not currently processing queued inputs;
  469. if ((int) embd_inp.size() <= n_consumed) {
  470. // check for reverse prompt
  471. if (params.antiprompt.size()) {
  472. std::string last_output;
  473. for (auto id : last_n_tokens) {
  474. last_output += llama_token_to_str(ctx, id);
  475. }
  476. is_antiprompt = false;
  477. // Check if each of the reverse prompts appears at the end of the output.
  478. // If we're not running interactively, the reverse prompt might be tokenized with some following characters
  479. // so we'll compensate for that by widening the search window a bit.
  480. for (std::string & antiprompt : params.antiprompt) {
  481. size_t extra_padding = params.interactive ? 0 : 2;
  482. size_t search_start_pos = last_output.length() > static_cast<size_t>(antiprompt.length() + extra_padding)
  483. ? last_output.length() - static_cast<size_t>(antiprompt.length() + extra_padding)
  484. : 0;
  485. if (last_output.find(antiprompt.c_str(), search_start_pos) != std::string::npos) {
  486. if (params.interactive) {
  487. is_interacting = true;
  488. console_set_color(con_st, CONSOLE_COLOR_USER_INPUT);
  489. }
  490. is_antiprompt = true;
  491. fflush(stdout);
  492. break;
  493. }
  494. }
  495. }
  496. if (n_past > 0 && is_interacting) {
  497. if (params.instruct) {
  498. printf("\n> ");
  499. }
  500. std::string buffer;
  501. if (!params.input_prefix.empty()) {
  502. buffer += params.input_prefix;
  503. printf("%s", buffer.c_str());
  504. }
  505. std::string line;
  506. bool another_line = true;
  507. do {
  508. another_line = console_readline(con_st, line);
  509. buffer += line;
  510. } while (another_line);
  511. // done taking input, reset color
  512. console_set_color(con_st, CONSOLE_COLOR_DEFAULT);
  513. // Add tokens to embd only if the input buffer is non-empty
  514. // Entering a empty line lets the user pass control back
  515. if (buffer.length() > 1) {
  516. // append input suffix if any
  517. if (!params.input_suffix.empty()) {
  518. buffer += params.input_suffix;
  519. printf("%s", params.input_suffix.c_str());
  520. }
  521. // instruct mode: insert instruction prefix
  522. if (params.instruct && !is_antiprompt) {
  523. n_consumed = embd_inp.size();
  524. embd_inp.insert(embd_inp.end(), inp_pfx.begin(), inp_pfx.end());
  525. }
  526. auto line_inp = ::llama_tokenize(ctx, buffer, false);
  527. embd_inp.insert(embd_inp.end(), line_inp.begin(), line_inp.end());
  528. // instruct mode: insert response suffix
  529. if (params.instruct) {
  530. embd_inp.insert(embd_inp.end(), inp_sfx.begin(), inp_sfx.end());
  531. }
  532. n_remain -= line_inp.size();
  533. }
  534. input_echo = false; // do not echo this again
  535. }
  536. if (n_past > 0) {
  537. is_interacting = false;
  538. }
  539. }
  540. // end of text token
  541. if (!embd.empty() && embd.back() == llama_token_eos()) {
  542. if (params.instruct) {
  543. is_interacting = true;
  544. } else {
  545. fprintf(stderr, " [end of text]\n");
  546. break;
  547. }
  548. }
  549. // In interactive mode, respect the maximum number of tokens and drop back to user input when reached.
  550. if (params.interactive && n_remain <= 0 && params.n_predict != -1) {
  551. n_remain = params.n_predict;
  552. is_interacting = true;
  553. }
  554. }
  555. if (!path_session.empty() && params.prompt_cache_all && !params.prompt_cache_ro) {
  556. fprintf(stderr, "\n%s: saving final output to session file '%s'\n", __func__, path_session.c_str());
  557. llama_save_session_file(ctx, path_session.c_str(), session_tokens.data(), session_tokens.size());
  558. }
  559. llama_print_timings(ctx);
  560. llama_free(ctx);
  561. return 0;
  562. }