main.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643
  1. // Defines sigaction on msys:
  2. #ifndef _GNU_SOURCE
  3. #define _GNU_SOURCE
  4. #endif
  5. #include "common.h"
  6. #include "llama.h"
  7. #include "build-info.h"
  8. #include <cassert>
  9. #include <cinttypes>
  10. #include <cmath>
  11. #include <cstdio>
  12. #include <cstring>
  13. #include <ctime>
  14. #include <fstream>
  15. #include <iostream>
  16. #include <string>
  17. #include <vector>
  18. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
  19. #include <signal.h>
  20. #include <unistd.h>
  21. #elif defined (_WIN32)
  22. #include <signal.h>
  23. #endif
  24. static console_state con_st;
  25. static llama_context ** g_ctx;
  26. static bool is_interacting = false;
  27. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__)) || defined (_WIN32)
  28. void sigint_handler(int signo) {
  29. set_console_color(con_st, CONSOLE_COLOR_DEFAULT);
  30. printf("\n"); // this also force flush stdout.
  31. if (signo == SIGINT) {
  32. if (!is_interacting) {
  33. is_interacting=true;
  34. } else {
  35. llama_print_timings(*g_ctx);
  36. _exit(130);
  37. }
  38. }
  39. }
  40. #endif
  41. int main(int argc, char ** argv) {
  42. gpt_params params;
  43. params.model = "models/llama-7B/ggml-model.bin";
  44. if (gpt_params_parse(argc, argv, params) == false) {
  45. return 1;
  46. }
  47. // save choice to use color for later
  48. // (note for later: this is a slightly awkward choice)
  49. con_st.use_color = params.use_color;
  50. #if defined (_WIN32)
  51. win32_console_init(params.use_color);
  52. #endif
  53. if (params.perplexity) {
  54. printf("\n************\n");
  55. printf("%s: please use the 'perplexity' tool for perplexity calculations\n", __func__);
  56. printf("************\n\n");
  57. return 0;
  58. }
  59. if (params.embedding) {
  60. printf("\n************\n");
  61. printf("%s: please use the 'embedding' tool for embedding calculations\n", __func__);
  62. printf("************\n\n");
  63. return 0;
  64. }
  65. if (params.n_ctx > 2048) {
  66. fprintf(stderr, "%s: warning: model does not support context sizes greater than 2048 tokens (%d specified);"
  67. "expect poor results\n", __func__, params.n_ctx);
  68. }
  69. fprintf(stderr, "%s: build = %d (%s)\n", __func__, BUILD_NUMBER, BUILD_COMMIT);
  70. if (params.seed <= 0) {
  71. params.seed = time(NULL);
  72. }
  73. fprintf(stderr, "%s: seed = %d\n", __func__, params.seed);
  74. std::mt19937 rng(params.seed);
  75. if (params.random_prompt) {
  76. params.prompt = gpt_random_prompt(rng);
  77. }
  78. // params.prompt = R"(// this function checks if the number n is prime
  79. //bool is_prime(int n) {)";
  80. llama_context * ctx;
  81. g_ctx = &ctx;
  82. // load the model
  83. {
  84. auto lparams = llama_context_default_params();
  85. lparams.n_ctx = params.n_ctx;
  86. lparams.n_parts = params.n_parts;
  87. lparams.seed = params.seed;
  88. lparams.f16_kv = params.memory_f16;
  89. lparams.use_mmap = params.use_mmap;
  90. lparams.use_mlock = params.use_mlock;
  91. ctx = llama_init_from_file(params.model.c_str(), lparams);
  92. if (ctx == NULL) {
  93. fprintf(stderr, "%s: error: failed to load model '%s'\n", __func__, params.model.c_str());
  94. return 1;
  95. }
  96. }
  97. if (!params.lora_adapter.empty()) {
  98. int err = llama_apply_lora_from_file(ctx,
  99. params.lora_adapter.c_str(),
  100. params.lora_base.empty() ? NULL : params.lora_base.c_str(),
  101. params.n_threads);
  102. if (err != 0) {
  103. fprintf(stderr, "%s: error: failed to apply lora adapter\n", __func__);
  104. return 1;
  105. }
  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_predict parameters
  114. // uncomment the "used_mem" line in llama.cpp to see the results
  115. if (params.mem_test) {
  116. {
  117. const std::vector<llama_token> tmp(params.n_batch, 0);
  118. llama_eval(ctx, tmp.data(), tmp.size(), 0, params.n_threads);
  119. }
  120. {
  121. const std::vector<llama_token> tmp = { 0, };
  122. llama_eval(ctx, tmp.data(), tmp.size(), params.n_predict - 1, params.n_threads);
  123. }
  124. llama_print_timings(ctx);
  125. llama_free(ctx);
  126. return 0;
  127. }
  128. // Add a space in front of the first character to match OG llama tokenizer behavior
  129. params.prompt.insert(0, 1, ' ');
  130. std::string path_session = params.path_session;
  131. std::vector<llama_token> session_tokens;
  132. if (!path_session.empty()) {
  133. fprintf(stderr, "%s: attempting to load saved session from '%s'\n", __func__, path_session.c_str());
  134. // fopen to check for existing session
  135. FILE * fp = std::fopen(path_session.c_str(), "rb");
  136. if (fp != NULL) {
  137. std::fclose(fp);
  138. session_tokens.resize(params.n_ctx);
  139. size_t n_token_count_out = 0;
  140. if (!llama_load_session_file(ctx, path_session.c_str(), session_tokens.data(), session_tokens.capacity(), &n_token_count_out)) {
  141. fprintf(stderr, "%s: error: failed to load session file '%s'\n", __func__, path_session.c_str());
  142. return 1;
  143. }
  144. session_tokens.resize(n_token_count_out);
  145. fprintf(stderr, "%s: loaded a session with prompt size of %d tokens\n", __func__, (int) session_tokens.size());
  146. } else {
  147. fprintf(stderr, "%s: session file does not exist, will create\n", __func__);
  148. }
  149. }
  150. // tokenize the prompt
  151. auto embd_inp = ::llama_tokenize(ctx, params.prompt, true);
  152. const int n_ctx = llama_n_ctx(ctx);
  153. if ((int) embd_inp.size() > n_ctx - 4) {
  154. fprintf(stderr, "%s: error: prompt is too long (%d tokens, max %d)\n", __func__, (int) embd_inp.size(), n_ctx - 4);
  155. return 1;
  156. }
  157. // debug message about similarity of saved session, if applicable
  158. size_t n_matching_session_tokens = 0;
  159. if (session_tokens.size()) {
  160. for (llama_token id : session_tokens) {
  161. if (n_matching_session_tokens >= embd_inp.size() || id != embd_inp[n_matching_session_tokens]) {
  162. break;
  163. }
  164. n_matching_session_tokens++;
  165. }
  166. if (n_matching_session_tokens >= embd_inp.size()) {
  167. fprintf(stderr, "%s: session file has exact match for prompt!\n", __func__);
  168. } else if (n_matching_session_tokens < (embd_inp.size() / 2)) {
  169. fprintf(stderr, "%s: warning: session file has low similarity to prompt (%zu / %zu tokens); will mostly be reevaluated\n",
  170. __func__, n_matching_session_tokens, embd_inp.size());
  171. } else {
  172. fprintf(stderr, "%s: session file matches %zu / %zu tokens of prompt\n",
  173. __func__, n_matching_session_tokens, embd_inp.size());
  174. }
  175. }
  176. // number of tokens to keep when resetting context
  177. if (params.n_keep < 0 || params.n_keep > (int) embd_inp.size() || params.instruct) {
  178. params.n_keep = (int)embd_inp.size();
  179. }
  180. // prefix & suffix for instruct mode
  181. const auto inp_pfx = ::llama_tokenize(ctx, "\n\n### Instruction:\n\n", true);
  182. const auto inp_sfx = ::llama_tokenize(ctx, "\n\n### Response:\n\n", false);
  183. // in instruct mode, we inject a prefix and a suffix to each input by the user
  184. if (params.instruct) {
  185. params.interactive_first = true;
  186. params.antiprompt.push_back("### Instruction:\n\n");
  187. }
  188. // enable interactive mode if reverse prompt or interactive start is specified
  189. if (params.antiprompt.size() != 0 || params.interactive_first) {
  190. params.interactive = true;
  191. }
  192. // determine newline token
  193. auto llama_token_newline = ::llama_tokenize(ctx, "\n", false);
  194. if (params.verbose_prompt) {
  195. fprintf(stderr, "\n");
  196. fprintf(stderr, "%s: prompt: '%s'\n", __func__, params.prompt.c_str());
  197. fprintf(stderr, "%s: number of tokens in prompt = %zu\n", __func__, embd_inp.size());
  198. for (int i = 0; i < (int) embd_inp.size(); i++) {
  199. fprintf(stderr, "%6d -> '%s'\n", embd_inp[i], llama_token_to_str(ctx, embd_inp[i]));
  200. }
  201. if (params.n_keep > 0) {
  202. fprintf(stderr, "%s: static prompt based on n_keep: '", __func__);
  203. for (int i = 0; i < params.n_keep; i++) {
  204. fprintf(stderr, "%s", llama_token_to_str(ctx, embd_inp[i]));
  205. }
  206. fprintf(stderr, "'\n");
  207. }
  208. fprintf(stderr, "\n");
  209. }
  210. if (params.interactive) {
  211. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
  212. struct sigaction sigint_action;
  213. sigint_action.sa_handler = sigint_handler;
  214. sigemptyset (&sigint_action.sa_mask);
  215. sigint_action.sa_flags = 0;
  216. sigaction(SIGINT, &sigint_action, NULL);
  217. #elif defined (_WIN32)
  218. signal(SIGINT, sigint_handler);
  219. #endif
  220. fprintf(stderr, "%s: interactive mode on.\n", __func__);
  221. if (params.antiprompt.size()) {
  222. for (auto antiprompt : params.antiprompt) {
  223. fprintf(stderr, "Reverse prompt: '%s'\n", antiprompt.c_str());
  224. }
  225. }
  226. if (!params.input_prefix.empty()) {
  227. fprintf(stderr, "Input prefix: '%s'\n", params.input_prefix.c_str());
  228. }
  229. }
  230. 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",
  231. 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);
  232. 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);
  233. fprintf(stderr, "\n\n");
  234. // TODO: replace with ring-buffer
  235. std::vector<llama_token> last_n_tokens(n_ctx);
  236. std::fill(last_n_tokens.begin(), last_n_tokens.end(), 0);
  237. if (params.interactive) {
  238. fprintf(stderr, "== Running in interactive mode. ==\n"
  239. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__)) || defined (_WIN32)
  240. " - Press Ctrl+C to interject at any time.\n"
  241. #endif
  242. " - Press Return to return control to LLaMa.\n"
  243. " - If you want to submit another line, end your input in '\\'.\n\n");
  244. is_interacting = params.interactive_first;
  245. }
  246. bool is_antiprompt = false;
  247. bool input_echo = true;
  248. // HACK - because session saving incurs a non-negligible delay, for now skip re-saving session
  249. // if we loaded a session with at least 75% similarity. It's currently just used to speed up the
  250. // initial prompt so it doesn't need to be an exact match.
  251. bool need_to_save_session = !path_session.empty() && n_matching_session_tokens < (embd_inp.size() * 3 / 4);
  252. int n_past = 0;
  253. int n_remain = params.n_predict;
  254. int n_consumed = 0;
  255. int n_session_consumed = 0;
  256. // the first thing we will do is to output the prompt, so set color accordingly
  257. set_console_color(con_st, CONSOLE_COLOR_PROMPT);
  258. std::vector<llama_token> embd;
  259. while (n_remain != 0 || params.interactive) {
  260. // predict
  261. if (embd.size() > 0) {
  262. // infinite text generation via context swapping
  263. // if we run out of context:
  264. // - take the n_keep first tokens from the original prompt (via n_past)
  265. // - take half of the last (n_ctx - n_keep) tokens and recompute the logits in batches
  266. if (n_past + (int) embd.size() > n_ctx) {
  267. const int n_left = n_past - params.n_keep;
  268. n_past = params.n_keep;
  269. // insert n_left/2 tokens at the start of embd from last_n_tokens
  270. embd.insert(embd.begin(), last_n_tokens.begin() + n_ctx - n_left/2 - embd.size(), last_n_tokens.end() - embd.size());
  271. // stop saving session if we run out of context
  272. path_session = "";
  273. //printf("\n---\n");
  274. //printf("resetting: '");
  275. //for (int i = 0; i < (int) embd.size(); i++) {
  276. // printf("%s", llama_token_to_str(ctx, embd[i]));
  277. //}
  278. //printf("'\n");
  279. //printf("\n---\n");
  280. }
  281. // try to reuse a matching prefix from the loaded session instead of re-eval (via n_past)
  282. // REVIEW
  283. if (n_session_consumed < (int) session_tokens.size()) {
  284. size_t i = 0;
  285. for ( ; i < embd.size(); i++) {
  286. if (embd[i] != session_tokens[n_session_consumed]) {
  287. session_tokens.resize(n_session_consumed);
  288. break;
  289. }
  290. n_past++;
  291. n_session_consumed++;
  292. if (n_session_consumed >= (int) session_tokens.size()) {
  293. ++i;
  294. break;
  295. }
  296. }
  297. if (i > 0) {
  298. embd.erase(embd.begin(), embd.begin() + i);
  299. }
  300. }
  301. // evaluate tokens in batches
  302. // embd is typically prepared beforehand to fit within a batch, but not always
  303. for (int i = 0; i < (int) embd.size(); i += params.n_batch) {
  304. int n_eval = (int) embd.size() - i;
  305. if (n_eval > params.n_batch) {
  306. n_eval = params.n_batch;
  307. }
  308. if (llama_eval(ctx, &embd[i], n_eval, n_past, params.n_threads)) {
  309. fprintf(stderr, "%s : failed to eval\n", __func__);
  310. return 1;
  311. }
  312. n_past += n_eval;
  313. }
  314. if (embd.size() > 0 && !path_session.empty()) {
  315. session_tokens.insert(session_tokens.end(), embd.begin(), embd.end());
  316. n_session_consumed = session_tokens.size();
  317. }
  318. }
  319. embd.clear();
  320. if ((int) embd_inp.size() <= n_consumed && !is_interacting) {
  321. // out of user input, sample next token
  322. const float temp = params.temp;
  323. const int32_t top_k = params.top_k <= 0 ? llama_n_vocab(ctx) : params.top_k;
  324. const float top_p = params.top_p;
  325. const float tfs_z = params.tfs_z;
  326. const float typical_p = params.typical_p;
  327. const int32_t repeat_last_n = params.repeat_last_n < 0 ? n_ctx : params.repeat_last_n;
  328. const float repeat_penalty = params.repeat_penalty;
  329. const float alpha_presence = params.presence_penalty;
  330. const float alpha_frequency = params.frequency_penalty;
  331. const int mirostat = params.mirostat;
  332. const float mirostat_tau = params.mirostat_tau;
  333. const float mirostat_eta = params.mirostat_eta;
  334. const bool penalize_nl = params.penalize_nl;
  335. // optionally save the session on first sample (for faster prompt loading next time)
  336. if (!path_session.empty() && need_to_save_session) {
  337. need_to_save_session = false;
  338. llama_save_session_file(ctx, path_session.c_str(), session_tokens.data(), session_tokens.size());
  339. }
  340. llama_token id = 0;
  341. {
  342. auto logits = llama_get_logits(ctx);
  343. auto n_vocab = llama_n_vocab(ctx);
  344. // Apply params.logit_bias map
  345. for (auto it = params.logit_bias.begin(); it != params.logit_bias.end(); it++) {
  346. logits[it->first] += it->second;
  347. }
  348. std::vector<llama_token_data> candidates;
  349. candidates.reserve(n_vocab);
  350. for (llama_token token_id = 0; token_id < n_vocab; token_id++) {
  351. candidates.emplace_back(llama_token_data{token_id, logits[token_id], 0.0f});
  352. }
  353. llama_token_data_array candidates_p = { candidates.data(), candidates.size(), false };
  354. // Apply penalties
  355. float nl_logit = logits[llama_token_nl()];
  356. auto last_n_repeat = std::min(std::min((int)last_n_tokens.size(), repeat_last_n), n_ctx);
  357. llama_sample_repetition_penalty(ctx, &candidates_p,
  358. last_n_tokens.data() + last_n_tokens.size() - last_n_repeat,
  359. last_n_repeat, repeat_penalty);
  360. llama_sample_frequency_and_presence_penalties(ctx, &candidates_p,
  361. last_n_tokens.data() + last_n_tokens.size() - last_n_repeat,
  362. last_n_repeat, alpha_frequency, alpha_presence);
  363. if (!penalize_nl) {
  364. logits[llama_token_nl()] = nl_logit;
  365. }
  366. if (temp <= 0) {
  367. // Greedy sampling
  368. id = llama_sample_token_greedy(ctx, &candidates_p);
  369. } else {
  370. if (mirostat == 1) {
  371. static float mirostat_mu = 2.0f * mirostat_tau;
  372. const int mirostat_m = 100;
  373. llama_sample_temperature(ctx, &candidates_p, temp);
  374. id = llama_sample_token_mirostat(ctx, &candidates_p, mirostat_tau, mirostat_eta, mirostat_m, &mirostat_mu);
  375. } else if (mirostat == 2) {
  376. static float mirostat_mu = 2.0f * mirostat_tau;
  377. llama_sample_temperature(ctx, &candidates_p, temp);
  378. id = llama_sample_token_mirostat_v2(ctx, &candidates_p, mirostat_tau, mirostat_eta, &mirostat_mu);
  379. } else {
  380. // Temperature sampling
  381. llama_sample_top_k(ctx, &candidates_p, top_k);
  382. llama_sample_tail_free(ctx, &candidates_p, tfs_z);
  383. llama_sample_typical(ctx, &candidates_p, typical_p);
  384. llama_sample_top_p(ctx, &candidates_p, top_p);
  385. llama_sample_temperature(ctx, &candidates_p, temp);
  386. id = llama_sample_token(ctx, &candidates_p);
  387. }
  388. }
  389. // printf("`%d`", candidates_p.size);
  390. last_n_tokens.erase(last_n_tokens.begin());
  391. last_n_tokens.push_back(id);
  392. }
  393. // replace end of text token with newline token when in interactive mode
  394. if (id == llama_token_eos() && params.interactive && !params.instruct) {
  395. id = llama_token_newline.front();
  396. if (params.antiprompt.size() != 0) {
  397. // tokenize and inject first reverse prompt
  398. const auto first_antiprompt = ::llama_tokenize(ctx, params.antiprompt.front(), false);
  399. embd_inp.insert(embd_inp.end(), first_antiprompt.begin(), first_antiprompt.end());
  400. }
  401. }
  402. // add it to the context
  403. embd.push_back(id);
  404. // echo this to console
  405. input_echo = true;
  406. // decrement remaining sampling budget
  407. --n_remain;
  408. } else {
  409. // some user input remains from prompt or interaction, forward it to processing
  410. while ((int) embd_inp.size() > n_consumed) {
  411. embd.push_back(embd_inp[n_consumed]);
  412. last_n_tokens.erase(last_n_tokens.begin());
  413. last_n_tokens.push_back(embd_inp[n_consumed]);
  414. ++n_consumed;
  415. if ((int) embd.size() >= params.n_batch) {
  416. break;
  417. }
  418. }
  419. }
  420. // display text
  421. if (input_echo) {
  422. for (auto id : embd) {
  423. printf("%s", llama_token_to_str(ctx, id));
  424. }
  425. fflush(stdout);
  426. }
  427. // reset color to default if we there is no pending user input
  428. if (input_echo && (int)embd_inp.size() == n_consumed) {
  429. set_console_color(con_st, CONSOLE_COLOR_DEFAULT);
  430. }
  431. // in interactive mode, and not currently processing queued inputs;
  432. // check if we should prompt the user for more
  433. if (params.interactive && (int) embd_inp.size() <= n_consumed) {
  434. // check for reverse prompt
  435. if (params.antiprompt.size()) {
  436. std::string last_output;
  437. for (auto id : last_n_tokens) {
  438. last_output += llama_token_to_str(ctx, id);
  439. }
  440. is_antiprompt = false;
  441. // Check if each of the reverse prompts appears at the end of the output.
  442. for (std::string & antiprompt : params.antiprompt) {
  443. if (last_output.find(antiprompt.c_str(), last_output.length() - antiprompt.length(), antiprompt.length()) != std::string::npos) {
  444. is_interacting = true;
  445. is_antiprompt = true;
  446. set_console_color(con_st, CONSOLE_COLOR_USER_INPUT);
  447. fflush(stdout);
  448. break;
  449. }
  450. }
  451. }
  452. if (n_past > 0 && is_interacting) {
  453. // potentially set color to indicate we are taking user input
  454. set_console_color(con_st, CONSOLE_COLOR_USER_INPUT);
  455. #if defined (_WIN32)
  456. // Windows: must reactivate sigint handler after each signal
  457. signal(SIGINT, sigint_handler);
  458. #endif
  459. if (params.instruct) {
  460. printf("\n> ");
  461. }
  462. std::string buffer;
  463. if (!params.input_prefix.empty()) {
  464. buffer += params.input_prefix;
  465. printf("%s", buffer.c_str());
  466. }
  467. std::string line;
  468. bool another_line = true;
  469. do {
  470. #if defined(_WIN32)
  471. std::wstring wline;
  472. if (!std::getline(std::wcin, wline)) {
  473. // input stream is bad or EOF received
  474. return 0;
  475. }
  476. win32_utf8_encode(wline, line);
  477. #else
  478. if (!std::getline(std::cin, line)) {
  479. // input stream is bad or EOF received
  480. return 0;
  481. }
  482. #endif
  483. if (line.empty() || line.back() != '\\') {
  484. another_line = false;
  485. } else {
  486. line.pop_back(); // Remove the continue character
  487. }
  488. buffer += line + '\n'; // Append the line to the result
  489. } while (another_line);
  490. // done taking input, reset color
  491. set_console_color(con_st, CONSOLE_COLOR_DEFAULT);
  492. // Add tokens to embd only if the input buffer is non-empty
  493. // Entering a empty line lets the user pass control back
  494. if (buffer.length() > 1) {
  495. // instruct mode: insert instruction prefix
  496. if (params.instruct && !is_antiprompt) {
  497. n_consumed = embd_inp.size();
  498. embd_inp.insert(embd_inp.end(), inp_pfx.begin(), inp_pfx.end());
  499. }
  500. auto line_inp = ::llama_tokenize(ctx, buffer, false);
  501. embd_inp.insert(embd_inp.end(), line_inp.begin(), line_inp.end());
  502. // instruct mode: insert response suffix
  503. if (params.instruct) {
  504. embd_inp.insert(embd_inp.end(), inp_sfx.begin(), inp_sfx.end());
  505. }
  506. n_remain -= line_inp.size();
  507. }
  508. input_echo = false; // do not echo this again
  509. }
  510. if (n_past > 0) {
  511. is_interacting = false;
  512. }
  513. }
  514. // end of text token
  515. if (!embd.empty() && embd.back() == llama_token_eos()) {
  516. if (params.instruct) {
  517. is_interacting = true;
  518. } else {
  519. fprintf(stderr, " [end of text]\n");
  520. break;
  521. }
  522. }
  523. // In interactive mode, respect the maximum number of tokens and drop back to user input when reached.
  524. if (params.interactive && n_remain <= 0 && params.n_predict != -1) {
  525. n_remain = params.n_predict;
  526. is_interacting = true;
  527. }
  528. }
  529. #if defined (_WIN32)
  530. signal(SIGINT, SIG_DFL);
  531. #endif
  532. llama_print_timings(ctx);
  533. llama_free(ctx);
  534. set_console_color(con_st, CONSOLE_COLOR_DEFAULT);
  535. return 0;
  536. }