main.cpp 37 KB

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