infill.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765
  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 = get_sortable_timestamp();
  46. const bool success = 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. dump_non_result_info_yaml(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. dump_string_yaml_multiline(logfile, "output", output.c_str());
  68. dump_vector_int_yaml(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. 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.chatml) {
  124. printf("\n************\n");
  125. printf("%s: please use the 'main' tool for chatml mode\n", __func__);
  126. printf("************\n\n");
  127. return 0;
  128. }
  129. if (!params.antiprompt.empty()) {
  130. printf("\n************\n");
  131. printf("%s: please use the 'main' tool for antiprompt mode\n", __func__);
  132. printf("************\n\n");
  133. return 0;
  134. }
  135. if (!params.interactive_first && (params.input_prefix.empty() && params.input_suffix.empty())) {
  136. printf("\n************\n");
  137. printf("%s: please use '--interactive_first' or specify '--in_prefix' and/or '--in_suffix'\n", __func__);
  138. printf("************\n\n");
  139. return 0;
  140. }
  141. if (params.random_prompt) {
  142. printf("\n************\n");
  143. printf("%s: please use the 'main' tool for random prompt mode\n", __func__);
  144. printf("************\n\n");
  145. return 0;
  146. }
  147. if (!params.path_prompt_cache.empty()) {
  148. printf("\n************\n");
  149. printf("%s: infill does not support prompt caching\n", __func__);
  150. printf("************\n\n");
  151. return 0;
  152. }
  153. if (params.rope_freq_base != 0.0) {
  154. LOG_TEE("%s: warning: changing RoPE frequency base to %g.\n", __func__, params.rope_freq_base);
  155. }
  156. if (params.rope_freq_scale != 0.0) {
  157. LOG_TEE("%s: warning: scaling RoPE frequency by %g.\n", __func__, params.rope_freq_scale);
  158. }
  159. LOG_TEE("%s: build = %d (%s)\n", __func__, LLAMA_BUILD_NUMBER, LLAMA_COMMIT);
  160. LOG_TEE("%s: built with %s for %s\n", __func__, LLAMA_COMPILER, LLAMA_BUILD_TARGET);
  161. if (params.seed == LLAMA_DEFAULT_SEED) {
  162. params.seed = time(NULL);
  163. }
  164. LOG_TEE("%s: seed = %u\n", __func__, params.seed);
  165. std::mt19937 rng(params.seed);
  166. LOG("%s: llama backend init\n", __func__);
  167. llama_backend_init(params.numa);
  168. llama_model * model;
  169. llama_context * ctx;
  170. llama_context * ctx_guidance = NULL;
  171. g_model = &model;
  172. g_ctx = &ctx;
  173. // load the model and apply lora adapter, if any
  174. LOG("%s: load the model and apply lora adapter, if any\n", __func__);
  175. std::tie(model, ctx) = llama_init_from_gpt_params(params);
  176. if (sparams.cfg_scale > 1.f) {
  177. struct llama_context_params lparams = llama_context_params_from_gpt_params(params);
  178. ctx_guidance = llama_new_context_with_model(model, lparams);
  179. }
  180. if (model == NULL) {
  181. LOG_TEE("%s: error: unable to load model\n", __func__);
  182. return 1;
  183. }
  184. const int n_ctx_train = llama_n_ctx_train(model);
  185. const int n_ctx = llama_n_ctx(ctx);
  186. LOG("n_ctx: %d\n", n_ctx);
  187. if (n_ctx > n_ctx_train) {
  188. LOG_TEE("%s: warning: model was trained on only %d context tokens (%d specified)\n",
  189. __func__, n_ctx_train, n_ctx);
  190. }
  191. // print system information
  192. {
  193. LOG_TEE("\n");
  194. LOG_TEE("%s\n", get_system_info(params).c_str());
  195. }
  196. const bool add_bos = llama_should_add_bos_token(model);
  197. LOG("add_bos: %d\n", add_bos);
  198. bool suff_rm_leading_spc = params.escape;
  199. if (suff_rm_leading_spc && params.input_suffix.find_first_of(' ') == 0 && params.input_suffix.size() > 1) {
  200. params.input_suffix.erase(0, 1);
  201. suff_rm_leading_spc = false;
  202. }
  203. std::vector<llama_token> embd_inp;
  204. std::vector<llama_token> inp_pfx = ::llama_tokenize(ctx, params.input_prefix, false);
  205. std::vector<llama_token> inp_sfx = ::llama_tokenize(ctx, params.input_suffix, false);
  206. const int space_token = 29871;
  207. if (suff_rm_leading_spc && inp_sfx[0] == space_token) {
  208. inp_sfx.erase(inp_sfx.begin());
  209. }
  210. inp_pfx.insert(inp_pfx.begin(), llama_token_prefix(model));
  211. if (add_bos) {
  212. inp_pfx.insert(inp_pfx.begin(), llama_token_bos(model));
  213. }
  214. inp_sfx.insert(inp_sfx.begin(), llama_token_suffix(model));
  215. embd_inp = inp_pfx;
  216. embd_inp.insert(embd_inp.end(), inp_sfx.begin(), inp_sfx.end());
  217. embd_inp.push_back(llama_token_middle(model));
  218. LOG("prefix: \"%s\"\n", log_tostr(params.input_prefix));
  219. LOG("suffix: \"%s\"\n", log_tostr(params.input_suffix));
  220. LOG("tokens: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx, embd_inp).c_str());
  221. // Should not run without any tokens
  222. if (embd_inp.empty()) {
  223. embd_inp.push_back(llama_token_bos(model));
  224. LOG("embd_inp was considered empty and bos was added: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx, embd_inp).c_str());
  225. }
  226. // Tokenize negative prompt
  227. std::vector<llama_token> guidance_inp;
  228. int guidance_offset = 0;
  229. int original_prompt_len = 0;
  230. if (ctx_guidance) {
  231. LOG("cfg_negative_prompt: \"%s\"\n", log_tostr(sparams.cfg_negative_prompt));
  232. guidance_inp = ::llama_tokenize(ctx_guidance, sparams.cfg_negative_prompt, add_bos);
  233. LOG("guidance_inp tokenized: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx_guidance, guidance_inp).c_str());
  234. std::vector<llama_token> original_inp = ::llama_tokenize(ctx, params.prompt, add_bos);
  235. LOG("original_inp tokenized: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx, original_inp).c_str());
  236. original_prompt_len = original_inp.size();
  237. guidance_offset = (int)guidance_inp.size() - original_prompt_len;
  238. LOG("original_prompt_len: %s", log_tostr(original_prompt_len));
  239. LOG("guidance_offset: %s", log_tostr(guidance_offset));
  240. }
  241. if ((int) embd_inp.size() > n_ctx - 4) {
  242. LOG_TEE("%s: error: prompt is too long (%d tokens, max %d)\n", __func__, (int) embd_inp.size(), n_ctx - 4);
  243. return 1;
  244. }
  245. // number of tokens to keep when resetting context
  246. if (params.n_keep < 0 || params.n_keep > (int) embd_inp.size()) {
  247. params.n_keep = (int)embd_inp.size();
  248. }
  249. LOG("inp_pfx: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx, inp_pfx).c_str());
  250. LOG("inp_sfx: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx, inp_sfx).c_str());
  251. // enable interactive mode if interactive start is specified
  252. if (params.interactive_first) {
  253. params.interactive = true;
  254. }
  255. if (params.verbose_prompt) {
  256. LOG_TEE("\n");
  257. LOG_TEE("%s: prompt: '%s'\n", __func__, params.prompt.c_str());
  258. LOG_TEE("%s: number of tokens in prompt = %zu\n", __func__, embd_inp.size());
  259. for (int i = 0; i < (int) embd_inp.size(); i++) {
  260. LOG_TEE("%6d -> '%s'\n", embd_inp[i], llama_token_to_piece(ctx, embd_inp[i]).c_str());
  261. }
  262. if (ctx_guidance) {
  263. LOG_TEE("\n");
  264. LOG_TEE("%s: negative prompt: '%s'\n", __func__, sparams.cfg_negative_prompt.c_str());
  265. LOG_TEE("%s: number of tokens in negative prompt = %zu\n", __func__, guidance_inp.size());
  266. for (int i = 0; i < (int) guidance_inp.size(); i++) {
  267. LOG_TEE("%6d -> '%s'\n", guidance_inp[i], llama_token_to_piece(ctx, guidance_inp[i]).c_str());
  268. }
  269. }
  270. if (params.n_keep > 0) {
  271. LOG_TEE("%s: static prompt based on n_keep: '", __func__);
  272. for (int i = 0; i < params.n_keep; i++) {
  273. LOG_TEE("%s", llama_token_to_piece(ctx, embd_inp[i]).c_str());
  274. }
  275. LOG_TEE("'\n");
  276. }
  277. LOG_TEE("\n");
  278. }
  279. if (params.interactive) {
  280. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
  281. struct sigaction sigint_action;
  282. sigint_action.sa_handler = sigint_handler;
  283. sigemptyset (&sigint_action.sa_mask);
  284. sigint_action.sa_flags = 0;
  285. sigaction(SIGINT, &sigint_action, NULL);
  286. #elif defined (_WIN32)
  287. auto console_ctrl_handler = +[](DWORD ctrl_type) -> BOOL {
  288. return (ctrl_type == CTRL_C_EVENT) ? (sigint_handler(SIGINT), true) : false;
  289. };
  290. SetConsoleCtrlHandler(reinterpret_cast<PHANDLER_ROUTINE>(console_ctrl_handler), true);
  291. #endif
  292. LOG_TEE("%s: interactive mode on.\n", __func__);
  293. if (params.input_prefix_bos) {
  294. LOG_TEE("Input prefix with BOS\n");
  295. }
  296. if (!params.input_prefix.empty()) {
  297. LOG_TEE("Input prefix: '%s'\n", params.input_prefix.c_str());
  298. }
  299. if (!params.input_suffix.empty()) {
  300. LOG_TEE("Input suffix: '%s'\n", params.input_suffix.c_str());
  301. }
  302. }
  303. LOG_TEE("sampling: \n%s\n", llama_sampling_print(sparams).c_str());
  304. 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);
  305. LOG_TEE("\n\n");
  306. LOG_TEE("\n##### Infill mode #####\n\n");
  307. if (params.infill) {
  308. printf("\n************\n");
  309. printf("no need to specify '--infill', always running infill\n");
  310. printf("************\n\n");
  311. }
  312. if (params.interactive) {
  313. const char *control_message;
  314. if (params.multiline_input) {
  315. control_message = " - To return control to LLaMa, end your input with '\\'.\n"
  316. " - To return control without starting a new line, end your input with '/'.\n";
  317. } else {
  318. control_message = " - Press Return to return control to LLaMa.\n"
  319. " - To return control without starting a new line, end your input with '/'.\n"
  320. " - If you want to submit another line, end your input with '\\'.\n";
  321. }
  322. LOG_TEE("== Running in interactive mode. ==\n");
  323. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__)) || defined (_WIN32)
  324. LOG_TEE( " - Press Ctrl+C to interject at any time.\n");
  325. #endif
  326. LOG_TEE( "%s\n", control_message);
  327. is_interacting = params.interactive_first;
  328. }
  329. bool input_echo = true;
  330. int n_past = 0;
  331. int n_remain = params.n_predict;
  332. int n_consumed = 0;
  333. int n_past_guidance = 0;
  334. std::vector<int> input_tokens; g_input_tokens = &input_tokens;
  335. std::vector<int> output_tokens; g_output_tokens = &output_tokens;
  336. std::ostringstream output_ss; g_output_ss = &output_ss;
  337. // the first thing we will do is to output the prompt, so set color accordingly
  338. console::set_display(console::prompt);
  339. std::vector<llama_token> embd;
  340. std::vector<llama_token> embd_guidance;
  341. struct llama_sampling_context * ctx_sampling = llama_sampling_init(sparams);
  342. while (n_remain != 0 || params.interactive) {
  343. // predict
  344. if (!embd.empty()) {
  345. // Note: n_ctx - 4 here is to match the logic for commandline prompt handling via
  346. // --prompt or --file which uses the same value.
  347. int max_embd_size = n_ctx - 4;
  348. // Ensure the input doesn't exceed the context size by truncating embd if necessary.
  349. if ((int) embd.size() > max_embd_size) {
  350. const int skipped_tokens = (int) embd.size() - max_embd_size;
  351. embd.resize(max_embd_size);
  352. console::set_display(console::error);
  353. printf("<<input too long: skipped %d token%s>>", skipped_tokens, skipped_tokens != 1 ? "s" : "");
  354. console::set_display(console::reset);
  355. fflush(stdout);
  356. }
  357. // infinite text generation via context swapping
  358. // if we run out of context:
  359. // - take the n_keep first tokens from the original prompt (via n_past)
  360. // - take half of the last (n_ctx - n_keep) tokens and recompute the logits in batches
  361. if (n_past + (int) embd.size() + std::max<int>(0, guidance_offset) > n_ctx) {
  362. if (params.n_predict == -2) {
  363. LOG_TEE("\n\n%s: context full and n_predict == -%d => stopping\n", __func__, params.n_predict);
  364. break;
  365. }
  366. const int n_left = n_past - params.n_keep - 1;
  367. const int n_discard = n_left/2;
  368. LOG("context full, swapping: n_past = %d, n_left = %d, n_ctx = %d, n_keep = %d, n_discard = %d\n",
  369. n_past, n_left, n_ctx, params.n_keep, n_discard);
  370. llama_kv_cache_seq_rm (ctx, 0, params.n_keep + 1 , params.n_keep + n_discard + 1);
  371. llama_kv_cache_seq_shift(ctx, 0, params.n_keep + 1 + n_discard, n_past, -n_discard);
  372. n_past -= n_discard;
  373. if (ctx_guidance) {
  374. n_past_guidance -= n_discard;
  375. }
  376. LOG("after swap: n_past = %d, n_past_guidance = %d\n", n_past, n_past_guidance);
  377. LOG("embd: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx, embd).c_str());
  378. }
  379. // evaluate tokens in batches
  380. // embd is typically prepared beforehand to fit within a batch, but not always
  381. if (ctx_guidance) {
  382. int input_size = 0;
  383. llama_token * input_buf = NULL;
  384. if (n_past_guidance < (int) guidance_inp.size()) {
  385. // Guidance context should have the same data with these modifications:
  386. //
  387. // * Replace the initial prompt
  388. // * Shift everything by guidance_offset
  389. embd_guidance = guidance_inp;
  390. if (embd.begin() + original_prompt_len < embd.end()) {
  391. embd_guidance.insert(
  392. embd_guidance.end(),
  393. embd.begin() + original_prompt_len,
  394. embd.end()
  395. );
  396. }
  397. input_buf = embd_guidance.data();
  398. input_size = embd_guidance.size();
  399. LOG("guidance context: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx, embd_guidance).c_str());
  400. } else {
  401. input_buf = embd.data();
  402. input_size = embd.size();
  403. }
  404. for (int i = 0; i < input_size; i += params.n_batch) {
  405. int n_eval = std::min(input_size - i, params.n_batch);
  406. if (llama_decode(ctx_guidance, llama_batch_get_one(input_buf + i, n_eval, n_past_guidance, 0))) {
  407. LOG_TEE("%s : failed to eval\n", __func__);
  408. return 1;
  409. }
  410. n_past_guidance += n_eval;
  411. }
  412. }
  413. for (int i = 0; i < (int) embd.size(); i += params.n_batch) {
  414. int n_eval = (int) embd.size() - i;
  415. if (n_eval > params.n_batch) {
  416. n_eval = params.n_batch;
  417. }
  418. LOG("eval: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx, embd).c_str());
  419. if (llama_decode(ctx, llama_batch_get_one(&embd[i], n_eval, n_past, 0))) {
  420. LOG_TEE("%s : failed to eval\n", __func__);
  421. return 1;
  422. }
  423. n_past += n_eval;
  424. LOG("n_past = %d\n", n_past);
  425. }
  426. }
  427. embd.clear();
  428. embd_guidance.clear();
  429. if ((int) embd_inp.size() <= n_consumed && !is_interacting) {
  430. const llama_token id = llama_sampling_sample(ctx_sampling, ctx, ctx_guidance);
  431. llama_sampling_accept(ctx_sampling, ctx, id, true);
  432. LOG("last: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx, ctx_sampling->prev).c_str());
  433. embd.push_back(id);
  434. // echo this to console
  435. input_echo = true;
  436. // decrement remaining sampling budget
  437. --n_remain;
  438. LOG("n_remain: %d\n", n_remain);
  439. } else {
  440. // some user input remains from prompt or interaction, forward it to processing
  441. LOG("embd_inp.size(): %d, n_consumed: %d\n", (int) embd_inp.size(), n_consumed);
  442. while ((int) embd_inp.size() > n_consumed) {
  443. embd.push_back(embd_inp[n_consumed]);
  444. // push the prompt in the sampling context in order to apply repetition penalties later
  445. // for the prompt, we don't apply grammar rules
  446. llama_sampling_accept(ctx_sampling, ctx, embd_inp[n_consumed], false);
  447. ++n_consumed;
  448. if ((int) embd.size() >= params.n_batch) {
  449. break;
  450. }
  451. }
  452. }
  453. // display text
  454. if (input_echo) {
  455. for (auto id : embd) {
  456. const std::string token_str = llama_token_to_piece(ctx, id);
  457. printf("%s", token_str.c_str());
  458. if (embd.size() > 1) {
  459. input_tokens.push_back(id);
  460. } else {
  461. output_tokens.push_back(id);
  462. output_ss << token_str;
  463. }
  464. }
  465. fflush(stdout);
  466. }
  467. // reset color to default if we there is no pending user input
  468. if (input_echo && (int) embd_inp.size() == n_consumed) {
  469. console::set_display(console::reset);
  470. }
  471. // if not currently processing queued inputs;
  472. if ((int) embd_inp.size() <= n_consumed) {
  473. // deal with eot token in infill mode
  474. if ((llama_sampling_last(ctx_sampling) == llama_token_eot(model) || is_interacting) && params.interactive){
  475. if(is_interacting && !params.interactive_first) {
  476. // print an eot token
  477. printf("%s", llama_token_to_piece(ctx, llama_token_eot(model)).c_str());
  478. }
  479. fflush(stdout);
  480. printf("\n");
  481. console::set_display(console::user_input);
  482. std::string buffer;
  483. std::string line;
  484. bool another_line=true;
  485. // set a new prefix via stdin
  486. do {
  487. another_line = console::readline(line, params.multiline_input);
  488. buffer += line;
  489. } while (another_line);
  490. // check if we got an empty line, if so we use the old input
  491. if (!buffer.empty() && !(buffer.length() == 1 && buffer[0] == '\n')) {
  492. params.input_prefix = buffer;
  493. }
  494. buffer.clear();
  495. // set a new suffix via stdin
  496. do {
  497. another_line = console::readline(line, params.multiline_input);
  498. buffer += line;
  499. } while (another_line);
  500. // check if we got an empty line
  501. if (!buffer.empty() && !(buffer.length() == 1 && buffer[0] == '\n')) {
  502. params.input_suffix = buffer;
  503. }
  504. buffer.clear();
  505. // done taking input, reset color
  506. console::set_display(console::reset);
  507. if (params.escape) {
  508. //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
  509. process_escapes(params.input_prefix);
  510. process_escapes(params.input_suffix);
  511. }
  512. suff_rm_leading_spc = params.escape;
  513. if (suff_rm_leading_spc && params.input_suffix.find_first_of(' ') == 0 && params.input_suffix.size() > 1) {
  514. params.input_suffix.erase(0, 1);
  515. suff_rm_leading_spc = false;
  516. }
  517. // tokenize new prefix and suffix
  518. std::vector<llama_token> inp_pfx = ::llama_tokenize(ctx, params.input_prefix, false);
  519. std::vector<llama_token> inp_sfx = ::llama_tokenize(ctx, params.input_suffix, false);
  520. if (suff_rm_leading_spc && inp_sfx[0] == space_token) {
  521. inp_sfx.erase(inp_sfx.begin());
  522. }
  523. inp_pfx.insert(inp_pfx.begin(), llama_token_prefix(model));
  524. if (add_bos) {
  525. inp_pfx.insert(inp_pfx.begin(), llama_token_bos(model));
  526. }
  527. inp_sfx.insert(inp_sfx.begin(), llama_token_suffix(model));
  528. embd_inp = inp_pfx;
  529. embd_inp.insert(embd_inp.end(), inp_sfx.begin(), inp_sfx.end());
  530. embd_inp.push_back(llama_token_middle(model));
  531. embd.clear();
  532. embd_guidance.clear();
  533. n_remain = params.n_predict;
  534. n_past = 0;
  535. n_consumed = 0;
  536. // LOG_TEE("took new input\n");
  537. is_interacting = false;
  538. }
  539. // deal with end of text token in interactive mode
  540. else if (llama_sampling_last(ctx_sampling) == llama_token_eos(model)) {
  541. LOG("found EOS token\n");
  542. if (params.interactive) {
  543. is_interacting = true;
  544. printf("\n");
  545. console::set_display(console::user_input);
  546. fflush(stdout);
  547. }
  548. }
  549. if (n_past > 0 && is_interacting && !params.interactive) {
  550. LOG("waiting for user input\n");
  551. if (params.input_prefix_bos) {
  552. LOG("adding input prefix BOS token\n");
  553. embd_inp.push_back(llama_token_bos(model));
  554. }
  555. std::string buffer;
  556. if (!params.input_prefix.empty()) {
  557. LOG("appending input prefix: '%s'\n", params.input_prefix.c_str());
  558. buffer += params.input_prefix;
  559. printf("%s", buffer.c_str());
  560. }
  561. std::string line;
  562. bool another_line = true;
  563. do {
  564. another_line = console::readline(line, params.multiline_input);
  565. buffer += line;
  566. } while (another_line);
  567. // done taking input, reset color
  568. console::set_display(console::reset);
  569. // Add tokens to embd only if the input buffer is non-empty
  570. // Entering a empty line lets the user pass control back
  571. if (buffer.length() > 1) {
  572. // append input suffix if any
  573. if (!params.input_suffix.empty()) {
  574. LOG("appending input suffix: '%s'\n", params.input_suffix.c_str());
  575. buffer += params.input_suffix;
  576. printf("%s", params.input_suffix.c_str());
  577. }
  578. LOG("buffer: '%s'\n", buffer.c_str());
  579. const size_t original_size = embd_inp.size();
  580. const auto line_inp = ::llama_tokenize(ctx, buffer, false);
  581. LOG("input tokens: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx, line_inp).c_str());
  582. embd_inp.insert(embd_inp.end(), line_inp.begin(), line_inp.end());
  583. for (size_t i = original_size; i < embd_inp.size(); ++i) {
  584. const llama_token token = embd_inp[i];
  585. output_tokens.push_back(token);
  586. output_ss << llama_token_to_piece(ctx, token);
  587. }
  588. n_remain -= line_inp.size();
  589. LOG("n_remain: %d\n", n_remain);
  590. } else {
  591. LOG("empty line, passing control back\n");
  592. }
  593. input_echo = false; // do not echo this again
  594. }
  595. if (n_past > 0) {
  596. if (is_interacting) {
  597. llama_sampling_reset(ctx_sampling);
  598. }
  599. is_interacting = false;
  600. }
  601. }
  602. // end of text token
  603. if (!embd.empty() && embd.back() == llama_token_eos(model) && !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(model)).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. llama_sampling_free(ctx_sampling);
  623. llama_backend_free();
  624. #ifndef LOG_DISABLE_LOGS
  625. LOG_TEE("Log end\n");
  626. #endif // LOG_DISABLE_LOGS
  627. return 0;
  628. }