main.cpp 33 KB

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