main.cpp 34 KB

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