1
0

main.cpp 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957
  1. #include "arg.h"
  2. #include "common.h"
  3. #include "console.h"
  4. #include "sampling.h"
  5. #include "llama.h"
  6. #include <cassert>
  7. #include <cinttypes>
  8. #include <cmath>
  9. #include <cstdio>
  10. #include <cstring>
  11. #include <ctime>
  12. #include <fstream>
  13. #include <iostream>
  14. #include <sstream>
  15. #include <string>
  16. #include <vector>
  17. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
  18. #include <signal.h>
  19. #include <unistd.h>
  20. #elif defined (_WIN32)
  21. #define WIN32_LEAN_AND_MEAN
  22. #ifndef NOMINMAX
  23. #define NOMINMAX
  24. #endif
  25. #include <windows.h>
  26. #include <signal.h>
  27. #endif
  28. #if defined(_MSC_VER)
  29. #pragma warning(disable: 4244 4267) // possible loss of data
  30. #endif
  31. static llama_context ** g_ctx;
  32. static llama_model ** g_model;
  33. static gpt_sampler ** g_smpl;
  34. static gpt_params * g_params;
  35. static std::vector<llama_token> * g_input_tokens;
  36. static std::ostringstream * g_output_ss;
  37. static std::vector<llama_token> * g_output_tokens;
  38. static bool is_interacting = false;
  39. static bool need_insert_eot = false;
  40. static void print_usage(int, char ** argv) {
  41. printf("\nexample usage:\n");
  42. printf("\n text generation: %s -m your_model.gguf -p \"I believe the meaning of life is\" -n 128\n", argv[0]);
  43. printf("\n chat (conversation): %s -m your_model.gguf -p \"You are a helpful assistant\" -cnv\n", argv[0]);
  44. printf("\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 gpt_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. fprintf(stderr, "%s: warning: failed to create logdir %s, cannot write logfile\n",
  68. __func__, params.logdir.c_str());
  69. return;
  70. }
  71. const std::string logfile_path = params.logdir + timestamp + ".yml";
  72. FILE * logfile = fopen(logfile_path.c_str(), "w");
  73. if (logfile == NULL) {
  74. fprintf(stderr, "%s: failed to open logfile %s\n", __func__, logfile_path.c_str());
  75. return;
  76. }
  77. fprintf(logfile, "binary: main\n");
  78. char model_desc[128];
  79. llama_model_desc(model, model_desc, sizeof(model_desc));
  80. yaml_dump_non_result_info(logfile, params, ctx, timestamp, input_tokens, model_desc);
  81. fprintf(logfile, "\n");
  82. fprintf(logfile, "######################\n");
  83. fprintf(logfile, "# Generation Results #\n");
  84. fprintf(logfile, "######################\n");
  85. fprintf(logfile, "\n");
  86. yaml_dump_string_multiline(logfile, "output", output.c_str());
  87. yaml_dump_vector_int(logfile, "output_tokens", output_tokens);
  88. llama_perf_dump_yaml(logfile, ctx);
  89. fclose(logfile);
  90. }
  91. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__)) || defined (_WIN32)
  92. static void sigint_handler(int signo) {
  93. if (signo == SIGINT) {
  94. if (!is_interacting && g_params->interactive) {
  95. is_interacting = true;
  96. need_insert_eot = true;
  97. } else {
  98. console::cleanup();
  99. printf("\n");
  100. gpt_perf_print(*g_ctx, *g_smpl);
  101. write_logfile(*g_ctx, *g_params, *g_model, *g_input_tokens, g_output_ss->str(), *g_output_tokens);
  102. _exit(130);
  103. }
  104. }
  105. }
  106. #endif
  107. static void llama_log_callback_logTee(ggml_log_level level, const char * text, void * user_data) {
  108. (void) level;
  109. (void) user_data;
  110. LOG_TEE("%s", text);
  111. }
  112. static std::string chat_add_and_format(struct llama_model * model, std::vector<llama_chat_msg> & chat_msgs, std::string role, std::string content) {
  113. llama_chat_msg new_msg{role, content};
  114. auto formatted = llama_chat_format_single(model, g_params->chat_template, chat_msgs, new_msg, role == "user");
  115. chat_msgs.push_back({role, content});
  116. LOG("formatted: %s\n", formatted.c_str());
  117. return formatted;
  118. }
  119. int main(int argc, char ** argv) {
  120. gpt_params params;
  121. g_params = &params;
  122. if (!gpt_params_parse(argc, argv, params, LLAMA_EXAMPLE_MAIN, print_usage)) {
  123. return 1;
  124. }
  125. auto & sparams = params.sparams;
  126. #ifndef LOG_DISABLE_LOGS
  127. log_set_target(log_filename_generator("main", "log"));
  128. LOG_TEE("Log start\n");
  129. log_dump_cmdline(argc, argv);
  130. llama_log_set(llama_log_callback_logTee, nullptr);
  131. #endif // LOG_DISABLE_LOGS
  132. // TODO: Dump params ?
  133. //LOG("Params perplexity: %s\n", LOG_TOSTR(params.perplexity));
  134. // save choice to use color for later
  135. // (note for later: this is a slightly awkward choice)
  136. console::init(params.simple_io, params.use_color);
  137. atexit([]() { console::cleanup(); });
  138. if (params.logits_all) {
  139. printf("\n************\n");
  140. printf("%s: please use the 'perplexity' tool for perplexity calculations\n", __func__);
  141. printf("************\n\n");
  142. return 0;
  143. }
  144. if (params.embedding) {
  145. printf("\n************\n");
  146. printf("%s: please use the 'embedding' tool for embedding calculations\n", __func__);
  147. printf("************\n\n");
  148. return 0;
  149. }
  150. if (params.n_ctx != 0 && params.n_ctx < 8) {
  151. LOG_TEE("%s: warning: minimum context size is 8, using minimum size.\n", __func__);
  152. params.n_ctx = 8;
  153. }
  154. if (params.rope_freq_base != 0.0) {
  155. LOG_TEE("%s: warning: changing RoPE frequency base to %g.\n", __func__, params.rope_freq_base);
  156. }
  157. if (params.rope_freq_scale != 0.0) {
  158. LOG_TEE("%s: warning: scaling RoPE frequency by %g.\n", __func__, params.rope_freq_scale);
  159. }
  160. print_build_info();
  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 seed: %u\n", gpt_sampler_get_seed(smpl));
  397. LOG_TEE("sampling params: \n%s\n", sparams.print().c_str());
  398. LOG_TEE("sampler constr: \n%s\n", gpt_sampler_print(smpl).c_str());
  399. 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);
  400. // group-attention state
  401. // number of grouped KV tokens so far (used only if params.grp_attn_n > 1)
  402. int ga_i = 0;
  403. const int ga_n = params.grp_attn_n;
  404. const int ga_w = params.grp_attn_w;
  405. if (ga_n != 1) {
  406. GGML_ASSERT(ga_n > 0 && "grp_attn_n must be positive"); // NOLINT
  407. GGML_ASSERT(ga_w % ga_n == 0 && "grp_attn_w must be a multiple of grp_attn_n"); // NOLINT
  408. //GGML_ASSERT(n_ctx_train % ga_w == 0 && "n_ctx_train must be a multiple of grp_attn_w"); // NOLINT
  409. //GGML_ASSERT(n_ctx >= n_ctx_train * ga_n && "n_ctx must be at least n_ctx_train * grp_attn_n"); // NOLINT
  410. LOG_TEE("self-extend: n_ctx_train = %d, grp_attn_n = %d, grp_attn_w = %d\n", n_ctx_train, ga_n, ga_w);
  411. }
  412. LOG_TEE("\n\n");
  413. if (params.interactive) {
  414. const char * control_message;
  415. if (params.multiline_input) {
  416. control_message = " - To return control to the AI, end your input with '\\'.\n"
  417. " - To return control without starting a new line, end your input with '/'.\n";
  418. } else {
  419. control_message = " - Press Return to return control to the AI.\n"
  420. " - To return control without starting a new line, end your input with '/'.\n"
  421. " - If you want to submit another line, end your input with '\\'.\n";
  422. }
  423. LOG_TEE("== Running in interactive mode. ==\n");
  424. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__)) || defined (_WIN32)
  425. LOG_TEE( " - Press Ctrl+C to interject at any time.\n");
  426. #endif
  427. LOG_TEE( "%s\n", control_message);
  428. is_interacting = params.interactive_first;
  429. }
  430. bool is_antiprompt = false;
  431. bool input_echo = true;
  432. bool display = true;
  433. bool need_to_save_session = !path_session.empty() && n_matching_session_tokens < embd_inp.size();
  434. int n_past = 0;
  435. int n_remain = params.n_predict;
  436. int n_consumed = 0;
  437. int n_session_consumed = 0;
  438. std::vector<int> input_tokens; g_input_tokens = &input_tokens;
  439. std::vector<int> output_tokens; g_output_tokens = &output_tokens;
  440. std::ostringstream output_ss; g_output_ss = &output_ss;
  441. std::ostringstream assistant_ss; // for storing current assistant message, used in conversation mode
  442. // the first thing we will do is to output the prompt, so set color accordingly
  443. console::set_display(console::prompt);
  444. display = params.display_prompt;
  445. std::vector<llama_token> embd;
  446. // tokenized antiprompts
  447. std::vector<std::vector<llama_token>> antiprompt_ids;
  448. antiprompt_ids.reserve(params.antiprompt.size());
  449. for (const std::string & antiprompt : params.antiprompt) {
  450. antiprompt_ids.emplace_back(::llama_tokenize(ctx, antiprompt, false, true));
  451. }
  452. if (llama_model_has_encoder(model)) {
  453. int enc_input_size = embd_inp.size();
  454. llama_token * enc_input_buf = embd_inp.data();
  455. if (llama_encode(ctx, llama_batch_get_one(enc_input_buf, enc_input_size, 0, 0))) {
  456. LOG_TEE("%s : failed to eval\n", __func__);
  457. return 1;
  458. }
  459. llama_token decoder_start_token_id = llama_model_decoder_start_token(model);
  460. if (decoder_start_token_id == -1) {
  461. decoder_start_token_id = llama_token_bos(model);
  462. }
  463. embd_inp.clear();
  464. embd_inp.push_back(decoder_start_token_id);
  465. }
  466. while ((n_remain != 0 && !is_antiprompt) || params.interactive) {
  467. // predict
  468. if (!embd.empty()) {
  469. // Note: (n_ctx - 4) here is to match the logic for commandline prompt handling via
  470. // --prompt or --file which uses the same value.
  471. int max_embd_size = n_ctx - 4;
  472. // Ensure the input doesn't exceed the context size by truncating embd if necessary.
  473. if ((int) embd.size() > max_embd_size) {
  474. const int skipped_tokens = (int) embd.size() - max_embd_size;
  475. embd.resize(max_embd_size);
  476. console::set_display(console::error);
  477. printf("<<input too long: skipped %d token%s>>", skipped_tokens, skipped_tokens != 1 ? "s" : "");
  478. console::set_display(console::reset);
  479. fflush(stdout);
  480. }
  481. if (ga_n == 1) {
  482. // infinite text generation via context shifting
  483. // if we run out of context:
  484. // - take the n_keep first tokens from the original prompt (via n_past)
  485. // - take half of the last (n_ctx - n_keep) tokens and recompute the logits in batches
  486. if (n_past + (int) embd.size() >= n_ctx) {
  487. if (params.n_predict == -2) {
  488. LOG_TEE("\n\n%s: context full and n_predict == -%d => stopping\n", __func__, params.n_predict);
  489. break;
  490. }
  491. const int n_left = n_past - params.n_keep;
  492. const int n_discard = n_left/2;
  493. LOG("context full, swapping: n_past = %d, n_left = %d, n_ctx = %d, n_keep = %d, n_discard = %d\n",
  494. n_past, n_left, n_ctx, params.n_keep, n_discard);
  495. llama_kv_cache_seq_rm (ctx, 0, params.n_keep , params.n_keep + n_discard);
  496. llama_kv_cache_seq_add(ctx, 0, params.n_keep + n_discard, n_past, -n_discard);
  497. n_past -= n_discard;
  498. LOG("after swap: n_past = %d\n", n_past);
  499. LOG("embd: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx, embd).c_str());
  500. LOG("clear session path\n");
  501. path_session.clear();
  502. }
  503. } else {
  504. // context extension via Self-Extend
  505. while (n_past >= ga_i + ga_w) {
  506. const int ib = (ga_n*ga_i)/ga_w;
  507. const int bd = (ga_w/ga_n)*(ga_n - 1);
  508. const int dd = (ga_w/ga_n) - ib*bd - ga_w;
  509. LOG("\n");
  510. LOG("shift: [%6d, %6d] + %6d -> [%6d, %6d]\n", ga_i, n_past, ib*bd, ga_i + ib*bd, n_past + ib*bd);
  511. 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);
  512. 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);
  513. llama_kv_cache_seq_add(ctx, 0, ga_i, n_past, ib*bd);
  514. llama_kv_cache_seq_div(ctx, 0, ga_i + ib*bd, ga_i + ib*bd + ga_w, ga_n);
  515. llama_kv_cache_seq_add(ctx, 0, ga_i + ib*bd + ga_w, n_past + ib*bd, dd);
  516. n_past -= bd;
  517. ga_i += ga_w/ga_n;
  518. LOG("\nn_past_old = %d, n_past = %d, ga_i = %d\n\n", n_past + bd, n_past, ga_i);
  519. }
  520. }
  521. // try to reuse a matching prefix from the loaded session instead of re-eval (via n_past)
  522. if (n_session_consumed < (int) session_tokens.size()) {
  523. size_t i = 0;
  524. for ( ; i < embd.size(); i++) {
  525. if (embd[i] != session_tokens[n_session_consumed]) {
  526. session_tokens.resize(n_session_consumed);
  527. break;
  528. }
  529. n_past++;
  530. n_session_consumed++;
  531. if (n_session_consumed >= (int) session_tokens.size()) {
  532. ++i;
  533. break;
  534. }
  535. }
  536. if (i > 0) {
  537. embd.erase(embd.begin(), embd.begin() + i);
  538. }
  539. }
  540. for (int i = 0; i < (int) embd.size(); i += params.n_batch) {
  541. int n_eval = (int) embd.size() - i;
  542. if (n_eval > params.n_batch) {
  543. n_eval = params.n_batch;
  544. }
  545. LOG("eval: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx, embd).c_str());
  546. if (llama_decode(ctx, llama_batch_get_one(&embd[i], n_eval, n_past, 0))) {
  547. LOG_TEE("%s : failed to eval\n", __func__);
  548. return 1;
  549. }
  550. n_past += n_eval;
  551. LOG("n_past = %d\n", n_past);
  552. // Display total tokens alongside total time
  553. if (params.n_print > 0 && n_past % params.n_print == 0) {
  554. LOG_TEE("\n\033[31mTokens consumed so far = %d / %d \033[0m\n", n_past, n_ctx);
  555. }
  556. }
  557. if (!embd.empty() && !path_session.empty()) {
  558. session_tokens.insert(session_tokens.end(), embd.begin(), embd.end());
  559. n_session_consumed = session_tokens.size();
  560. }
  561. }
  562. embd.clear();
  563. if ((int) embd_inp.size() <= n_consumed && !is_interacting) {
  564. // optionally save the session on first sample (for faster prompt loading next time)
  565. if (!path_session.empty() && need_to_save_session && !params.prompt_cache_ro) {
  566. need_to_save_session = false;
  567. llama_state_save_file(ctx, path_session.c_str(), session_tokens.data(), session_tokens.size());
  568. LOG("saved session to %s\n", path_session.c_str());
  569. }
  570. const llama_token id = gpt_sampler_sample(smpl, ctx, -1);
  571. gpt_sampler_accept(smpl, id, /* apply_grammar= */ true);
  572. // LOG("last: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx, smpl->prev.to_vector()).c_str());
  573. embd.push_back(id);
  574. // echo this to console
  575. input_echo = true;
  576. // decrement remaining sampling budget
  577. --n_remain;
  578. LOG("n_remain: %d\n", n_remain);
  579. } else {
  580. // some user input remains from prompt or interaction, forward it to processing
  581. LOG("embd_inp.size(): %d, n_consumed: %d\n", (int) embd_inp.size(), n_consumed);
  582. while ((int) embd_inp.size() > n_consumed) {
  583. embd.push_back(embd_inp[n_consumed]);
  584. // push the prompt in the sampling context in order to apply repetition penalties later
  585. // for the prompt, we don't apply grammar rules
  586. gpt_sampler_accept(smpl, embd_inp[n_consumed], /* apply_grammar= */ false);
  587. ++n_consumed;
  588. if ((int) embd.size() >= params.n_batch) {
  589. break;
  590. }
  591. }
  592. }
  593. // display text
  594. if (input_echo && display) {
  595. for (auto id : embd) {
  596. const std::string token_str = llama_token_to_piece(ctx, id, params.special);
  597. // Console/Stream Output
  598. fprintf(stdout, "%s", token_str.c_str());
  599. // Record Displayed Tokens To Log
  600. // Note: Generated tokens are created one by one hence this check
  601. if (embd.size() > 1) {
  602. // Incoming Requested Tokens
  603. input_tokens.push_back(id);
  604. } else {
  605. // Outgoing Generated Tokens
  606. output_tokens.push_back(id);
  607. output_ss << token_str;
  608. }
  609. fflush(stdout);
  610. }
  611. }
  612. // reset color to default if there is no pending user input
  613. if (input_echo && (int) embd_inp.size() == n_consumed) {
  614. console::set_display(console::reset);
  615. display = true;
  616. }
  617. // if not currently processing queued inputs;
  618. if ((int) embd_inp.size() <= n_consumed) {
  619. // check for reverse prompt in the last n_prev tokens
  620. if (!params.antiprompt.empty()) {
  621. const int n_prev = 32;
  622. const std::string last_output = gpt_sampler_prev_str(smpl, ctx, n_prev);
  623. is_antiprompt = false;
  624. // Check if each of the reverse prompts appears at the end of the output.
  625. // If we're not running interactively, the reverse prompt might be tokenized with some following characters
  626. // so we'll compensate for that by widening the search window a bit.
  627. for (std::string & antiprompt : params.antiprompt) {
  628. size_t extra_padding = params.interactive ? 0 : 2;
  629. size_t search_start_pos = last_output.length() > static_cast<size_t>(antiprompt.length() + extra_padding)
  630. ? last_output.length() - static_cast<size_t>(antiprompt.length() + extra_padding)
  631. : 0;
  632. if (last_output.find(antiprompt, search_start_pos) != std::string::npos) {
  633. if (params.interactive) {
  634. is_interacting = true;
  635. }
  636. is_antiprompt = true;
  637. break;
  638. }
  639. }
  640. // check for reverse prompt using special tokens
  641. llama_token last_token = gpt_sampler_last(smpl);
  642. for (std::vector<llama_token> ids : antiprompt_ids) {
  643. if (ids.size() == 1 && last_token == ids[0]) {
  644. if (params.interactive) {
  645. is_interacting = true;
  646. }
  647. is_antiprompt = true;
  648. break;
  649. }
  650. }
  651. if (is_antiprompt) {
  652. LOG("found antiprompt: %s\n", last_output.c_str());
  653. }
  654. }
  655. // deal with end of generation tokens in interactive mode
  656. if (llama_token_is_eog(model, gpt_sampler_last(smpl))) {
  657. LOG("found an EOG token\n");
  658. if (params.interactive) {
  659. if (!params.antiprompt.empty()) {
  660. // tokenize and inject first reverse prompt
  661. const auto first_antiprompt = ::llama_tokenize(ctx, params.antiprompt.front(), false, true);
  662. embd_inp.insert(embd_inp.end(), first_antiprompt.begin(), first_antiprompt.end());
  663. is_antiprompt = true;
  664. }
  665. if (params.enable_chat_template) {
  666. chat_add_and_format(model, chat_msgs, "assistant", assistant_ss.str());
  667. }
  668. is_interacting = true;
  669. printf("\n");
  670. }
  671. }
  672. // if current token is not EOG, we add it to current assistant message
  673. if (params.conversation) {
  674. const auto id = gpt_sampler_last(smpl);
  675. assistant_ss << llama_token_to_piece(ctx, id, false);
  676. }
  677. if (n_past > 0 && is_interacting) {
  678. LOG("waiting for user input\n");
  679. if (params.conversation) {
  680. printf("\n> ");
  681. }
  682. if (params.input_prefix_bos) {
  683. LOG("adding input prefix BOS token\n");
  684. embd_inp.push_back(llama_token_bos(model));
  685. }
  686. std::string buffer;
  687. if (!params.input_prefix.empty() && !params.conversation) {
  688. LOG("appending input prefix: '%s'\n", params.input_prefix.c_str());
  689. printf("%s", params.input_prefix.c_str());
  690. }
  691. // color user input only
  692. console::set_display(console::user_input);
  693. display = params.display_prompt;
  694. std::string line;
  695. bool another_line = true;
  696. do {
  697. another_line = console::readline(line, params.multiline_input);
  698. buffer += line;
  699. } while (another_line);
  700. // done taking input, reset color
  701. console::set_display(console::reset);
  702. display = true;
  703. // Add tokens to embd only if the input buffer is non-empty
  704. // Entering a empty line lets the user pass control back
  705. if (buffer.length() > 1) {
  706. // append input suffix if any
  707. if (!params.input_suffix.empty() && !params.conversation) {
  708. LOG("appending input suffix: '%s'\n", params.input_suffix.c_str());
  709. printf("%s", params.input_suffix.c_str());
  710. }
  711. LOG("buffer: '%s'\n", buffer.c_str());
  712. const size_t original_size = embd_inp.size();
  713. if (params.escape) {
  714. string_process_escapes(buffer);
  715. }
  716. bool format_chat = params.conversation && params.enable_chat_template;
  717. std::string user_inp = format_chat
  718. ? chat_add_and_format(model, chat_msgs, "user", std::move(buffer))
  719. : std::move(buffer);
  720. // TODO: one inconvenient of current chat template implementation is that we can't distinguish between user input and special tokens (prefix/postfix)
  721. const auto line_pfx = ::llama_tokenize(ctx, params.input_prefix, false, true);
  722. const auto line_inp = ::llama_tokenize(ctx, user_inp, false, format_chat);
  723. const auto line_sfx = ::llama_tokenize(ctx, params.input_suffix, false, true);
  724. LOG("input tokens: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx, line_inp).c_str());
  725. // if user stop generation mid-way, we must add EOT to finish model's last response
  726. if (need_insert_eot && format_chat) {
  727. llama_token eot = llama_token_eot(model);
  728. embd_inp.push_back(eot == -1 ? llama_token_eos(model) : eot);
  729. need_insert_eot = false;
  730. }
  731. embd_inp.insert(embd_inp.end(), line_pfx.begin(), line_pfx.end());
  732. embd_inp.insert(embd_inp.end(), line_inp.begin(), line_inp.end());
  733. embd_inp.insert(embd_inp.end(), line_sfx.begin(), line_sfx.end());
  734. for (size_t i = original_size; i < embd_inp.size(); ++i) {
  735. const llama_token token = embd_inp[i];
  736. output_tokens.push_back(token);
  737. output_ss << llama_token_to_piece(ctx, token);
  738. }
  739. // reset assistant message
  740. assistant_ss.str("");
  741. n_remain -= line_inp.size();
  742. LOG("n_remain: %d\n", n_remain);
  743. } else {
  744. LOG("empty line, passing control back\n");
  745. }
  746. input_echo = false; // do not echo this again
  747. }
  748. if (n_past > 0) {
  749. if (is_interacting) {
  750. gpt_sampler_reset(smpl);
  751. }
  752. is_interacting = false;
  753. }
  754. }
  755. // end of generation
  756. if (!embd.empty() && llama_token_is_eog(model, embd.back()) && !(params.interactive)) {
  757. LOG_TEE(" [end of text]\n");
  758. break;
  759. }
  760. // In interactive mode, respect the maximum number of tokens and drop back to user input when reached.
  761. // We skip this logic when n_predict == -1 (infinite) or -2 (stop at context size).
  762. if (params.interactive && n_remain <= 0 && params.n_predict >= 0) {
  763. n_remain = params.n_predict;
  764. is_interacting = true;
  765. }
  766. }
  767. if (!path_session.empty() && params.prompt_cache_all && !params.prompt_cache_ro) {
  768. LOG_TEE("\n%s: saving final output to session file '%s'\n", __func__, path_session.c_str());
  769. llama_state_save_file(ctx, path_session.c_str(), session_tokens.data(), session_tokens.size());
  770. }
  771. LOG_TEE("\n");
  772. gpt_perf_print(ctx, smpl);
  773. write_logfile(ctx, params, model, input_tokens, output_ss.str(), output_tokens);
  774. gpt_sampler_free(smpl);
  775. llama_free(ctx);
  776. llama_free_model(model);
  777. llama_backend_free();
  778. ggml_threadpool_free(threadpool);
  779. ggml_threadpool_free(threadpool_batch);
  780. #ifndef LOG_DISABLE_LOGS
  781. LOG_TEE("Log end\n");
  782. #endif // LOG_DISABLE_LOGS
  783. return 0;
  784. }