main.cpp 33 KB

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