main.cpp 37 KB

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