infill.cpp 23 KB

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