infill.cpp 24 KB

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