main.cpp 37 KB

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