1
0

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