1
0

main.cpp 40 KB

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