completion.cpp 40 KB

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