main.cpp 24 KB

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