1
0

main.cpp 33 KB

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