infill.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  1. #include "arg.h"
  2. #include "common.h"
  3. #include "console.h"
  4. #include "sampling.h"
  5. #include "log.h"
  6. #include "llama.h"
  7. #include <cassert>
  8. #include <cinttypes>
  9. #include <cmath>
  10. #include <cstdio>
  11. #include <cstring>
  12. #include <ctime>
  13. #include <fstream>
  14. #include <iostream>
  15. #include <sstream>
  16. #include <string>
  17. #include <vector>
  18. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
  19. #include <signal.h>
  20. #include <unistd.h>
  21. #elif defined (_WIN32)
  22. #define WIN32_LEAN_AND_MEAN
  23. #ifndef NOMINMAX
  24. #define NOMINMAX
  25. #endif
  26. #include <windows.h>
  27. #include <signal.h>
  28. #endif
  29. #if defined(_MSC_VER)
  30. #pragma warning(disable: 4244 4267) // possible loss of data
  31. #endif
  32. static llama_context ** g_ctx;
  33. static llama_model ** g_model;
  34. static common_sampler ** g_smpl;
  35. static common_params * g_params;
  36. static std::vector<llama_token> * g_input_tokens;
  37. static std::ostringstream * g_output_ss;
  38. static std::vector<llama_token> * g_output_tokens;
  39. static bool is_interacting = false;
  40. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__)) || defined (_WIN32)
  41. static void sigint_handler(int signo) {
  42. if (signo == SIGINT) {
  43. if (!is_interacting) {
  44. is_interacting = true;
  45. } else {
  46. console::cleanup();
  47. LOG("\n");
  48. common_perf_print(*g_ctx, *g_smpl);
  49. // make sure all logs are flushed
  50. LOG("Interrupted by user\n");
  51. common_log_pause(common_log_main());
  52. _exit(130);
  53. }
  54. }
  55. }
  56. #endif
  57. int main(int argc, char ** argv) {
  58. common_params params;
  59. g_params = &params;
  60. if (!common_params_parse(argc, argv, params, LLAMA_EXAMPLE_INFILL)) {
  61. return 1;
  62. }
  63. common_init();
  64. auto & sparams = params.sampling;
  65. console::init(params.simple_io, params.use_color);
  66. atexit([]() { console::cleanup(); });
  67. if (params.logits_all) {
  68. LOG_ERR("\n************\n");
  69. LOG_ERR("%s: please use the 'perplexity' tool for perplexity calculations\n", __func__);
  70. LOG_ERR("************\n\n");
  71. return 0;
  72. }
  73. if (params.embedding) {
  74. LOG_ERR("\n************\n");
  75. LOG_ERR("%s: please use the 'embedding' tool for embedding calculations\n", __func__);
  76. LOG_ERR("************\n\n");
  77. return 0;
  78. }
  79. if (params.n_ctx != 0 && params.n_ctx < 8) {
  80. LOG_WRN("%s: minimum context size is 8, using minimum size.\n", __func__);
  81. params.n_ctx = 8;
  82. }
  83. if (!params.interactive_first && (params.input_prefix.empty() && params.input_suffix.empty())) {
  84. LOG_ERR("\n************\n");
  85. LOG_ERR("%s: please use '--interactive_first' or specify '--in_prefix' and/or '--in_suffix'\n", __func__);
  86. LOG_ERR("************\n\n");
  87. return 0;
  88. }
  89. if (params.rope_freq_base != 0.0) {
  90. LOG_WRN("%s: changing RoPE frequency base to %g.\n", __func__, params.rope_freq_base);
  91. }
  92. if (params.rope_freq_scale != 0.0) {
  93. LOG_WRN("%s: scaling RoPE frequency by %g.\n", __func__, params.rope_freq_scale);
  94. }
  95. LOG_INF("%s: llama backend init\n", __func__);
  96. llama_backend_init();
  97. llama_numa_init(params.numa);
  98. llama_model * model = nullptr;
  99. llama_context * ctx = nullptr;
  100. common_sampler * smpl = nullptr;
  101. g_model = &model;
  102. g_ctx = &ctx;
  103. g_smpl = &smpl;
  104. // load the model and apply lora adapter, if any
  105. LOG_INF("%s: load the model and apply lora adapter, if any\n", __func__);
  106. common_init_result llama_init = common_init_from_params(params);
  107. model = llama_init.model;
  108. ctx = llama_init.context;
  109. if (model == NULL) {
  110. LOG_ERR("%s: unable to load model\n", __func__);
  111. return 1;
  112. }
  113. const int n_ctx_train = llama_n_ctx_train(model);
  114. const int n_ctx = llama_n_ctx(ctx);
  115. LOG_DBG("n_ctx: %d\n", n_ctx);
  116. if (n_ctx > n_ctx_train) {
  117. LOG_WRN("%s: model was trained on only %d context tokens (%d specified)\n", __func__, n_ctx_train, n_ctx);
  118. }
  119. // print system information
  120. {
  121. LOG_INF("\n");
  122. LOG_INF("%s\n", common_params_get_system_info(params).c_str());
  123. }
  124. const bool add_bos = llama_add_bos_token(model);
  125. GGML_ASSERT(!llama_add_eos_token(model));
  126. std::vector<llama_token> embd_inp;
  127. std::vector<llama_token> embd_end;
  128. std::vector<llama_token> inp_pfx = common_tokenize(ctx, params.input_prefix, false);
  129. std::vector<llama_token> inp_sfx = common_tokenize(ctx, params.input_suffix, false);
  130. GGML_ASSERT(llama_token_fim_pre(model) >= 0);
  131. GGML_ASSERT(llama_token_fim_suf(model) >= 0);
  132. inp_pfx.insert(inp_pfx.begin(), llama_token_fim_pre(model));
  133. inp_sfx.insert(inp_sfx.begin(), llama_token_fim_suf(model));
  134. embd_inp = params.spm_infill ? inp_sfx : inp_pfx;
  135. embd_end = params.spm_infill ? inp_pfx : inp_sfx;
  136. if (add_bos) {
  137. embd_inp.insert(embd_inp.begin(), llama_token_bos(model));
  138. }
  139. embd_inp.insert(embd_inp.end(), embd_end.begin(), embd_end.end());
  140. const llama_token middle_token = llama_token_fim_mid(model);
  141. if (middle_token >= 0) {
  142. embd_inp.push_back(middle_token);
  143. }
  144. LOG_DBG("add_bos: %d\n", add_bos);
  145. LOG_DBG("prefix: \"%s\"\n", params.input_prefix.c_str());
  146. LOG_DBG("suffix: \"%s\"\n", params.input_suffix.c_str());
  147. LOG_DBG("tokens: %s\n", string_from(ctx, embd_inp).c_str());
  148. // Should not run without any tokens
  149. if (embd_inp.empty()) {
  150. embd_inp.push_back(llama_token_bos(model));
  151. LOG_WRN("embd_inp was considered empty and bos was added: %s\n", string_from(ctx, embd_inp).c_str());
  152. }
  153. if ((int) embd_inp.size() > n_ctx - 4) {
  154. LOG_ERR("%s: prompt is too long (%d tokens, max %d)\n", __func__, (int) embd_inp.size(), n_ctx - 4);
  155. return 1;
  156. }
  157. // number of tokens to keep when resetting context
  158. if (params.n_keep < 0 || params.n_keep > (int) embd_inp.size()) {
  159. params.n_keep = (int)embd_inp.size();
  160. }
  161. LOG_INF("inp_pfx: %s\n", string_from(ctx, inp_pfx).c_str());
  162. LOG_INF("inp_sfx: %s\n", string_from(ctx, inp_sfx).c_str());
  163. // enable interactive mode if interactive start is specified
  164. if (params.interactive_first) {
  165. params.interactive = true;
  166. }
  167. if (params.verbose_prompt) {
  168. LOG_INF("\n");
  169. LOG_INF("%s: prompt: '%s'\n", __func__, params.prompt.c_str());
  170. LOG_INF("%s: number of tokens in prompt = %zu\n", __func__, embd_inp.size());
  171. for (int i = 0; i < (int) embd_inp.size(); i++) {
  172. LOG_INF("%6d -> '%s'\n", embd_inp[i], common_token_to_piece(ctx, embd_inp[i]).c_str());
  173. }
  174. if (params.n_keep > 0) {
  175. LOG_INF("%s: static prompt based on n_keep: '", __func__);
  176. for (int i = 0; i < params.n_keep; i++) {
  177. LOG_CNT("%s", common_token_to_piece(ctx, embd_inp[i]).c_str());
  178. }
  179. LOG_CNT("'\n");
  180. }
  181. LOG_INF("\n");
  182. }
  183. if (params.interactive) {
  184. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
  185. struct sigaction sigint_action;
  186. sigint_action.sa_handler = sigint_handler;
  187. sigemptyset (&sigint_action.sa_mask);
  188. sigint_action.sa_flags = 0;
  189. sigaction(SIGINT, &sigint_action, NULL);
  190. #elif defined (_WIN32)
  191. auto console_ctrl_handler = +[](DWORD ctrl_type) -> BOOL {
  192. return (ctrl_type == CTRL_C_EVENT) ? (sigint_handler(SIGINT), true) : false;
  193. };
  194. SetConsoleCtrlHandler(reinterpret_cast<PHANDLER_ROUTINE>(console_ctrl_handler), true);
  195. #endif
  196. LOG_INF("%s: interactive mode on.\n", __func__);
  197. if (params.input_prefix_bos) {
  198. LOG_INF("Input prefix with BOS\n");
  199. }
  200. if (!params.input_prefix.empty()) {
  201. LOG_INF("Input prefix: '%s'\n", params.input_prefix.c_str());
  202. }
  203. if (!params.input_suffix.empty()) {
  204. LOG_INF("Input suffix: '%s'\n", params.input_suffix.c_str());
  205. }
  206. }
  207. smpl = common_sampler_init(model, sparams);
  208. LOG_INF("sampler seed: %u\n", common_sampler_get_seed(smpl));
  209. LOG_INF("sampler params: \n%s\n", sparams.print().c_str());
  210. LOG_INF("sampler chain: %s\n", common_sampler_print(smpl).c_str());
  211. LOG_INF("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);
  212. LOG_INF("\n");
  213. LOG_INF("\n##### Infill mode #####\n\n");
  214. if (params.interactive) {
  215. const char *control_message;
  216. if (params.multiline_input) {
  217. control_message = " - To return control to LLaMA, end your input with '\\'.\n"
  218. " - To return control without starting a new line, end your input with '/'.\n";
  219. } else {
  220. control_message = " - Press Return to return control to LLaMA.\n"
  221. " - To return control without starting a new line, end your input with '/'.\n"
  222. " - If you want to submit another line, end your input with '\\'.\n";
  223. }
  224. LOG_INF("== Running in interactive mode. ==\n");
  225. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__)) || defined (_WIN32)
  226. LOG_INF( " - Press Ctrl+C to interject at any time.\n");
  227. #endif
  228. LOG_INF( "%s\n", control_message);
  229. is_interacting = params.interactive_first;
  230. }
  231. bool input_echo = true;
  232. int n_past = 0;
  233. int n_remain = params.n_predict;
  234. int n_consumed = 0;
  235. std::vector<int> input_tokens; g_input_tokens = &input_tokens;
  236. std::vector<int> output_tokens; g_output_tokens = &output_tokens;
  237. std::ostringstream output_ss; g_output_ss = &output_ss;
  238. // the first thing we will do is to output the prompt, so set color accordingly
  239. console::set_display(console::prompt);
  240. std::vector<llama_token> embd;
  241. while (n_remain != 0 || params.interactive) {
  242. // predict
  243. if (!embd.empty()) {
  244. // Note: n_ctx - 4 here is to match the logic for commandline prompt handling via
  245. // --prompt or --file which uses the same value.
  246. int max_embd_size = n_ctx - 4;
  247. // Ensure the input doesn't exceed the context size by truncating embd if necessary.
  248. if ((int) embd.size() > max_embd_size) {
  249. const int skipped_tokens = (int) embd.size() - max_embd_size;
  250. embd.resize(max_embd_size);
  251. console::set_display(console::error);
  252. LOG_WRN("<<input too long: skipped %d token%s>>", skipped_tokens, skipped_tokens != 1 ? "s" : "");
  253. console::set_display(console::reset);
  254. }
  255. // infinite text generation via context swapping
  256. // if we run out of context:
  257. // - take the n_keep first tokens from the original prompt (via n_past)
  258. // - take half of the last (n_ctx - n_keep) tokens and recompute the logits in batches
  259. if (n_past + (int) embd.size() > n_ctx) {
  260. if (params.n_predict == -2) {
  261. LOG_DBG("\n\n%s: context full and n_predict == -%d => stopping\n", __func__, params.n_predict);
  262. break;
  263. }
  264. const int n_left = n_past - params.n_keep - 1;
  265. const int n_discard = n_left/2;
  266. LOG_DBG("context full, swapping: n_past = %d, n_left = %d, n_ctx = %d, n_keep = %d, n_discard = %d\n",
  267. n_past, n_left, n_ctx, params.n_keep, n_discard);
  268. llama_kv_cache_seq_rm (ctx, 0, params.n_keep + 1 , params.n_keep + n_discard + 1);
  269. llama_kv_cache_seq_add(ctx, 0, params.n_keep + 1 + n_discard, n_past, -n_discard);
  270. n_past -= n_discard;
  271. LOG_DBG("after swap: n_past = %d\n", n_past);
  272. LOG_DBG("embd: %s\n", string_from(ctx, embd).c_str());
  273. }
  274. // evaluate tokens in batches
  275. // embd is typically prepared beforehand to fit within a batch, but not always
  276. for (int i = 0; i < (int) embd.size(); i += params.n_batch) {
  277. int n_eval = (int) embd.size() - i;
  278. if (n_eval > params.n_batch) {
  279. n_eval = params.n_batch;
  280. }
  281. LOG_DBG("eval: %s\n", string_from(ctx, embd).c_str());
  282. if (llama_decode(ctx, llama_batch_get_one(&embd[i], n_eval))) {
  283. LOG_ERR("%s : failed to eval\n", __func__);
  284. return 1;
  285. }
  286. n_past += n_eval;
  287. LOG_DBG("n_past = %d\n", n_past);
  288. }
  289. }
  290. embd.clear();
  291. if ((int) embd_inp.size() <= n_consumed && !is_interacting) {
  292. const llama_token id = common_sampler_sample(smpl, ctx, -1);
  293. common_sampler_accept(smpl, id, true);
  294. // LOG_DBG("last: %s\n", string_from(ctx, smpl->prev.to_vector()).c_str());
  295. embd.push_back(id);
  296. // echo this to console
  297. input_echo = true;
  298. // decrement remaining sampling budget
  299. --n_remain;
  300. LOG_DBG("n_remain: %d\n", n_remain);
  301. } else {
  302. // some user input remains from prompt or interaction, forward it to processing
  303. LOG_DBG("embd_inp.size(): %d, n_consumed: %d\n", (int) embd_inp.size(), n_consumed);
  304. while ((int) embd_inp.size() > n_consumed) {
  305. embd.push_back(embd_inp[n_consumed]);
  306. // push the prompt in the sampling context in order to apply repetition penalties later
  307. // for the prompt, we don't apply grammar rules
  308. common_sampler_accept(smpl, embd_inp[n_consumed], false);
  309. ++n_consumed;
  310. if ((int) embd.size() >= params.n_batch) {
  311. break;
  312. }
  313. }
  314. }
  315. // display text
  316. if (input_echo) {
  317. for (auto id : embd) {
  318. const std::string token_str = common_token_to_piece(ctx, id);
  319. LOG("%s", token_str.c_str());
  320. if (embd.size() > 1) {
  321. input_tokens.push_back(id);
  322. } else {
  323. output_tokens.push_back(id);
  324. output_ss << token_str;
  325. }
  326. }
  327. }
  328. // reset color to default if we there is no pending user input
  329. if (input_echo && (int) embd_inp.size() == n_consumed) {
  330. console::set_display(console::reset);
  331. }
  332. // if not currently processing queued inputs;
  333. if ((int) embd_inp.size() <= n_consumed) {
  334. // deal with eot token in infill mode
  335. if ((common_sampler_last(smpl) == llama_token_eot(model) || is_interacting) && params.interactive){
  336. if (is_interacting && !params.interactive_first) {
  337. // print an eot token
  338. LOG("%s", common_token_to_piece(ctx, llama_token_eot(model)).c_str());
  339. }
  340. LOG("\n");
  341. console::set_display(console::user_input);
  342. std::string buffer;
  343. std::string line;
  344. bool another_line=true;
  345. // set a new prefix via stdin
  346. do {
  347. another_line = console::readline(line, params.multiline_input);
  348. buffer += line;
  349. } while (another_line);
  350. // check if we got an empty line, if so we use the old input
  351. if (!buffer.empty() && !(buffer.length() == 1 && buffer[0] == '\n')) {
  352. params.input_prefix = buffer;
  353. }
  354. buffer.clear();
  355. // set a new suffix via stdin
  356. do {
  357. another_line = console::readline(line, params.multiline_input);
  358. buffer += line;
  359. } while (another_line);
  360. // check if we got an empty line
  361. if (!buffer.empty() && !(buffer.length() == 1 && buffer[0] == '\n')) {
  362. params.input_suffix = buffer;
  363. }
  364. buffer.clear();
  365. // done taking input, reset color
  366. console::set_display(console::reset);
  367. if (params.escape) {
  368. //process escape sequences, for the initial prompt this is done in common.cpp when we load the params, but for the interactive mode we need to do it here
  369. string_process_escapes(params.input_prefix);
  370. string_process_escapes(params.input_suffix);
  371. }
  372. // tokenize new prefix and suffix
  373. std::vector<llama_token> inp_pfx = common_tokenize(ctx, params.input_prefix, false);
  374. std::vector<llama_token> inp_sfx = common_tokenize(ctx, params.input_suffix, false);
  375. inp_pfx.insert(inp_pfx.begin(), llama_token_fim_pre(model));
  376. inp_sfx.insert(inp_sfx.begin(), llama_token_fim_suf(model));
  377. embd_inp = params.spm_infill ? inp_sfx : inp_pfx;
  378. embd_end = params.spm_infill ? inp_pfx : inp_sfx;
  379. if (add_bos) {
  380. embd_inp.insert(embd_inp.begin(), llama_token_bos(model));
  381. }
  382. embd_inp.insert(embd_inp.end(), embd_end.begin(), embd_end.end());
  383. if (middle_token >= 0) {
  384. embd_inp.push_back(middle_token);
  385. }
  386. embd.clear();
  387. n_remain = params.n_predict;
  388. n_past = 0;
  389. n_consumed = 0;
  390. is_interacting = false;
  391. }
  392. // deal with end of generation tokens in interactive mode
  393. else if (llama_token_is_eog(model, common_sampler_last(smpl))) {
  394. LOG_DBG("found EOS token\n");
  395. if (params.interactive) {
  396. is_interacting = true;
  397. LOG("\n");
  398. console::set_display(console::user_input);
  399. }
  400. }
  401. if (n_past > 0 && is_interacting && !params.interactive) {
  402. LOG_DBG("waiting for user input\n");
  403. if (params.input_prefix_bos) {
  404. LOG_DBG("adding input prefix BOS token\n");
  405. embd_inp.push_back(llama_token_bos(model));
  406. }
  407. std::string buffer;
  408. if (!params.input_prefix.empty()) {
  409. LOG_DBG("appending input prefix: '%s'\n", params.input_prefix.c_str());
  410. buffer += params.input_prefix;
  411. LOG("%s", buffer.c_str());
  412. }
  413. std::string line;
  414. bool another_line = true;
  415. do {
  416. another_line = console::readline(line, params.multiline_input);
  417. buffer += line;
  418. } while (another_line);
  419. // done taking input, reset color
  420. console::set_display(console::reset);
  421. // Add tokens to embd only if the input buffer is non-empty
  422. // Entering a empty line lets the user pass control back
  423. if (buffer.length() > 1) {
  424. // append input suffix if any
  425. if (!params.input_suffix.empty()) {
  426. LOG_DBG("appending input suffix: '%s'\n", params.input_suffix.c_str());
  427. buffer += params.input_suffix;
  428. LOG("%s", params.input_suffix.c_str());
  429. }
  430. LOG_DBG("buffer: '%s'\n", buffer.c_str());
  431. const size_t original_size = embd_inp.size();
  432. const auto line_inp = common_tokenize(ctx, buffer, false);
  433. LOG_DBG("input tokens: %s\n", string_from(ctx, line_inp).c_str());
  434. embd_inp.insert(embd_inp.end(), line_inp.begin(), line_inp.end());
  435. for (size_t i = original_size; i < embd_inp.size(); ++i) {
  436. const llama_token token = embd_inp[i];
  437. output_tokens.push_back(token);
  438. output_ss << common_token_to_piece(ctx, token);
  439. }
  440. n_remain -= line_inp.size();
  441. LOG_DBG("n_remain: %d\n", n_remain);
  442. } else {
  443. LOG_DBG("empty line, passing control back\n");
  444. }
  445. input_echo = false; // do not echo this again
  446. }
  447. if (n_past > 0) {
  448. if (is_interacting) {
  449. common_sampler_reset(smpl);
  450. }
  451. is_interacting = false;
  452. }
  453. }
  454. // end of generation
  455. if (!embd.empty() && llama_token_is_eog(model, embd.back()) && !params.interactive) {
  456. break;
  457. }
  458. // In interactive mode, respect the maximum number of tokens and drop back to user input when reached.
  459. // We skip this logic when n_predict == -1 (infinite) or -2 (stop at context size).
  460. if (params.interactive && n_remain <= 0 && params.n_predict >= 0) {
  461. n_remain = params.n_predict;
  462. is_interacting = true;
  463. }
  464. }
  465. if (!params.interactive && n_remain <= 0) {
  466. LOG("%s", common_token_to_piece(ctx, llama_token_eot(model)).c_str());
  467. }
  468. LOG("\n");
  469. common_perf_print(ctx, smpl);
  470. llama_free(ctx);
  471. llama_free_model(model);
  472. common_sampler_free(smpl);
  473. llama_backend_free();
  474. return 0;
  475. }