main.cpp 33 KB

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