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