main.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865
  1. #include "common.h"
  2. #include "console.h"
  3. #include "llama.h"
  4. #include <cassert>
  5. #include <cinttypes>
  6. #include <cmath>
  7. #include <cstdio>
  8. #include <cstring>
  9. #include <ctime>
  10. #include <fstream>
  11. #include <iostream>
  12. #include <sstream>
  13. #include <string>
  14. #include <vector>
  15. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
  16. #include <signal.h>
  17. #include <unistd.h>
  18. #elif defined (_WIN32)
  19. #define WIN32_LEAN_AND_MEAN
  20. #ifndef NOMINMAX
  21. #define NOMINMAX
  22. #endif
  23. #include <windows.h>
  24. #include <signal.h>
  25. #endif
  26. #if defined(_MSC_VER)
  27. #pragma warning(disable: 4244 4267) // possible loss of data
  28. #endif
  29. static llama_context ** g_ctx;
  30. static llama_model ** g_model;
  31. static gpt_params * g_params;
  32. static std::vector<llama_token> * g_input_tokens;
  33. static std::ostringstream * g_output_ss;
  34. static std::vector<llama_token> * g_output_tokens;
  35. static bool is_interacting = false;
  36. static void write_logfile(
  37. const llama_context * ctx, const gpt_params & params, const llama_model * model,
  38. const std::vector<llama_token> & input_tokens, const std::string & output,
  39. const std::vector<llama_token> & output_tokens
  40. ) {
  41. if (params.logdir.empty()) {
  42. return;
  43. }
  44. const std::string timestamp = get_sortable_timestamp();
  45. const bool success = create_directory_with_parents(params.logdir);
  46. if (!success) {
  47. fprintf(stderr, "%s: warning: failed to create logdir %s, cannot write logfile\n",
  48. __func__, params.logdir.c_str());
  49. return;
  50. }
  51. const std::string logfile_path = params.logdir + timestamp + ".yml";
  52. FILE * logfile = fopen(logfile_path.c_str(), "w");
  53. if (logfile == NULL) {
  54. fprintf(stderr, "%s: failed to open logfile %s\n", __func__, logfile_path.c_str());
  55. return;
  56. }
  57. fprintf(logfile, "binary: main\n");
  58. char model_desc[128];
  59. llama_model_desc(model, model_desc, sizeof(model_desc));
  60. dump_non_result_info_yaml(logfile, params, ctx, timestamp, input_tokens, model_desc);
  61. fprintf(logfile, "\n");
  62. fprintf(logfile, "######################\n");
  63. fprintf(logfile, "# Generation Results #\n");
  64. fprintf(logfile, "######################\n");
  65. fprintf(logfile, "\n");
  66. dump_string_yaml_multiline(logfile, "output", output.c_str());
  67. dump_vector_int_yaml(logfile, "output_tokens", output_tokens);
  68. llama_dump_timing_info_yaml(logfile, ctx);
  69. fclose(logfile);
  70. }
  71. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__)) || defined (_WIN32)
  72. static void sigint_handler(int signo) {
  73. if (signo == SIGINT) {
  74. if (!is_interacting) {
  75. is_interacting = true;
  76. } else {
  77. console::cleanup();
  78. printf("\n");
  79. llama_print_timings(*g_ctx);
  80. write_logfile(*g_ctx, *g_params, *g_model, *g_input_tokens, g_output_ss->str(), *g_output_tokens);
  81. _exit(130);
  82. }
  83. }
  84. }
  85. #endif
  86. int main(int argc, char ** argv) {
  87. gpt_params params;
  88. g_params = &params;
  89. if (!gpt_params_parse(argc, argv, params)) {
  90. return 1;
  91. }
  92. llama_sampling_params & sparams = params.sparams;
  93. #ifndef LOG_DISABLE_LOGS
  94. log_set_target(log_filename_generator("main", "log"));
  95. LOG_TEE("Log start\n");
  96. log_dump_cmdline(argc, argv);
  97. #endif // LOG_DISABLE_LOGS
  98. // TODO: Dump params ?
  99. //LOG("Params perplexity: %s\n", LOG_TOSTR(params.perplexity));
  100. // save choice to use color for later
  101. // (note for later: this is a slightly awkward choice)
  102. console::init(params.simple_io, params.use_color);
  103. atexit([]() { console::cleanup(); });
  104. if (params.logits_all) {
  105. printf("\n************\n");
  106. printf("%s: please use the 'perplexity' tool for perplexity calculations\n", __func__);
  107. printf("************\n\n");
  108. return 0;
  109. }
  110. if (params.embedding) {
  111. printf("\n************\n");
  112. printf("%s: please use the 'embedding' tool for embedding calculations\n", __func__);
  113. printf("************\n\n");
  114. return 0;
  115. }
  116. if (params.n_ctx != 0 && params.n_ctx < 8) {
  117. LOG_TEE("%s: warning: minimum context size is 8, using minimum size.\n", __func__);
  118. params.n_ctx = 8;
  119. }
  120. if (params.rope_freq_base != 0.0) {
  121. LOG_TEE("%s: warning: changing RoPE frequency base to %g.\n", __func__, params.rope_freq_base);
  122. }
  123. if (params.rope_freq_scale != 0.0) {
  124. LOG_TEE("%s: warning: scaling RoPE frequency by %g.\n", __func__, params.rope_freq_scale);
  125. }
  126. LOG_TEE("%s: build = %d (%s)\n", __func__, LLAMA_BUILD_NUMBER, LLAMA_COMMIT);
  127. LOG_TEE("%s: built with %s for %s\n", __func__, LLAMA_COMPILER, LLAMA_BUILD_TARGET);
  128. if (params.seed == LLAMA_DEFAULT_SEED) {
  129. params.seed = time(NULL);
  130. }
  131. LOG_TEE("%s: seed = %u\n", __func__, params.seed);
  132. std::mt19937 rng(params.seed);
  133. if (params.random_prompt) {
  134. params.prompt = gpt_random_prompt(rng);
  135. }
  136. LOG("%s: llama backend init\n", __func__);
  137. llama_backend_init(params.numa);
  138. llama_model * model;
  139. llama_context * ctx;
  140. llama_context * ctx_guidance = NULL;
  141. g_model = &model;
  142. g_ctx = &ctx;
  143. // load the model and apply lora adapter, if any
  144. LOG("%s: load the model and apply lora adapter, if any\n", __func__);
  145. std::tie(model, ctx) = llama_init_from_gpt_params(params);
  146. if (sparams.cfg_scale > 1.f) {
  147. struct llama_context_params lparams = llama_context_params_from_gpt_params(params);
  148. ctx_guidance = llama_new_context_with_model(model, lparams);
  149. }
  150. if (model == NULL) {
  151. LOG_TEE("%s: error: unable to load model\n", __func__);
  152. return 1;
  153. }
  154. const int n_ctx_train = llama_n_ctx_train(model);
  155. const int n_ctx = llama_n_ctx(ctx);
  156. LOG("n_ctx: %d\n", n_ctx);
  157. if (n_ctx > n_ctx_train) {
  158. LOG_TEE("%s: warning: model was trained on only %d context tokens (%d specified)\n",
  159. __func__, n_ctx_train, n_ctx);
  160. }
  161. // print system information
  162. {
  163. LOG_TEE("\n");
  164. LOG_TEE("%s\n", get_system_info(params).c_str());
  165. }
  166. std::string path_session = params.path_prompt_cache;
  167. std::vector<llama_token> session_tokens;
  168. if (!path_session.empty()) {
  169. LOG_TEE("%s: attempting to load saved session from '%s'\n", __func__, path_session.c_str());
  170. // fopen to check for existing session
  171. FILE * fp = std::fopen(path_session.c_str(), "rb");
  172. if (fp != NULL) {
  173. std::fclose(fp);
  174. session_tokens.resize(n_ctx);
  175. size_t n_token_count_out = 0;
  176. if (!llama_load_session_file(ctx, path_session.c_str(), session_tokens.data(), session_tokens.capacity(), &n_token_count_out)) {
  177. LOG_TEE("%s: error: failed to load session file '%s'\n", __func__, path_session.c_str());
  178. return 1;
  179. }
  180. session_tokens.resize(n_token_count_out);
  181. llama_set_rng_seed(ctx, params.seed);
  182. LOG_TEE("%s: loaded a session with prompt size of %d tokens\n", __func__, (int) session_tokens.size());
  183. } else {
  184. LOG_TEE("%s: session file does not exist, will create\n", __func__);
  185. }
  186. }
  187. const bool add_bos = llama_should_add_bos_token(model);
  188. LOG("add_bos: %d\n", add_bos);
  189. std::vector<llama_token> embd_inp;
  190. if (params.interactive_first || params.instruct || params.chatml || !params.prompt.empty() || session_tokens.empty()) {
  191. LOG("tokenize the prompt\n");
  192. if (params.chatml) {
  193. params.prompt = "<|im_start|>system\n" + params.prompt + "<|im_end|>";
  194. }
  195. embd_inp = ::llama_tokenize(ctx, params.prompt, add_bos, true);
  196. } else {
  197. LOG("use session tokens\n");
  198. embd_inp = session_tokens;
  199. }
  200. LOG("prompt: \"%s\"\n", log_tostr(params.prompt));
  201. LOG("tokens: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx, embd_inp).c_str());
  202. // Should not run without any tokens
  203. if (embd_inp.empty()) {
  204. embd_inp.push_back(llama_token_bos(model));
  205. LOG("embd_inp was considered empty and bos was added: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx, embd_inp).c_str());
  206. }
  207. // Tokenize negative prompt
  208. std::vector<llama_token> guidance_inp;
  209. int guidance_offset = 0;
  210. int original_prompt_len = 0;
  211. if (ctx_guidance) {
  212. LOG("cfg_negative_prompt: \"%s\"\n", log_tostr(sparams.cfg_negative_prompt));
  213. guidance_inp = ::llama_tokenize(ctx_guidance, sparams.cfg_negative_prompt, add_bos, true);
  214. LOG("guidance_inp tokenized: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx_guidance, guidance_inp).c_str());
  215. std::vector<llama_token> original_inp = ::llama_tokenize(ctx, params.prompt, add_bos, true);
  216. LOG("original_inp tokenized: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx, original_inp).c_str());
  217. original_prompt_len = original_inp.size();
  218. guidance_offset = (int)guidance_inp.size() - original_prompt_len;
  219. LOG("original_prompt_len: %s", log_tostr(original_prompt_len));
  220. LOG("guidance_offset: %s", log_tostr(guidance_offset));
  221. }
  222. if ((int) embd_inp.size() > n_ctx - 4) {
  223. LOG_TEE("%s: error: prompt is too long (%d tokens, max %d)\n", __func__, (int) embd_inp.size(), n_ctx - 4);
  224. return 1;
  225. }
  226. // debug message about similarity of saved session, if applicable
  227. size_t n_matching_session_tokens = 0;
  228. if (!session_tokens.empty()) {
  229. for (llama_token id : session_tokens) {
  230. if (n_matching_session_tokens >= embd_inp.size() || id != embd_inp[n_matching_session_tokens]) {
  231. break;
  232. }
  233. n_matching_session_tokens++;
  234. }
  235. if (params.prompt.empty() && n_matching_session_tokens == embd_inp.size()) {
  236. LOG_TEE("%s: using full prompt from session file\n", __func__);
  237. } else if (n_matching_session_tokens >= embd_inp.size()) {
  238. LOG_TEE("%s: session file has exact match for prompt!\n", __func__);
  239. } else if (n_matching_session_tokens < (embd_inp.size() / 2)) {
  240. LOG_TEE("%s: warning: session file has low similarity to prompt (%zu / %zu tokens); will mostly be reevaluated\n",
  241. __func__, n_matching_session_tokens, embd_inp.size());
  242. } else {
  243. LOG_TEE("%s: session file matches %zu / %zu tokens of prompt\n",
  244. __func__, n_matching_session_tokens, embd_inp.size());
  245. }
  246. // remove any "future" tokens that we might have inherited from the previous session
  247. llama_kv_cache_seq_rm(ctx, -1, n_matching_session_tokens, -1);
  248. }
  249. LOGLN(
  250. "recalculate the cached logits (check): embd_inp.empty() %s, n_matching_session_tokens %zu, embd_inp.size() %zu, session_tokens.size() %zu, embd_inp.size() %zu",
  251. log_tostr(embd_inp.empty()), n_matching_session_tokens, embd_inp.size(), session_tokens.size(), embd_inp.size());
  252. // if we will use the cache for the full prompt without reaching the end of the cache, force
  253. // reevaluation of the last token token to recalculate the cached logits
  254. if (!embd_inp.empty() && n_matching_session_tokens == embd_inp.size() && session_tokens.size() > embd_inp.size()) {
  255. LOGLN("recalculate the cached logits (do): session_tokens.resize( %zu )", embd_inp.size() - 1);
  256. session_tokens.resize(embd_inp.size() - 1);
  257. }
  258. // number of tokens to keep when resetting context
  259. if (params.n_keep < 0 || params.n_keep > (int) embd_inp.size() || params.instruct || params.chatml) {
  260. params.n_keep = (int)embd_inp.size();
  261. }
  262. // prefix & suffix for instruct mode
  263. const auto inp_pfx = ::llama_tokenize(ctx, "\n\n### Instruction:\n\n", add_bos, true);
  264. const auto inp_sfx = ::llama_tokenize(ctx, "\n\n### Response:\n\n", false, true);
  265. LOG("inp_pfx: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx, inp_pfx).c_str());
  266. LOG("inp_sfx: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx, inp_sfx).c_str());
  267. // chatml prefix & suffix
  268. const auto cml_pfx = ::llama_tokenize(ctx, "\n<|im_start|>user\n", add_bos, true);
  269. const auto cml_sfx = ::llama_tokenize(ctx, "<|im_end|>\n<|im_start|>assistant\n", false, true);
  270. LOG("cml_pfx: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx, cml_pfx).c_str());
  271. LOG("cml_sfx: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx, cml_sfx).c_str());
  272. // in instruct mode, we inject a prefix and a suffix to each input by the user
  273. if (params.instruct) {
  274. params.interactive_first = true;
  275. params.antiprompt.push_back("### Instruction:\n\n");
  276. }
  277. // similar for chatml mode
  278. else if (params.chatml) {
  279. params.interactive_first = true;
  280. params.antiprompt.push_back("<|im_start|>user\n");
  281. }
  282. // enable interactive mode if interactive start is specified
  283. if (params.interactive_first) {
  284. params.interactive = true;
  285. }
  286. if (params.verbose_prompt) {
  287. LOG_TEE("\n");
  288. LOG_TEE("%s: prompt: '%s'\n", __func__, params.prompt.c_str());
  289. LOG_TEE("%s: number of tokens in prompt = %zu\n", __func__, embd_inp.size());
  290. for (int i = 0; i < (int) embd_inp.size(); i++) {
  291. LOG_TEE("%6d -> '%s'\n", embd_inp[i], llama_token_to_piece(ctx, embd_inp[i]).c_str());
  292. }
  293. if (ctx_guidance) {
  294. LOG_TEE("\n");
  295. LOG_TEE("%s: negative prompt: '%s'\n", __func__, sparams.cfg_negative_prompt.c_str());
  296. LOG_TEE("%s: number of tokens in negative prompt = %zu\n", __func__, guidance_inp.size());
  297. for (int i = 0; i < (int) guidance_inp.size(); i++) {
  298. LOG_TEE("%6d -> '%s'\n", guidance_inp[i], llama_token_to_piece(ctx, guidance_inp[i]).c_str());
  299. }
  300. }
  301. if (params.n_keep > 0) {
  302. LOG_TEE("%s: static prompt based on n_keep: '", __func__);
  303. for (int i = 0; i < params.n_keep; i++) {
  304. LOG_TEE("%s", llama_token_to_piece(ctx, embd_inp[i]).c_str());
  305. }
  306. LOG_TEE("'\n");
  307. }
  308. LOG_TEE("\n");
  309. }
  310. if (params.interactive) {
  311. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
  312. struct sigaction sigint_action;
  313. sigint_action.sa_handler = sigint_handler;
  314. sigemptyset (&sigint_action.sa_mask);
  315. sigint_action.sa_flags = 0;
  316. sigaction(SIGINT, &sigint_action, NULL);
  317. #elif defined (_WIN32)
  318. auto console_ctrl_handler = +[](DWORD ctrl_type) -> BOOL {
  319. return (ctrl_type == CTRL_C_EVENT) ? (sigint_handler(SIGINT), true) : false;
  320. };
  321. SetConsoleCtrlHandler(reinterpret_cast<PHANDLER_ROUTINE>(console_ctrl_handler), true);
  322. #endif
  323. LOG_TEE("%s: interactive mode on.\n", __func__);
  324. if (!params.antiprompt.empty()) {
  325. for (const auto & antiprompt : params.antiprompt) {
  326. LOG_TEE("Reverse prompt: '%s'\n", antiprompt.c_str());
  327. if (params.verbose_prompt) {
  328. auto tmp = ::llama_tokenize(ctx, antiprompt, false, true);
  329. for (int i = 0; i < (int) tmp.size(); i++) {
  330. LOG_TEE("%6d -> '%s'\n", tmp[i], llama_token_to_piece(ctx, tmp[i]).c_str());
  331. }
  332. }
  333. }
  334. }
  335. if (params.input_prefix_bos) {
  336. LOG_TEE("Input prefix with BOS\n");
  337. }
  338. if (!params.input_prefix.empty()) {
  339. LOG_TEE("Input prefix: '%s'\n", params.input_prefix.c_str());
  340. if (params.verbose_prompt) {
  341. auto tmp = ::llama_tokenize(ctx, params.input_prefix, true, true);
  342. for (int i = 0; i < (int) tmp.size(); i++) {
  343. LOG_TEE("%6d -> '%s'\n", tmp[i], llama_token_to_piece(ctx, tmp[i]).c_str());
  344. }
  345. }
  346. }
  347. if (!params.input_suffix.empty()) {
  348. LOG_TEE("Input suffix: '%s'\n", params.input_suffix.c_str());
  349. if (params.verbose_prompt) {
  350. auto tmp = ::llama_tokenize(ctx, params.input_suffix, false, true);
  351. for (int i = 0; i < (int) tmp.size(); i++) {
  352. LOG_TEE("%6d -> '%s'\n", tmp[i], llama_token_to_piece(ctx, tmp[i]).c_str());
  353. }
  354. }
  355. }
  356. }
  357. LOG_TEE("sampling: \n%s\n", llama_sampling_print(sparams).c_str());
  358. 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);
  359. LOG_TEE("\n\n");
  360. if (params.interactive) {
  361. const char *control_message;
  362. if (params.multiline_input) {
  363. control_message = " - To return control to LLaMa, end your input with '\\'.\n"
  364. " - To return control without starting a new line, end your input with '/'.\n";
  365. } else {
  366. control_message = " - Press Return to return control to LLaMa.\n"
  367. " - To return control without starting a new line, end your input with '/'.\n"
  368. " - If you want to submit another line, end your input with '\\'.\n";
  369. }
  370. LOG_TEE("== Running in interactive mode. ==\n");
  371. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__)) || defined (_WIN32)
  372. LOG_TEE( " - Press Ctrl+C to interject at any time.\n");
  373. #endif
  374. LOG_TEE( "%s\n", control_message);
  375. is_interacting = params.interactive_first;
  376. }
  377. bool is_antiprompt = false;
  378. bool input_echo = true;
  379. bool need_to_save_session = !path_session.empty() && n_matching_session_tokens < embd_inp.size();
  380. int n_past = 0;
  381. int n_remain = params.n_predict;
  382. int n_consumed = 0;
  383. int n_session_consumed = 0;
  384. int n_past_guidance = 0;
  385. std::vector<int> input_tokens; g_input_tokens = &input_tokens;
  386. std::vector<int> output_tokens; g_output_tokens = &output_tokens;
  387. std::ostringstream output_ss; g_output_ss = &output_ss;
  388. // the first thing we will do is to output the prompt, so set color accordingly
  389. console::set_display(console::prompt);
  390. std::vector<llama_token> embd;
  391. std::vector<llama_token> embd_guidance;
  392. struct llama_sampling_context * ctx_sampling = llama_sampling_init(sparams);
  393. while ((n_remain != 0 && !is_antiprompt) || params.interactive) {
  394. // predict
  395. if (!embd.empty()) {
  396. // Note: n_ctx - 4 here is to match the logic for commandline prompt handling via
  397. // --prompt or --file which uses the same value.
  398. int max_embd_size = n_ctx - 4;
  399. // Ensure the input doesn't exceed the context size by truncating embd if necessary.
  400. if ((int) embd.size() > max_embd_size) {
  401. const int skipped_tokens = (int) embd.size() - max_embd_size;
  402. embd.resize(max_embd_size);
  403. console::set_display(console::error);
  404. printf("<<input too long: skipped %d token%s>>", skipped_tokens, skipped_tokens != 1 ? "s" : "");
  405. console::set_display(console::reset);
  406. fflush(stdout);
  407. }
  408. // infinite text generation via context swapping
  409. // if we run out of context:
  410. // - take the n_keep first tokens from the original prompt (via n_past)
  411. // - take half of the last (n_ctx - n_keep) tokens and recompute the logits in batches
  412. if (n_past + (int) embd.size() + std::max<int>(0, guidance_offset) > n_ctx) {
  413. if (params.n_predict == -2) {
  414. LOG_TEE("\n\n%s: context full and n_predict == -%d => stopping\n", __func__, params.n_predict);
  415. break;
  416. }
  417. const int n_left = n_past - params.n_keep - 1;
  418. const int n_discard = n_left/2;
  419. LOG("context full, swapping: n_past = %d, n_left = %d, n_ctx = %d, n_keep = %d, n_discard = %d\n",
  420. n_past, n_left, n_ctx, params.n_keep, n_discard);
  421. llama_kv_cache_seq_rm (ctx, 0, params.n_keep + 1 , params.n_keep + n_discard + 1);
  422. llama_kv_cache_seq_shift(ctx, 0, params.n_keep + 1 + n_discard, n_past, -n_discard);
  423. n_past -= n_discard;
  424. if (ctx_guidance) {
  425. n_past_guidance -= n_discard;
  426. }
  427. LOG("after swap: n_past = %d, n_past_guidance = %d\n", n_past, n_past_guidance);
  428. LOG("embd: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx, embd).c_str());
  429. LOG("clear session path\n");
  430. path_session.clear();
  431. }
  432. // try to reuse a matching prefix from the loaded session instead of re-eval (via n_past)
  433. if (n_session_consumed < (int) session_tokens.size()) {
  434. size_t i = 0;
  435. for ( ; i < embd.size(); i++) {
  436. if (embd[i] != session_tokens[n_session_consumed]) {
  437. session_tokens.resize(n_session_consumed);
  438. break;
  439. }
  440. n_past++;
  441. n_session_consumed++;
  442. if (n_session_consumed >= (int) session_tokens.size()) {
  443. ++i;
  444. break;
  445. }
  446. }
  447. if (i > 0) {
  448. embd.erase(embd.begin(), embd.begin() + i);
  449. }
  450. }
  451. // evaluate tokens in batches
  452. // embd is typically prepared beforehand to fit within a batch, but not always
  453. if (ctx_guidance) {
  454. int input_size = 0;
  455. llama_token * input_buf = NULL;
  456. if (n_past_guidance < (int) guidance_inp.size()) {
  457. // Guidance context should have the same data with these modifications:
  458. //
  459. // * Replace the initial prompt
  460. // * Shift everything by guidance_offset
  461. embd_guidance = guidance_inp;
  462. if (embd.begin() + original_prompt_len < embd.end()) {
  463. embd_guidance.insert(
  464. embd_guidance.end(),
  465. embd.begin() + original_prompt_len,
  466. embd.end()
  467. );
  468. }
  469. input_buf = embd_guidance.data();
  470. input_size = embd_guidance.size();
  471. LOG("guidance context: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx, embd_guidance).c_str());
  472. } else {
  473. input_buf = embd.data();
  474. input_size = embd.size();
  475. }
  476. for (int i = 0; i < input_size; i += params.n_batch) {
  477. int n_eval = std::min(input_size - i, params.n_batch);
  478. if (llama_decode(ctx_guidance, llama_batch_get_one(input_buf + i, n_eval, n_past_guidance, 0))) {
  479. LOG_TEE("%s : failed to eval\n", __func__);
  480. return 1;
  481. }
  482. n_past_guidance += n_eval;
  483. }
  484. }
  485. for (int i = 0; i < (int) embd.size(); i += params.n_batch) {
  486. int n_eval = (int) embd.size() - i;
  487. if (n_eval > params.n_batch) {
  488. n_eval = params.n_batch;
  489. }
  490. LOG("eval: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx, embd).c_str());
  491. if (llama_decode(ctx, llama_batch_get_one(&embd[i], n_eval, n_past, 0))) {
  492. LOG_TEE("%s : failed to eval\n", __func__);
  493. return 1;
  494. }
  495. n_past += n_eval;
  496. LOG("n_past = %d\n", n_past);
  497. }
  498. if (!embd.empty() && !path_session.empty()) {
  499. session_tokens.insert(session_tokens.end(), embd.begin(), embd.end());
  500. n_session_consumed = session_tokens.size();
  501. }
  502. }
  503. embd.clear();
  504. embd_guidance.clear();
  505. if ((int) embd_inp.size() <= n_consumed && !is_interacting) {
  506. // optionally save the session on first sample (for faster prompt loading next time)
  507. if (!path_session.empty() && need_to_save_session && !params.prompt_cache_ro) {
  508. need_to_save_session = false;
  509. llama_save_session_file(ctx, path_session.c_str(), session_tokens.data(), session_tokens.size());
  510. LOG("saved session to %s\n", path_session.c_str());
  511. }
  512. const llama_token id = llama_sampling_sample(ctx_sampling, ctx, ctx_guidance);
  513. llama_sampling_accept(ctx_sampling, ctx, id, true);
  514. LOG("last: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx, ctx_sampling->prev).c_str());
  515. embd.push_back(id);
  516. // echo this to console
  517. input_echo = true;
  518. // decrement remaining sampling budget
  519. --n_remain;
  520. LOG("n_remain: %d\n", n_remain);
  521. } else {
  522. // some user input remains from prompt or interaction, forward it to processing
  523. LOG("embd_inp.size(): %d, n_consumed: %d\n", (int) embd_inp.size(), n_consumed);
  524. while ((int) embd_inp.size() > n_consumed) {
  525. embd.push_back(embd_inp[n_consumed]);
  526. // push the prompt in the sampling context in order to apply repetition penalties later
  527. // for the prompt, we don't apply grammar rules
  528. llama_sampling_accept(ctx_sampling, ctx, embd_inp[n_consumed], false);
  529. ++n_consumed;
  530. if ((int) embd.size() >= params.n_batch) {
  531. break;
  532. }
  533. }
  534. }
  535. // display text
  536. if (input_echo) {
  537. for (auto id : embd) {
  538. const std::string token_str = llama_token_to_piece(ctx, id);
  539. printf("%s", token_str.c_str());
  540. if (embd.size() > 1) {
  541. input_tokens.push_back(id);
  542. } else {
  543. output_tokens.push_back(id);
  544. output_ss << token_str;
  545. }
  546. }
  547. fflush(stdout);
  548. }
  549. // reset color to default if there is no pending user input
  550. if (input_echo && (int) embd_inp.size() == n_consumed) {
  551. console::set_display(console::reset);
  552. }
  553. // if not currently processing queued inputs;
  554. if ((int) embd_inp.size() <= n_consumed) {
  555. // check for reverse prompt in the last n_prev tokens
  556. if (!params.antiprompt.empty()) {
  557. const int n_prev = 32;
  558. const std::string last_output = llama_sampling_prev_str(ctx_sampling, ctx, n_prev);
  559. is_antiprompt = false;
  560. // Check if each of the reverse prompts appears at the end of the output.
  561. // If we're not running interactively, the reverse prompt might be tokenized with some following characters
  562. // so we'll compensate for that by widening the search window a bit.
  563. for (std::string & antiprompt : params.antiprompt) {
  564. size_t extra_padding = params.interactive ? 0 : 2;
  565. size_t search_start_pos = last_output.length() > static_cast<size_t>(antiprompt.length() + extra_padding)
  566. ? last_output.length() - static_cast<size_t>(antiprompt.length() + extra_padding)
  567. : 0;
  568. if (last_output.find(antiprompt, search_start_pos) != std::string::npos) {
  569. if (params.interactive) {
  570. is_interacting = true;
  571. }
  572. is_antiprompt = true;
  573. break;
  574. }
  575. }
  576. if (is_antiprompt) {
  577. LOG("found antiprompt: %s\n", last_output.c_str());
  578. }
  579. }
  580. // deal with end of text token in interactive mode
  581. if (llama_sampling_last(ctx_sampling) == llama_token_eos(model)) {
  582. LOG("found EOS token\n");
  583. if (params.interactive) {
  584. if (!params.antiprompt.empty()) {
  585. // tokenize and inject first reverse prompt
  586. const auto first_antiprompt = ::llama_tokenize(ctx, params.antiprompt.front(), false, true);
  587. embd_inp.insert(embd_inp.end(), first_antiprompt.begin(), first_antiprompt.end());
  588. is_antiprompt = true;
  589. }
  590. is_interacting = true;
  591. printf("\n");
  592. } else if (params.instruct || params.chatml) {
  593. is_interacting = true;
  594. }
  595. }
  596. if (n_past > 0 && is_interacting) {
  597. LOG("waiting for user input\n");
  598. if (params.instruct || params.chatml) {
  599. printf("\n> ");
  600. }
  601. if (params.input_prefix_bos) {
  602. LOG("adding input prefix BOS token\n");
  603. embd_inp.push_back(llama_token_bos(model));
  604. }
  605. std::string buffer;
  606. if (!params.input_prefix.empty()) {
  607. LOG("appending input prefix: '%s'\n", params.input_prefix.c_str());
  608. printf("%s", params.input_prefix.c_str());
  609. }
  610. // color user input only
  611. console::set_display(console::user_input);
  612. std::string line;
  613. bool another_line = true;
  614. do {
  615. another_line = console::readline(line, params.multiline_input);
  616. buffer += line;
  617. } while (another_line);
  618. // done taking input, reset color
  619. console::set_display(console::reset);
  620. // Add tokens to embd only if the input buffer is non-empty
  621. // Entering a empty line lets the user pass control back
  622. if (buffer.length() > 1) {
  623. // append input suffix if any
  624. if (!params.input_suffix.empty()) {
  625. LOG("appending input suffix: '%s'\n", params.input_suffix.c_str());
  626. printf("%s", params.input_suffix.c_str());
  627. }
  628. LOG("buffer: '%s'\n", buffer.c_str());
  629. const size_t original_size = embd_inp.size();
  630. // instruct mode: insert instruction prefix
  631. if (params.instruct && !is_antiprompt) {
  632. LOG("inserting instruction prefix\n");
  633. n_consumed = embd_inp.size();
  634. embd_inp.insert(embd_inp.end(), inp_pfx.begin(), inp_pfx.end());
  635. }
  636. // chatml mode: insert user chat prefix
  637. if (params.chatml && !is_antiprompt) {
  638. LOG("inserting chatml prefix\n");
  639. n_consumed = embd_inp.size();
  640. embd_inp.insert(embd_inp.end(), cml_pfx.begin(), cml_pfx.end());
  641. }
  642. if (params.escape) {
  643. process_escapes(buffer);
  644. }
  645. const auto line_pfx = ::llama_tokenize(ctx, params.input_prefix, false, true);
  646. const auto line_inp = ::llama_tokenize(ctx, buffer, false, false);
  647. const auto line_sfx = ::llama_tokenize(ctx, params.input_suffix, false, true);
  648. LOG("input tokens: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx, line_inp).c_str());
  649. embd_inp.insert(embd_inp.end(), line_pfx.begin(), line_pfx.end());
  650. embd_inp.insert(embd_inp.end(), line_inp.begin(), line_inp.end());
  651. embd_inp.insert(embd_inp.end(), line_sfx.begin(), line_sfx.end());
  652. // instruct mode: insert response suffix
  653. if (params.instruct) {
  654. LOG("inserting instruction suffix\n");
  655. embd_inp.insert(embd_inp.end(), inp_sfx.begin(), inp_sfx.end());
  656. }
  657. // chatml mode: insert assistant chat suffix
  658. if (params.chatml) {
  659. LOG("inserting chatml suffix\n");
  660. embd_inp.insert(embd_inp.end(), cml_sfx.begin(), cml_sfx.end());
  661. }
  662. for (size_t i = original_size; i < embd_inp.size(); ++i) {
  663. const llama_token token = embd_inp[i];
  664. output_tokens.push_back(token);
  665. output_ss << llama_token_to_piece(ctx, token);
  666. }
  667. n_remain -= line_inp.size();
  668. LOG("n_remain: %d\n", n_remain);
  669. } else {
  670. LOG("empty line, passing control back\n");
  671. }
  672. input_echo = false; // do not echo this again
  673. }
  674. if (n_past > 0) {
  675. if (is_interacting) {
  676. llama_sampling_reset(ctx_sampling);
  677. }
  678. is_interacting = false;
  679. }
  680. }
  681. // end of text token
  682. if (!embd.empty() && embd.back() == llama_token_eos(model) && !(params.instruct || params.interactive || params.chatml)) {
  683. LOG_TEE(" [end of text]\n");
  684. break;
  685. }
  686. // In interactive mode, respect the maximum number of tokens and drop back to user input when reached.
  687. // We skip this logic when n_predict == -1 (infinite) or -2 (stop at context size).
  688. if (params.interactive && n_remain <= 0 && params.n_predict >= 0) {
  689. n_remain = params.n_predict;
  690. is_interacting = true;
  691. }
  692. }
  693. if (!path_session.empty() && params.prompt_cache_all && !params.prompt_cache_ro) {
  694. LOG_TEE("\n%s: saving final output to session file '%s'\n", __func__, path_session.c_str());
  695. llama_save_session_file(ctx, path_session.c_str(), session_tokens.data(), session_tokens.size());
  696. }
  697. llama_print_timings(ctx);
  698. write_logfile(ctx, params, model, input_tokens, output_ss.str(), output_tokens);
  699. if (ctx_guidance) { llama_free(ctx_guidance); }
  700. llama_free(ctx);
  701. llama_free_model(model);
  702. llama_sampling_free(ctx_sampling);
  703. llama_backend_free();
  704. #ifndef LOG_DISABLE_LOGS
  705. LOG_TEE("Log end\n");
  706. #endif // LOG_DISABLE_LOGS
  707. return 0;
  708. }