main.cpp 27 KB

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