main.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821
  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());
  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. // Add a space in front of the first character to match OG llama tokenizer behavior
  158. params.prompt.insert(0, 1, ' ');
  159. if (params.interactive_first || params.instruct || !params.prompt.empty() || session_tokens.empty()) {
  160. embd_inp = ::llama_tokenize(ctx, params.prompt, true);
  161. } else {
  162. embd_inp = session_tokens;
  163. }
  164. // Tokenize negative prompt
  165. std::vector<llama_token> guidance_inp;
  166. int guidance_offset = 0;
  167. int original_prompt_len = 0;
  168. if (ctx_guidance) {
  169. params.cfg_negative_prompt.insert(0, 1, ' ');
  170. guidance_inp = ::llama_tokenize(ctx_guidance, params.cfg_negative_prompt, true);
  171. std::vector<llama_token> original_inp = ::llama_tokenize(ctx, params.prompt, true);
  172. original_prompt_len = original_inp.size();
  173. guidance_offset = (int)guidance_inp.size() - original_prompt_len;
  174. }
  175. const int n_ctx = llama_n_ctx(ctx);
  176. if ((int) embd_inp.size() > n_ctx - 4) {
  177. fprintf(stderr, "%s: error: prompt is too long (%d tokens, max %d)\n", __func__, (int) embd_inp.size(), n_ctx - 4);
  178. return 1;
  179. }
  180. // debug message about similarity of saved session, if applicable
  181. size_t n_matching_session_tokens = 0;
  182. if (session_tokens.size()) {
  183. for (llama_token id : session_tokens) {
  184. if (n_matching_session_tokens >= embd_inp.size() || id != embd_inp[n_matching_session_tokens]) {
  185. break;
  186. }
  187. n_matching_session_tokens++;
  188. }
  189. if (params.prompt.empty() && n_matching_session_tokens == embd_inp.size()) {
  190. fprintf(stderr, "%s: using full prompt from session file\n", __func__);
  191. } else if (n_matching_session_tokens >= embd_inp.size()) {
  192. fprintf(stderr, "%s: session file has exact match for prompt!\n", __func__);
  193. } else if (n_matching_session_tokens < (embd_inp.size() / 2)) {
  194. fprintf(stderr, "%s: warning: session file has low similarity to prompt (%zu / %zu tokens); will mostly be reevaluated\n",
  195. __func__, n_matching_session_tokens, embd_inp.size());
  196. } else {
  197. fprintf(stderr, "%s: session file matches %zu / %zu tokens of prompt\n",
  198. __func__, n_matching_session_tokens, embd_inp.size());
  199. }
  200. }
  201. // if we will use the cache for the full prompt without reaching the end of the cache, force
  202. // reevaluation of the last token token to recalculate the cached logits
  203. if (!embd_inp.empty() && n_matching_session_tokens == embd_inp.size() &&
  204. session_tokens.size() > embd_inp.size()) {
  205. session_tokens.resize(embd_inp.size() - 1);
  206. }
  207. // number of tokens to keep when resetting context
  208. if (params.n_keep < 0 || params.n_keep > (int) embd_inp.size() || params.instruct) {
  209. params.n_keep = (int)embd_inp.size();
  210. }
  211. // prefix & suffix for instruct mode
  212. const auto inp_pfx = ::llama_tokenize(ctx, "\n\n### Instruction:\n\n", true);
  213. const auto inp_sfx = ::llama_tokenize(ctx, "\n\n### Response:\n\n", false);
  214. // in instruct mode, we inject a prefix and a suffix to each input by the user
  215. if (params.instruct) {
  216. params.interactive_first = true;
  217. params.antiprompt.push_back("### Instruction:\n\n");
  218. }
  219. // enable interactive mode if interactive start is specified
  220. if (params.interactive_first) {
  221. params.interactive = true;
  222. }
  223. // determine newline token
  224. auto llama_token_newline = ::llama_tokenize(ctx, "\n", false);
  225. if (params.verbose_prompt) {
  226. fprintf(stderr, "\n");
  227. fprintf(stderr, "%s: prompt: '%s'\n", __func__, params.prompt.c_str());
  228. fprintf(stderr, "%s: number of tokens in prompt = %zu\n", __func__, embd_inp.size());
  229. for (int i = 0; i < (int) embd_inp.size(); i++) {
  230. fprintf(stderr, "%6d -> '%s'\n", embd_inp[i], llama_token_to_str(ctx, embd_inp[i]));
  231. }
  232. if (ctx_guidance) {
  233. fprintf(stderr, "\n");
  234. fprintf(stderr, "%s: negative prompt: '%s'\n", __func__, params.cfg_negative_prompt.c_str());
  235. fprintf(stderr, "%s: number of tokens in negative prompt = %zu\n", __func__, guidance_inp.size());
  236. for (int i = 0; i < (int) guidance_inp.size(); i++) {
  237. fprintf(stderr, "%6d -> '%s'\n", guidance_inp[i], llama_token_to_str(ctx, guidance_inp[i]));
  238. }
  239. }
  240. if (params.n_keep > 0) {
  241. fprintf(stderr, "%s: static prompt based on n_keep: '", __func__);
  242. for (int i = 0; i < params.n_keep; i++) {
  243. fprintf(stderr, "%s", llama_token_to_str(ctx, embd_inp[i]));
  244. }
  245. fprintf(stderr, "'\n");
  246. }
  247. fprintf(stderr, "\n");
  248. }
  249. if (params.interactive) {
  250. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
  251. struct sigaction sigint_action;
  252. sigint_action.sa_handler = sigint_handler;
  253. sigemptyset (&sigint_action.sa_mask);
  254. sigint_action.sa_flags = 0;
  255. sigaction(SIGINT, &sigint_action, NULL);
  256. #elif defined (_WIN32)
  257. auto console_ctrl_handler = +[](DWORD ctrl_type) -> BOOL {
  258. return (ctrl_type == CTRL_C_EVENT) ? (sigint_handler(SIGINT), true) : false;
  259. };
  260. SetConsoleCtrlHandler(static_cast<PHANDLER_ROUTINE>(console_ctrl_handler), true);
  261. #endif
  262. fprintf(stderr, "%s: interactive mode on.\n", __func__);
  263. if (params.antiprompt.size()) {
  264. for (auto antiprompt : params.antiprompt) {
  265. fprintf(stderr, "Reverse prompt: '%s'\n", antiprompt.c_str());
  266. }
  267. }
  268. if (params.input_prefix_bos) {
  269. fprintf(stderr, "Input prefix with BOS\n");
  270. }
  271. if (!params.input_prefix.empty()) {
  272. fprintf(stderr, "Input prefix: '%s'\n", params.input_prefix.c_str());
  273. }
  274. if (!params.input_suffix.empty()) {
  275. fprintf(stderr, "Input suffix: '%s'\n", params.input_suffix.c_str());
  276. }
  277. }
  278. 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",
  279. 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);
  280. 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);
  281. fprintf(stderr, "\n\n");
  282. grammar_parser::parse_state parsed_grammar;
  283. llama_grammar * grammar = NULL;
  284. if (!params.grammar.empty()) {
  285. parsed_grammar = grammar_parser::parse(params.grammar.c_str());
  286. // will be empty (default) if there are parse errors
  287. if (parsed_grammar.rules.empty()) {
  288. return 1;
  289. }
  290. fprintf(stderr, "%s: grammar:\n", __func__);
  291. grammar_parser::print_grammar(stderr, parsed_grammar);
  292. fprintf(stderr, "\n");
  293. {
  294. auto it = params.logit_bias.find(llama_token_eos());
  295. if (it != params.logit_bias.end() && it->second == -INFINITY) {
  296. fprintf(stderr,
  297. "%s: warning: EOS token is disabled, which will cause most grammars to fail\n", __func__);
  298. }
  299. }
  300. std::vector<const llama_grammar_element *> grammar_rules(parsed_grammar.c_rules());
  301. grammar = llama_grammar_init(
  302. grammar_rules.data(), grammar_rules.size(), parsed_grammar.symbol_ids.at("root"));
  303. }
  304. // TODO: replace with ring-buffer
  305. std::vector<llama_token> last_n_tokens(n_ctx);
  306. std::fill(last_n_tokens.begin(), last_n_tokens.end(), 0);
  307. if (params.interactive) {
  308. const char *control_message;
  309. if (params.multiline_input) {
  310. control_message = " - To return control to LLaMa, end your input with '\\'.\n"
  311. " - To return control without starting a new line, end your input with '/'.\n";
  312. } else {
  313. control_message = " - Press Return to return control to LLaMa.\n"
  314. " - To return control without starting a new line, end your input with '/'.\n"
  315. " - If you want to submit another line, end your input with '\\'.\n";
  316. }
  317. fprintf(stderr, "== Running in interactive mode. ==\n"
  318. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__)) || defined (_WIN32)
  319. " - Press Ctrl+C to interject at any time.\n"
  320. #endif
  321. "%s\n", control_message);
  322. is_interacting = params.interactive_first;
  323. }
  324. bool is_antiprompt = false;
  325. bool input_echo = true;
  326. bool need_to_save_session = !path_session.empty() && n_matching_session_tokens < embd_inp.size();
  327. int n_past = 0;
  328. int n_remain = params.n_predict;
  329. int n_consumed = 0;
  330. int n_session_consumed = 0;
  331. int n_past_guidance = 0;
  332. // the first thing we will do is to output the prompt, so set color accordingly
  333. console::set_display(console::prompt);
  334. std::vector<llama_token> embd;
  335. std::vector<llama_token> embd_guidance;
  336. // do one empty run to warm up the model
  337. {
  338. const std::vector<llama_token> tmp = { llama_token_bos(), };
  339. llama_eval(ctx, tmp.data(), tmp.size(), 0, params.n_threads);
  340. llama_reset_timings(ctx);
  341. }
  342. while ((n_remain != 0 && !is_antiprompt) || params.interactive) {
  343. // predict
  344. if (embd.size() > 0) {
  345. // Note: n_ctx - 4 here is to match the logic for commandline prompt handling via
  346. // --prompt or --file which uses the same value.
  347. auto max_embd_size = n_ctx - 4;
  348. // Ensure the input doesn't exceed the context size by truncating embd if necessary.
  349. if ((int)embd.size() > max_embd_size) {
  350. auto skipped_tokens = embd.size() - max_embd_size;
  351. console::set_display(console::error);
  352. printf("<<input too long: skipped %zu token%s>>", skipped_tokens, skipped_tokens != 1 ? "s" : "");
  353. console::set_display(console::reset);
  354. fflush(stdout);
  355. embd.resize(max_embd_size);
  356. }
  357. // infinite text generation via context swapping
  358. // if we run out of context:
  359. // - take the n_keep first tokens from the original prompt (via n_past)
  360. // - take half of the last (n_ctx - n_keep) tokens and recompute the logits in batches
  361. if (n_past + (int) embd.size() + std::max<int>(0, guidance_offset) > n_ctx) {
  362. const int n_left = n_past - params.n_keep;
  363. // always keep the first token - BOS
  364. n_past = std::max(1, params.n_keep);
  365. n_past_guidance = std::max(1, params.n_keep + guidance_offset);
  366. // insert n_left/2 tokens at the start of embd from last_n_tokens
  367. embd.insert(embd.begin(), last_n_tokens.begin() + n_ctx - n_left/2 - embd.size(), last_n_tokens.end() - embd.size());
  368. // stop saving session if we run out of context
  369. path_session.clear();
  370. //printf("\n---\n");
  371. //printf("resetting: '");
  372. //for (int i = 0; i < (int) embd.size(); i++) {
  373. // printf("%s", llama_token_to_str(ctx, embd[i]));
  374. //}
  375. //printf("'\n");
  376. //printf("\n---\n");
  377. }
  378. // try to reuse a matching prefix from the loaded session instead of re-eval (via n_past)
  379. if (n_session_consumed < (int) session_tokens.size()) {
  380. size_t i = 0;
  381. for ( ; i < embd.size(); i++) {
  382. if (embd[i] != session_tokens[n_session_consumed]) {
  383. session_tokens.resize(n_session_consumed);
  384. break;
  385. }
  386. n_past++;
  387. n_session_consumed++;
  388. if (n_session_consumed >= (int) session_tokens.size()) {
  389. ++i;
  390. break;
  391. }
  392. }
  393. if (i > 0) {
  394. embd.erase(embd.begin(), embd.begin() + i);
  395. }
  396. }
  397. // evaluate tokens in batches
  398. // embd is typically prepared beforehand to fit within a batch, but not always
  399. if (ctx_guidance) {
  400. int input_size = 0;
  401. llama_token* input_buf = NULL;
  402. if (n_past_guidance < (int) guidance_inp.size()) {
  403. // Guidance context should have the same data with these modifications:
  404. //
  405. // * Replace the initial prompt
  406. // * Shift everything by guidance_offset
  407. embd_guidance = guidance_inp;
  408. if (embd.begin() + original_prompt_len < embd.end()) {
  409. embd_guidance.insert(
  410. embd_guidance.end(),
  411. embd.begin() + original_prompt_len,
  412. embd.end()
  413. );
  414. }
  415. input_buf = embd_guidance.data();
  416. input_size = embd_guidance.size();
  417. //fprintf(stderr, "\n---------------------\n");
  418. //for (int i = 0; i < (int) embd_guidance.size(); i++) {
  419. //fprintf(stderr, "%s", llama_token_to_str(ctx, embd_guidance[i]));
  420. //}
  421. //fprintf(stderr, "\n---------------------\n");
  422. } else {
  423. input_buf = embd.data();
  424. input_size = embd.size();
  425. }
  426. for (int i = 0; i < input_size; i += params.n_batch) {
  427. int n_eval = std::min(input_size - i, params.n_batch);
  428. if (llama_eval(ctx_guidance, input_buf + i, n_eval, n_past_guidance, params.n_threads)) {
  429. fprintf(stderr, "%s : failed to eval\n", __func__);
  430. return 1;
  431. }
  432. n_past_guidance += n_eval;
  433. }
  434. }
  435. for (int i = 0; i < (int) embd.size(); i += params.n_batch) {
  436. int n_eval = (int) embd.size() - i;
  437. if (n_eval > params.n_batch) {
  438. n_eval = params.n_batch;
  439. }
  440. if (llama_eval(ctx, &embd[i], n_eval, n_past, params.n_threads)) {
  441. fprintf(stderr, "%s : failed to eval\n", __func__);
  442. return 1;
  443. }
  444. n_past += n_eval;
  445. }
  446. if (embd.size() > 0 && !path_session.empty()) {
  447. session_tokens.insert(session_tokens.end(), embd.begin(), embd.end());
  448. n_session_consumed = session_tokens.size();
  449. }
  450. }
  451. embd.clear();
  452. embd_guidance.clear();
  453. if ((int) embd_inp.size() <= n_consumed && !is_interacting) {
  454. // out of user input, sample next token
  455. const float temp = params.temp;
  456. const int32_t top_k = params.top_k <= 0 ? llama_n_vocab(ctx) : params.top_k;
  457. const float top_p = params.top_p;
  458. const float tfs_z = params.tfs_z;
  459. const float typical_p = params.typical_p;
  460. const int32_t repeat_last_n = params.repeat_last_n < 0 ? n_ctx : params.repeat_last_n;
  461. const float repeat_penalty = params.repeat_penalty;
  462. const float alpha_presence = params.presence_penalty;
  463. const float alpha_frequency = params.frequency_penalty;
  464. const int mirostat = params.mirostat;
  465. const float mirostat_tau = params.mirostat_tau;
  466. const float mirostat_eta = params.mirostat_eta;
  467. const bool penalize_nl = params.penalize_nl;
  468. // optionally save the session on first sample (for faster prompt loading next time)
  469. if (!path_session.empty() && need_to_save_session && !params.prompt_cache_ro) {
  470. need_to_save_session = false;
  471. llama_save_session_file(ctx, path_session.c_str(), session_tokens.data(), session_tokens.size());
  472. }
  473. llama_token id = 0;
  474. {
  475. auto logits = llama_get_logits(ctx);
  476. auto n_vocab = llama_n_vocab(ctx);
  477. // Apply params.logit_bias map
  478. for (auto it = params.logit_bias.begin(); it != params.logit_bias.end(); it++) {
  479. logits[it->first] += it->second;
  480. }
  481. std::vector<llama_token_data> candidates;
  482. candidates.reserve(n_vocab);
  483. for (llama_token token_id = 0; token_id < n_vocab; token_id++) {
  484. candidates.emplace_back(llama_token_data{token_id, logits[token_id], 0.0f});
  485. }
  486. llama_token_data_array candidates_p = { candidates.data(), candidates.size(), false };
  487. if (ctx_guidance) {
  488. llama_sample_classifier_free_guidance(ctx, &candidates_p, ctx_guidance, params.cfg_scale);
  489. }
  490. // Apply penalties
  491. float nl_logit = logits[llama_token_nl()];
  492. auto last_n_repeat = std::min(std::min((int)last_n_tokens.size(), repeat_last_n), n_ctx);
  493. llama_sample_repetition_penalty(ctx, &candidates_p,
  494. last_n_tokens.data() + last_n_tokens.size() - last_n_repeat,
  495. last_n_repeat, repeat_penalty);
  496. llama_sample_frequency_and_presence_penalties(ctx, &candidates_p,
  497. last_n_tokens.data() + last_n_tokens.size() - last_n_repeat,
  498. last_n_repeat, alpha_frequency, alpha_presence);
  499. if (!penalize_nl) {
  500. logits[llama_token_nl()] = nl_logit;
  501. }
  502. if (grammar != NULL) {
  503. llama_sample_grammar(ctx, &candidates_p, grammar);
  504. }
  505. if (temp <= 0) {
  506. // Greedy sampling
  507. id = llama_sample_token_greedy(ctx, &candidates_p);
  508. } else {
  509. if (mirostat == 1) {
  510. static float mirostat_mu = 2.0f * mirostat_tau;
  511. const int mirostat_m = 100;
  512. llama_sample_temperature(ctx, &candidates_p, temp);
  513. id = llama_sample_token_mirostat(ctx, &candidates_p, mirostat_tau, mirostat_eta, mirostat_m, &mirostat_mu);
  514. } else if (mirostat == 2) {
  515. static float mirostat_mu = 2.0f * mirostat_tau;
  516. llama_sample_temperature(ctx, &candidates_p, temp);
  517. id = llama_sample_token_mirostat_v2(ctx, &candidates_p, mirostat_tau, mirostat_eta, &mirostat_mu);
  518. } else {
  519. // Temperature sampling
  520. llama_sample_top_k(ctx, &candidates_p, top_k, 1);
  521. llama_sample_tail_free(ctx, &candidates_p, tfs_z, 1);
  522. llama_sample_typical(ctx, &candidates_p, typical_p, 1);
  523. llama_sample_top_p(ctx, &candidates_p, top_p, 1);
  524. llama_sample_temperature(ctx, &candidates_p, temp);
  525. id = llama_sample_token(ctx, &candidates_p);
  526. }
  527. }
  528. // printf("`%d`", candidates_p.size);
  529. if (grammar != NULL) {
  530. llama_grammar_accept_token(ctx, grammar, id);
  531. }
  532. last_n_tokens.erase(last_n_tokens.begin());
  533. last_n_tokens.push_back(id);
  534. }
  535. // add it to the context
  536. embd.push_back(id);
  537. // echo this to console
  538. input_echo = true;
  539. // decrement remaining sampling budget
  540. --n_remain;
  541. } else {
  542. // some user input remains from prompt or interaction, forward it to processing
  543. while ((int) embd_inp.size() > n_consumed) {
  544. embd.push_back(embd_inp[n_consumed]);
  545. last_n_tokens.erase(last_n_tokens.begin());
  546. last_n_tokens.push_back(embd_inp[n_consumed]);
  547. ++n_consumed;
  548. if ((int) embd.size() >= params.n_batch) {
  549. break;
  550. }
  551. }
  552. }
  553. // display text
  554. if (input_echo) {
  555. for (auto id : embd) {
  556. printf("%s", llama_token_to_str(ctx, id));
  557. }
  558. fflush(stdout);
  559. }
  560. // reset color to default if we there is no pending user input
  561. if (input_echo && (int)embd_inp.size() == n_consumed) {
  562. console::set_display(console::reset);
  563. }
  564. // if not currently processing queued inputs;
  565. if ((int) embd_inp.size() <= n_consumed) {
  566. // check for reverse prompt
  567. if (params.antiprompt.size()) {
  568. std::string last_output;
  569. for (auto id : last_n_tokens) {
  570. last_output += llama_token_to_str(ctx, id);
  571. }
  572. is_antiprompt = false;
  573. // Check if each of the reverse prompts appears at the end of the output.
  574. // If we're not running interactively, the reverse prompt might be tokenized with some following characters
  575. // so we'll compensate for that by widening the search window a bit.
  576. for (std::string & antiprompt : params.antiprompt) {
  577. size_t extra_padding = params.interactive ? 0 : 2;
  578. size_t search_start_pos = last_output.length() > static_cast<size_t>(antiprompt.length() + extra_padding)
  579. ? last_output.length() - static_cast<size_t>(antiprompt.length() + extra_padding)
  580. : 0;
  581. if (last_output.find(antiprompt.c_str(), search_start_pos) != std::string::npos) {
  582. if (params.interactive) {
  583. is_interacting = true;
  584. console::set_display(console::user_input);
  585. }
  586. is_antiprompt = true;
  587. fflush(stdout);
  588. break;
  589. }
  590. }
  591. }
  592. // deal with end of text token in interactive mode
  593. if (last_n_tokens.back() == llama_token_eos()) {
  594. if (params.interactive) {
  595. if (params.antiprompt.size() != 0) {
  596. // tokenize and inject first reverse prompt
  597. const auto first_antiprompt = ::llama_tokenize(ctx, params.antiprompt.front(), false);
  598. embd_inp.insert(embd_inp.end(), first_antiprompt.begin(), first_antiprompt.end());
  599. is_antiprompt = true;
  600. }
  601. is_interacting = true;
  602. printf("\n");
  603. console::set_display(console::user_input);
  604. fflush(stdout);
  605. } else if (params.instruct) {
  606. is_interacting = true;
  607. }
  608. }
  609. if (n_past > 0 && is_interacting) {
  610. if (params.instruct) {
  611. printf("\n> ");
  612. }
  613. if (params.input_prefix_bos) {
  614. embd_inp.push_back(llama_token_bos());
  615. }
  616. std::string buffer;
  617. if (!params.input_prefix.empty()) {
  618. buffer += params.input_prefix;
  619. printf("%s", buffer.c_str());
  620. }
  621. std::string line;
  622. bool another_line = true;
  623. do {
  624. another_line = console::readline(line, params.multiline_input);
  625. buffer += line;
  626. } while (another_line);
  627. // done taking input, reset color
  628. console::set_display(console::reset);
  629. // Add tokens to embd only if the input buffer is non-empty
  630. // Entering a empty line lets the user pass control back
  631. if (buffer.length() > 1) {
  632. // append input suffix if any
  633. if (!params.input_suffix.empty()) {
  634. buffer += params.input_suffix;
  635. printf("%s", params.input_suffix.c_str());
  636. }
  637. // instruct mode: insert instruction prefix
  638. if (params.instruct && !is_antiprompt) {
  639. n_consumed = embd_inp.size();
  640. embd_inp.insert(embd_inp.end(), inp_pfx.begin(), inp_pfx.end());
  641. }
  642. auto line_inp = ::llama_tokenize(ctx, buffer, false);
  643. embd_inp.insert(embd_inp.end(), line_inp.begin(), line_inp.end());
  644. // instruct mode: insert response suffix
  645. if (params.instruct) {
  646. embd_inp.insert(embd_inp.end(), inp_sfx.begin(), inp_sfx.end());
  647. }
  648. n_remain -= line_inp.size();
  649. }
  650. input_echo = false; // do not echo this again
  651. }
  652. if (n_past > 0) {
  653. if (is_interacting) {
  654. // reset grammar state if we're restarting generation
  655. if (grammar != NULL) {
  656. llama_grammar_free(grammar);
  657. std::vector<const llama_grammar_element *> grammar_rules(
  658. parsed_grammar.c_rules());
  659. grammar = llama_grammar_init(
  660. grammar_rules.data(), grammar_rules.size(),
  661. parsed_grammar.symbol_ids.at("root"));
  662. }
  663. }
  664. is_interacting = false;
  665. }
  666. }
  667. // end of text token
  668. if (!embd.empty() && embd.back() == llama_token_eos() && !(params.instruct || params.interactive)) {
  669. fprintf(stderr, " [end of text]\n");
  670. break;
  671. }
  672. // In interactive mode, respect the maximum number of tokens and drop back to user input when reached.
  673. if (params.interactive && n_remain <= 0 && params.n_predict != -1) {
  674. n_remain = params.n_predict;
  675. is_interacting = true;
  676. }
  677. }
  678. if (!path_session.empty() && params.prompt_cache_all && !params.prompt_cache_ro) {
  679. fprintf(stderr, "\n%s: saving final output to session file '%s'\n", __func__, path_session.c_str());
  680. llama_save_session_file(ctx, path_session.c_str(), session_tokens.data(), session_tokens.size());
  681. }
  682. llama_print_timings(ctx);
  683. if (ctx_guidance) { llama_free(ctx_guidance); }
  684. llama_free(ctx);
  685. llama_free_model(model);
  686. if (grammar != NULL) {
  687. llama_grammar_free(grammar);
  688. }
  689. llama_backend_free();
  690. return 0;
  691. }