main.cpp 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997
  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_params * g_params;
  32. static std::vector<llama_token> * g_input_tokens;
  33. static std::ostringstream * g_output_ss;
  34. static std::vector<llama_token> * g_output_tokens;
  35. static bool is_interacting = false;
  36. static bool need_insert_eot = false;
  37. static bool file_exists(const std::string & path) {
  38. std::ifstream f(path.c_str());
  39. return f.good();
  40. }
  41. static bool file_is_empty(const std::string & path) {
  42. std::ifstream f;
  43. f.exceptions(std::ifstream::failbit | std::ifstream::badbit);
  44. f.open(path.c_str(), std::ios::in | std::ios::binary | std::ios::ate);
  45. return f.tellg() == 0;
  46. }
  47. static void write_logfile(
  48. const llama_context * ctx, const gpt_params & params, const llama_model * model,
  49. const std::vector<llama_token> & input_tokens, const std::string & output,
  50. const std::vector<llama_token> & output_tokens
  51. ) {
  52. if (params.logdir.empty()) {
  53. return;
  54. }
  55. const std::string timestamp = string_get_sortable_timestamp();
  56. const bool success = fs_create_directory_with_parents(params.logdir);
  57. if (!success) {
  58. fprintf(stderr, "%s: warning: failed to create logdir %s, cannot write logfile\n",
  59. __func__, params.logdir.c_str());
  60. return;
  61. }
  62. const std::string logfile_path = params.logdir + timestamp + ".yml";
  63. FILE * logfile = fopen(logfile_path.c_str(), "w");
  64. if (logfile == NULL) {
  65. fprintf(stderr, "%s: failed to open logfile %s\n", __func__, logfile_path.c_str());
  66. return;
  67. }
  68. fprintf(logfile, "binary: main\n");
  69. char model_desc[128];
  70. llama_model_desc(model, model_desc, sizeof(model_desc));
  71. yaml_dump_non_result_info(logfile, params, ctx, timestamp, input_tokens, model_desc);
  72. fprintf(logfile, "\n");
  73. fprintf(logfile, "######################\n");
  74. fprintf(logfile, "# Generation Results #\n");
  75. fprintf(logfile, "######################\n");
  76. fprintf(logfile, "\n");
  77. yaml_dump_string_multiline(logfile, "output", output.c_str());
  78. yaml_dump_vector_int(logfile, "output_tokens", output_tokens);
  79. llama_dump_timing_info_yaml(logfile, ctx);
  80. fclose(logfile);
  81. }
  82. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__)) || defined (_WIN32)
  83. static void sigint_handler(int signo) {
  84. if (signo == SIGINT) {
  85. if (!is_interacting && g_params->interactive) {
  86. is_interacting = true;
  87. need_insert_eot = true;
  88. } else {
  89. console::cleanup();
  90. printf("\n");
  91. llama_print_timings(*g_ctx);
  92. write_logfile(*g_ctx, *g_params, *g_model, *g_input_tokens, g_output_ss->str(), *g_output_tokens);
  93. _exit(130);
  94. }
  95. }
  96. }
  97. #endif
  98. static void llama_log_callback_logTee(ggml_log_level level, const char * text, void * user_data) {
  99. (void) level;
  100. (void) user_data;
  101. LOG_TEE("%s", text);
  102. }
  103. static std::string chat_add_and_format(struct llama_model * model, std::vector<llama_chat_msg> & chat_msgs, std::string role, std::string content) {
  104. llama_chat_msg new_msg{role, content};
  105. auto formatted = llama_chat_format_single(
  106. 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. llama_sampling_params & 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. LOG_TEE("%s: build = %d (%s)\n", __func__, LLAMA_BUILD_NUMBER, LLAMA_COMMIT);
  154. LOG_TEE("%s: built with %s for %s\n", __func__, LLAMA_COMPILER, LLAMA_BUILD_TARGET);
  155. if (params.seed == LLAMA_DEFAULT_SEED) {
  156. params.seed = time(NULL);
  157. }
  158. LOG_TEE("%s: seed = %u\n", __func__, params.seed);
  159. std::mt19937 rng(params.seed);
  160. LOG("%s: llama backend init\n", __func__);
  161. llama_backend_init();
  162. llama_numa_init(params.numa);
  163. llama_model * model;
  164. llama_context * ctx;
  165. llama_context * ctx_guidance = NULL;
  166. std::vector<llama_chat_msg> chat_msgs;
  167. g_model = &model;
  168. g_ctx = &ctx;
  169. // load the model and apply lora adapter, if any
  170. LOG("%s: load the model and apply lora adapter, if any\n", __func__);
  171. llama_init_result llama_init = llama_init_from_gpt_params(params);
  172. model = llama_init.model;
  173. ctx = llama_init.context;
  174. if (sparams.cfg_scale > 1.f) {
  175. struct llama_context_params lparams = llama_context_params_from_gpt_params(params);
  176. ctx_guidance = llama_new_context_with_model(model, lparams);
  177. }
  178. if (model == NULL) {
  179. LOG_TEE("%s: error: unable to load model\n", __func__);
  180. return 1;
  181. }
  182. const int n_ctx_train = llama_n_ctx_train(model);
  183. const int n_ctx = llama_n_ctx(ctx);
  184. LOG("n_ctx: %d\n", n_ctx);
  185. if (n_ctx > n_ctx_train) {
  186. LOG_TEE("%s: warning: model was trained on only %d context tokens (%d specified)\n",
  187. __func__, n_ctx_train, n_ctx);
  188. }
  189. // print chat template example in conversation mode
  190. if (params.conversation) {
  191. if (params.enable_chat_template) {
  192. LOG_TEE("%s: chat template example: %s\n", __func__, llama_chat_format_example(model, params.chat_template).c_str());
  193. } else {
  194. LOG_TEE("%s: in-suffix/prefix is specified, chat template will be disabled\n", __func__);
  195. }
  196. }
  197. // print system information
  198. {
  199. LOG_TEE("\n");
  200. LOG_TEE("%s\n", gpt_params_get_system_info(params).c_str());
  201. }
  202. std::string path_session = params.path_prompt_cache;
  203. std::vector<llama_token> session_tokens;
  204. if (!path_session.empty()) {
  205. LOG_TEE("%s: attempting to load saved session from '%s'\n", __func__, path_session.c_str());
  206. if (!file_exists(path_session)) {
  207. LOG_TEE("%s: session file does not exist, will create.\n", __func__);
  208. } else if (file_is_empty(path_session)) {
  209. LOG_TEE("%s: The session file is empty. A new session will be initialized.\n", __func__);
  210. } else {
  211. // The file exists and is not empty
  212. session_tokens.resize(n_ctx);
  213. size_t n_token_count_out = 0;
  214. if (!llama_state_load_file(ctx, path_session.c_str(), session_tokens.data(), session_tokens.capacity(), &n_token_count_out)) {
  215. LOG_TEE("%s: error: failed to load session file '%s'\n", __func__, path_session.c_str());
  216. return 1;
  217. }
  218. session_tokens.resize(n_token_count_out);
  219. LOG_TEE("%s: loaded a session with prompt size of %d tokens\n", __func__, (int)session_tokens.size());
  220. }
  221. }
  222. const bool add_bos = llama_add_bos_token(model);
  223. if (!llama_model_has_encoder(model)) {
  224. GGML_ASSERT(!llama_add_eos_token(model));
  225. }
  226. LOG("add_bos: %d\n", add_bos);
  227. std::vector<llama_token> embd_inp;
  228. {
  229. auto prompt = (params.conversation && params.enable_chat_template && !params.prompt.empty())
  230. ? chat_add_and_format(model, chat_msgs, "system", params.prompt) // format the system prompt in conversation mode
  231. : params.prompt;
  232. if (params.interactive_first || !params.prompt.empty() || session_tokens.empty()) {
  233. LOG("tokenize the prompt\n");
  234. embd_inp = ::llama_tokenize(ctx, prompt, true, true);
  235. } else {
  236. LOG("use session tokens\n");
  237. embd_inp = session_tokens;
  238. }
  239. LOG("prompt: \"%s\"\n", log_tostr(prompt));
  240. LOG("tokens: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx, embd_inp).c_str());
  241. }
  242. // Should not run without any tokens
  243. if (embd_inp.empty()) {
  244. if (add_bos) {
  245. embd_inp.push_back(llama_token_bos(model));
  246. LOG("embd_inp was considered empty and bos was added: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx, embd_inp).c_str());
  247. } else {
  248. LOG_TEE("error: input is empty\n");
  249. return -1;
  250. }
  251. }
  252. // Tokenize negative prompt
  253. std::vector<llama_token> guidance_inp;
  254. int guidance_offset = 0;
  255. int original_prompt_len = 0;
  256. if (ctx_guidance) {
  257. LOG("cfg_negative_prompt: \"%s\"\n", log_tostr(sparams.cfg_negative_prompt));
  258. guidance_inp = ::llama_tokenize(ctx_guidance, sparams.cfg_negative_prompt, true, true);
  259. LOG("guidance_inp tokenized: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx_guidance, guidance_inp).c_str());
  260. std::vector<llama_token> original_inp = ::llama_tokenize(ctx, params.prompt, true, true);
  261. LOG("original_inp tokenized: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx, original_inp).c_str());
  262. original_prompt_len = original_inp.size();
  263. guidance_offset = (int)guidance_inp.size() - original_prompt_len;
  264. LOG("original_prompt_len: %s", log_tostr(original_prompt_len));
  265. LOG("guidance_offset: %s", log_tostr(guidance_offset));
  266. }
  267. if ((int) embd_inp.size() > n_ctx - 4) {
  268. LOG_TEE("%s: error: prompt is too long (%d tokens, max %d)\n", __func__, (int) embd_inp.size(), n_ctx - 4);
  269. return 1;
  270. }
  271. // debug message about similarity of saved session, if applicable
  272. size_t n_matching_session_tokens = 0;
  273. if (!session_tokens.empty()) {
  274. for (llama_token id : session_tokens) {
  275. if (n_matching_session_tokens >= embd_inp.size() || id != embd_inp[n_matching_session_tokens]) {
  276. break;
  277. }
  278. n_matching_session_tokens++;
  279. }
  280. if (params.prompt.empty() && n_matching_session_tokens == embd_inp.size()) {
  281. LOG_TEE("%s: using full prompt from session file\n", __func__);
  282. } else if (n_matching_session_tokens >= embd_inp.size()) {
  283. LOG_TEE("%s: session file has exact match for prompt!\n", __func__);
  284. } else if (n_matching_session_tokens < (embd_inp.size() / 2)) {
  285. LOG_TEE("%s: warning: session file has low similarity to prompt (%zu / %zu tokens); will mostly be reevaluated\n",
  286. __func__, n_matching_session_tokens, embd_inp.size());
  287. } else {
  288. LOG_TEE("%s: session file matches %zu / %zu tokens of prompt\n",
  289. __func__, n_matching_session_tokens, embd_inp.size());
  290. }
  291. // remove any "future" tokens that we might have inherited from the previous session
  292. llama_kv_cache_seq_rm(ctx, -1, n_matching_session_tokens, -1);
  293. }
  294. LOGLN(
  295. "recalculate the cached logits (check): embd_inp.empty() %s, n_matching_session_tokens %zu, embd_inp.size() %zu, session_tokens.size() %zu, embd_inp.size() %zu",
  296. log_tostr(embd_inp.empty()), n_matching_session_tokens, embd_inp.size(), session_tokens.size(), embd_inp.size());
  297. // if we will use the cache for the full prompt without reaching the end of the cache, force
  298. // reevaluation of the last token to recalculate the cached logits
  299. if (!embd_inp.empty() && n_matching_session_tokens == embd_inp.size() && session_tokens.size() > embd_inp.size()) {
  300. LOGLN("recalculate the cached logits (do): session_tokens.resize( %zu )", embd_inp.size() - 1);
  301. session_tokens.resize(embd_inp.size() - 1);
  302. }
  303. // number of tokens to keep when resetting context
  304. if (params.n_keep < 0 || params.n_keep > (int) embd_inp.size()) {
  305. params.n_keep = (int)embd_inp.size();
  306. } else {
  307. params.n_keep += add_bos; // always keep the BOS token
  308. }
  309. if (params.conversation) {
  310. params.interactive_first = true;
  311. }
  312. // enable interactive mode if interactive start is specified
  313. if (params.interactive_first) {
  314. params.interactive = true;
  315. }
  316. if (params.verbose_prompt) {
  317. LOG_TEE("\n");
  318. LOG_TEE("%s: prompt: '%s'\n", __func__, params.prompt.c_str());
  319. LOG_TEE("%s: number of tokens in prompt = %zu\n", __func__, embd_inp.size());
  320. for (int i = 0; i < (int) embd_inp.size(); i++) {
  321. LOG_TEE("%6d -> '%s'\n", embd_inp[i], llama_token_to_piece(ctx, embd_inp[i]).c_str());
  322. }
  323. if (ctx_guidance) {
  324. LOG_TEE("\n");
  325. LOG_TEE("%s: negative prompt: '%s'\n", __func__, sparams.cfg_negative_prompt.c_str());
  326. LOG_TEE("%s: number of tokens in negative prompt = %zu\n", __func__, guidance_inp.size());
  327. for (int i = 0; i < (int) guidance_inp.size(); i++) {
  328. LOG_TEE("%6d -> '%s'\n", guidance_inp[i], llama_token_to_piece(ctx, guidance_inp[i]).c_str());
  329. }
  330. }
  331. if (params.n_keep > add_bos) {
  332. LOG_TEE("%s: static prompt based on n_keep: '", __func__);
  333. for (int i = 0; i < params.n_keep; i++) {
  334. LOG_TEE("%s", llama_token_to_piece(ctx, embd_inp[i]).c_str());
  335. }
  336. LOG_TEE("'\n");
  337. }
  338. LOG_TEE("\n");
  339. }
  340. // ctrl+C handling
  341. {
  342. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
  343. struct sigaction sigint_action;
  344. sigint_action.sa_handler = sigint_handler;
  345. sigemptyset (&sigint_action.sa_mask);
  346. sigint_action.sa_flags = 0;
  347. sigaction(SIGINT, &sigint_action, NULL);
  348. #elif defined (_WIN32)
  349. auto console_ctrl_handler = +[](DWORD ctrl_type) -> BOOL {
  350. return (ctrl_type == CTRL_C_EVENT) ? (sigint_handler(SIGINT), true) : false;
  351. };
  352. SetConsoleCtrlHandler(reinterpret_cast<PHANDLER_ROUTINE>(console_ctrl_handler), true);
  353. #endif
  354. }
  355. if (params.interactive) {
  356. LOG_TEE("%s: interactive mode on.\n", __func__);
  357. if (!params.antiprompt.empty()) {
  358. for (const auto & antiprompt : params.antiprompt) {
  359. LOG_TEE("Reverse prompt: '%s'\n", antiprompt.c_str());
  360. if (params.verbose_prompt) {
  361. auto tmp = ::llama_tokenize(ctx, antiprompt, false, true);
  362. for (int i = 0; i < (int) tmp.size(); i++) {
  363. LOG_TEE("%6d -> '%s'\n", tmp[i], llama_token_to_piece(ctx, tmp[i]).c_str());
  364. }
  365. }
  366. }
  367. }
  368. if (params.input_prefix_bos) {
  369. LOG_TEE("Input prefix with BOS\n");
  370. }
  371. if (!params.input_prefix.empty()) {
  372. LOG_TEE("Input prefix: '%s'\n", params.input_prefix.c_str());
  373. if (params.verbose_prompt) {
  374. auto tmp = ::llama_tokenize(ctx, params.input_prefix, true, true);
  375. for (int i = 0; i < (int) tmp.size(); i++) {
  376. LOG_TEE("%6d -> '%s'\n", tmp[i], llama_token_to_piece(ctx, tmp[i]).c_str());
  377. }
  378. }
  379. }
  380. if (!params.input_suffix.empty()) {
  381. LOG_TEE("Input suffix: '%s'\n", params.input_suffix.c_str());
  382. if (params.verbose_prompt) {
  383. auto tmp = ::llama_tokenize(ctx, params.input_suffix, false, true);
  384. for (int i = 0; i < (int) tmp.size(); i++) {
  385. LOG_TEE("%6d -> '%s'\n", tmp[i], llama_token_to_piece(ctx, tmp[i]).c_str());
  386. }
  387. }
  388. }
  389. }
  390. LOG_TEE("sampling: \n%s\n", llama_sampling_print(sparams).c_str());
  391. LOG_TEE("sampling order: \n%s\n", llama_sampling_order_print(sparams).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. int n_past_guidance = 0;
  432. std::vector<int> input_tokens; g_input_tokens = &input_tokens;
  433. std::vector<int> output_tokens; g_output_tokens = &output_tokens;
  434. std::ostringstream output_ss; g_output_ss = &output_ss;
  435. std::ostringstream assistant_ss; // for storing current assistant message, used in conversation mode
  436. // the first thing we will do is to output the prompt, so set color accordingly
  437. console::set_display(console::prompt);
  438. display = params.display_prompt;
  439. std::vector<llama_token> embd;
  440. std::vector<llama_token> embd_guidance;
  441. // tokenized antiprompts
  442. std::vector<std::vector<llama_token>> antiprompt_ids;
  443. antiprompt_ids.reserve(params.antiprompt.size());
  444. for (const std::string & antiprompt : params.antiprompt) {
  445. antiprompt_ids.emplace_back(::llama_tokenize(ctx, antiprompt, false, true));
  446. }
  447. struct llama_sampling_context * ctx_sampling = llama_sampling_init(sparams);
  448. if (!ctx_sampling) {
  449. fprintf(stderr, "%s: failed to initialize sampling subsystem\n", __func__);
  450. exit(1);
  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() + std::max<int>(0, guidance_offset) >= 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. if (ctx_guidance) {
  499. n_past_guidance -= n_discard;
  500. }
  501. LOG("after swap: n_past = %d, n_past_guidance = %d\n", n_past, n_past_guidance);
  502. LOG("embd: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx, embd).c_str());
  503. LOG("clear session path\n");
  504. path_session.clear();
  505. }
  506. } else {
  507. // context extension via Self-Extend
  508. while (n_past >= ga_i + ga_w) {
  509. const int ib = (ga_n*ga_i)/ga_w;
  510. const int bd = (ga_w/ga_n)*(ga_n - 1);
  511. const int dd = (ga_w/ga_n) - ib*bd - ga_w;
  512. LOG("\n");
  513. LOG("shift: [%6d, %6d] + %6d -> [%6d, %6d]\n", ga_i, n_past, ib*bd, ga_i + ib*bd, n_past + ib*bd);
  514. 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);
  515. 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);
  516. llama_kv_cache_seq_add(ctx, 0, ga_i, n_past, ib*bd);
  517. llama_kv_cache_seq_div(ctx, 0, ga_i + ib*bd, ga_i + ib*bd + ga_w, ga_n);
  518. llama_kv_cache_seq_add(ctx, 0, ga_i + ib*bd + ga_w, n_past + ib*bd, dd);
  519. n_past -= bd;
  520. ga_i += ga_w/ga_n;
  521. LOG("\nn_past_old = %d, n_past = %d, ga_i = %d\n\n", n_past + bd, n_past, ga_i);
  522. }
  523. }
  524. // try to reuse a matching prefix from the loaded session instead of re-eval (via n_past)
  525. if (n_session_consumed < (int) session_tokens.size()) {
  526. size_t i = 0;
  527. for ( ; i < embd.size(); i++) {
  528. if (embd[i] != session_tokens[n_session_consumed]) {
  529. session_tokens.resize(n_session_consumed);
  530. break;
  531. }
  532. n_past++;
  533. n_session_consumed++;
  534. if (n_session_consumed >= (int) session_tokens.size()) {
  535. ++i;
  536. break;
  537. }
  538. }
  539. if (i > 0) {
  540. embd.erase(embd.begin(), embd.begin() + i);
  541. }
  542. }
  543. // evaluate tokens in batches
  544. // embd is typically prepared beforehand to fit within a batch, but not always
  545. if (ctx_guidance) {
  546. int input_size = 0;
  547. llama_token * input_buf = NULL;
  548. if (n_past_guidance < (int) guidance_inp.size()) {
  549. // Guidance context should have the same data with these modifications:
  550. //
  551. // * Replace the initial prompt
  552. // * Shift everything by guidance_offset
  553. embd_guidance = guidance_inp;
  554. if (embd.begin() + original_prompt_len < embd.end()) {
  555. embd_guidance.insert(
  556. embd_guidance.end(),
  557. embd.begin() + original_prompt_len,
  558. embd.end()
  559. );
  560. }
  561. input_buf = embd_guidance.data();
  562. input_size = embd_guidance.size();
  563. LOG("guidance context: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx, embd_guidance).c_str());
  564. } else {
  565. input_buf = embd.data();
  566. input_size = embd.size();
  567. }
  568. for (int i = 0; i < input_size; i += params.n_batch) {
  569. int n_eval = std::min(input_size - i, params.n_batch);
  570. if (llama_decode(ctx_guidance, llama_batch_get_one(input_buf + i, n_eval, n_past_guidance, 0))) {
  571. LOG_TEE("%s : failed to eval\n", __func__);
  572. return 1;
  573. }
  574. n_past_guidance += n_eval;
  575. }
  576. }
  577. for (int i = 0; i < (int) embd.size(); i += params.n_batch) {
  578. int n_eval = (int) embd.size() - i;
  579. if (n_eval > params.n_batch) {
  580. n_eval = params.n_batch;
  581. }
  582. LOG("eval: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx, embd).c_str());
  583. if (llama_decode(ctx, llama_batch_get_one(&embd[i], n_eval, n_past, 0))) {
  584. LOG_TEE("%s : failed to eval\n", __func__);
  585. return 1;
  586. }
  587. n_past += n_eval;
  588. LOG("n_past = %d\n", n_past);
  589. // Display total tokens alongside total time
  590. if (params.n_print > 0 && n_past % params.n_print == 0) {
  591. LOG_TEE("\n\033[31mTokens consumed so far = %d / %d \033[0m\n", n_past, n_ctx);
  592. }
  593. }
  594. if (!embd.empty() && !path_session.empty()) {
  595. session_tokens.insert(session_tokens.end(), embd.begin(), embd.end());
  596. n_session_consumed = session_tokens.size();
  597. }
  598. }
  599. embd.clear();
  600. embd_guidance.clear();
  601. if ((int) embd_inp.size() <= n_consumed && !is_interacting) {
  602. // optionally save the session on first sample (for faster prompt loading next time)
  603. if (!path_session.empty() && need_to_save_session && !params.prompt_cache_ro) {
  604. need_to_save_session = false;
  605. llama_state_save_file(ctx, path_session.c_str(), session_tokens.data(), session_tokens.size());
  606. LOG("saved session to %s\n", path_session.c_str());
  607. }
  608. const llama_token id = llama_sampling_sample(ctx_sampling, ctx, ctx_guidance);
  609. llama_sampling_accept(ctx_sampling, ctx, id, /* apply_grammar= */ true);
  610. LOG("last: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx, ctx_sampling->prev).c_str());
  611. embd.push_back(id);
  612. // echo this to console
  613. input_echo = true;
  614. // decrement remaining sampling budget
  615. --n_remain;
  616. LOG("n_remain: %d\n", n_remain);
  617. } else {
  618. // some user input remains from prompt or interaction, forward it to processing
  619. LOG("embd_inp.size(): %d, n_consumed: %d\n", (int) embd_inp.size(), n_consumed);
  620. while ((int) embd_inp.size() > n_consumed) {
  621. embd.push_back(embd_inp[n_consumed]);
  622. // push the prompt in the sampling context in order to apply repetition penalties later
  623. // for the prompt, we don't apply grammar rules
  624. llama_sampling_accept(ctx_sampling, ctx, embd_inp[n_consumed], /* apply_grammar= */ false);
  625. ++n_consumed;
  626. if ((int) embd.size() >= params.n_batch) {
  627. break;
  628. }
  629. }
  630. }
  631. // display text
  632. if (input_echo && display) {
  633. for (auto id : embd) {
  634. const std::string token_str = llama_token_to_piece(ctx, id, params.special);
  635. // Console/Stream Output
  636. fprintf(stdout, "%s", token_str.c_str());
  637. // Record Displayed Tokens To Log
  638. // Note: Generated tokens are created one by one hence this check
  639. if (embd.size() > 1) {
  640. // Incoming Requested Tokens
  641. input_tokens.push_back(id);
  642. } else {
  643. // Outgoing Generated Tokens
  644. output_tokens.push_back(id);
  645. output_ss << token_str;
  646. }
  647. fflush(stdout);
  648. }
  649. }
  650. // reset color to default if there is no pending user input
  651. if (input_echo && (int) embd_inp.size() == n_consumed) {
  652. console::set_display(console::reset);
  653. display = true;
  654. }
  655. // if not currently processing queued inputs;
  656. if ((int) embd_inp.size() <= n_consumed) {
  657. // check for reverse prompt in the last n_prev tokens
  658. if (!params.antiprompt.empty()) {
  659. const int n_prev = 32;
  660. const std::string last_output = llama_sampling_prev_str(ctx_sampling, ctx, n_prev);
  661. is_antiprompt = false;
  662. // Check if each of the reverse prompts appears at the end of the output.
  663. // If we're not running interactively, the reverse prompt might be tokenized with some following characters
  664. // so we'll compensate for that by widening the search window a bit.
  665. for (std::string & antiprompt : params.antiprompt) {
  666. size_t extra_padding = params.interactive ? 0 : 2;
  667. size_t search_start_pos = last_output.length() > static_cast<size_t>(antiprompt.length() + extra_padding)
  668. ? last_output.length() - static_cast<size_t>(antiprompt.length() + extra_padding)
  669. : 0;
  670. if (last_output.find(antiprompt, search_start_pos) != std::string::npos) {
  671. if (params.interactive) {
  672. is_interacting = true;
  673. }
  674. is_antiprompt = true;
  675. break;
  676. }
  677. }
  678. // check for reverse prompt using special tokens
  679. llama_token last_token = llama_sampling_last(ctx_sampling);
  680. for (std::vector<llama_token> ids : antiprompt_ids) {
  681. if (ids.size() == 1 && last_token == ids[0]) {
  682. if (params.interactive) {
  683. is_interacting = true;
  684. }
  685. is_antiprompt = true;
  686. break;
  687. }
  688. }
  689. if (is_antiprompt) {
  690. LOG("found antiprompt: %s\n", last_output.c_str());
  691. }
  692. }
  693. // deal with end of generation tokens in interactive mode
  694. if (llama_token_is_eog(model, llama_sampling_last(ctx_sampling))) {
  695. LOG("found an EOG token\n");
  696. if (params.interactive) {
  697. if (!params.antiprompt.empty()) {
  698. // tokenize and inject first reverse prompt
  699. const auto first_antiprompt = ::llama_tokenize(ctx, params.antiprompt.front(), false, true);
  700. embd_inp.insert(embd_inp.end(), first_antiprompt.begin(), first_antiprompt.end());
  701. is_antiprompt = true;
  702. }
  703. if (params.enable_chat_template) {
  704. chat_add_and_format(model, chat_msgs, "assistant", assistant_ss.str());
  705. }
  706. is_interacting = true;
  707. printf("\n");
  708. }
  709. }
  710. // if current token is not EOG, we add it to current assistant message
  711. if (params.conversation) {
  712. auto id = llama_sampling_last(ctx_sampling);
  713. assistant_ss << llama_token_to_piece(ctx, id, false);
  714. }
  715. if (n_past > 0 && is_interacting) {
  716. LOG("waiting for user input\n");
  717. if (params.conversation) {
  718. printf("\n> ");
  719. }
  720. if (params.input_prefix_bos) {
  721. LOG("adding input prefix BOS token\n");
  722. embd_inp.push_back(llama_token_bos(model));
  723. }
  724. std::string buffer;
  725. if (!params.input_prefix.empty() && !params.conversation) {
  726. LOG("appending input prefix: '%s'\n", params.input_prefix.c_str());
  727. printf("%s", params.input_prefix.c_str());
  728. }
  729. // color user input only
  730. console::set_display(console::user_input);
  731. display = params.display_prompt;
  732. std::string line;
  733. bool another_line = true;
  734. do {
  735. another_line = console::readline(line, params.multiline_input);
  736. buffer += line;
  737. } while (another_line);
  738. // done taking input, reset color
  739. console::set_display(console::reset);
  740. display = true;
  741. // Add tokens to embd only if the input buffer is non-empty
  742. // Entering a empty line lets the user pass control back
  743. if (buffer.length() > 1) {
  744. // append input suffix if any
  745. if (!params.input_suffix.empty() && !params.conversation) {
  746. LOG("appending input suffix: '%s'\n", params.input_suffix.c_str());
  747. printf("%s", params.input_suffix.c_str());
  748. }
  749. LOG("buffer: '%s'\n", buffer.c_str());
  750. const size_t original_size = embd_inp.size();
  751. if (params.escape) {
  752. string_process_escapes(buffer);
  753. }
  754. bool format_chat = params.conversation && params.enable_chat_template;
  755. std::string user_inp = format_chat
  756. ? chat_add_and_format(model, chat_msgs, "user", std::move(buffer))
  757. : std::move(buffer);
  758. // TODO: one inconvenient of current chat template implementation is that we can't distinguish between user input and special tokens (prefix/postfix)
  759. const auto line_pfx = ::llama_tokenize(ctx, params.input_prefix, false, true);
  760. const auto line_inp = ::llama_tokenize(ctx, user_inp, false, format_chat);
  761. const auto line_sfx = ::llama_tokenize(ctx, params.input_suffix, false, true);
  762. LOG("input tokens: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx, line_inp).c_str());
  763. // if user stop generation mid-way, we must add EOT to finish model's last response
  764. if (need_insert_eot && format_chat) {
  765. llama_token eot = llama_token_eot(model);
  766. embd_inp.push_back(eot == -1 ? llama_token_eos(model) : eot);
  767. need_insert_eot = false;
  768. }
  769. embd_inp.insert(embd_inp.end(), line_pfx.begin(), line_pfx.end());
  770. embd_inp.insert(embd_inp.end(), line_inp.begin(), line_inp.end());
  771. embd_inp.insert(embd_inp.end(), line_sfx.begin(), line_sfx.end());
  772. for (size_t i = original_size; i < embd_inp.size(); ++i) {
  773. const llama_token token = embd_inp[i];
  774. output_tokens.push_back(token);
  775. output_ss << llama_token_to_piece(ctx, token);
  776. }
  777. // reset assistant message
  778. assistant_ss.str("");
  779. n_remain -= line_inp.size();
  780. LOG("n_remain: %d\n", n_remain);
  781. } else {
  782. LOG("empty line, passing control back\n");
  783. }
  784. input_echo = false; // do not echo this again
  785. }
  786. if (n_past > 0) {
  787. if (is_interacting) {
  788. llama_sampling_reset(ctx_sampling);
  789. }
  790. is_interacting = false;
  791. }
  792. }
  793. // end of generation
  794. if (!embd.empty() && llama_token_is_eog(model, embd.back()) && !(params.interactive)) {
  795. LOG_TEE(" [end of text]\n");
  796. break;
  797. }
  798. // In interactive mode, respect the maximum number of tokens and drop back to user input when reached.
  799. // We skip this logic when n_predict == -1 (infinite) or -2 (stop at context size).
  800. if (params.interactive && n_remain <= 0 && params.n_predict >= 0) {
  801. n_remain = params.n_predict;
  802. is_interacting = true;
  803. }
  804. }
  805. if (!path_session.empty() && params.prompt_cache_all && !params.prompt_cache_ro) {
  806. LOG_TEE("\n%s: saving final output to session file '%s'\n", __func__, path_session.c_str());
  807. llama_state_save_file(ctx, path_session.c_str(), session_tokens.data(), session_tokens.size());
  808. }
  809. llama_print_timings(ctx);
  810. write_logfile(ctx, params, model, input_tokens, output_ss.str(), output_tokens);
  811. if (ctx_guidance) { llama_free(ctx_guidance); }
  812. llama_free(ctx);
  813. llama_free_model(model);
  814. llama_sampling_free(ctx_sampling);
  815. llama_backend_free();
  816. #ifndef LOG_DISABLE_LOGS
  817. LOG_TEE("Log end\n");
  818. #endif // LOG_DISABLE_LOGS
  819. return 0;
  820. }