completion.cpp 40 KB

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