main.cpp 30 KB

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