1
0

infill.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769
  1. #include "common.h"
  2. #include "console.h"
  3. #include "llama.h"
  4. #include "build-info.h"
  5. #include "grammar-parser.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_params * g_params;
  34. static std::vector<llama_token> * g_input_tokens;
  35. static std::ostringstream * g_output_ss;
  36. static std::vector<llama_token> * g_output_tokens;
  37. static bool is_interacting = false;
  38. static void write_logfile(
  39. const llama_context * ctx, const gpt_params & params, const llama_model * model,
  40. const std::vector<llama_token> & input_tokens, const std::string & output,
  41. const std::vector<llama_token> & output_tokens
  42. ) {
  43. if (params.logdir.empty()) {
  44. return;
  45. }
  46. const std::string timestamp = get_sortable_timestamp();
  47. const bool success = create_directory_with_parents(params.logdir);
  48. if (!success) {
  49. fprintf(stderr, "%s: warning: failed to create logdir %s, cannot write logfile\n",
  50. __func__, params.logdir.c_str());
  51. return;
  52. }
  53. const std::string logfile_path = params.logdir + timestamp + ".yml";
  54. FILE * logfile = fopen(logfile_path.c_str(), "w");
  55. if (logfile == NULL) {
  56. fprintf(stderr, "%s: failed to open logfile %s\n", __func__, logfile_path.c_str());
  57. return;
  58. }
  59. fprintf(logfile, "binary: infill\n");
  60. char model_desc[128];
  61. llama_model_desc(model, model_desc, sizeof(model_desc));
  62. dump_non_result_info_yaml(logfile, params, ctx, timestamp, input_tokens, model_desc);
  63. fprintf(logfile, "\n");
  64. fprintf(logfile, "######################\n");
  65. fprintf(logfile, "# Generation Results #\n");
  66. fprintf(logfile, "######################\n");
  67. fprintf(logfile, "\n");
  68. dump_string_yaml_multiline(logfile, "output", output.c_str());
  69. dump_vector_int_yaml(logfile, "output_tokens", output_tokens);
  70. llama_dump_timing_info_yaml(logfile, ctx);
  71. fclose(logfile);
  72. }
  73. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__)) || defined (_WIN32)
  74. static void sigint_handler(int signo) {
  75. if (signo == SIGINT) {
  76. if (!is_interacting) {
  77. is_interacting = true;
  78. } else {
  79. console::cleanup();
  80. printf("\n");
  81. llama_print_timings(*g_ctx);
  82. write_logfile(*g_ctx, *g_params, *g_model, *g_input_tokens, g_output_ss->str(), *g_output_tokens);
  83. _exit(130);
  84. }
  85. }
  86. }
  87. #endif
  88. int main(int argc, char ** argv) {
  89. gpt_params params;
  90. g_params = &params;
  91. if (!gpt_params_parse(argc, argv, params)) {
  92. return 1;
  93. }
  94. #ifndef LOG_DISABLE_LOGS
  95. log_set_target(log_filename_generator("infill", "log"));
  96. LOG_TEE("Log start\n");
  97. log_dump_cmdline(argc, argv);
  98. #endif // LOG_DISABLE_LOGS
  99. console::init(params.simple_io, params.use_color);
  100. atexit([]() { console::cleanup(); });
  101. if (params.logits_all) {
  102. printf("\n************\n");
  103. printf("%s: please use the 'perplexity' tool for perplexity calculations\n", __func__);
  104. printf("************\n\n");
  105. return 0;
  106. }
  107. if (params.embedding) {
  108. printf("\n************\n");
  109. printf("%s: please use the 'embedding' tool for embedding calculations\n", __func__);
  110. printf("************\n\n");
  111. return 0;
  112. }
  113. if (params.n_ctx != 0 && params.n_ctx < 8) {
  114. LOG_TEE("%s: warning: minimum context size is 8, using minimum size.\n", __func__);
  115. params.n_ctx = 8;
  116. }
  117. if (params.instruct) {
  118. printf("\n************\n");
  119. printf("%s: please use the 'main' tool for instruct mode\n", __func__);
  120. printf("************\n\n");
  121. return 0;
  122. }
  123. if (!params.antiprompt.empty()) {
  124. printf("\n************\n");
  125. printf("%s: please use the 'main' tool for antiprompt mode\n", __func__);
  126. printf("************\n\n");
  127. return 0;
  128. }
  129. if (!params.interactive_first && (params.input_prefix.empty() && params.input_suffix.empty())) {
  130. printf("\n************\n");
  131. printf("%s: please use '--interactive_first' or specify '--in_prefix' and/or '--in_suffix'\n", __func__);
  132. printf("************\n\n");
  133. return 0;
  134. }
  135. if (params.random_prompt) {
  136. printf("\n************\n");
  137. printf("%s: please use the 'main' tool for random prompt mode\n", __func__);
  138. printf("************\n\n");
  139. return 0;
  140. }
  141. if (!params.path_prompt_cache.empty()) {
  142. printf("\n************\n");
  143. printf("%s: infill does not support prompt caching\n", __func__);
  144. printf("************\n\n");
  145. return 0;
  146. }
  147. if (params.rope_freq_base != 0.0) {
  148. LOG_TEE("%s: warning: changing RoPE frequency base to %g.\n", __func__, params.rope_freq_base);
  149. }
  150. if (params.rope_freq_scale != 0.0) {
  151. LOG_TEE("%s: warning: scaling RoPE frequency by %g.\n", __func__, params.rope_freq_scale);
  152. }
  153. LOG_TEE("%s: build = %d (%s)\n", __func__, BUILD_NUMBER, BUILD_COMMIT);
  154. LOG_TEE("%s: built with %s for %s\n", __func__, BUILD_COMPILER, BUILD_TARGET);
  155. if (params.seed == LLAMA_DEFAULT_SEED) {
  156. params.seed = time(NULL);
  157. }
  158. LOG_TEE("%s: seed = %u\n", __func__, params.seed);
  159. std::mt19937 rng(params.seed);
  160. LOG("%s: llama backend init\n", __func__);
  161. llama_backend_init(params.numa);
  162. llama_model * model;
  163. llama_context * ctx;
  164. llama_context * ctx_guidance = NULL;
  165. g_model = &model;
  166. g_ctx = &ctx;
  167. // load the model and apply lora adapter, if any
  168. LOG("%s: load the model and apply lora adapter, if any\n", __func__);
  169. std::tie(model, ctx) = llama_init_from_gpt_params(params);
  170. if (params.cfg_scale > 1.f) {
  171. struct llama_context_params lparams = llama_context_params_from_gpt_params(params);
  172. ctx_guidance = llama_new_context_with_model(model, lparams);
  173. }
  174. if (model == NULL) {
  175. LOG_TEE("%s: error: unable to load model\n", __func__);
  176. return 1;
  177. }
  178. const int n_ctx_train = llama_n_ctx_train(model);
  179. const int n_ctx = llama_n_ctx(ctx);
  180. LOG("n_ctx: %d\n", n_ctx);
  181. if (n_ctx > n_ctx_train) {
  182. LOG_TEE("%s: warning: model was trained on only %d context tokens (%d specified)\n",
  183. __func__, n_ctx_train, n_ctx);
  184. }
  185. // print system information
  186. {
  187. LOG_TEE("\n");
  188. LOG_TEE("%s\n", get_system_info(params).c_str());
  189. }
  190. const bool add_bos = llama_vocab_type(model) == LLAMA_VOCAB_TYPE_SPM;
  191. LOG("add_bos: %d\n", add_bos);
  192. std::vector<llama_token> embd_inp;
  193. std::vector<llama_token> inp_pfx = ::llama_tokenize(ctx, params.input_prefix, add_bos);
  194. std::vector<llama_token> inp_sfx = ::llama_tokenize(ctx, params.input_suffix, add_bos);
  195. inp_pfx.insert(inp_pfx.begin(), llama_token_prefix(ctx));
  196. inp_sfx.insert(inp_sfx.begin(), llama_token_suffix(ctx));
  197. embd_inp = inp_pfx;
  198. embd_inp.insert(embd_inp.end(), inp_sfx.begin(), inp_sfx.end());
  199. embd_inp.push_back(llama_token_middle(ctx));
  200. LOG("prefix: \"%s\"\n", log_tostr(params.input_prefix));
  201. LOG("suffix: \"%s\"\n", log_tostr(params.input_suffix));
  202. LOG("tokens: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx, embd_inp));
  203. // Should not run without any tokens
  204. if (embd_inp.empty()) {
  205. embd_inp.push_back(llama_token_bos(ctx));
  206. LOG("embd_inp was considered empty and bos was added: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx, embd_inp));
  207. }
  208. // Tokenize negative prompt
  209. std::vector<llama_token> guidance_inp;
  210. int guidance_offset = 0;
  211. int original_prompt_len = 0;
  212. if (ctx_guidance) {
  213. LOG("cfg_negative_prompt: \"%s\"\n", log_tostr(params.cfg_negative_prompt));
  214. guidance_inp = ::llama_tokenize(ctx_guidance, params.cfg_negative_prompt, add_bos);
  215. LOG("guidance_inp tokenized: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx_guidance, guidance_inp));
  216. std::vector<llama_token> original_inp = ::llama_tokenize(ctx, params.prompt, add_bos);
  217. LOG("original_inp tokenized: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx, original_inp));
  218. original_prompt_len = original_inp.size();
  219. guidance_offset = (int)guidance_inp.size() - original_prompt_len;
  220. LOG("original_prompt_len: %s", log_tostr(original_prompt_len));
  221. LOG("guidance_offset: %s", log_tostr(guidance_offset));
  222. }
  223. if ((int) embd_inp.size() > n_ctx - 4) {
  224. LOG_TEE("%s: error: prompt is too long (%d tokens, max %d)\n", __func__, (int) embd_inp.size(), n_ctx - 4);
  225. return 1;
  226. }
  227. // number of tokens to keep when resetting context
  228. if (params.n_keep < 0 || params.n_keep > (int) embd_inp.size()) {
  229. params.n_keep = (int)embd_inp.size();
  230. }
  231. LOG("inp_pfx: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx, inp_pfx));
  232. LOG("inp_sfx: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx, inp_sfx));
  233. // enable interactive mode if interactive start is specified
  234. if (params.interactive_first) {
  235. params.interactive = true;
  236. }
  237. if (params.verbose_prompt) {
  238. LOG_TEE("\n");
  239. LOG_TEE("%s: prompt: '%s'\n", __func__, params.prompt.c_str());
  240. LOG_TEE("%s: number of tokens in prompt = %zu\n", __func__, embd_inp.size());
  241. for (int i = 0; i < (int) embd_inp.size(); i++) {
  242. LOG_TEE("%6d -> '%s'\n", embd_inp[i], llama_token_to_piece(ctx, embd_inp[i]).c_str());
  243. }
  244. if (ctx_guidance) {
  245. LOG_TEE("\n");
  246. LOG_TEE("%s: negative prompt: '%s'\n", __func__, params.cfg_negative_prompt.c_str());
  247. LOG_TEE("%s: number of tokens in negative prompt = %zu\n", __func__, guidance_inp.size());
  248. for (int i = 0; i < (int) guidance_inp.size(); i++) {
  249. LOG_TEE("%6d -> '%s'\n", guidance_inp[i], llama_token_to_piece(ctx, guidance_inp[i]).c_str());
  250. }
  251. }
  252. if (params.n_keep > 0) {
  253. LOG_TEE("%s: static prompt based on n_keep: '", __func__);
  254. for (int i = 0; i < params.n_keep; i++) {
  255. LOG_TEE("%s", llama_token_to_piece(ctx, embd_inp[i]).c_str());
  256. }
  257. LOG_TEE("'\n");
  258. }
  259. LOG_TEE("\n");
  260. }
  261. if (params.interactive) {
  262. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
  263. struct sigaction sigint_action;
  264. sigint_action.sa_handler = sigint_handler;
  265. sigemptyset (&sigint_action.sa_mask);
  266. sigint_action.sa_flags = 0;
  267. sigaction(SIGINT, &sigint_action, NULL);
  268. #elif defined (_WIN32)
  269. auto console_ctrl_handler = +[](DWORD ctrl_type) -> BOOL {
  270. return (ctrl_type == CTRL_C_EVENT) ? (sigint_handler(SIGINT), true) : false;
  271. };
  272. SetConsoleCtrlHandler(reinterpret_cast<PHANDLER_ROUTINE>(console_ctrl_handler), true);
  273. #endif
  274. LOG_TEE("%s: interactive mode on.\n", __func__);
  275. if (params.input_prefix_bos) {
  276. LOG_TEE("Input prefix with BOS\n");
  277. }
  278. if (!params.input_prefix.empty()) {
  279. LOG_TEE("Input prefix: '%s'\n", params.input_prefix.c_str());
  280. }
  281. if (!params.input_suffix.empty()) {
  282. LOG_TEE("Input suffix: '%s'\n", params.input_suffix.c_str());
  283. }
  284. }
  285. LOG_TEE("sampling: repeat_last_n = %d, repeat_penalty = %f, presence_penalty = %f, frequency_penalty = %f, top_k = %d, tfs_z = %f, top_p = %f, typical_p = %f, temp = %f, mirostat = %d, mirostat_lr = %f, mirostat_ent = %f\n",
  286. params.repeat_last_n, params.repeat_penalty, params.presence_penalty, params.frequency_penalty, params.top_k, params.tfs_z, params.top_p, params.typical_p, params.temp, params.mirostat, params.mirostat_eta, params.mirostat_tau);
  287. 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);
  288. LOG_TEE("\n\n");
  289. struct llama_grammar * grammar = NULL;
  290. grammar_parser::parse_state parsed_grammar;
  291. if (!params.grammar.empty()) {
  292. parsed_grammar = grammar_parser::parse(params.grammar.c_str());
  293. // will be empty (default) if there are parse errors
  294. if (parsed_grammar.rules.empty()) {
  295. return 1;
  296. }
  297. LOG_TEE("%s: grammar:\n", __func__);
  298. grammar_parser::print_grammar(stderr, parsed_grammar);
  299. LOG_TEE("\n");
  300. {
  301. auto it = params.logit_bias.find(llama_token_eos(ctx));
  302. if (it != params.logit_bias.end() && it->second == -INFINITY) {
  303. LOG_TEE("%s: warning: EOS token is disabled, which will cause most grammars to fail\n", __func__);
  304. }
  305. }
  306. std::vector<const llama_grammar_element *> grammar_rules(parsed_grammar.c_rules());
  307. grammar = llama_grammar_init(
  308. grammar_rules.data(), grammar_rules.size(), parsed_grammar.symbol_ids.at("root"));
  309. }
  310. // TODO: replace with ring-buffer
  311. std::vector<llama_token> last_tokens(n_ctx);
  312. std::fill(last_tokens.begin(), last_tokens.end(), 0);
  313. LOG_TEE("\n##### Infill mode #####\n\n");
  314. if (params.infill) {
  315. printf("\n************\n");
  316. printf("no need to specify '--infill', always running infill\n");
  317. printf("************\n\n");
  318. }
  319. if (params.interactive) {
  320. const char *control_message;
  321. if (params.multiline_input) {
  322. control_message = " - To return control to LLaMa, end your input with '\\'.\n"
  323. " - To return control without starting a new line, end your input with '/'.\n";
  324. } else {
  325. control_message = " - Press Return to return control to LLaMa.\n"
  326. " - To return control without starting a new line, end your input with '/'.\n"
  327. " - If you want to submit another line, end your input with '\\'.\n";
  328. }
  329. LOG_TEE("== Running in interactive mode. ==\n");
  330. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__)) || defined (_WIN32)
  331. LOG_TEE( " - Press Ctrl+C to interject at any time.\n");
  332. #endif
  333. LOG_TEE( "%s\n", control_message);
  334. is_interacting = params.interactive_first;
  335. }
  336. bool input_echo = true;
  337. int n_past = 0;
  338. int n_remain = params.n_predict;
  339. int n_consumed = 0;
  340. int n_past_guidance = 0;
  341. std::vector<int> input_tokens; g_input_tokens = &input_tokens;
  342. std::vector<int> output_tokens; g_output_tokens = &output_tokens;
  343. std::ostringstream output_ss; g_output_ss = &output_ss;
  344. // the first thing we will do is to output the prompt, so set color accordingly
  345. console::set_display(console::prompt);
  346. std::vector<llama_token> embd;
  347. std::vector<llama_token> embd_guidance;
  348. const int n_vocab = llama_n_vocab(model);
  349. std::vector<llama_token_data> candidates;
  350. candidates.reserve(n_vocab);
  351. while (n_remain != 0 || params.interactive) {
  352. // predict
  353. if (!embd.empty()) {
  354. // Note: n_ctx - 4 here is to match the logic for commandline prompt handling via
  355. // --prompt or --file which uses the same value.
  356. int max_embd_size = n_ctx - 4;
  357. // Ensure the input doesn't exceed the context size by truncating embd if necessary.
  358. if ((int) embd.size() > max_embd_size) {
  359. const int skipped_tokens = (int) embd.size() - max_embd_size;
  360. embd.resize(max_embd_size);
  361. console::set_display(console::error);
  362. printf("<<input too long: skipped %d token%s>>", skipped_tokens, skipped_tokens != 1 ? "s" : "");
  363. console::set_display(console::reset);
  364. fflush(stdout);
  365. }
  366. // infinite text generation via context swapping
  367. // if we run out of context:
  368. // - take the n_keep first tokens from the original prompt (via n_past)
  369. // - take half of the last (n_ctx - n_keep) tokens and recompute the logits in batches
  370. if (n_past + (int) embd.size() + std::max<int>(0, guidance_offset) > n_ctx) {
  371. if (params.n_predict == -2) {
  372. LOG_TEE("\n\n%s: context full and n_predict == -%d => stopping\n", __func__, params.n_predict);
  373. break;
  374. }
  375. const int n_left = n_past - params.n_keep - 1;
  376. const int n_discard = n_left/2;
  377. LOG("context full, swapping: n_past = %d, n_left = %d, n_ctx = %d, n_keep = %d, n_discard = %d\n",
  378. n_past, n_left, n_ctx, params.n_keep, n_discard);
  379. llama_kv_cache_seq_rm (ctx, 0, params.n_keep + 1 , params.n_keep + n_discard + 1);
  380. llama_kv_cache_seq_shift(ctx, 0, params.n_keep + 1 + n_discard, n_past, -n_discard);
  381. n_past -= n_discard;
  382. if (ctx_guidance) {
  383. n_past_guidance -= n_discard;
  384. }
  385. LOG("after swap: n_past = %d, n_past_guidance = %d\n", n_past, n_past_guidance);
  386. LOG("embd: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx, embd));
  387. }
  388. // evaluate tokens in batches
  389. // embd is typically prepared beforehand to fit within a batch, but not always
  390. if (ctx_guidance) {
  391. int input_size = 0;
  392. llama_token * input_buf = NULL;
  393. if (n_past_guidance < (int) guidance_inp.size()) {
  394. // Guidance context should have the same data with these modifications:
  395. //
  396. // * Replace the initial prompt
  397. // * Shift everything by guidance_offset
  398. embd_guidance = guidance_inp;
  399. if (embd.begin() + original_prompt_len < embd.end()) {
  400. embd_guidance.insert(
  401. embd_guidance.end(),
  402. embd.begin() + original_prompt_len,
  403. embd.end()
  404. );
  405. }
  406. input_buf = embd_guidance.data();
  407. input_size = embd_guidance.size();
  408. LOG("guidance context: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx, embd_guidance));
  409. } else {
  410. input_buf = embd.data();
  411. input_size = embd.size();
  412. }
  413. for (int i = 0; i < input_size; i += params.n_batch) {
  414. int n_eval = std::min(input_size - i, params.n_batch);
  415. if (llama_decode(ctx_guidance, llama_batch_get_one(input_buf + i, n_eval, n_past_guidance, 0))) {
  416. LOG_TEE("%s : failed to eval\n", __func__);
  417. return 1;
  418. }
  419. n_past_guidance += n_eval;
  420. }
  421. }
  422. for (int i = 0; i < (int) embd.size(); i += params.n_batch) {
  423. int n_eval = (int) embd.size() - i;
  424. if (n_eval > params.n_batch) {
  425. n_eval = params.n_batch;
  426. }
  427. LOG("eval: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx, embd));
  428. if (llama_decode(ctx, llama_batch_get_one(&embd[i], n_eval, n_past, 0))) {
  429. LOG_TEE("%s : failed to eval\n", __func__);
  430. return 1;
  431. }
  432. n_past += n_eval;
  433. LOG("n_past = %d\n", n_past);
  434. }
  435. }
  436. embd.clear();
  437. embd_guidance.clear();
  438. if ((int) embd_inp.size() <= n_consumed && !is_interacting) {
  439. const llama_token id = llama_sample_token(ctx, ctx_guidance, grammar, params, last_tokens, candidates);
  440. last_tokens.erase(last_tokens.begin());
  441. last_tokens.push_back(id);
  442. LOG("last: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx, last_tokens));
  443. embd.push_back(id);
  444. // echo this to console
  445. input_echo = true;
  446. // decrement remaining sampling budget
  447. --n_remain;
  448. LOG("n_remain: %d\n", n_remain);
  449. } else {
  450. // some user input remains from prompt or interaction, forward it to processing
  451. LOG("embd_inp.size(): %d, n_consumed: %d\n", (int) embd_inp.size(), n_consumed);
  452. while ((int) embd_inp.size() > n_consumed) {
  453. embd.push_back(embd_inp[n_consumed]);
  454. last_tokens.erase(last_tokens.begin());
  455. last_tokens.push_back(embd_inp[n_consumed]);
  456. ++n_consumed;
  457. if ((int) embd.size() >= params.n_batch) {
  458. break;
  459. }
  460. }
  461. }
  462. // display text
  463. if (input_echo) {
  464. for (auto id : embd) {
  465. const std::string token_str = llama_token_to_piece(ctx, id);
  466. printf("%s", token_str.c_str());
  467. if (embd.size() > 1) {
  468. input_tokens.push_back(id);
  469. } else {
  470. output_tokens.push_back(id);
  471. output_ss << token_str;
  472. }
  473. }
  474. fflush(stdout);
  475. }
  476. // reset color to default if we there is no pending user input
  477. if (input_echo && (int) embd_inp.size() == n_consumed) {
  478. console::set_display(console::reset);
  479. }
  480. // if not currently processing queued inputs;
  481. if ((int) embd_inp.size() <= n_consumed) {
  482. // deal with eot token in infill mode
  483. if ((last_tokens.back() == llama_token_eot(ctx) || is_interacting) && params.interactive){
  484. if(is_interacting && !params.interactive_first) {
  485. // print an eot token
  486. printf("%s", llama_token_to_piece(ctx, llama_token_eot(ctx)).c_str());
  487. }
  488. fflush(stdout);
  489. printf("\n");
  490. console::set_display(console::user_input);
  491. std::string buffer;
  492. std::string line;
  493. bool another_line=true;
  494. // set a new prefix via stdin
  495. do {
  496. another_line = console::readline(line, params.multiline_input);
  497. buffer += line;
  498. } while (another_line);
  499. // check if we got an empty line, if so we use the old input
  500. if(!buffer.empty() && !(buffer.length() == 1 && buffer[0] == '\n')) {
  501. params.input_prefix = buffer;
  502. }
  503. buffer.clear();
  504. // set a new suffix via stdin
  505. do {
  506. another_line = console::readline(line, params.multiline_input);
  507. buffer += line;
  508. } while (another_line);
  509. // check if we got an empty line
  510. if(!buffer.empty() && !(buffer.length() == 1 && buffer[0] == '\n')) {
  511. params.input_suffix = buffer;
  512. }
  513. buffer.clear();
  514. // done taking input, reset color
  515. console::set_display(console::reset);
  516. // tokenize new prefix and suffix
  517. std::vector<llama_token> inp_pfx = ::llama_tokenize(ctx, params.input_prefix, add_bos);
  518. std::vector<llama_token> inp_sfx = ::llama_tokenize(ctx, params.input_suffix, add_bos);
  519. inp_pfx.insert(inp_pfx.begin(), llama_token_prefix(ctx));
  520. inp_sfx.insert(inp_sfx.begin(), llama_token_suffix(ctx));
  521. embd_inp = inp_pfx;
  522. embd_inp.insert(embd_inp.end(), inp_sfx.begin(), inp_sfx.end());
  523. embd_inp.push_back(llama_token_middle(ctx));
  524. embd.clear();
  525. embd_guidance.clear();
  526. n_remain = params.n_predict;
  527. n_past = 0;
  528. n_consumed = 0;
  529. // LOG_TEE("took new input\n");
  530. is_interacting = false;
  531. }
  532. // deal with end of text token in interactive mode
  533. else if (last_tokens.back() == llama_token_eos(ctx)) {
  534. LOG("found EOS token\n");
  535. if (params.interactive) {
  536. is_interacting = true;
  537. printf("\n");
  538. console::set_display(console::user_input);
  539. fflush(stdout);
  540. }
  541. }
  542. if (n_past > 0 && is_interacting && !params.interactive) {
  543. LOG("waiting for user input\n");
  544. if (params.input_prefix_bos) {
  545. LOG("adding input prefix BOS token\n");
  546. embd_inp.push_back(llama_token_bos(ctx));
  547. }
  548. std::string buffer;
  549. if (!params.input_prefix.empty()) {
  550. LOG("appending input prefix: '%s'\n", params.input_prefix.c_str());
  551. buffer += params.input_prefix;
  552. printf("%s", buffer.c_str());
  553. }
  554. std::string line;
  555. bool another_line = true;
  556. do {
  557. another_line = console::readline(line, params.multiline_input);
  558. buffer += line;
  559. } while (another_line);
  560. // done taking input, reset color
  561. console::set_display(console::reset);
  562. // Add tokens to embd only if the input buffer is non-empty
  563. // Entering a empty line lets the user pass control back
  564. if (buffer.length() > 1) {
  565. // append input suffix if any
  566. if (!params.input_suffix.empty()) {
  567. LOG("appending input suffix: '%s'\n", params.input_suffix.c_str());
  568. buffer += params.input_suffix;
  569. printf("%s", params.input_suffix.c_str());
  570. }
  571. LOG("buffer: '%s'\n", buffer.c_str());
  572. const size_t original_size = embd_inp.size();
  573. const auto line_inp = ::llama_tokenize(ctx, buffer, false);
  574. LOG("input tokens: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx, line_inp));
  575. embd_inp.insert(embd_inp.end(), line_inp.begin(), line_inp.end());
  576. for (size_t i = original_size; i < embd_inp.size(); ++i) {
  577. const llama_token token = embd_inp[i];
  578. output_tokens.push_back(token);
  579. output_ss << llama_token_to_piece(ctx, token);
  580. }
  581. n_remain -= line_inp.size();
  582. LOG("n_remain: %d\n", n_remain);
  583. } else {
  584. LOG("empty line, passing control back\n");
  585. }
  586. input_echo = false; // do not echo this again
  587. }
  588. if (n_past > 0) {
  589. if (is_interacting) {
  590. // reset grammar state if we're restarting generation
  591. if (grammar != NULL) {
  592. llama_grammar_free(grammar);
  593. std::vector<const llama_grammar_element *> grammar_rules(parsed_grammar.c_rules());
  594. grammar = llama_grammar_init(
  595. grammar_rules.data(), grammar_rules.size(),
  596. parsed_grammar.symbol_ids.at("root"));
  597. }
  598. }
  599. is_interacting = false;
  600. }
  601. }
  602. // end of text token
  603. if (!embd.empty() && embd.back() == llama_token_eos(ctx) && !params.interactive) {
  604. break;
  605. }
  606. // In interactive mode, respect the maximum number of tokens and drop back to user input when reached.
  607. // We skip this logic when n_predict == -1 (infinite) or -2 (stop at context size).
  608. if (params.interactive && n_remain <= 0 && params.n_predict >= 0) {
  609. n_remain = params.n_predict;
  610. is_interacting = true;
  611. }
  612. }
  613. if (!params.interactive && n_remain <= 0) {
  614. printf("%s", llama_token_to_piece(ctx, llama_token_eot(ctx)).c_str());
  615. fflush(stdout);
  616. }
  617. llama_print_timings(ctx);
  618. write_logfile(ctx, params, model, input_tokens, output_ss.str(), output_tokens);
  619. if (ctx_guidance) { llama_free(ctx_guidance); }
  620. llama_free(ctx);
  621. llama_free_model(model);
  622. if (grammar != NULL) {
  623. llama_grammar_free(grammar);
  624. }
  625. llama_backend_free();
  626. #ifndef LOG_DISABLE_LOGS
  627. LOG_TEE("Log end\n");
  628. #endif // LOG_DISABLE_LOGS
  629. return 0;
  630. }