infill.cpp 30 KB

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