infill.cpp 23 KB

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