main.cpp 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982
  1. // Defines sigaction on msys:
  2. #ifndef _GNU_SOURCE
  3. #define _GNU_SOURCE
  4. #endif
  5. #include "common.h"
  6. #include "console.h"
  7. #include "llama.h"
  8. #include "build-info.h"
  9. #include "grammar-parser.h"
  10. #include <cassert>
  11. #include <cinttypes>
  12. #include <cmath>
  13. #include <cstdio>
  14. #include <cstring>
  15. #include <ctime>
  16. #include <fstream>
  17. #include <iostream>
  18. #include <sstream>
  19. #include <string>
  20. #include <vector>
  21. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
  22. #include <signal.h>
  23. #include <unistd.h>
  24. #elif defined (_WIN32)
  25. #define WIN32_LEAN_AND_MEAN
  26. #ifndef NOMINMAX
  27. #define NOMINMAX
  28. #endif
  29. #include <windows.h>
  30. #include <signal.h>
  31. #endif
  32. #if defined(_MSC_VER)
  33. #pragma warning(disable: 4244 4267) // possible loss of data
  34. #endif
  35. static llama_context ** g_ctx;
  36. static llama_model ** g_model;
  37. static gpt_params * g_params;
  38. static std::vector<llama_token> * g_input_tokens;
  39. static std::ostringstream * g_output_ss;
  40. static std::vector<llama_token> * g_output_tokens;
  41. static bool is_interacting = false;
  42. void write_logfile(
  43. const llama_context * ctx, const gpt_params & params, const llama_model * model,
  44. const std::vector<llama_token> input_tokens, const std::string output, const std::vector<llama_token> output_tokens) {
  45. if (params.logdir.empty()) {
  46. return;
  47. }
  48. const std::string timestamp = get_sortable_timestamp();
  49. const bool success = create_directory_with_parents(params.logdir);
  50. if (!success) {
  51. fprintf(stderr, "%s: warning: failed to create logdir %s, cannot write logfile\n",
  52. __func__, params.logdir.c_str());
  53. return;
  54. }
  55. const std::string logfile_path = params.logdir + timestamp + ".yml";
  56. FILE * logfile = fopen(logfile_path.c_str(), "w");
  57. if (logfile == NULL) {
  58. fprintf(stderr, "%s: failed to open logfile %s\n", __func__, logfile_path.c_str());
  59. return;
  60. }
  61. fprintf(logfile, "binary: main\n");
  62. char model_desc[128];
  63. llama_model_desc(model, model_desc, sizeof(model_desc));
  64. dump_non_result_info_yaml(logfile, params, ctx, timestamp, input_tokens, model_desc);
  65. fprintf(logfile, "\n");
  66. fprintf(logfile, "######################\n");
  67. fprintf(logfile, "# Generation Results #\n");
  68. fprintf(logfile, "######################\n");
  69. fprintf(logfile, "\n");
  70. dump_string_yaml_multiline(logfile, "output", output.c_str());
  71. dump_vector_int_yaml(logfile, "output_tokens", output_tokens);
  72. llama_dump_timing_info_yaml(logfile, ctx);
  73. fclose(logfile);
  74. }
  75. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__)) || defined (_WIN32)
  76. void sigint_handler(int signo) {
  77. if (signo == SIGINT) {
  78. if (!is_interacting) {
  79. is_interacting = true;
  80. } else {
  81. console::cleanup();
  82. printf("\n");
  83. llama_print_timings(*g_ctx);
  84. write_logfile(*g_ctx, *g_params, *g_model, *g_input_tokens, g_output_ss->str(), *g_output_tokens);
  85. _exit(130);
  86. }
  87. }
  88. }
  89. #endif
  90. int main(int argc, char ** argv) {
  91. gpt_params params;
  92. g_params = &params;
  93. if (gpt_params_parse(argc, argv, params) == false) {
  94. return 1;
  95. }
  96. #ifndef LOG_DISABLE_LOGS
  97. log_set_target(log_filename_generator("main", "log"));
  98. LOG_TEE("Log start\n");
  99. log_dump_cmdline(argc,argv);
  100. #endif // LOG_DISABLE_LOGS
  101. // TODO: Dump params ?
  102. //LOG("Params perplexity: %s\n", LOG_TOSTR(params.perplexity));
  103. // save choice to use color for later
  104. // (note for later: this is a slightly awkward choice)
  105. console::init(params.simple_io, params.use_color);
  106. atexit([]() { console::cleanup(); });
  107. if (params.perplexity) {
  108. printf("\n************\n");
  109. printf("%s: please use the 'perplexity' tool for perplexity calculations\n", __func__);
  110. printf("************\n\n");
  111. return 0;
  112. }
  113. if (params.embedding) {
  114. printf("\n************\n");
  115. printf("%s: please use the 'embedding' tool for embedding calculations\n", __func__);
  116. printf("************\n\n");
  117. return 0;
  118. }
  119. if (params.rope_freq_base != 10000.0) {
  120. LOG_TEE("%s: warning: changing RoPE frequency base to %g (default 10000.0)\n", __func__, params.rope_freq_base);
  121. }
  122. if (params.rope_freq_scale != 1.0) {
  123. LOG_TEE("%s: warning: scaling RoPE frequency by %g (default 1.0)\n", __func__, params.rope_freq_scale);
  124. }
  125. if (params.n_ctx > 2048) {
  126. // TODO: determine the actual max context of the model (e.g. 4096 for LLaMA v2) and use that instead of 2048
  127. LOG_TEE("%s: warning: base model only supports context sizes no greater than 2048 tokens (%d specified)\n", __func__, params.n_ctx);
  128. } else if (params.n_ctx < 8) {
  129. LOG_TEE("%s: warning: minimum context size is 8, using minimum size.\n", __func__);
  130. params.n_ctx = 8;
  131. }
  132. LOG_TEE("%s: build = %d (%s)\n", __func__, BUILD_NUMBER, BUILD_COMMIT);
  133. if (params.seed == LLAMA_DEFAULT_SEED) {
  134. params.seed = time(NULL);
  135. }
  136. LOG_TEE("%s: seed = %u\n", __func__, params.seed);
  137. std::mt19937 rng(params.seed);
  138. if (params.random_prompt) {
  139. params.prompt = gpt_random_prompt(rng);
  140. }
  141. LOG("%s: llama backend init\n", __func__);
  142. llama_backend_init(params.numa);
  143. llama_model * model;
  144. llama_context * ctx;
  145. llama_context * ctx_guidance = NULL;
  146. g_model = &model;
  147. g_ctx = &ctx;
  148. // load the model and apply lora adapter, if any
  149. LOG("%s: load the model and apply lora adapter, if any\n", __func__);
  150. std::tie(model, ctx) = llama_init_from_gpt_params(params);
  151. if (params.cfg_scale > 1.f) {
  152. struct llama_context_params lparams = llama_context_params_from_gpt_params(params);
  153. ctx_guidance = llama_new_context_with_model(model, lparams);
  154. }
  155. if (model == NULL) {
  156. LOG_TEE("%s: error: unable to load model\n", __func__);
  157. return 1;
  158. }
  159. // print system information
  160. {
  161. LOG_TEE("\n");
  162. LOG_TEE("system_info: n_threads = %d / %d | %s\n",
  163. params.n_threads, std::thread::hardware_concurrency(), llama_print_system_info());
  164. }
  165. // determine the maximum memory usage needed to do inference for the given n_batch and n_ctx parameters
  166. // uncomment the "used_mem" line in llama.cpp to see the results
  167. if (params.mem_test) {
  168. {
  169. LOG_TEE("%s: testing memory usage for n_batch = %d, n_ctx = %d\n", __func__, params.n_batch, params.n_ctx);
  170. const std::vector<llama_token> tmp(params.n_batch, llama_token_bos(ctx));
  171. llama_eval(ctx, tmp.data(), tmp.size(), params.n_ctx, params.n_threads);
  172. }
  173. llama_print_timings(ctx);
  174. llama_free(ctx);
  175. llama_free_model(model);
  176. return 0;
  177. }
  178. // export the cgraph and exit
  179. if (params.export_cgraph) {
  180. llama_eval_export(ctx, "llama.ggml");
  181. llama_free(ctx);
  182. llama_free_model(model);
  183. return 0;
  184. }
  185. std::string path_session = params.path_prompt_cache;
  186. std::vector<llama_token> session_tokens;
  187. if (!path_session.empty()) {
  188. LOG_TEE("%s: attempting to load saved session from '%s'\n", __func__, path_session.c_str());
  189. // fopen to check for existing session
  190. FILE * fp = std::fopen(path_session.c_str(), "rb");
  191. if (fp != NULL) {
  192. std::fclose(fp);
  193. session_tokens.resize(params.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. } else {
  203. LOG_TEE("%s: session file does not exist, will create\n", __func__);
  204. }
  205. }
  206. const bool add_bos = llama_vocab_type(ctx) == LLAMA_VOCAB_TYPE_SPM;
  207. LOG("add_bos: %d\n", add_bos);
  208. std::vector<llama_token> embd_inp;
  209. if (params.interactive_first || params.instruct || !params.prompt.empty() || session_tokens.empty()) {
  210. LOG("tokenize the prompt\n");
  211. embd_inp = ::llama_tokenize(ctx, params.prompt, add_bos);
  212. } else {
  213. LOG("use session tokens\n");
  214. embd_inp = session_tokens;
  215. }
  216. LOG("prompt: \"%s\"\n", log_tostr(params.prompt));
  217. LOG("tokens: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx, embd_inp));
  218. // Should not run without any tokens
  219. if (embd_inp.empty()) {
  220. embd_inp.push_back(llama_token_bos(ctx));
  221. LOG("embd_inp was considered empty and bos was added: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx, embd_inp));
  222. }
  223. // Tokenize negative prompt
  224. std::vector<llama_token> guidance_inp;
  225. int guidance_offset = 0;
  226. int original_prompt_len = 0;
  227. if (ctx_guidance) {
  228. LOG("cfg_negative_prompt: \"%s\"\n", log_tostr(params.cfg_negative_prompt));
  229. guidance_inp = ::llama_tokenize(ctx_guidance, params.cfg_negative_prompt, add_bos);
  230. LOG("guidance_inp tokenized: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx_guidance, guidance_inp));
  231. std::vector<llama_token> original_inp = ::llama_tokenize(ctx, params.prompt, add_bos);
  232. LOG("original_inp tokenized: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx, original_inp));
  233. original_prompt_len = original_inp.size();
  234. guidance_offset = (int)guidance_inp.size() - original_prompt_len;
  235. LOG("original_prompt_len: %s", log_tostr(original_prompt_len));
  236. LOG("guidance_offset: %s", log_tostr(guidance_offset));
  237. }
  238. const int n_ctx = llama_n_ctx(ctx);
  239. LOG("n_ctx: %d\n", n_ctx);
  240. if ((int) embd_inp.size() > n_ctx - 4) {
  241. LOG_TEE("%s: error: prompt is too long (%d tokens, max %d)\n", __func__, (int) embd_inp.size(), n_ctx - 4);
  242. return 1;
  243. }
  244. // debug message about similarity of saved session, if applicable
  245. size_t n_matching_session_tokens = 0;
  246. if (session_tokens.size() > 0) {
  247. for (llama_token id : session_tokens) {
  248. if (n_matching_session_tokens >= embd_inp.size() || id != embd_inp[n_matching_session_tokens]) {
  249. break;
  250. }
  251. n_matching_session_tokens++;
  252. }
  253. if (params.prompt.empty() && n_matching_session_tokens == embd_inp.size()) {
  254. LOG_TEE("%s: using full prompt from session file\n", __func__);
  255. } else if (n_matching_session_tokens >= embd_inp.size()) {
  256. LOG_TEE("%s: session file has exact match for prompt!\n", __func__);
  257. } else if (n_matching_session_tokens < (embd_inp.size() / 2)) {
  258. LOG_TEE("%s: warning: session file has low similarity to prompt (%zu / %zu tokens); will mostly be reevaluated\n",
  259. __func__, n_matching_session_tokens, embd_inp.size());
  260. } else {
  261. LOG_TEE("%s: session file matches %zu / %zu tokens of prompt\n",
  262. __func__, n_matching_session_tokens, embd_inp.size());
  263. }
  264. }
  265. LOGLN(
  266. "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",
  267. log_tostr(embd_inp.empty()), n_matching_session_tokens, embd_inp.size(), session_tokens.size(), embd_inp.size());
  268. // if we will use the cache for the full prompt without reaching the end of the cache, force
  269. // reevaluation of the last token token to recalculate the cached logits
  270. if (!embd_inp.empty() && n_matching_session_tokens == embd_inp.size() && session_tokens.size() > embd_inp.size()) {
  271. LOGLN("recalculate the cached logits (do): session_tokens.resize( %zu )", embd_inp.size() - 1);
  272. session_tokens.resize(embd_inp.size() - 1);
  273. }
  274. // number of tokens to keep when resetting context
  275. if (params.n_keep < 0 || params.n_keep > (int) embd_inp.size() || params.instruct) {
  276. params.n_keep = (int)embd_inp.size();
  277. }
  278. // prefix & suffix for instruct mode
  279. const auto inp_pfx = ::llama_tokenize(ctx, "\n\n### Instruction:\n\n", add_bos);
  280. const auto inp_sfx = ::llama_tokenize(ctx, "\n\n### Response:\n\n", false);
  281. LOG("inp_pfx: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx, inp_pfx));
  282. LOG("inp_sfx: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx, inp_sfx));
  283. // in instruct mode, we inject a prefix and a suffix to each input by the user
  284. if (params.instruct) {
  285. params.interactive_first = true;
  286. params.antiprompt.push_back("### Instruction:\n\n");
  287. }
  288. // enable interactive mode if interactive start is specified
  289. if (params.interactive_first) {
  290. params.interactive = true;
  291. }
  292. if (params.verbose_prompt) {
  293. LOG_TEE("\n");
  294. LOG_TEE("%s: prompt: '%s'\n", __func__, params.prompt.c_str());
  295. LOG_TEE("%s: number of tokens in prompt = %zu\n", __func__, embd_inp.size());
  296. for (int i = 0; i < (int) embd_inp.size(); i++) {
  297. LOG_TEE("%6d -> '%s'\n", embd_inp[i], llama_token_to_piece(ctx, embd_inp[i]).c_str());
  298. }
  299. if (ctx_guidance) {
  300. LOG_TEE("\n");
  301. LOG_TEE("%s: negative prompt: '%s'\n", __func__, params.cfg_negative_prompt.c_str());
  302. LOG_TEE("%s: number of tokens in negative prompt = %zu\n", __func__, guidance_inp.size());
  303. for (int i = 0; i < (int) guidance_inp.size(); i++) {
  304. LOG_TEE("%6d -> '%s'\n", guidance_inp[i], llama_token_to_piece(ctx, guidance_inp[i]).c_str());
  305. }
  306. }
  307. if (params.n_keep > 0) {
  308. LOG_TEE("%s: static prompt based on n_keep: '", __func__);
  309. for (int i = 0; i < params.n_keep; i++) {
  310. LOG_TEE("%s", llama_token_to_piece(ctx, embd_inp[i]).c_str());
  311. }
  312. LOG_TEE("'\n");
  313. }
  314. LOG_TEE("\n");
  315. }
  316. if (params.interactive) {
  317. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
  318. struct sigaction sigint_action;
  319. sigint_action.sa_handler = sigint_handler;
  320. sigemptyset (&sigint_action.sa_mask);
  321. sigint_action.sa_flags = 0;
  322. sigaction(SIGINT, &sigint_action, NULL);
  323. #elif defined (_WIN32)
  324. auto console_ctrl_handler = +[](DWORD ctrl_type) -> BOOL {
  325. return (ctrl_type == CTRL_C_EVENT) ? (sigint_handler(SIGINT), true) : false;
  326. };
  327. SetConsoleCtrlHandler(reinterpret_cast<PHANDLER_ROUTINE>(console_ctrl_handler), true);
  328. #endif
  329. LOG_TEE("%s: interactive mode on.\n", __func__);
  330. if (params.antiprompt.size()) {
  331. for (const auto & antiprompt : params.antiprompt) {
  332. LOG_TEE("Reverse prompt: '%s'\n", antiprompt.c_str());
  333. }
  334. }
  335. if (params.input_prefix_bos) {
  336. LOG_TEE("Input prefix with BOS\n");
  337. }
  338. if (!params.input_prefix.empty()) {
  339. LOG_TEE("Input prefix: '%s'\n", params.input_prefix.c_str());
  340. }
  341. if (!params.input_suffix.empty()) {
  342. LOG_TEE("Input suffix: '%s'\n", params.input_suffix.c_str());
  343. }
  344. }
  345. LOG_TEE("sampling: repeat_last_n = %d, repeat_penalty = %f, presence_penalty = %f, frequency_penalty = %f, top_k = %d, tfs_z = %f, top_p = %f, typical_p = %f, temp = %f, mirostat = %d, mirostat_lr = %f, mirostat_ent = %f\n",
  346. params.repeat_last_n, params.repeat_penalty, params.presence_penalty, params.frequency_penalty, params.top_k, params.tfs_z, params.top_p, params.typical_p, params.temp, params.mirostat, params.mirostat_eta, params.mirostat_tau);
  347. 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);
  348. LOG_TEE("\n\n");
  349. grammar_parser::parse_state parsed_grammar;
  350. llama_grammar * grammar = NULL;
  351. if (!params.grammar.empty()) {
  352. parsed_grammar = grammar_parser::parse(params.grammar.c_str());
  353. // will be empty (default) if there are parse errors
  354. if (parsed_grammar.rules.empty()) {
  355. return 1;
  356. }
  357. LOG_TEE("%s: grammar:\n", __func__);
  358. grammar_parser::print_grammar(stderr, parsed_grammar);
  359. LOG_TEE("\n");
  360. {
  361. auto it = params.logit_bias.find(llama_token_eos(ctx));
  362. if (it != params.logit_bias.end() && it->second == -INFINITY) {
  363. LOG_TEE("%s: warning: EOS token is disabled, which will cause most grammars to fail\n", __func__);
  364. }
  365. }
  366. std::vector<const llama_grammar_element *> grammar_rules(parsed_grammar.c_rules());
  367. grammar = llama_grammar_init(
  368. grammar_rules.data(), grammar_rules.size(), parsed_grammar.symbol_ids.at("root"));
  369. }
  370. // TODO: replace with ring-buffer
  371. std::vector<llama_token> last_n_tokens(n_ctx);
  372. std::fill(last_n_tokens.begin(), last_n_tokens.end(), 0);
  373. if (params.interactive) {
  374. const char *control_message;
  375. if (params.multiline_input) {
  376. control_message = " - To return control to LLaMa, end your input with '\\'.\n"
  377. " - To return control without starting a new line, end your input with '/'.\n";
  378. } else {
  379. control_message = " - Press Return to return control to LLaMa.\n"
  380. " - To return control without starting a new line, end your input with '/'.\n"
  381. " - If you want to submit another line, end your input with '\\'.\n";
  382. }
  383. LOG_TEE("== Running in interactive mode. ==\n");
  384. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__)) || defined (_WIN32)
  385. LOG_TEE( " - Press Ctrl+C to interject at any time.\n");
  386. #endif
  387. LOG_TEE( "%s\n", control_message);
  388. is_interacting = params.interactive_first;
  389. }
  390. bool is_antiprompt = false;
  391. bool input_echo = true;
  392. bool need_to_save_session = !path_session.empty() && n_matching_session_tokens < embd_inp.size();
  393. int n_past = 0;
  394. int n_remain = params.n_predict;
  395. int n_consumed = 0;
  396. int n_session_consumed = 0;
  397. int n_past_guidance = 0;
  398. std::vector<int> input_tokens; g_input_tokens = &input_tokens;
  399. std::vector<int> output_tokens; g_output_tokens = &output_tokens;
  400. std::ostringstream output_ss; g_output_ss = &output_ss;
  401. // the first thing we will do is to output the prompt, so set color accordingly
  402. console::set_display(console::prompt);
  403. std::vector<llama_token> embd;
  404. std::vector<llama_token> embd_guidance;
  405. {
  406. LOG("warming up the model with an empty run\n");
  407. const std::vector<llama_token> tmp = { llama_token_bos(ctx), };
  408. llama_eval(ctx, tmp.data(), tmp.size(), 0, params.n_threads);
  409. llama_reset_timings(ctx);
  410. }
  411. while ((n_remain != 0 && !is_antiprompt) || params.interactive) {
  412. // predict
  413. if (embd.size() > 0) {
  414. // Note: n_ctx - 4 here is to match the logic for commandline prompt handling via
  415. // --prompt or --file which uses the same value.
  416. int max_embd_size = n_ctx - 4;
  417. // Ensure the input doesn't exceed the context size by truncating embd if necessary.
  418. if ((int) embd.size() > max_embd_size) {
  419. const int skipped_tokens = (int) embd.size() - max_embd_size;
  420. embd.resize(max_embd_size);
  421. console::set_display(console::error);
  422. printf("<<input too long: skipped %d token%s>>", skipped_tokens, skipped_tokens != 1 ? "s" : "");
  423. console::set_display(console::reset);
  424. fflush(stdout);
  425. }
  426. // infinite text generation via context swapping
  427. // if we run out of context:
  428. // - take the n_keep first tokens from the original prompt (via n_past)
  429. // - take half of the last (n_ctx - n_keep) tokens and recompute the logits in batches
  430. if (n_past + (int) embd.size() + std::max<int>(0, guidance_offset) > n_ctx) {
  431. if (params.n_predict == -2) {
  432. LOG_TEE("\n\n%s: context full and n_predict == -%d => stopping\n", __func__, params.n_predict);
  433. break;
  434. }
  435. const int n_left = n_past - params.n_keep;
  436. LOG("context full, swapping: n_past = %d, n_left = %d, n_ctx = %d, n_keep = %d\n", n_past, n_left, n_ctx, params.n_keep);
  437. // always keep the first token - BOS
  438. n_past = std::max(1, params.n_keep);
  439. n_past_guidance = std::max(1, params.n_keep + guidance_offset);
  440. LOG("after swap: n_past = %d, n_past_guidance = %d\n", n_past, n_past_guidance);
  441. // insert n_left/2 tokens at the start of embd from last_n_tokens
  442. embd.insert(embd.begin(), last_n_tokens.begin() + n_ctx - n_left/2 - embd.size(), last_n_tokens.end() - embd.size());
  443. LOG("embd: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx, embd));
  444. LOG("clear session path\n");
  445. path_session.clear();
  446. }
  447. // try to reuse a matching prefix from the loaded session instead of re-eval (via n_past)
  448. if (n_session_consumed < (int) session_tokens.size()) {
  449. size_t i = 0;
  450. for ( ; i < embd.size(); i++) {
  451. if (embd[i] != session_tokens[n_session_consumed]) {
  452. session_tokens.resize(n_session_consumed);
  453. break;
  454. }
  455. n_past++;
  456. n_session_consumed++;
  457. if (n_session_consumed >= (int) session_tokens.size()) {
  458. ++i;
  459. break;
  460. }
  461. }
  462. if (i > 0) {
  463. embd.erase(embd.begin(), embd.begin() + i);
  464. }
  465. }
  466. // evaluate tokens in batches
  467. // embd is typically prepared beforehand to fit within a batch, but not always
  468. if (ctx_guidance) {
  469. int input_size = 0;
  470. llama_token * input_buf = NULL;
  471. if (n_past_guidance < (int) guidance_inp.size()) {
  472. // Guidance context should have the same data with these modifications:
  473. //
  474. // * Replace the initial prompt
  475. // * Shift everything by guidance_offset
  476. embd_guidance = guidance_inp;
  477. if (embd.begin() + original_prompt_len < embd.end()) {
  478. embd_guidance.insert(
  479. embd_guidance.end(),
  480. embd.begin() + original_prompt_len,
  481. embd.end()
  482. );
  483. }
  484. input_buf = embd_guidance.data();
  485. input_size = embd_guidance.size();
  486. LOG("guidance context: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx, embd_guidance));
  487. } else {
  488. input_buf = embd.data();
  489. input_size = embd.size();
  490. }
  491. for (int i = 0; i < input_size; i += params.n_batch) {
  492. int n_eval = std::min(input_size - i, params.n_batch);
  493. if (llama_eval(ctx_guidance, input_buf + i, n_eval, n_past_guidance, params.n_threads)) {
  494. LOG_TEE("%s : failed to eval\n", __func__);
  495. return 1;
  496. }
  497. n_past_guidance += n_eval;
  498. }
  499. }
  500. for (int i = 0; i < (int) embd.size(); i += params.n_batch) {
  501. int n_eval = (int) embd.size() - i;
  502. if (n_eval > params.n_batch) {
  503. n_eval = params.n_batch;
  504. }
  505. LOG("eval: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx, embd));
  506. if (llama_eval(ctx, &embd[i], n_eval, n_past, params.n_threads)) {
  507. LOG_TEE("%s : failed to eval\n", __func__);
  508. return 1;
  509. }
  510. n_past += n_eval;
  511. LOG("n_past = %d\n", n_past);
  512. }
  513. if (embd.size() > 0 && !path_session.empty()) {
  514. session_tokens.insert(session_tokens.end(), embd.begin(), embd.end());
  515. n_session_consumed = session_tokens.size();
  516. }
  517. }
  518. embd.clear();
  519. embd_guidance.clear();
  520. if ((int) embd_inp.size() <= n_consumed && !is_interacting) {
  521. const float temp = params.temp;
  522. const int32_t top_k = params.top_k <= 0 ? llama_n_vocab(ctx) : params.top_k;
  523. const float top_p = params.top_p;
  524. const float tfs_z = params.tfs_z;
  525. const float typical_p = params.typical_p;
  526. const int32_t repeat_last_n = params.repeat_last_n < 0 ? n_ctx : params.repeat_last_n;
  527. const float repeat_penalty = params.repeat_penalty;
  528. const float alpha_presence = params.presence_penalty;
  529. const float alpha_frequency = params.frequency_penalty;
  530. const int mirostat = params.mirostat;
  531. const float mirostat_tau = params.mirostat_tau;
  532. const float mirostat_eta = params.mirostat_eta;
  533. const bool penalize_nl = params.penalize_nl;
  534. // optionally save the session on first sample (for faster prompt loading next time)
  535. if (!path_session.empty() && need_to_save_session && !params.prompt_cache_ro) {
  536. need_to_save_session = false;
  537. llama_save_session_file(ctx, path_session.c_str(), session_tokens.data(), session_tokens.size());
  538. LOG("saved session to %s\n", path_session.c_str());
  539. }
  540. llama_token id = 0;
  541. {
  542. auto logits = llama_get_logits(ctx);
  543. auto n_vocab = llama_n_vocab(ctx);
  544. // Apply params.logit_bias map
  545. for (auto it = params.logit_bias.begin(); it != params.logit_bias.end(); it++) {
  546. logits[it->first] += it->second;
  547. }
  548. std::vector<llama_token_data> candidates;
  549. candidates.reserve(n_vocab);
  550. for (llama_token token_id = 0; token_id < n_vocab; token_id++) {
  551. candidates.emplace_back(llama_token_data{token_id, logits[token_id], 0.0f});
  552. }
  553. llama_token_data_array cur_p = { candidates.data(), candidates.size(), false };
  554. if (ctx_guidance) {
  555. llama_sample_classifier_free_guidance(ctx, &cur_p, ctx_guidance, params.cfg_scale);
  556. }
  557. // Apply penalties
  558. float nl_logit = logits[llama_token_nl(ctx)];
  559. auto last_n_repeat = std::min(std::min((int)last_n_tokens.size(), repeat_last_n), n_ctx);
  560. llama_sample_repetition_penalty(ctx, &cur_p,
  561. last_n_tokens.data() + last_n_tokens.size() - last_n_repeat,
  562. last_n_repeat, repeat_penalty);
  563. llama_sample_frequency_and_presence_penalties(ctx, &cur_p,
  564. last_n_tokens.data() + last_n_tokens.size() - last_n_repeat,
  565. last_n_repeat, alpha_frequency, alpha_presence);
  566. if (!penalize_nl) {
  567. for (size_t idx = 0; idx < cur_p.size; idx++) {
  568. if (cur_p.data[idx].id == llama_token_nl(ctx)) {
  569. cur_p.data[idx].logit = nl_logit;
  570. break;
  571. }
  572. }
  573. }
  574. if (grammar != NULL) {
  575. llama_sample_grammar(ctx, &cur_p, grammar);
  576. }
  577. if (temp <= 0) {
  578. // Greedy sampling
  579. id = llama_sample_token_greedy(ctx, &cur_p);
  580. } else {
  581. if (mirostat == 1) {
  582. static float mirostat_mu = 2.0f * mirostat_tau;
  583. const int mirostat_m = 100;
  584. llama_sample_temperature(ctx, &cur_p, temp);
  585. id = llama_sample_token_mirostat(ctx, &cur_p, mirostat_tau, mirostat_eta, mirostat_m, &mirostat_mu);
  586. } else if (mirostat == 2) {
  587. static float mirostat_mu = 2.0f * mirostat_tau;
  588. llama_sample_temperature(ctx, &cur_p, temp);
  589. id = llama_sample_token_mirostat_v2(ctx, &cur_p, mirostat_tau, mirostat_eta, &mirostat_mu);
  590. } else {
  591. // Temperature sampling
  592. llama_sample_top_k (ctx, &cur_p, top_k, 1);
  593. llama_sample_tail_free (ctx, &cur_p, tfs_z, 1);
  594. llama_sample_typical (ctx, &cur_p, typical_p, 1);
  595. llama_sample_top_p (ctx, &cur_p, top_p, 1);
  596. llama_sample_temperature(ctx, &cur_p, temp);
  597. {
  598. const int n_top = 10;
  599. LOG("top %d candidates:\n", n_top);
  600. for (int i = 0; i < n_top; i++) {
  601. const llama_token id = cur_p.data[i].id;
  602. LOG(" - %5d: '%12s' (%.3f)\n", id, llama_token_to_piece(ctx, id).c_str(), cur_p.data[i].p);
  603. }
  604. }
  605. id = llama_sample_token(ctx, &cur_p);
  606. LOG("sampled token: %5d: '%s'\n", id, llama_token_to_piece(ctx, id).c_str());
  607. }
  608. }
  609. // printf("`%d`", candidates_p.size);
  610. if (grammar != NULL) {
  611. llama_grammar_accept_token(ctx, grammar, id);
  612. }
  613. last_n_tokens.erase(last_n_tokens.begin());
  614. last_n_tokens.push_back(id);
  615. LOG("last: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx, last_n_tokens));
  616. }
  617. embd.push_back(id);
  618. // echo this to console
  619. input_echo = true;
  620. // decrement remaining sampling budget
  621. --n_remain;
  622. LOG("n_remain: %d\n", n_remain);
  623. } else {
  624. // some user input remains from prompt or interaction, forward it to processing
  625. LOG("embd_inp.size(): %d, n_consumed: %d\n", (int) embd_inp.size(), n_consumed);
  626. while ((int) embd_inp.size() > n_consumed) {
  627. embd.push_back(embd_inp[n_consumed]);
  628. last_n_tokens.erase(last_n_tokens.begin());
  629. last_n_tokens.push_back(embd_inp[n_consumed]);
  630. ++n_consumed;
  631. if ((int) embd.size() >= params.n_batch) {
  632. break;
  633. }
  634. }
  635. }
  636. // display text
  637. if (input_echo) {
  638. for (auto id : embd) {
  639. const std::string token_str = llama_token_to_piece(ctx, id);
  640. printf("%s", token_str.c_str());
  641. if (embd.size() > 1) {
  642. input_tokens.push_back(id);
  643. } else {
  644. output_tokens.push_back(id);
  645. output_ss << token_str;
  646. }
  647. }
  648. fflush(stdout);
  649. }
  650. // reset color to default if we there is no pending user input
  651. if (input_echo && (int) embd_inp.size() == n_consumed) {
  652. console::set_display(console::reset);
  653. }
  654. // if not currently processing queued inputs;
  655. if ((int) embd_inp.size() <= n_consumed) {
  656. // check for reverse prompt
  657. if (params.antiprompt.size()) {
  658. std::string last_output;
  659. for (auto id : last_n_tokens) {
  660. last_output += llama_token_to_piece(ctx, id);
  661. }
  662. is_antiprompt = false;
  663. // Check if each of the reverse prompts appears at the end of the output.
  664. // If we're not running interactively, the reverse prompt might be tokenized with some following characters
  665. // so we'll compensate for that by widening the search window a bit.
  666. for (std::string & antiprompt : params.antiprompt) {
  667. size_t extra_padding = params.interactive ? 0 : 2;
  668. size_t search_start_pos = last_output.length() > static_cast<size_t>(antiprompt.length() + extra_padding)
  669. ? last_output.length() - static_cast<size_t>(antiprompt.length() + extra_padding)
  670. : 0;
  671. if (last_output.find(antiprompt, search_start_pos) != std::string::npos) {
  672. if (params.interactive) {
  673. is_interacting = true;
  674. console::set_display(console::user_input);
  675. }
  676. is_antiprompt = true;
  677. fflush(stdout);
  678. break;
  679. }
  680. }
  681. if (is_antiprompt) {
  682. LOG("found antiprompt: %s\n", last_output.c_str());
  683. }
  684. }
  685. // deal with end of text token in interactive mode
  686. if (last_n_tokens.back() == llama_token_eos(ctx)) {
  687. LOG("found EOS token\n");
  688. if (params.interactive) {
  689. if (params.antiprompt.size() != 0) {
  690. // tokenize and inject first reverse prompt
  691. const auto first_antiprompt = ::llama_tokenize(ctx, params.antiprompt.front(), false);
  692. embd_inp.insert(embd_inp.end(), first_antiprompt.begin(), first_antiprompt.end());
  693. is_antiprompt = true;
  694. }
  695. is_interacting = true;
  696. printf("\n");
  697. console::set_display(console::user_input);
  698. fflush(stdout);
  699. } else if (params.instruct) {
  700. is_interacting = true;
  701. }
  702. }
  703. if (n_past > 0 && is_interacting) {
  704. LOG("waiting for user input\n");
  705. if (params.instruct) {
  706. printf("\n> ");
  707. }
  708. if (params.input_prefix_bos) {
  709. LOG("adding input prefix BOS token\n");
  710. embd_inp.push_back(llama_token_bos(ctx));
  711. }
  712. std::string buffer;
  713. if (!params.input_prefix.empty()) {
  714. LOG("appending input prefix: '%s'\n", params.input_prefix.c_str());
  715. buffer += params.input_prefix;
  716. printf("%s", buffer.c_str());
  717. }
  718. std::string line;
  719. bool another_line = true;
  720. do {
  721. another_line = console::readline(line, params.multiline_input);
  722. buffer += line;
  723. } while (another_line);
  724. // done taking input, reset color
  725. console::set_display(console::reset);
  726. // Add tokens to embd only if the input buffer is non-empty
  727. // Entering a empty line lets the user pass control back
  728. if (buffer.length() > 1) {
  729. // append input suffix if any
  730. if (!params.input_suffix.empty()) {
  731. LOG("appending input suffix: '%s'\n", params.input_suffix.c_str());
  732. buffer += params.input_suffix;
  733. printf("%s", params.input_suffix.c_str());
  734. }
  735. LOG("buffer: '%s'\n", buffer.c_str());
  736. const size_t original_size = embd_inp.size();
  737. // instruct mode: insert instruction prefix
  738. if (params.instruct && !is_antiprompt) {
  739. LOG("inserting instruction prefix\n");
  740. n_consumed = embd_inp.size();
  741. embd_inp.insert(embd_inp.end(), inp_pfx.begin(), inp_pfx.end());
  742. }
  743. const auto line_inp = ::llama_tokenize(ctx, buffer, false);
  744. LOG("input tokens: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx, line_inp));
  745. embd_inp.insert(embd_inp.end(), line_inp.begin(), line_inp.end());
  746. // instruct mode: insert response suffix
  747. if (params.instruct) {
  748. LOG("inserting instruction suffix\n");
  749. embd_inp.insert(embd_inp.end(), inp_sfx.begin(), inp_sfx.end());
  750. }
  751. for (size_t i = original_size; i < embd_inp.size(); ++i) {
  752. const llama_token token = embd_inp[i];
  753. output_tokens.push_back(token);
  754. output_ss << llama_token_to_piece(ctx, token);
  755. }
  756. n_remain -= line_inp.size();
  757. LOG("n_remain: %d\n", n_remain);
  758. } else {
  759. LOG("empty line, passing control back\n");
  760. }
  761. input_echo = false; // do not echo this again
  762. }
  763. if (n_past > 0) {
  764. if (is_interacting) {
  765. // reset grammar state if we're restarting generation
  766. if (grammar != NULL) {
  767. llama_grammar_free(grammar);
  768. std::vector<const llama_grammar_element *> grammar_rules( parsed_grammar.c_rules());
  769. grammar = llama_grammar_init(
  770. grammar_rules.data(), grammar_rules.size(),
  771. parsed_grammar.symbol_ids.at("root"));
  772. }
  773. }
  774. is_interacting = false;
  775. }
  776. }
  777. // end of text token
  778. if (!embd.empty() && embd.back() == llama_token_eos(ctx) && !(params.instruct || params.interactive)) {
  779. LOG_TEE(" [end of text]\n");
  780. break;
  781. }
  782. // In interactive mode, respect the maximum number of tokens and drop back to user input when reached.
  783. // We skip this logic when n_predict == -1 (infinite) or -2 (stop at context size).
  784. if (params.interactive && n_remain <= 0 && params.n_predict >= 0) {
  785. n_remain = params.n_predict;
  786. is_interacting = true;
  787. }
  788. }
  789. if (!path_session.empty() && params.prompt_cache_all && !params.prompt_cache_ro) {
  790. LOG_TEE("\n%s: saving final output to session file '%s'\n", __func__, path_session.c_str());
  791. llama_save_session_file(ctx, path_session.c_str(), session_tokens.data(), session_tokens.size());
  792. }
  793. llama_print_timings(ctx);
  794. write_logfile(ctx, params, model, input_tokens, output_ss.str(), output_tokens);
  795. if (ctx_guidance) { llama_free(ctx_guidance); }
  796. llama_free(ctx);
  797. llama_free_model(model);
  798. if (grammar != NULL) {
  799. llama_grammar_free(grammar);
  800. }
  801. llama_backend_free();
  802. #ifndef LOG_DISABLE_LOGS
  803. LOG_TEE("Log end\n")
  804. #endif // LOG_DISABLE_LOGS
  805. return 0;
  806. }