main.cpp 36 KB

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