infill.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632
  1. #include "arg.h"
  2. #include "common.h"
  3. #include "console.h"
  4. #include "sampling.h"
  5. #include "log.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 <sstream>
  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 llama_context ** g_ctx;
  33. static llama_model ** g_model;
  34. static gpt_sampler ** g_smpl;
  35. static gpt_params * g_params;
  36. static std::vector<llama_token> * g_input_tokens;
  37. static std::ostringstream * g_output_ss;
  38. static std::vector<llama_token> * g_output_tokens;
  39. static bool is_interacting = false;
  40. static void write_logfile(
  41. const llama_context * ctx, const gpt_params & params, const llama_model * model,
  42. const std::vector<llama_token> & input_tokens, const std::string & output,
  43. const std::vector<llama_token> & output_tokens
  44. ) {
  45. if (params.logdir.empty()) {
  46. return;
  47. }
  48. const std::string timestamp = string_get_sortable_timestamp();
  49. const bool success = fs_create_directory_with_parents(params.logdir);
  50. if (!success) {
  51. LOG_ERR("%s: warning: failed to create logdir %s, cannot write logfile\n",
  52. __func__, params.logdir.c_str());
  53. return;
  54. }
  55. const std::string logfile_path = params.logdir + timestamp + ".yml";
  56. FILE * logfile = fopen(logfile_path.c_str(), "w");
  57. if (logfile == NULL) {
  58. LOG_ERR("%s: failed to open logfile %s\n", __func__, logfile_path.c_str());
  59. return;
  60. }
  61. fprintf(logfile, "binary: infill\n");
  62. char model_desc[128];
  63. llama_model_desc(model, model_desc, sizeof(model_desc));
  64. yaml_dump_non_result_info(logfile, params, ctx, timestamp, input_tokens, model_desc);
  65. fprintf(logfile, "\n");
  66. fprintf(logfile, "######################\n");
  67. fprintf(logfile, "# Generation Results #\n");
  68. fprintf(logfile, "######################\n");
  69. fprintf(logfile, "\n");
  70. yaml_dump_string_multiline(logfile, "output", output.c_str());
  71. yaml_dump_vector_int(logfile, "output_tokens", output_tokens);
  72. llama_perf_dump_yaml(logfile, ctx);
  73. fclose(logfile);
  74. }
  75. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__)) || defined (_WIN32)
  76. static void sigint_handler(int signo) {
  77. if (signo == SIGINT) {
  78. if (!is_interacting) {
  79. is_interacting = true;
  80. } else {
  81. console::cleanup();
  82. LOG("\n");
  83. gpt_perf_print(*g_ctx, *g_smpl);
  84. write_logfile(*g_ctx, *g_params, *g_model, *g_input_tokens, g_output_ss->str(), *g_output_tokens);
  85. _exit(130);
  86. }
  87. }
  88. }
  89. #endif
  90. int main(int argc, char ** argv) {
  91. gpt_params params;
  92. g_params = &params;
  93. if (!gpt_params_parse(argc, argv, params, LLAMA_EXAMPLE_INFILL)) {
  94. return 1;
  95. }
  96. gpt_init();
  97. auto & sparams = params.sparams;
  98. console::init(params.simple_io, params.use_color);
  99. atexit([]() { console::cleanup(); });
  100. if (params.logits_all) {
  101. LOG_ERR("\n************\n");
  102. LOG_ERR("%s: please use the 'perplexity' tool for perplexity calculations\n", __func__);
  103. LOG_ERR("************\n\n");
  104. return 0;
  105. }
  106. if (params.embedding) {
  107. LOG_ERR("\n************\n");
  108. LOG_ERR("%s: please use the 'embedding' tool for embedding calculations\n", __func__);
  109. LOG_ERR("************\n\n");
  110. return 0;
  111. }
  112. if (params.n_ctx != 0 && params.n_ctx < 8) {
  113. LOG_WRN("%s: minimum context size is 8, using minimum size.\n", __func__);
  114. params.n_ctx = 8;
  115. }
  116. if (!params.interactive_first && (params.input_prefix.empty() && params.input_suffix.empty())) {
  117. LOG_ERR("\n************\n");
  118. LOG_ERR("%s: please use '--interactive_first' or specify '--in_prefix' and/or '--in_suffix'\n", __func__);
  119. LOG_ERR("************\n\n");
  120. return 0;
  121. }
  122. if (params.rope_freq_base != 0.0) {
  123. LOG_WRN("%s: changing RoPE frequency base to %g.\n", __func__, params.rope_freq_base);
  124. }
  125. if (params.rope_freq_scale != 0.0) {
  126. LOG_WRN("%s: scaling RoPE frequency by %g.\n", __func__, params.rope_freq_scale);
  127. }
  128. LOG_INF("%s: llama backend init\n", __func__);
  129. llama_backend_init();
  130. llama_numa_init(params.numa);
  131. llama_model * model = nullptr;
  132. llama_context * ctx = nullptr;
  133. gpt_sampler * smpl = nullptr;
  134. g_model = &model;
  135. g_ctx = &ctx;
  136. g_smpl = &smpl;
  137. // load the model and apply lora adapter, if any
  138. LOG_INF("%s: load the model and apply lora adapter, if any\n", __func__);
  139. llama_init_result llama_init = llama_init_from_gpt_params(params);
  140. model = llama_init.model;
  141. ctx = llama_init.context;
  142. if (model == NULL) {
  143. LOG_ERR("%s: unable to load model\n", __func__);
  144. return 1;
  145. }
  146. const int n_ctx_train = llama_n_ctx_train(model);
  147. const int n_ctx = llama_n_ctx(ctx);
  148. LOG_DBG("n_ctx: %d\n", n_ctx);
  149. if (n_ctx > n_ctx_train) {
  150. LOG_WRN("%s: model was trained on only %d context tokens (%d specified)\n", __func__, n_ctx_train, n_ctx);
  151. }
  152. // print system information
  153. {
  154. LOG_INF("\n");
  155. LOG_INF("%s\n", gpt_params_get_system_info(params).c_str());
  156. }
  157. const bool add_bos = llama_add_bos_token(model);
  158. GGML_ASSERT(!llama_add_eos_token(model));
  159. std::vector<llama_token> embd_inp;
  160. std::vector<llama_token> embd_end;
  161. std::vector<llama_token> inp_pfx = ::llama_tokenize(ctx, params.input_prefix, false);
  162. std::vector<llama_token> inp_sfx = ::llama_tokenize(ctx, params.input_suffix, false);
  163. GGML_ASSERT(llama_token_prefix(model) >= 0);
  164. GGML_ASSERT(llama_token_suffix(model) >= 0);
  165. inp_pfx.insert(inp_pfx.begin(), llama_token_prefix(model));
  166. inp_sfx.insert(inp_sfx.begin(), llama_token_suffix(model));
  167. embd_inp = params.spm_infill ? inp_sfx : inp_pfx;
  168. embd_end = params.spm_infill ? inp_pfx : inp_sfx;
  169. if (add_bos) {
  170. embd_inp.insert(embd_inp.begin(), llama_token_bos(model));
  171. }
  172. embd_inp.insert(embd_inp.end(), embd_end.begin(), embd_end.end());
  173. const llama_token middle_token = llama_token_middle(model);
  174. if (middle_token >= 0) {
  175. embd_inp.push_back(middle_token);
  176. }
  177. LOG_DBG("add_bos: %d\n", add_bos);
  178. LOG_DBG("prefix: \"%s\"\n", params.input_prefix.c_str());
  179. LOG_DBG("suffix: \"%s\"\n", params.input_suffix.c_str());
  180. LOG_DBG("tokens: %s\n", string_from(ctx, embd_inp).c_str());
  181. // Should not run without any tokens
  182. if (embd_inp.empty()) {
  183. embd_inp.push_back(llama_token_bos(model));
  184. LOG_WRN("embd_inp was considered empty and bos was added: %s\n", string_from(ctx, embd_inp).c_str());
  185. }
  186. if ((int) embd_inp.size() > n_ctx - 4) {
  187. LOG_ERR("%s: prompt is too long (%d tokens, max %d)\n", __func__, (int) embd_inp.size(), n_ctx - 4);
  188. return 1;
  189. }
  190. // number of tokens to keep when resetting context
  191. if (params.n_keep < 0 || params.n_keep > (int) embd_inp.size()) {
  192. params.n_keep = (int)embd_inp.size();
  193. }
  194. LOG_INF("inp_pfx: %s\n", string_from(ctx, inp_pfx).c_str());
  195. LOG_INF("inp_sfx: %s\n", string_from(ctx, inp_sfx).c_str());
  196. // enable interactive mode if interactive start is specified
  197. if (params.interactive_first) {
  198. params.interactive = true;
  199. }
  200. if (params.verbose_prompt) {
  201. LOG_INF("\n");
  202. LOG_INF("%s: prompt: '%s'\n", __func__, params.prompt.c_str());
  203. LOG_INF("%s: number of tokens in prompt = %zu\n", __func__, embd_inp.size());
  204. for (int i = 0; i < (int) embd_inp.size(); i++) {
  205. LOG_INF("%6d -> '%s'\n", embd_inp[i], llama_token_to_piece(ctx, embd_inp[i]).c_str());
  206. }
  207. if (params.n_keep > 0) {
  208. LOG_INF("%s: static prompt based on n_keep: '", __func__);
  209. for (int i = 0; i < params.n_keep; i++) {
  210. LOG("%s", llama_token_to_piece(ctx, embd_inp[i]).c_str());
  211. }
  212. LOG("'\n");
  213. }
  214. LOG_INF("\n");
  215. }
  216. if (params.interactive) {
  217. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
  218. struct sigaction sigint_action;
  219. sigint_action.sa_handler = sigint_handler;
  220. sigemptyset (&sigint_action.sa_mask);
  221. sigint_action.sa_flags = 0;
  222. sigaction(SIGINT, &sigint_action, NULL);
  223. #elif defined (_WIN32)
  224. auto console_ctrl_handler = +[](DWORD ctrl_type) -> BOOL {
  225. return (ctrl_type == CTRL_C_EVENT) ? (sigint_handler(SIGINT), true) : false;
  226. };
  227. SetConsoleCtrlHandler(reinterpret_cast<PHANDLER_ROUTINE>(console_ctrl_handler), true);
  228. #endif
  229. LOG_INF("%s: interactive mode on.\n", __func__);
  230. if (params.input_prefix_bos) {
  231. LOG_INF("Input prefix with BOS\n");
  232. }
  233. if (!params.input_prefix.empty()) {
  234. LOG_INF("Input prefix: '%s'\n", params.input_prefix.c_str());
  235. }
  236. if (!params.input_suffix.empty()) {
  237. LOG_INF("Input suffix: '%s'\n", params.input_suffix.c_str());
  238. }
  239. }
  240. smpl = gpt_sampler_init(model, sparams);
  241. LOG_INF("sampler seed: %u\n", gpt_sampler_get_seed(smpl));
  242. LOG_INF("sampler params: \n%s\n", sparams.print().c_str());
  243. LOG_INF("sampler chain: %s\n", gpt_sampler_print(smpl).c_str());
  244. LOG_INF("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);
  245. LOG("\n");
  246. LOG("\n##### Infill mode #####\n\n");
  247. if (params.interactive) {
  248. const char *control_message;
  249. if (params.multiline_input) {
  250. control_message = " - To return control to LLaMA, end your input with '\\'.\n"
  251. " - To return control without starting a new line, end your input with '/'.\n";
  252. } else {
  253. control_message = " - Press Return to return control to LLaMA.\n"
  254. " - To return control without starting a new line, end your input with '/'.\n"
  255. " - If you want to submit another line, end your input with '\\'.\n";
  256. }
  257. LOG("== Running in interactive mode. ==\n");
  258. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__)) || defined (_WIN32)
  259. LOG( " - Press Ctrl+C to interject at any time.\n");
  260. #endif
  261. LOG( "%s\n", control_message);
  262. is_interacting = params.interactive_first;
  263. }
  264. bool input_echo = true;
  265. int n_past = 0;
  266. int n_remain = params.n_predict;
  267. int n_consumed = 0;
  268. std::vector<int> input_tokens; g_input_tokens = &input_tokens;
  269. std::vector<int> output_tokens; g_output_tokens = &output_tokens;
  270. std::ostringstream output_ss; g_output_ss = &output_ss;
  271. // the first thing we will do is to output the prompt, so set color accordingly
  272. console::set_display(console::prompt);
  273. std::vector<llama_token> embd;
  274. while (n_remain != 0 || params.interactive) {
  275. // predict
  276. if (!embd.empty()) {
  277. // Note: n_ctx - 4 here is to match the logic for commandline prompt handling via
  278. // --prompt or --file which uses the same value.
  279. int max_embd_size = n_ctx - 4;
  280. // Ensure the input doesn't exceed the context size by truncating embd if necessary.
  281. if ((int) embd.size() > max_embd_size) {
  282. const int skipped_tokens = (int) embd.size() - max_embd_size;
  283. embd.resize(max_embd_size);
  284. console::set_display(console::error);
  285. LOG_WRN("<<input too long: skipped %d token%s>>", skipped_tokens, skipped_tokens != 1 ? "s" : "");
  286. console::set_display(console::reset);
  287. }
  288. // infinite text generation via context swapping
  289. // if we run out of context:
  290. // - take the n_keep first tokens from the original prompt (via n_past)
  291. // - take half of the last (n_ctx - n_keep) tokens and recompute the logits in batches
  292. if (n_past + (int) embd.size() > n_ctx) {
  293. if (params.n_predict == -2) {
  294. LOG_DBG("\n\n%s: context full and n_predict == -%d => stopping\n", __func__, params.n_predict);
  295. break;
  296. }
  297. const int n_left = n_past - params.n_keep - 1;
  298. const int n_discard = n_left/2;
  299. LOG_DBG("context full, swapping: n_past = %d, n_left = %d, n_ctx = %d, n_keep = %d, n_discard = %d\n",
  300. n_past, n_left, n_ctx, params.n_keep, n_discard);
  301. llama_kv_cache_seq_rm (ctx, 0, params.n_keep + 1 , params.n_keep + n_discard + 1);
  302. llama_kv_cache_seq_add(ctx, 0, params.n_keep + 1 + n_discard, n_past, -n_discard);
  303. n_past -= n_discard;
  304. LOG_DBG("after swap: n_past = %d\n", n_past);
  305. LOG_DBG("embd: %s\n", string_from(ctx, embd).c_str());
  306. }
  307. // evaluate tokens in batches
  308. // embd is typically prepared beforehand to fit within a batch, but not always
  309. for (int i = 0; i < (int) embd.size(); i += params.n_batch) {
  310. int n_eval = (int) embd.size() - i;
  311. if (n_eval > params.n_batch) {
  312. n_eval = params.n_batch;
  313. }
  314. LOG_DBG("eval: %s\n", string_from(ctx, embd).c_str());
  315. if (llama_decode(ctx, llama_batch_get_one(&embd[i], n_eval, n_past, 0))) {
  316. LOG_ERR("%s : failed to eval\n", __func__);
  317. return 1;
  318. }
  319. n_past += n_eval;
  320. LOG_DBG("n_past = %d\n", n_past);
  321. }
  322. }
  323. embd.clear();
  324. if ((int) embd_inp.size() <= n_consumed && !is_interacting) {
  325. const llama_token id = gpt_sampler_sample(smpl, ctx, -1);
  326. gpt_sampler_accept(smpl, id, true);
  327. // LOG_DBG("last: %s\n", string_from(ctx, smpl->prev.to_vector()).c_str());
  328. embd.push_back(id);
  329. // echo this to console
  330. input_echo = true;
  331. // decrement remaining sampling budget
  332. --n_remain;
  333. LOG_DBG("n_remain: %d\n", n_remain);
  334. } else {
  335. // some user input remains from prompt or interaction, forward it to processing
  336. LOG_DBG("embd_inp.size(): %d, n_consumed: %d\n", (int) embd_inp.size(), n_consumed);
  337. while ((int) embd_inp.size() > n_consumed) {
  338. embd.push_back(embd_inp[n_consumed]);
  339. // push the prompt in the sampling context in order to apply repetition penalties later
  340. // for the prompt, we don't apply grammar rules
  341. gpt_sampler_accept(smpl, embd_inp[n_consumed], false);
  342. ++n_consumed;
  343. if ((int) embd.size() >= params.n_batch) {
  344. break;
  345. }
  346. }
  347. }
  348. // display text
  349. if (input_echo) {
  350. for (auto id : embd) {
  351. const std::string token_str = llama_token_to_piece(ctx, id);
  352. LOG("%s", token_str.c_str());
  353. if (embd.size() > 1) {
  354. input_tokens.push_back(id);
  355. } else {
  356. output_tokens.push_back(id);
  357. output_ss << token_str;
  358. }
  359. }
  360. }
  361. // reset color to default if we there is no pending user input
  362. if (input_echo && (int) embd_inp.size() == n_consumed) {
  363. console::set_display(console::reset);
  364. }
  365. // if not currently processing queued inputs;
  366. if ((int) embd_inp.size() <= n_consumed) {
  367. // deal with eot token in infill mode
  368. if ((gpt_sampler_last(smpl) == llama_token_eot(model) || is_interacting) && params.interactive){
  369. if (is_interacting && !params.interactive_first) {
  370. // print an eot token
  371. LOG("%s", llama_token_to_piece(ctx, llama_token_eot(model)).c_str());
  372. }
  373. LOG("\n");
  374. console::set_display(console::user_input);
  375. std::string buffer;
  376. std::string line;
  377. bool another_line=true;
  378. // set a new prefix via stdin
  379. do {
  380. another_line = console::readline(line, params.multiline_input);
  381. buffer += line;
  382. } while (another_line);
  383. // check if we got an empty line, if so we use the old input
  384. if (!buffer.empty() && !(buffer.length() == 1 && buffer[0] == '\n')) {
  385. params.input_prefix = buffer;
  386. }
  387. buffer.clear();
  388. // set a new suffix via stdin
  389. do {
  390. another_line = console::readline(line, params.multiline_input);
  391. buffer += line;
  392. } while (another_line);
  393. // check if we got an empty line
  394. if (!buffer.empty() && !(buffer.length() == 1 && buffer[0] == '\n')) {
  395. params.input_suffix = buffer;
  396. }
  397. buffer.clear();
  398. // done taking input, reset color
  399. console::set_display(console::reset);
  400. if (params.escape) {
  401. //process escape sequences, for the initial prompt this is done in common.cpp when we load the params, but for the interactive mode we need to do it here
  402. string_process_escapes(params.input_prefix);
  403. string_process_escapes(params.input_suffix);
  404. }
  405. // tokenize new prefix and suffix
  406. std::vector<llama_token> inp_pfx = ::llama_tokenize(ctx, params.input_prefix, false);
  407. std::vector<llama_token> inp_sfx = ::llama_tokenize(ctx, params.input_suffix, false);
  408. inp_pfx.insert(inp_pfx.begin(), llama_token_prefix(model));
  409. inp_sfx.insert(inp_sfx.begin(), llama_token_suffix(model));
  410. embd_inp = params.spm_infill ? inp_sfx : inp_pfx;
  411. embd_end = params.spm_infill ? inp_pfx : inp_sfx;
  412. if (add_bos) {
  413. embd_inp.insert(embd_inp.begin(), llama_token_bos(model));
  414. }
  415. embd_inp.insert(embd_inp.end(), embd_end.begin(), embd_end.end());
  416. if (middle_token >= 0) {
  417. embd_inp.push_back(middle_token);
  418. }
  419. embd.clear();
  420. n_remain = params.n_predict;
  421. n_past = 0;
  422. n_consumed = 0;
  423. is_interacting = false;
  424. }
  425. // deal with end of generation tokens in interactive mode
  426. else if (llama_token_is_eog(model, gpt_sampler_last(smpl))) {
  427. LOG_DBG("found EOS token\n");
  428. if (params.interactive) {
  429. is_interacting = true;
  430. LOG("\n");
  431. console::set_display(console::user_input);
  432. }
  433. }
  434. if (n_past > 0 && is_interacting && !params.interactive) {
  435. LOG_DBG("waiting for user input\n");
  436. if (params.input_prefix_bos) {
  437. LOG_DBG("adding input prefix BOS token\n");
  438. embd_inp.push_back(llama_token_bos(model));
  439. }
  440. std::string buffer;
  441. if (!params.input_prefix.empty()) {
  442. LOG_DBG("appending input prefix: '%s'\n", params.input_prefix.c_str());
  443. buffer += params.input_prefix;
  444. LOG("%s", buffer.c_str());
  445. }
  446. std::string line;
  447. bool another_line = true;
  448. do {
  449. another_line = console::readline(line, params.multiline_input);
  450. buffer += line;
  451. } while (another_line);
  452. // done taking input, reset color
  453. console::set_display(console::reset);
  454. // Add tokens to embd only if the input buffer is non-empty
  455. // Entering a empty line lets the user pass control back
  456. if (buffer.length() > 1) {
  457. // append input suffix if any
  458. if (!params.input_suffix.empty()) {
  459. LOG_DBG("appending input suffix: '%s'\n", params.input_suffix.c_str());
  460. buffer += params.input_suffix;
  461. LOG("%s", params.input_suffix.c_str());
  462. }
  463. LOG_DBG("buffer: '%s'\n", buffer.c_str());
  464. const size_t original_size = embd_inp.size();
  465. const auto line_inp = ::llama_tokenize(ctx, buffer, false);
  466. LOG_DBG("input tokens: %s\n", string_from(ctx, line_inp).c_str());
  467. embd_inp.insert(embd_inp.end(), line_inp.begin(), line_inp.end());
  468. for (size_t i = original_size; i < embd_inp.size(); ++i) {
  469. const llama_token token = embd_inp[i];
  470. output_tokens.push_back(token);
  471. output_ss << llama_token_to_piece(ctx, token);
  472. }
  473. n_remain -= line_inp.size();
  474. LOG_DBG("n_remain: %d\n", n_remain);
  475. } else {
  476. LOG_DBG("empty line, passing control back\n");
  477. }
  478. input_echo = false; // do not echo this again
  479. }
  480. if (n_past > 0) {
  481. if (is_interacting) {
  482. gpt_sampler_reset(smpl);
  483. }
  484. is_interacting = false;
  485. }
  486. }
  487. // end of generation
  488. if (!embd.empty() && llama_token_is_eog(model, embd.back()) && !params.interactive) {
  489. break;
  490. }
  491. // In interactive mode, respect the maximum number of tokens and drop back to user input when reached.
  492. // We skip this logic when n_predict == -1 (infinite) or -2 (stop at context size).
  493. if (params.interactive && n_remain <= 0 && params.n_predict >= 0) {
  494. n_remain = params.n_predict;
  495. is_interacting = true;
  496. }
  497. }
  498. if (!params.interactive && n_remain <= 0) {
  499. LOG("%s", llama_token_to_piece(ctx, llama_token_eot(model)).c_str());
  500. }
  501. LOG("\n");
  502. gpt_perf_print(ctx, smpl);
  503. write_logfile(ctx, params, model, input_tokens, output_ss.str(), output_tokens);
  504. llama_free(ctx);
  505. llama_free_model(model);
  506. gpt_sampler_free(smpl);
  507. llama_backend_free();
  508. return 0;
  509. }