main.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811
  1. // Defines sigaction on msys:
  2. #ifndef _GNU_SOURCE
  3. #define _GNU_SOURCE
  4. #endif
  5. #include "common.h"
  6. #include "llama.h"
  7. #include "build-info.h"
  8. #include "grammar-parser.h"
  9. #include <cassert>
  10. #include <cinttypes>
  11. #include <cmath>
  12. #include <cstdio>
  13. #include <cstring>
  14. #include <ctime>
  15. #include <fstream>
  16. #include <iostream>
  17. #include <string>
  18. #include <vector>
  19. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
  20. #include <signal.h>
  21. #include <unistd.h>
  22. #elif defined (_WIN32)
  23. #define WIN32_LEAN_AND_MEAN
  24. #ifndef NOMINMAX
  25. #define NOMINMAX
  26. #endif
  27. #include <windows.h>
  28. #include <signal.h>
  29. #endif
  30. #if defined(_MSC_VER)
  31. #pragma warning(disable: 4244 4267) // possible loss of data
  32. #endif
  33. static console_state con_st;
  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(con_st);
  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. con_st.use_color = params.use_color;
  58. con_st.multiline_input = params.multiline_input;
  59. console_init(con_st);
  60. atexit([]() { console_cleanup(con_st); });
  61. if (params.perplexity) {
  62. printf("\n************\n");
  63. printf("%s: please use the 'perplexity' tool for perplexity calculations\n", __func__);
  64. printf("************\n\n");
  65. return 0;
  66. }
  67. if (params.embedding) {
  68. printf("\n************\n");
  69. printf("%s: please use the 'embedding' tool for embedding calculations\n", __func__);
  70. printf("************\n\n");
  71. return 0;
  72. }
  73. if (params.rope_freq_base != 10000.0) {
  74. fprintf(stderr, "%s: warning: changing RoPE frequency base to %g (default 10000.0)\n", __func__, params.rope_freq_base);
  75. }
  76. if (params.rope_freq_scale != 1.0) {
  77. fprintf(stderr, "%s: warning: scaling RoPE frequency by %g (default 1.0)\n", __func__, params.rope_freq_scale);
  78. }
  79. if (params.n_ctx > 2048) {
  80. // TODO: determine the actual max context of the model (e.g. 4096 for LLaMA v2) and use that instead of 2048
  81. fprintf(stderr, "%s: warning: base model only supports context sizes no greater than 2048 tokens (%d specified)\n", __func__, params.n_ctx);
  82. } else if (params.n_ctx < 8) {
  83. fprintf(stderr, "%s: warning: minimum context size is 8, using minimum size.\n", __func__);
  84. params.n_ctx = 8;
  85. }
  86. fprintf(stderr, "%s: build = %d (%s)\n", __func__, BUILD_NUMBER, BUILD_COMMIT);
  87. if (params.seed == LLAMA_DEFAULT_SEED) {
  88. params.seed = time(NULL);
  89. }
  90. fprintf(stderr, "%s: seed = %u\n", __func__, params.seed);
  91. std::mt19937 rng(params.seed);
  92. if (params.random_prompt) {
  93. params.prompt = gpt_random_prompt(rng);
  94. }
  95. llama_backend_init(params.numa);
  96. llama_model * model;
  97. llama_context * ctx;
  98. llama_context * ctx_guidance = NULL;
  99. g_ctx = &ctx;
  100. // load the model and apply lora adapter, if any
  101. std::tie(model, ctx) = llama_init_from_gpt_params(params);
  102. if (params.cfg_scale > 1.f) {
  103. struct llama_context_params lparams = llama_context_params_from_gpt_params(params);
  104. ctx_guidance = llama_new_context_with_model(model, lparams);
  105. }
  106. if (model == NULL) {
  107. fprintf(stderr, "%s: error: unable to load model\n", __func__);
  108. return 1;
  109. }
  110. // print system information
  111. {
  112. fprintf(stderr, "\n");
  113. fprintf(stderr, "system_info: n_threads = %d / %d | %s\n",
  114. params.n_threads, std::thread::hardware_concurrency(), llama_print_system_info());
  115. }
  116. // determine the maximum memory usage needed to do inference for the given n_batch and n_ctx parameters
  117. // uncomment the "used_mem" line in llama.cpp to see the results
  118. if (params.mem_test) {
  119. {
  120. fprintf(stderr, "%s: testing memory usage for n_batch = %d, n_ctx = %d\n", __func__, params.n_batch, params.n_ctx);
  121. const std::vector<llama_token> tmp(params.n_batch, llama_token_bos());
  122. llama_eval(ctx, tmp.data(), tmp.size(), params.n_ctx, params.n_threads);
  123. }
  124. llama_print_timings(ctx);
  125. llama_free(ctx);
  126. llama_free_model(model);
  127. return 0;
  128. }
  129. // export the cgraph and exit
  130. if (params.export_cgraph) {
  131. llama_eval_export(ctx, "llama.ggml");
  132. llama_free(ctx);
  133. llama_free_model(model);
  134. return 0;
  135. }
  136. std::string path_session = params.path_prompt_cache;
  137. std::vector<llama_token> session_tokens;
  138. if (!path_session.empty()) {
  139. fprintf(stderr, "%s: attempting to load saved session from '%s'\n", __func__, path_session.c_str());
  140. // fopen to check for existing session
  141. FILE * fp = std::fopen(path_session.c_str(), "rb");
  142. if (fp != NULL) {
  143. std::fclose(fp);
  144. session_tokens.resize(params.n_ctx);
  145. size_t n_token_count_out = 0;
  146. if (!llama_load_session_file(ctx, path_session.c_str(), session_tokens.data(), session_tokens.capacity(), &n_token_count_out)) {
  147. fprintf(stderr, "%s: error: failed to load session file '%s'\n", __func__, path_session.c_str());
  148. return 1;
  149. }
  150. session_tokens.resize(n_token_count_out);
  151. llama_set_rng_seed(ctx, params.seed);
  152. fprintf(stderr, "%s: loaded a session with prompt size of %d tokens\n", __func__, (int) session_tokens.size());
  153. } else {
  154. fprintf(stderr, "%s: session file does not exist, will create\n", __func__);
  155. }
  156. }
  157. // tokenize the prompt
  158. std::vector<llama_token> embd_inp;
  159. // Add a space in front of the first character to match OG llama tokenizer behavior
  160. params.prompt.insert(0, 1, ' ');
  161. if (params.interactive_first || params.instruct || !params.prompt.empty() || session_tokens.empty()) {
  162. embd_inp = ::llama_tokenize(ctx, params.prompt, true);
  163. } else {
  164. embd_inp = session_tokens;
  165. }
  166. // Tokenize negative prompt
  167. std::vector<llama_token> guidance_inp;
  168. int guidance_offset = 0;
  169. int original_prompt_len = 0;
  170. if (ctx_guidance) {
  171. params.cfg_negative_prompt.insert(0, 1, ' ');
  172. guidance_inp = ::llama_tokenize(ctx_guidance, params.cfg_negative_prompt, true);
  173. std::vector<llama_token> original_inp = ::llama_tokenize(ctx, params.prompt, true);
  174. original_prompt_len = original_inp.size();
  175. guidance_offset = (int)guidance_inp.size() - original_prompt_len;
  176. }
  177. const int n_ctx = llama_n_ctx(ctx);
  178. if ((int) embd_inp.size() > n_ctx - 4) {
  179. fprintf(stderr, "%s: error: prompt is too long (%d tokens, max %d)\n", __func__, (int) embd_inp.size(), n_ctx - 4);
  180. return 1;
  181. }
  182. // debug message about similarity of saved session, if applicable
  183. size_t n_matching_session_tokens = 0;
  184. if (session_tokens.size()) {
  185. for (llama_token id : session_tokens) {
  186. if (n_matching_session_tokens >= embd_inp.size() || id != embd_inp[n_matching_session_tokens]) {
  187. break;
  188. }
  189. n_matching_session_tokens++;
  190. }
  191. if (params.prompt.empty() && n_matching_session_tokens == embd_inp.size()) {
  192. fprintf(stderr, "%s: using full prompt from session file\n", __func__);
  193. } else if (n_matching_session_tokens >= embd_inp.size()) {
  194. fprintf(stderr, "%s: session file has exact match for prompt!\n", __func__);
  195. } else if (n_matching_session_tokens < (embd_inp.size() / 2)) {
  196. fprintf(stderr, "%s: warning: session file has low similarity to prompt (%zu / %zu tokens); will mostly be reevaluated\n",
  197. __func__, n_matching_session_tokens, embd_inp.size());
  198. } else {
  199. fprintf(stderr, "%s: session file matches %zu / %zu tokens of prompt\n",
  200. __func__, n_matching_session_tokens, embd_inp.size());
  201. }
  202. }
  203. // if we will use the cache for the full prompt without reaching the end of the cache, force
  204. // reevaluation of the last token token to recalculate the cached logits
  205. if (!embd_inp.empty() && n_matching_session_tokens == embd_inp.size() &&
  206. session_tokens.size() > embd_inp.size()) {
  207. session_tokens.resize(embd_inp.size() - 1);
  208. }
  209. // number of tokens to keep when resetting context
  210. if (params.n_keep < 0 || params.n_keep > (int) embd_inp.size() || params.instruct) {
  211. params.n_keep = (int)embd_inp.size();
  212. }
  213. // prefix & suffix for instruct mode
  214. const auto inp_pfx = ::llama_tokenize(ctx, "\n\n### Instruction:\n\n", true);
  215. const auto inp_sfx = ::llama_tokenize(ctx, "\n\n### Response:\n\n", false);
  216. // in instruct mode, we inject a prefix and a suffix to each input by the user
  217. if (params.instruct) {
  218. params.interactive_first = true;
  219. params.antiprompt.push_back("### Instruction:\n\n");
  220. }
  221. // enable interactive mode if interactive start is specified
  222. if (params.interactive_first) {
  223. params.interactive = true;
  224. }
  225. // determine newline token
  226. auto llama_token_newline = ::llama_tokenize(ctx, "\n", false);
  227. if (params.verbose_prompt) {
  228. fprintf(stderr, "\n");
  229. fprintf(stderr, "%s: prompt: '%s'\n", __func__, params.prompt.c_str());
  230. fprintf(stderr, "%s: number of tokens in prompt = %zu\n", __func__, embd_inp.size());
  231. for (int i = 0; i < (int) embd_inp.size(); i++) {
  232. fprintf(stderr, "%6d -> '%s'\n", embd_inp[i], llama_token_to_str(ctx, embd_inp[i]));
  233. }
  234. if (ctx_guidance) {
  235. fprintf(stderr, "\n");
  236. fprintf(stderr, "%s: negative prompt: '%s'\n", __func__, params.cfg_negative_prompt.c_str());
  237. fprintf(stderr, "%s: number of tokens in negative prompt = %zu\n", __func__, guidance_inp.size());
  238. for (int i = 0; i < (int) guidance_inp.size(); i++) {
  239. fprintf(stderr, "%6d -> '%s'\n", guidance_inp[i], llama_token_to_str(ctx, guidance_inp[i]));
  240. }
  241. }
  242. if (params.n_keep > 0) {
  243. fprintf(stderr, "%s: static prompt based on n_keep: '", __func__);
  244. for (int i = 0; i < params.n_keep; i++) {
  245. fprintf(stderr, "%s", llama_token_to_str(ctx, embd_inp[i]));
  246. }
  247. fprintf(stderr, "'\n");
  248. }
  249. fprintf(stderr, "\n");
  250. }
  251. if (params.interactive) {
  252. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
  253. struct sigaction sigint_action;
  254. sigint_action.sa_handler = sigint_handler;
  255. sigemptyset (&sigint_action.sa_mask);
  256. sigint_action.sa_flags = 0;
  257. sigaction(SIGINT, &sigint_action, NULL);
  258. #elif defined (_WIN32)
  259. auto console_ctrl_handler = +[](DWORD ctrl_type) -> BOOL {
  260. return (ctrl_type == CTRL_C_EVENT) ? (sigint_handler(SIGINT), true) : false;
  261. };
  262. SetConsoleCtrlHandler(static_cast<PHANDLER_ROUTINE>(console_ctrl_handler), true);
  263. #endif
  264. fprintf(stderr, "%s: interactive mode on.\n", __func__);
  265. if (params.antiprompt.size()) {
  266. for (auto antiprompt : params.antiprompt) {
  267. fprintf(stderr, "Reverse prompt: '%s'\n", antiprompt.c_str());
  268. }
  269. }
  270. if (!params.input_prefix.empty()) {
  271. fprintf(stderr, "Input prefix: '%s'\n", params.input_prefix.c_str());
  272. }
  273. if (!params.input_suffix.empty()) {
  274. fprintf(stderr, "Input suffix: '%s'\n", params.input_suffix.c_str());
  275. }
  276. }
  277. 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",
  278. 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);
  279. 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);
  280. fprintf(stderr, "\n\n");
  281. grammar_parser::parse_state parsed_grammar;
  282. llama_grammar * grammar = NULL;
  283. if (!params.grammar.empty()) {
  284. parsed_grammar = grammar_parser::parse(params.grammar.c_str());
  285. // will be empty (default) if there are parse errors
  286. if (parsed_grammar.rules.empty()) {
  287. return 1;
  288. }
  289. fprintf(stderr, "%s: grammar:\n", __func__);
  290. grammar_parser::print_grammar(stderr, parsed_grammar);
  291. fprintf(stderr, "\n");
  292. {
  293. auto it = params.logit_bias.find(llama_token_eos());
  294. if (it != params.logit_bias.end() && it->second == -INFINITY) {
  295. fprintf(stderr,
  296. "%s: warning: EOS token is disabled, which will cause most grammars to fail\n", __func__);
  297. }
  298. }
  299. std::vector<const llama_grammar_element *> grammar_rules(parsed_grammar.c_rules());
  300. grammar = llama_grammar_init(
  301. grammar_rules.data(), grammar_rules.size(), parsed_grammar.symbol_ids.at("root"));
  302. }
  303. // TODO: replace with ring-buffer
  304. std::vector<llama_token> last_n_tokens(n_ctx);
  305. std::fill(last_n_tokens.begin(), last_n_tokens.end(), 0);
  306. if (params.interactive) {
  307. const char *control_message;
  308. if (con_st.multiline_input) {
  309. control_message = " - To return control to LLaMa, end your input with '\\'.\n"
  310. " - To return control without starting a new line, end your input with '/'.\n";
  311. } else {
  312. control_message = " - Press Return to return control to LLaMa.\n"
  313. " - To return control without starting a new line, end your input with '/'.\n"
  314. " - If you want to submit another line, end your input with '\\'.\n";
  315. }
  316. fprintf(stderr, "== Running in interactive mode. ==\n"
  317. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__)) || defined (_WIN32)
  318. " - Press Ctrl+C to interject at any time.\n"
  319. #endif
  320. "%s\n", control_message);
  321. is_interacting = params.interactive_first;
  322. }
  323. bool is_antiprompt = false;
  324. bool input_echo = true;
  325. bool need_to_save_session = !path_session.empty() && n_matching_session_tokens < embd_inp.size();
  326. int n_past = 0;
  327. int n_remain = params.n_predict;
  328. int n_consumed = 0;
  329. int n_session_consumed = 0;
  330. int n_past_guidance = 0;
  331. // the first thing we will do is to output the prompt, so set color accordingly
  332. console_set_color(con_st, CONSOLE_COLOR_PROMPT);
  333. std::vector<llama_token> embd;
  334. std::vector<llama_token> embd_guidance;
  335. // do one empty run to warm up the model
  336. {
  337. const std::vector<llama_token> tmp = { llama_token_bos(), };
  338. llama_eval(ctx, tmp.data(), tmp.size(), 0, params.n_threads);
  339. llama_reset_timings(ctx);
  340. }
  341. while ((n_remain != 0 && !is_antiprompt) || params.interactive) {
  342. // predict
  343. if (embd.size() > 0) {
  344. // Note: n_ctx - 4 here is to match the logic for commandline prompt handling via
  345. // --prompt or --file which uses the same value.
  346. auto max_embd_size = n_ctx - 4;
  347. // Ensure the input doesn't exceed the context size by truncating embd if necessary.
  348. if ((int)embd.size() > max_embd_size) {
  349. auto skipped_tokens = embd.size() - max_embd_size;
  350. console_set_color(con_st, CONSOLE_COLOR_ERROR);
  351. printf("<<input too long: skipped %zu token%s>>", skipped_tokens, skipped_tokens != 1 ? "s" : "");
  352. console_set_color(con_st, CONSOLE_COLOR_DEFAULT);
  353. fflush(stdout);
  354. embd.resize(max_embd_size);
  355. }
  356. // infinite text generation via context swapping
  357. // if we run out of context:
  358. // - take the n_keep first tokens from the original prompt (via n_past)
  359. // - take half of the last (n_ctx - n_keep) tokens and recompute the logits in batches
  360. if (n_past + (int) embd.size() + std::max<int>(0, guidance_offset) > n_ctx) {
  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()];
  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()] = 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. // replace end of text token with newline token when in interactive mode
  535. if (id == llama_token_eos() && params.interactive && !params.instruct) {
  536. id = llama_token_newline.front();
  537. if (params.antiprompt.size() != 0) {
  538. // tokenize and inject first reverse prompt
  539. const auto first_antiprompt = ::llama_tokenize(ctx, params.antiprompt.front(), false);
  540. embd_inp.insert(embd_inp.end(), first_antiprompt.begin(), first_antiprompt.end());
  541. }
  542. }
  543. // add it to the context
  544. embd.push_back(id);
  545. // echo this to console
  546. input_echo = true;
  547. // decrement remaining sampling budget
  548. --n_remain;
  549. } else {
  550. // some user input remains from prompt or interaction, forward it to processing
  551. while ((int) embd_inp.size() > n_consumed) {
  552. embd.push_back(embd_inp[n_consumed]);
  553. last_n_tokens.erase(last_n_tokens.begin());
  554. last_n_tokens.push_back(embd_inp[n_consumed]);
  555. ++n_consumed;
  556. if ((int) embd.size() >= params.n_batch) {
  557. break;
  558. }
  559. }
  560. }
  561. // display text
  562. if (input_echo) {
  563. for (auto id : embd) {
  564. printf("%s", llama_token_to_str(ctx, id));
  565. }
  566. fflush(stdout);
  567. }
  568. // reset color to default if we there is no pending user input
  569. if (input_echo && (int)embd_inp.size() == n_consumed) {
  570. console_set_color(con_st, CONSOLE_COLOR_DEFAULT);
  571. }
  572. // if not currently processing queued inputs;
  573. if ((int) embd_inp.size() <= n_consumed) {
  574. // check for reverse prompt
  575. if (params.antiprompt.size()) {
  576. std::string last_output;
  577. for (auto id : last_n_tokens) {
  578. last_output += llama_token_to_str(ctx, id);
  579. }
  580. is_antiprompt = false;
  581. // Check if each of the reverse prompts appears at the end of the output.
  582. // If we're not running interactively, the reverse prompt might be tokenized with some following characters
  583. // so we'll compensate for that by widening the search window a bit.
  584. for (std::string & antiprompt : params.antiprompt) {
  585. size_t extra_padding = params.interactive ? 0 : 2;
  586. size_t search_start_pos = last_output.length() > static_cast<size_t>(antiprompt.length() + extra_padding)
  587. ? last_output.length() - static_cast<size_t>(antiprompt.length() + extra_padding)
  588. : 0;
  589. if (last_output.find(antiprompt.c_str(), search_start_pos) != std::string::npos) {
  590. if (params.interactive) {
  591. is_interacting = true;
  592. console_set_color(con_st, CONSOLE_COLOR_USER_INPUT);
  593. }
  594. is_antiprompt = true;
  595. fflush(stdout);
  596. break;
  597. }
  598. }
  599. }
  600. if (n_past > 0 && is_interacting) {
  601. if (params.instruct) {
  602. printf("\n> ");
  603. }
  604. std::string buffer;
  605. if (!params.input_prefix.empty()) {
  606. buffer += params.input_prefix;
  607. printf("%s", buffer.c_str());
  608. }
  609. std::string line;
  610. bool another_line = true;
  611. do {
  612. another_line = console_readline(con_st, line);
  613. buffer += line;
  614. } while (another_line);
  615. // done taking input, reset color
  616. console_set_color(con_st, CONSOLE_COLOR_DEFAULT);
  617. // Add tokens to embd only if the input buffer is non-empty
  618. // Entering a empty line lets the user pass control back
  619. if (buffer.length() > 1) {
  620. // append input suffix if any
  621. if (!params.input_suffix.empty()) {
  622. buffer += params.input_suffix;
  623. printf("%s", params.input_suffix.c_str());
  624. }
  625. // instruct mode: insert instruction prefix
  626. if (params.instruct && !is_antiprompt) {
  627. n_consumed = embd_inp.size();
  628. embd_inp.insert(embd_inp.end(), inp_pfx.begin(), inp_pfx.end());
  629. }
  630. auto line_inp = ::llama_tokenize(ctx, buffer, false);
  631. embd_inp.insert(embd_inp.end(), line_inp.begin(), line_inp.end());
  632. // instruct mode: insert response suffix
  633. if (params.instruct) {
  634. embd_inp.insert(embd_inp.end(), inp_sfx.begin(), inp_sfx.end());
  635. }
  636. n_remain -= line_inp.size();
  637. }
  638. input_echo = false; // do not echo this again
  639. }
  640. if (n_past > 0) {
  641. if (is_interacting) {
  642. // reset grammar state if we're restarting generation
  643. if (grammar != NULL) {
  644. llama_grammar_free(grammar);
  645. std::vector<const llama_grammar_element *> grammar_rules(
  646. parsed_grammar.c_rules());
  647. grammar = llama_grammar_init(
  648. grammar_rules.data(), grammar_rules.size(),
  649. parsed_grammar.symbol_ids.at("root"));
  650. }
  651. }
  652. is_interacting = false;
  653. }
  654. }
  655. // end of text token
  656. if (!embd.empty() && embd.back() == llama_token_eos()) {
  657. if (params.instruct) {
  658. is_interacting = true;
  659. } else {
  660. fprintf(stderr, " [end of text]\n");
  661. break;
  662. }
  663. }
  664. // In interactive mode, respect the maximum number of tokens and drop back to user input when reached.
  665. if (params.interactive && n_remain <= 0 && params.n_predict != -1) {
  666. n_remain = params.n_predict;
  667. is_interacting = true;
  668. }
  669. }
  670. if (!path_session.empty() && params.prompt_cache_all && !params.prompt_cache_ro) {
  671. fprintf(stderr, "\n%s: saving final output to session file '%s'\n", __func__, path_session.c_str());
  672. llama_save_session_file(ctx, path_session.c_str(), session_tokens.data(), session_tokens.size());
  673. }
  674. llama_print_timings(ctx);
  675. if (ctx_guidance) { llama_free(ctx_guidance); }
  676. llama_free(ctx);
  677. llama_free_model(model);
  678. if (grammar != NULL) {
  679. llama_grammar_free(grammar);
  680. }
  681. llama_backend_free();
  682. return 0;
  683. }