main.cpp 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898
  1. #include "arg.h"
  2. #include "common.h"
  3. #include "console.h"
  4. #include "log.h"
  5. #include "sampling.h"
  6. #include "llama.h"
  7. #include <cassert>
  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 common_sampler ** g_smpl;
  33. static common_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 bool need_insert_eot = false;
  39. static void print_usage(int argc, char ** argv) {
  40. (void) argc;
  41. LOG("\nexample usage:\n");
  42. LOG("\n text generation: %s -m your_model.gguf -p \"I believe the meaning of life is\" -n 128\n", argv[0]);
  43. LOG("\n chat (conversation): %s -m your_model.gguf -p \"You are a helpful assistant\" -cnv\n", argv[0]);
  44. LOG("\n");
  45. }
  46. static bool file_exists(const std::string & path) {
  47. std::ifstream f(path.c_str());
  48. return f.good();
  49. }
  50. static bool file_is_empty(const std::string & path) {
  51. std::ifstream f;
  52. f.exceptions(std::ifstream::failbit | std::ifstream::badbit);
  53. f.open(path.c_str(), std::ios::in | std::ios::binary | std::ios::ate);
  54. return f.tellg() == 0;
  55. }
  56. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__)) || defined (_WIN32)
  57. static void sigint_handler(int signo) {
  58. if (signo == SIGINT) {
  59. if (!is_interacting && g_params->interactive) {
  60. is_interacting = true;
  61. need_insert_eot = true;
  62. } else {
  63. console::cleanup();
  64. LOG("\n");
  65. common_perf_print(*g_ctx, *g_smpl);
  66. // make sure all logs are flushed
  67. LOG("Interrupted by user\n");
  68. common_log_pause(common_log_main());
  69. _exit(130);
  70. }
  71. }
  72. }
  73. #endif
  74. static std::string chat_add_and_format(struct llama_model * model, std::vector<common_chat_msg> & chat_msgs, const std::string & role, const std::string & content) {
  75. common_chat_msg new_msg{role, content};
  76. auto formatted = common_chat_format_single(model, g_params->chat_template, chat_msgs, new_msg, role == "user");
  77. chat_msgs.push_back({role, content});
  78. LOG_DBG("formatted: '%s'\n", formatted.c_str());
  79. return formatted;
  80. }
  81. int main(int argc, char ** argv) {
  82. common_params params;
  83. g_params = &params;
  84. if (!common_params_parse(argc, argv, params, LLAMA_EXAMPLE_MAIN, print_usage)) {
  85. return 1;
  86. }
  87. common_init();
  88. auto & sparams = params.sampling;
  89. // save choice to use color for later
  90. // (note for later: this is a slightly awkward choice)
  91. console::init(params.simple_io, params.use_color);
  92. atexit([]() { console::cleanup(); });
  93. if (params.logits_all) {
  94. LOG_ERR("************\n");
  95. LOG_ERR("%s: please use the 'perplexity' tool for perplexity calculations\n", __func__);
  96. LOG_ERR("************\n\n");
  97. return 0;
  98. }
  99. if (params.embedding) {
  100. LOG_ERR("************\n");
  101. LOG_ERR("%s: please use the 'embedding' tool for embedding calculations\n", __func__);
  102. LOG_ERR("************\n\n");
  103. return 0;
  104. }
  105. if (params.n_ctx != 0 && params.n_ctx < 8) {
  106. LOG_WRN("%s: warning: minimum context size is 8, using minimum size.\n", __func__);
  107. params.n_ctx = 8;
  108. }
  109. if (params.rope_freq_base != 0.0) {
  110. LOG_WRN("%s: warning: changing RoPE frequency base to %g.\n", __func__, params.rope_freq_base);
  111. }
  112. if (params.rope_freq_scale != 0.0) {
  113. LOG_WRN("%s: warning: scaling RoPE frequency by %g.\n", __func__, params.rope_freq_scale);
  114. }
  115. LOG_INF("%s: llama backend init\n", __func__);
  116. llama_backend_init();
  117. llama_numa_init(params.numa);
  118. llama_model * model = nullptr;
  119. llama_context * ctx = nullptr;
  120. common_sampler * smpl = nullptr;
  121. g_model = &model;
  122. g_ctx = &ctx;
  123. g_smpl = &smpl;
  124. std::vector<common_chat_msg> chat_msgs;
  125. // load the model and apply lora adapter, if any
  126. LOG_INF("%s: load the model and apply lora adapter, if any\n", __func__);
  127. common_init_result llama_init = common_init_from_params(params);
  128. model = llama_init.model.get();
  129. ctx = llama_init.context.get();
  130. if (model == NULL) {
  131. LOG_ERR("%s: error: unable to load model\n", __func__);
  132. return 1;
  133. }
  134. LOG_INF("%s: llama threadpool init, n_threads = %d\n", __func__, (int) params.cpuparams.n_threads);
  135. auto * reg = ggml_backend_dev_backend_reg(ggml_backend_dev_by_type(GGML_BACKEND_DEVICE_TYPE_CPU));
  136. auto * ggml_threadpool_new_fn = (decltype(ggml_threadpool_new) *) ggml_backend_reg_get_proc_address(reg, "ggml_threadpool_new");
  137. auto * ggml_threadpool_free_fn = (decltype(ggml_threadpool_free) *) ggml_backend_reg_get_proc_address(reg, "ggml_threadpool_free");
  138. struct ggml_threadpool_params tpp_batch =
  139. ggml_threadpool_params_from_cpu_params(params.cpuparams_batch);
  140. struct ggml_threadpool_params tpp =
  141. ggml_threadpool_params_from_cpu_params(params.cpuparams);
  142. set_process_priority(params.cpuparams.priority);
  143. struct ggml_threadpool * threadpool_batch = NULL;
  144. if (!ggml_threadpool_params_match(&tpp, &tpp_batch)) {
  145. threadpool_batch = ggml_threadpool_new_fn(&tpp_batch);
  146. if (!threadpool_batch) {
  147. LOG_ERR("%s: batch threadpool create failed : n_threads %d\n", __func__, tpp_batch.n_threads);
  148. return 1;
  149. }
  150. // Start the non-batch threadpool in the paused state
  151. tpp.paused = true;
  152. }
  153. struct ggml_threadpool * threadpool = ggml_threadpool_new_fn(&tpp);
  154. if (!threadpool) {
  155. LOG_ERR("%s: threadpool create failed : n_threads %d\n", __func__, tpp.n_threads);
  156. return 1;
  157. }
  158. llama_attach_threadpool(ctx, threadpool, threadpool_batch);
  159. const int n_ctx_train = llama_n_ctx_train(model);
  160. const int n_ctx = llama_n_ctx(ctx);
  161. if (n_ctx > n_ctx_train) {
  162. LOG_WRN("%s: model was trained on only %d context tokens (%d specified)\n", __func__, n_ctx_train, n_ctx);
  163. }
  164. // print chat template example in conversation mode
  165. if (params.conversation) {
  166. if (params.enable_chat_template) {
  167. LOG_INF("%s: chat template example:\n%s\n", __func__, common_chat_format_example(model, params.chat_template).c_str());
  168. } else {
  169. LOG_INF("%s: in-suffix/prefix is specified, chat template will be disabled\n", __func__);
  170. }
  171. }
  172. // print system information
  173. {
  174. LOG_INF("\n");
  175. LOG_INF("%s\n", common_params_get_system_info(params).c_str());
  176. LOG_INF("\n");
  177. }
  178. std::string path_session = params.path_prompt_cache;
  179. std::vector<llama_token> session_tokens;
  180. if (!path_session.empty()) {
  181. LOG_INF("%s: attempting to load saved session from '%s'\n", __func__, path_session.c_str());
  182. if (!file_exists(path_session)) {
  183. LOG_INF("%s: session file does not exist, will create.\n", __func__);
  184. } else if (file_is_empty(path_session)) {
  185. LOG_INF("%s: The session file is empty. A new session will be initialized.\n", __func__);
  186. } else {
  187. // The file exists and is not empty
  188. session_tokens.resize(n_ctx);
  189. size_t n_token_count_out = 0;
  190. if (!llama_state_load_file(ctx, path_session.c_str(), session_tokens.data(), session_tokens.capacity(), &n_token_count_out)) {
  191. LOG_ERR("%s: failed to load session file '%s'\n", __func__, path_session.c_str());
  192. return 1;
  193. }
  194. session_tokens.resize(n_token_count_out);
  195. LOG_INF("%s: loaded a session with prompt size of %d tokens\n", __func__, (int)session_tokens.size());
  196. }
  197. }
  198. const bool add_bos = llama_add_bos_token(model);
  199. if (!llama_model_has_encoder(model)) {
  200. GGML_ASSERT(!llama_add_eos_token(model));
  201. }
  202. LOG_DBG("n_ctx: %d, add_bos: %d\n", n_ctx, add_bos);
  203. std::vector<llama_token> embd_inp;
  204. {
  205. auto prompt = (params.conversation && params.enable_chat_template && !params.prompt.empty())
  206. ? chat_add_and_format(model, chat_msgs, "system", params.prompt) // format the system prompt in conversation mode
  207. : params.prompt;
  208. if (params.interactive_first || !params.prompt.empty() || session_tokens.empty()) {
  209. LOG_DBG("tokenize the prompt\n");
  210. embd_inp = common_tokenize(ctx, prompt, true, true);
  211. } else {
  212. LOG_DBG("use session tokens\n");
  213. embd_inp = session_tokens;
  214. }
  215. LOG_DBG("prompt: \"%s\"\n", prompt.c_str());
  216. LOG_DBG("tokens: %s\n", string_from(ctx, embd_inp).c_str());
  217. }
  218. // Should not run without any tokens
  219. if (embd_inp.empty()) {
  220. if (add_bos) {
  221. embd_inp.push_back(llama_token_bos(model));
  222. LOG_WRN("embd_inp was considered empty and bos was added: %s\n", string_from(ctx, embd_inp).c_str());
  223. } else {
  224. LOG_ERR("input is empty\n");
  225. return -1;
  226. }
  227. }
  228. // Tokenize negative prompt
  229. if ((int) embd_inp.size() > n_ctx - 4) {
  230. LOG_ERR("%s: prompt is too long (%d tokens, max %d)\n", __func__, (int) embd_inp.size(), n_ctx - 4);
  231. return 1;
  232. }
  233. // debug message about similarity of saved session, if applicable
  234. size_t n_matching_session_tokens = 0;
  235. if (!session_tokens.empty()) {
  236. for (llama_token id : session_tokens) {
  237. if (n_matching_session_tokens >= embd_inp.size() || id != embd_inp[n_matching_session_tokens]) {
  238. break;
  239. }
  240. n_matching_session_tokens++;
  241. }
  242. if (params.prompt.empty() && n_matching_session_tokens == embd_inp.size()) {
  243. LOG_INF("%s: using full prompt from session file\n", __func__);
  244. } else if (n_matching_session_tokens >= embd_inp.size()) {
  245. LOG_INF("%s: session file has exact match for prompt!\n", __func__);
  246. } else if (n_matching_session_tokens < (embd_inp.size() / 2)) {
  247. LOG_WRN("%s: session file has low similarity to prompt (%zu / %zu tokens); will mostly be reevaluated\n",
  248. __func__, n_matching_session_tokens, embd_inp.size());
  249. } else {
  250. LOG_INF("%s: session file matches %zu / %zu tokens of prompt\n",
  251. __func__, n_matching_session_tokens, embd_inp.size());
  252. }
  253. // remove any "future" tokens that we might have inherited from the previous session
  254. llama_kv_cache_seq_rm(ctx, -1, n_matching_session_tokens, -1);
  255. }
  256. LOG_DBG("recalculate the cached logits (check): embd_inp.size() %zu, n_matching_session_tokens %zu, embd_inp.size() %zu, session_tokens.size() %zu\n",
  257. embd_inp.size(), n_matching_session_tokens, embd_inp.size(), session_tokens.size());
  258. // if we will use the cache for the full prompt without reaching the end of the cache, force
  259. // reevaluation of the last token to recalculate the cached logits
  260. if (!embd_inp.empty() && n_matching_session_tokens == embd_inp.size() && session_tokens.size() > embd_inp.size()) {
  261. LOG_DBG("recalculate the cached logits (do): session_tokens.resize( %zu )\n", embd_inp.size() - 1);
  262. session_tokens.resize(embd_inp.size() - 1);
  263. }
  264. // number of tokens to keep when resetting context
  265. if (params.n_keep < 0 || params.n_keep > (int) embd_inp.size()) {
  266. params.n_keep = (int)embd_inp.size();
  267. } else {
  268. params.n_keep += add_bos; // always keep the BOS token
  269. }
  270. if (params.conversation) {
  271. params.interactive_first = true;
  272. }
  273. // enable interactive mode if interactive start is specified
  274. if (params.interactive_first) {
  275. params.interactive = true;
  276. }
  277. if (params.verbose_prompt) {
  278. LOG_INF("%s: prompt: '%s'\n", __func__, params.prompt.c_str());
  279. LOG_INF("%s: number of tokens in prompt = %zu\n", __func__, embd_inp.size());
  280. for (int i = 0; i < (int) embd_inp.size(); i++) {
  281. LOG_INF("%6d -> '%s'\n", embd_inp[i], common_token_to_piece(ctx, embd_inp[i]).c_str());
  282. }
  283. if (params.n_keep > add_bos) {
  284. LOG_INF("%s: static prompt based on n_keep: '", __func__);
  285. for (int i = 0; i < params.n_keep; i++) {
  286. LOG_CNT("%s", common_token_to_piece(ctx, embd_inp[i]).c_str());
  287. }
  288. LOG_CNT("'\n");
  289. }
  290. LOG_INF("\n");
  291. }
  292. // ctrl+C handling
  293. {
  294. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
  295. struct sigaction sigint_action;
  296. sigint_action.sa_handler = sigint_handler;
  297. sigemptyset (&sigint_action.sa_mask);
  298. sigint_action.sa_flags = 0;
  299. sigaction(SIGINT, &sigint_action, NULL);
  300. #elif defined (_WIN32)
  301. auto console_ctrl_handler = +[](DWORD ctrl_type) -> BOOL {
  302. return (ctrl_type == CTRL_C_EVENT) ? (sigint_handler(SIGINT), true) : false;
  303. };
  304. SetConsoleCtrlHandler(reinterpret_cast<PHANDLER_ROUTINE>(console_ctrl_handler), true);
  305. #endif
  306. }
  307. if (params.interactive) {
  308. LOG_INF("%s: interactive mode on.\n", __func__);
  309. if (!params.antiprompt.empty()) {
  310. for (const auto & antiprompt : params.antiprompt) {
  311. LOG_INF("Reverse prompt: '%s'\n", antiprompt.c_str());
  312. if (params.verbose_prompt) {
  313. auto tmp = common_tokenize(ctx, antiprompt, false, true);
  314. for (int i = 0; i < (int) tmp.size(); i++) {
  315. LOG_INF("%6d -> '%s'\n", tmp[i], common_token_to_piece(ctx, tmp[i]).c_str());
  316. }
  317. }
  318. }
  319. }
  320. if (params.input_prefix_bos) {
  321. LOG_INF("Input prefix with BOS\n");
  322. }
  323. if (!params.input_prefix.empty()) {
  324. LOG_INF("Input prefix: '%s'\n", params.input_prefix.c_str());
  325. if (params.verbose_prompt) {
  326. auto tmp = common_tokenize(ctx, params.input_prefix, true, true);
  327. for (int i = 0; i < (int) tmp.size(); i++) {
  328. LOG_INF("%6d -> '%s'\n", tmp[i], common_token_to_piece(ctx, tmp[i]).c_str());
  329. }
  330. }
  331. }
  332. if (!params.input_suffix.empty()) {
  333. LOG_INF("Input suffix: '%s'\n", params.input_suffix.c_str());
  334. if (params.verbose_prompt) {
  335. auto tmp = common_tokenize(ctx, params.input_suffix, false, true);
  336. for (int i = 0; i < (int) tmp.size(); i++) {
  337. LOG_INF("%6d -> '%s'\n", tmp[i], common_token_to_piece(ctx, tmp[i]).c_str());
  338. }
  339. }
  340. }
  341. }
  342. smpl = common_sampler_init(model, sparams);
  343. if (!smpl) {
  344. LOG_ERR("%s: failed to initialize sampling subsystem\n", __func__);
  345. return 1;
  346. }
  347. LOG_INF("sampler seed: %u\n", common_sampler_get_seed(smpl));
  348. LOG_INF("sampler params: \n%s\n", sparams.print().c_str());
  349. LOG_INF("sampler chain: %s\n", common_sampler_print(smpl).c_str());
  350. LOG_INF("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);
  351. // group-attention state
  352. // number of grouped KV tokens so far (used only if params.grp_attn_n > 1)
  353. int ga_i = 0;
  354. const int ga_n = params.grp_attn_n;
  355. const int ga_w = params.grp_attn_w;
  356. if (ga_n != 1) {
  357. GGML_ASSERT(ga_n > 0 && "grp_attn_n must be positive"); // NOLINT
  358. GGML_ASSERT(ga_w % ga_n == 0 && "grp_attn_w must be a multiple of grp_attn_n"); // NOLINT
  359. //GGML_ASSERT(n_ctx_train % ga_w == 0 && "n_ctx_train must be a multiple of grp_attn_w"); // NOLINT
  360. //GGML_ASSERT(n_ctx >= n_ctx_train * ga_n && "n_ctx must be at least n_ctx_train * grp_attn_n"); // NOLINT
  361. LOG_INF("self-extend: n_ctx_train = %d, grp_attn_n = %d, grp_attn_w = %d\n", n_ctx_train, ga_n, ga_w);
  362. }
  363. LOG_INF("\n");
  364. if (params.interactive) {
  365. const char * control_message;
  366. if (params.multiline_input) {
  367. control_message = " - To return control to the AI, end your input with '\\'.\n"
  368. " - To return control without starting a new line, end your input with '/'.\n";
  369. } else {
  370. control_message = " - Press Return to return control to the AI.\n"
  371. " - To return control without starting a new line, end your input with '/'.\n"
  372. " - If you want to submit another line, end your input with '\\'.\n";
  373. }
  374. LOG_INF("== Running in interactive mode. ==\n");
  375. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__)) || defined (_WIN32)
  376. LOG_INF( " - Press Ctrl+C to interject at any time.\n");
  377. #endif
  378. LOG_INF( "%s\n", control_message);
  379. is_interacting = params.interactive_first;
  380. }
  381. bool is_antiprompt = false;
  382. bool input_echo = true;
  383. bool display = true;
  384. bool need_to_save_session = !path_session.empty() && n_matching_session_tokens < embd_inp.size();
  385. int n_past = 0;
  386. int n_remain = params.n_predict;
  387. int n_consumed = 0;
  388. int n_session_consumed = 0;
  389. std::vector<int> input_tokens; g_input_tokens = &input_tokens;
  390. std::vector<int> output_tokens; g_output_tokens = &output_tokens;
  391. std::ostringstream output_ss; g_output_ss = &output_ss;
  392. std::ostringstream assistant_ss; // for storing current assistant message, used in conversation mode
  393. // the first thing we will do is to output the prompt, so set color accordingly
  394. console::set_display(console::prompt);
  395. display = params.display_prompt;
  396. std::vector<llama_token> embd;
  397. // tokenized antiprompts
  398. std::vector<std::vector<llama_token>> antiprompt_ids;
  399. antiprompt_ids.reserve(params.antiprompt.size());
  400. for (const std::string & antiprompt : params.antiprompt) {
  401. antiprompt_ids.emplace_back(::common_tokenize(ctx, antiprompt, false, true));
  402. }
  403. if (llama_model_has_encoder(model)) {
  404. int enc_input_size = embd_inp.size();
  405. llama_token * enc_input_buf = embd_inp.data();
  406. if (llama_encode(ctx, llama_batch_get_one(enc_input_buf, enc_input_size))) {
  407. LOG_ERR("%s : failed to eval\n", __func__);
  408. return 1;
  409. }
  410. llama_token decoder_start_token_id = llama_model_decoder_start_token(model);
  411. if (decoder_start_token_id == LLAMA_TOKEN_NULL) {
  412. decoder_start_token_id = llama_token_bos(model);
  413. }
  414. embd_inp.clear();
  415. embd_inp.push_back(decoder_start_token_id);
  416. }
  417. while ((n_remain != 0 && !is_antiprompt) || params.interactive) {
  418. // predict
  419. if (!embd.empty()) {
  420. // Note: (n_ctx - 4) here is to match the logic for commandline prompt handling via
  421. // --prompt or --file which uses the same value.
  422. int max_embd_size = n_ctx - 4;
  423. // Ensure the input doesn't exceed the context size by truncating embd if necessary.
  424. if ((int) embd.size() > max_embd_size) {
  425. const int skipped_tokens = (int) embd.size() - max_embd_size;
  426. embd.resize(max_embd_size);
  427. console::set_display(console::error);
  428. LOG_WRN("<<input too long: skipped %d token%s>>", skipped_tokens, skipped_tokens != 1 ? "s" : "");
  429. console::set_display(console::reset);
  430. }
  431. if (ga_n == 1) {
  432. // infinite text generation via context shifting
  433. // if we run out of context:
  434. // - take the n_keep first tokens from the original prompt (via n_past)
  435. // - take half of the last (n_ctx - n_keep) tokens and recompute the logits in batches
  436. if (n_past + (int) embd.size() >= n_ctx) {
  437. if (!params.ctx_shift){
  438. LOG_DBG("\n\n%s: context full and context shift is disabled => stopping\n", __func__);
  439. break;
  440. }
  441. if (params.n_predict == -2) {
  442. LOG_DBG("\n\n%s: context full and n_predict == -%d => stopping\n", __func__, params.n_predict);
  443. break;
  444. }
  445. const int n_left = n_past - params.n_keep;
  446. const int n_discard = n_left/2;
  447. LOG_DBG("context full, swapping: n_past = %d, n_left = %d, n_ctx = %d, n_keep = %d, n_discard = %d\n",
  448. n_past, n_left, n_ctx, params.n_keep, n_discard);
  449. llama_kv_cache_seq_rm (ctx, 0, params.n_keep , params.n_keep + n_discard);
  450. llama_kv_cache_seq_add(ctx, 0, params.n_keep + n_discard, n_past, -n_discard);
  451. n_past -= n_discard;
  452. LOG_DBG("after swap: n_past = %d\n", n_past);
  453. LOG_DBG("embd: %s\n", string_from(ctx, embd).c_str());
  454. LOG_DBG("clear session path\n");
  455. path_session.clear();
  456. }
  457. } else {
  458. // context extension via Self-Extend
  459. while (n_past >= ga_i + ga_w) {
  460. const int ib = (ga_n*ga_i)/ga_w;
  461. const int bd = (ga_w/ga_n)*(ga_n - 1);
  462. const int dd = (ga_w/ga_n) - ib*bd - ga_w;
  463. LOG_DBG("\n");
  464. LOG_DBG("shift: [%6d, %6d] + %6d -> [%6d, %6d]\n", ga_i, n_past, ib*bd, ga_i + ib*bd, n_past + ib*bd);
  465. LOG_DBG("div: [%6d, %6d] / %6d -> [%6d, %6d]\n", ga_i + ib*bd, ga_i + ib*bd + ga_w, ga_n, (ga_i + ib*bd)/ga_n, (ga_i + ib*bd + ga_w)/ga_n);
  466. LOG_DBG("shift: [%6d, %6d] + %6d -> [%6d, %6d]\n", ga_i + ib*bd + ga_w, n_past + ib*bd, dd, ga_i + ib*bd + ga_w + dd, n_past + ib*bd + dd);
  467. llama_kv_cache_seq_add(ctx, 0, ga_i, n_past, ib*bd);
  468. llama_kv_cache_seq_div(ctx, 0, ga_i + ib*bd, ga_i + ib*bd + ga_w, ga_n);
  469. llama_kv_cache_seq_add(ctx, 0, ga_i + ib*bd + ga_w, n_past + ib*bd, dd);
  470. n_past -= bd;
  471. ga_i += ga_w/ga_n;
  472. LOG_DBG("\nn_past_old = %d, n_past = %d, ga_i = %d\n\n", n_past + bd, n_past, ga_i);
  473. }
  474. }
  475. // try to reuse a matching prefix from the loaded session instead of re-eval (via n_past)
  476. if (n_session_consumed < (int) session_tokens.size()) {
  477. size_t i = 0;
  478. for ( ; i < embd.size(); i++) {
  479. if (embd[i] != session_tokens[n_session_consumed]) {
  480. session_tokens.resize(n_session_consumed);
  481. break;
  482. }
  483. n_past++;
  484. n_session_consumed++;
  485. if (n_session_consumed >= (int) session_tokens.size()) {
  486. ++i;
  487. break;
  488. }
  489. }
  490. if (i > 0) {
  491. embd.erase(embd.begin(), embd.begin() + i);
  492. }
  493. }
  494. for (int i = 0; i < (int) embd.size(); i += params.n_batch) {
  495. int n_eval = (int) embd.size() - i;
  496. if (n_eval > params.n_batch) {
  497. n_eval = params.n_batch;
  498. }
  499. LOG_DBG("eval: %s\n", string_from(ctx, embd).c_str());
  500. if (llama_decode(ctx, llama_batch_get_one(&embd[i], n_eval))) {
  501. LOG_ERR("%s : failed to eval\n", __func__);
  502. return 1;
  503. }
  504. n_past += n_eval;
  505. LOG_DBG("n_past = %d\n", n_past);
  506. // Display total tokens alongside total time
  507. if (params.n_print > 0 && n_past % params.n_print == 0) {
  508. LOG_DBG("\n\033[31mTokens consumed so far = %d / %d \033[0m\n", n_past, n_ctx);
  509. }
  510. }
  511. if (!embd.empty() && !path_session.empty()) {
  512. session_tokens.insert(session_tokens.end(), embd.begin(), embd.end());
  513. n_session_consumed = session_tokens.size();
  514. }
  515. }
  516. embd.clear();
  517. if ((int) embd_inp.size() <= n_consumed && !is_interacting) {
  518. // optionally save the session on first sample (for faster prompt loading next time)
  519. if (!path_session.empty() && need_to_save_session && !params.prompt_cache_ro) {
  520. need_to_save_session = false;
  521. llama_state_save_file(ctx, path_session.c_str(), session_tokens.data(), session_tokens.size());
  522. LOG_DBG("saved session to %s\n", path_session.c_str());
  523. }
  524. const llama_token id = common_sampler_sample(smpl, ctx, -1);
  525. common_sampler_accept(smpl, id, /* accept_grammar= */ true);
  526. // LOG_DBG("last: %s\n", string_from(ctx, smpl->prev.to_vector()).c_str());
  527. embd.push_back(id);
  528. // echo this to console
  529. input_echo = true;
  530. // decrement remaining sampling budget
  531. --n_remain;
  532. LOG_DBG("n_remain: %d\n", n_remain);
  533. } else {
  534. // some user input remains from prompt or interaction, forward it to processing
  535. LOG_DBG("embd_inp.size(): %d, n_consumed: %d\n", (int) embd_inp.size(), n_consumed);
  536. while ((int) embd_inp.size() > n_consumed) {
  537. embd.push_back(embd_inp[n_consumed]);
  538. // push the prompt in the sampling context in order to apply repetition penalties later
  539. // for the prompt, we don't apply grammar rules
  540. common_sampler_accept(smpl, embd_inp[n_consumed], /* accept_grammar= */ false);
  541. ++n_consumed;
  542. if ((int) embd.size() >= params.n_batch) {
  543. break;
  544. }
  545. }
  546. }
  547. // display text
  548. if (input_echo && display) {
  549. for (auto id : embd) {
  550. const std::string token_str = common_token_to_piece(ctx, id, params.special);
  551. // Console/Stream Output
  552. LOG("%s", token_str.c_str());
  553. // Record Displayed Tokens To Log
  554. // Note: Generated tokens are created one by one hence this check
  555. if (embd.size() > 1) {
  556. // Incoming Requested Tokens
  557. input_tokens.push_back(id);
  558. } else {
  559. // Outgoing Generated Tokens
  560. output_tokens.push_back(id);
  561. output_ss << token_str;
  562. }
  563. }
  564. }
  565. // reset color to default if there is no pending user input
  566. if (input_echo && (int) embd_inp.size() == n_consumed) {
  567. console::set_display(console::reset);
  568. display = true;
  569. }
  570. // if not currently processing queued inputs;
  571. if ((int) embd_inp.size() <= n_consumed) {
  572. // check for reverse prompt in the last n_prev tokens
  573. if (!params.antiprompt.empty()) {
  574. const int n_prev = 32;
  575. const std::string last_output = common_sampler_prev_str(smpl, ctx, n_prev);
  576. is_antiprompt = false;
  577. // Check if each of the reverse prompts appears at the end of the output.
  578. // If we're not running interactively, the reverse prompt might be tokenized with some following characters
  579. // so we'll compensate for that by widening the search window a bit.
  580. for (std::string & antiprompt : params.antiprompt) {
  581. size_t extra_padding = params.interactive ? 0 : 2;
  582. size_t search_start_pos = last_output.length() > static_cast<size_t>(antiprompt.length() + extra_padding)
  583. ? last_output.length() - static_cast<size_t>(antiprompt.length() + extra_padding)
  584. : 0;
  585. if (last_output.find(antiprompt, search_start_pos) != std::string::npos) {
  586. if (params.interactive) {
  587. is_interacting = true;
  588. }
  589. is_antiprompt = true;
  590. break;
  591. }
  592. }
  593. // check for reverse prompt using special tokens
  594. llama_token last_token = common_sampler_last(smpl);
  595. for (std::vector<llama_token> ids : antiprompt_ids) {
  596. if (ids.size() == 1 && last_token == ids[0]) {
  597. if (params.interactive) {
  598. is_interacting = true;
  599. }
  600. is_antiprompt = true;
  601. break;
  602. }
  603. }
  604. if (is_antiprompt) {
  605. LOG_DBG("found antiprompt: %s\n", last_output.c_str());
  606. }
  607. }
  608. // deal with end of generation tokens in interactive mode
  609. if (llama_token_is_eog(model, common_sampler_last(smpl))) {
  610. LOG_DBG("found an EOG token\n");
  611. if (params.interactive) {
  612. if (!params.antiprompt.empty()) {
  613. // tokenize and inject first reverse prompt
  614. const auto first_antiprompt = common_tokenize(ctx, params.antiprompt.front(), false, true);
  615. embd_inp.insert(embd_inp.end(), first_antiprompt.begin(), first_antiprompt.end());
  616. is_antiprompt = true;
  617. }
  618. if (params.enable_chat_template) {
  619. chat_add_and_format(model, chat_msgs, "assistant", assistant_ss.str());
  620. }
  621. is_interacting = true;
  622. LOG("\n");
  623. }
  624. }
  625. // if current token is not EOG, we add it to current assistant message
  626. if (params.conversation) {
  627. const auto id = common_sampler_last(smpl);
  628. assistant_ss << common_token_to_piece(ctx, id, false);
  629. }
  630. if (n_past > 0 && is_interacting) {
  631. LOG_DBG("waiting for user input\n");
  632. if (params.conversation) {
  633. LOG("\n> ");
  634. }
  635. if (params.input_prefix_bos) {
  636. LOG_DBG("adding input prefix BOS token\n");
  637. embd_inp.push_back(llama_token_bos(model));
  638. }
  639. std::string buffer;
  640. if (!params.input_prefix.empty() && !params.conversation) {
  641. LOG_DBG("appending input prefix: '%s'\n", params.input_prefix.c_str());
  642. LOG("%s", params.input_prefix.c_str());
  643. }
  644. // color user input only
  645. console::set_display(console::user_input);
  646. display = params.display_prompt;
  647. std::string line;
  648. bool another_line = true;
  649. do {
  650. another_line = console::readline(line, params.multiline_input);
  651. buffer += line;
  652. } while (another_line);
  653. // done taking input, reset color
  654. console::set_display(console::reset);
  655. display = true;
  656. // Add tokens to embd only if the input buffer is non-empty
  657. // Entering a empty line lets the user pass control back
  658. if (buffer.length() > 1) {
  659. // append input suffix if any
  660. if (!params.input_suffix.empty() && !params.conversation) {
  661. LOG_DBG("appending input suffix: '%s'\n", params.input_suffix.c_str());
  662. LOG("%s", params.input_suffix.c_str());
  663. }
  664. LOG_DBG("buffer: '%s'\n", buffer.c_str());
  665. const size_t original_size = embd_inp.size();
  666. if (params.escape) {
  667. string_process_escapes(buffer);
  668. }
  669. bool format_chat = params.conversation && params.enable_chat_template;
  670. std::string user_inp = format_chat
  671. ? chat_add_and_format(model, chat_msgs, "user", std::move(buffer))
  672. : std::move(buffer);
  673. // TODO: one inconvenient of current chat template implementation is that we can't distinguish between user input and special tokens (prefix/postfix)
  674. const auto line_pfx = common_tokenize(ctx, params.input_prefix, false, true);
  675. const auto line_inp = common_tokenize(ctx, user_inp, false, format_chat);
  676. const auto line_sfx = common_tokenize(ctx, params.input_suffix, false, true);
  677. LOG_DBG("input tokens: %s\n", string_from(ctx, line_inp).c_str());
  678. // if user stop generation mid-way, we must add EOT to finish model's last response
  679. if (need_insert_eot && format_chat) {
  680. llama_token eot = llama_token_eot(model);
  681. embd_inp.push_back(eot == LLAMA_TOKEN_NULL ? llama_token_eos(model) : eot);
  682. need_insert_eot = false;
  683. }
  684. embd_inp.insert(embd_inp.end(), line_pfx.begin(), line_pfx.end());
  685. embd_inp.insert(embd_inp.end(), line_inp.begin(), line_inp.end());
  686. embd_inp.insert(embd_inp.end(), line_sfx.begin(), line_sfx.end());
  687. for (size_t i = original_size; i < embd_inp.size(); ++i) {
  688. const llama_token token = embd_inp[i];
  689. output_tokens.push_back(token);
  690. output_ss << common_token_to_piece(ctx, token);
  691. }
  692. // reset assistant message
  693. assistant_ss.str("");
  694. n_remain -= line_inp.size();
  695. LOG_DBG("n_remain: %d\n", n_remain);
  696. } else {
  697. LOG_DBG("empty line, passing control back\n");
  698. }
  699. input_echo = false; // do not echo this again
  700. }
  701. if (n_past > 0) {
  702. if (is_interacting) {
  703. common_sampler_reset(smpl);
  704. }
  705. is_interacting = false;
  706. }
  707. }
  708. // end of generation
  709. if (!embd.empty() && llama_token_is_eog(model, embd.back()) && !(params.interactive)) {
  710. LOG(" [end of text]\n");
  711. break;
  712. }
  713. // In interactive mode, respect the maximum number of tokens and drop back to user input when reached.
  714. // We skip this logic when n_predict == -1 (infinite) or -2 (stop at context size).
  715. if (params.interactive && n_remain <= 0 && params.n_predict >= 0) {
  716. n_remain = params.n_predict;
  717. is_interacting = true;
  718. }
  719. }
  720. if (!path_session.empty() && params.prompt_cache_all && !params.prompt_cache_ro) {
  721. LOG("\n%s: saving final output to session file '%s'\n", __func__, path_session.c_str());
  722. llama_state_save_file(ctx, path_session.c_str(), session_tokens.data(), session_tokens.size());
  723. }
  724. LOG("\n\n");
  725. common_perf_print(ctx, smpl);
  726. common_sampler_free(smpl);
  727. llama_backend_free();
  728. ggml_threadpool_free_fn(threadpool);
  729. ggml_threadpool_free_fn(threadpool_batch);
  730. return 0;
  731. }