main.cpp 38 KB

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