1
0

completion.cpp 40 KB

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