main.cpp 37 KB

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