1
0

infill.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590
  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.get();
  108. ctx = llama_init.context.get();
  109. if (model == NULL) {
  110. LOG_ERR("%s: unable to load model\n", __func__);
  111. return 1;
  112. }
  113. const llama_vocab * vocab = llama_model_get_vocab(model);
  114. const int n_ctx_train = llama_model_n_ctx_train(model);
  115. const int n_ctx = llama_n_ctx(ctx);
  116. LOG_DBG("n_ctx: %d\n", n_ctx);
  117. if (n_ctx > n_ctx_train) {
  118. LOG_WRN("%s: model was trained on only %d context tokens (%d specified)\n", __func__, n_ctx_train, n_ctx);
  119. }
  120. // print system information
  121. {
  122. LOG_INF("\n");
  123. LOG_INF("%s\n", common_params_get_system_info(params).c_str());
  124. }
  125. const bool add_bos = llama_vocab_get_add_bos(vocab);
  126. GGML_ASSERT(!llama_vocab_get_add_eos(vocab));
  127. std::vector<llama_token> embd_inp;
  128. std::vector<llama_token> embd_end;
  129. std::vector<llama_token> inp_pfx = common_tokenize(ctx, params.input_prefix, false);
  130. std::vector<llama_token> inp_sfx = common_tokenize(ctx, params.input_suffix, false);
  131. GGML_ASSERT(llama_vocab_fim_pre(vocab) >= 0);
  132. GGML_ASSERT(llama_vocab_fim_suf(vocab) >= 0);
  133. inp_pfx.insert(inp_pfx.begin(), llama_vocab_fim_pre(vocab));
  134. inp_sfx.insert(inp_sfx.begin(), llama_vocab_fim_suf(vocab));
  135. embd_inp = params.spm_infill ? inp_sfx : inp_pfx;
  136. embd_end = params.spm_infill ? inp_pfx : inp_sfx;
  137. if (add_bos) {
  138. embd_inp.insert(embd_inp.begin(), llama_vocab_bos(vocab));
  139. }
  140. embd_inp.insert(embd_inp.end(), embd_end.begin(), embd_end.end());
  141. const llama_token middle_token = llama_vocab_fim_mid(vocab);
  142. if (middle_token >= 0) {
  143. embd_inp.push_back(middle_token);
  144. }
  145. LOG_DBG("add_bos: %d\n", add_bos);
  146. LOG_DBG("prefix: \"%s\"\n", params.input_prefix.c_str());
  147. LOG_DBG("suffix: \"%s\"\n", params.input_suffix.c_str());
  148. LOG_DBG("tokens: %s\n", string_from(ctx, embd_inp).c_str());
  149. // Should not run without any tokens
  150. if (embd_inp.empty()) {
  151. embd_inp.push_back(llama_vocab_bos(vocab));
  152. LOG_WRN("embd_inp was considered empty and bos was added: %s\n", string_from(ctx, embd_inp).c_str());
  153. }
  154. if ((int) embd_inp.size() > n_ctx - 4) {
  155. LOG_ERR("%s: prompt is too long (%d tokens, max %d)\n", __func__, (int) embd_inp.size(), n_ctx - 4);
  156. return 1;
  157. }
  158. // number of tokens to keep when resetting context
  159. if (params.n_keep < 0 || params.n_keep > (int) embd_inp.size()) {
  160. params.n_keep = (int)embd_inp.size();
  161. }
  162. LOG_INF("inp_pfx: %s\n", string_from(ctx, inp_pfx).c_str());
  163. LOG_INF("inp_sfx: %s\n", string_from(ctx, inp_sfx).c_str());
  164. // enable interactive mode if interactive start is specified
  165. if (params.interactive_first) {
  166. params.interactive = true;
  167. }
  168. if (params.verbose_prompt) {
  169. LOG_INF("\n");
  170. LOG_INF("%s: prompt: '%s'\n", __func__, params.prompt.c_str());
  171. LOG_INF("%s: number of tokens in prompt = %zu\n", __func__, embd_inp.size());
  172. for (int i = 0; i < (int) embd_inp.size(); i++) {
  173. LOG_INF("%6d -> '%s'\n", embd_inp[i], common_token_to_piece(ctx, embd_inp[i]).c_str());
  174. }
  175. if (params.n_keep > 0) {
  176. LOG_INF("%s: static prompt based on n_keep: '", __func__);
  177. for (int i = 0; i < params.n_keep; i++) {
  178. LOG_CNT("%s", common_token_to_piece(ctx, embd_inp[i]).c_str());
  179. }
  180. LOG_CNT("'\n");
  181. }
  182. LOG_INF("\n");
  183. }
  184. if (params.interactive) {
  185. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
  186. struct sigaction sigint_action;
  187. sigint_action.sa_handler = sigint_handler;
  188. sigemptyset (&sigint_action.sa_mask);
  189. sigint_action.sa_flags = 0;
  190. sigaction(SIGINT, &sigint_action, NULL);
  191. #elif defined (_WIN32)
  192. auto console_ctrl_handler = +[](DWORD ctrl_type) -> BOOL {
  193. return (ctrl_type == CTRL_C_EVENT) ? (sigint_handler(SIGINT), true) : false;
  194. };
  195. SetConsoleCtrlHandler(reinterpret_cast<PHANDLER_ROUTINE>(console_ctrl_handler), true);
  196. #endif
  197. LOG_INF("%s: interactive mode on.\n", __func__);
  198. if (params.input_prefix_bos) {
  199. LOG_INF("Input prefix with BOS\n");
  200. }
  201. if (!params.input_prefix.empty()) {
  202. LOG_INF("Input prefix: '%s'\n", params.input_prefix.c_str());
  203. }
  204. if (!params.input_suffix.empty()) {
  205. LOG_INF("Input suffix: '%s'\n", params.input_suffix.c_str());
  206. }
  207. }
  208. smpl = common_sampler_init(model, sparams);
  209. LOG_INF("sampler seed: %u\n", common_sampler_get_seed(smpl));
  210. LOG_INF("sampler params: \n%s\n", sparams.print().c_str());
  211. LOG_INF("sampler chain: %s\n", common_sampler_print(smpl).c_str());
  212. 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);
  213. LOG_INF("\n");
  214. LOG_INF("\n##### Infill mode #####\n\n");
  215. if (params.interactive) {
  216. const char *control_message;
  217. if (params.multiline_input) {
  218. control_message = " - To return control to LLaMA, end your input with '\\'.\n"
  219. " - To return control without starting a new line, end your input with '/'.\n";
  220. } else {
  221. control_message = " - Press Return to return control to LLaMA.\n"
  222. " - To return control without starting a new line, end your input with '/'.\n"
  223. " - If you want to submit another line, end your input with '\\'.\n";
  224. }
  225. LOG_INF("== Running in interactive mode. ==\n");
  226. #if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__)) || defined (_WIN32)
  227. LOG_INF( " - Press Ctrl+C to interject at any time.\n");
  228. #endif
  229. LOG_INF( "%s\n", control_message);
  230. is_interacting = params.interactive_first;
  231. }
  232. bool input_echo = true;
  233. int n_past = 0;
  234. int n_remain = params.n_predict;
  235. int n_consumed = 0;
  236. std::vector<int> input_tokens; g_input_tokens = &input_tokens;
  237. std::vector<int> output_tokens; g_output_tokens = &output_tokens;
  238. std::ostringstream output_ss; g_output_ss = &output_ss;
  239. // the first thing we will do is to output the prompt, so set color accordingly
  240. console::set_display(console::prompt);
  241. std::vector<llama_token> embd;
  242. while (n_remain != 0 || params.interactive) {
  243. // predict
  244. if (!embd.empty()) {
  245. // Note: n_ctx - 4 here is to match the logic for commandline prompt handling via
  246. // --prompt or --file which uses the same value.
  247. int max_embd_size = n_ctx - 4;
  248. // Ensure the input doesn't exceed the context size by truncating embd if necessary.
  249. if ((int) embd.size() > max_embd_size) {
  250. const int skipped_tokens = (int) embd.size() - max_embd_size;
  251. embd.resize(max_embd_size);
  252. console::set_display(console::error);
  253. LOG_WRN("<<input too long: skipped %d token%s>>", skipped_tokens, skipped_tokens != 1 ? "s" : "");
  254. console::set_display(console::reset);
  255. }
  256. // infinite text generation via context swapping
  257. // if we run out of context:
  258. // - take the n_keep first tokens from the original prompt (via n_past)
  259. // - take half of the last (n_ctx - n_keep) tokens and recompute the logits in batches
  260. if (n_past + (int) embd.size() > n_ctx) {
  261. if (params.n_predict == -2) {
  262. LOG_DBG("\n\n%s: context full and n_predict == -%d => stopping\n", __func__, params.n_predict);
  263. break;
  264. }
  265. const int n_left = n_past - params.n_keep - 1;
  266. const int n_discard = n_left/2;
  267. LOG_DBG("context full, swapping: n_past = %d, n_left = %d, n_ctx = %d, n_keep = %d, n_discard = %d\n",
  268. n_past, n_left, n_ctx, params.n_keep, n_discard);
  269. llama_kv_cache_seq_rm (ctx, 0, params.n_keep + 1 , params.n_keep + n_discard + 1);
  270. llama_kv_cache_seq_add(ctx, 0, params.n_keep + 1 + n_discard, n_past, -n_discard);
  271. n_past -= n_discard;
  272. LOG_DBG("after swap: n_past = %d\n", n_past);
  273. LOG_DBG("embd: %s\n", string_from(ctx, embd).c_str());
  274. }
  275. // evaluate tokens in batches
  276. // embd is typically prepared beforehand to fit within a batch, but not always
  277. for (int i = 0; i < (int) embd.size(); i += params.n_batch) {
  278. int n_eval = (int) embd.size() - i;
  279. if (n_eval > params.n_batch) {
  280. n_eval = params.n_batch;
  281. }
  282. LOG_DBG("eval: %s\n", string_from(ctx, embd).c_str());
  283. if (llama_decode(ctx, llama_batch_get_one(&embd[i], n_eval))) {
  284. LOG_ERR("%s : failed to eval\n", __func__);
  285. return 1;
  286. }
  287. n_past += n_eval;
  288. LOG_DBG("n_past = %d\n", n_past);
  289. }
  290. }
  291. embd.clear();
  292. if ((int) embd_inp.size() <= n_consumed && !is_interacting) {
  293. const llama_token id = common_sampler_sample(smpl, ctx, -1);
  294. common_sampler_accept(smpl, id, true);
  295. // LOG_DBG("last: %s\n", string_from(ctx, smpl->prev.to_vector()).c_str());
  296. embd.push_back(id);
  297. // echo this to console
  298. input_echo = true;
  299. // decrement remaining sampling budget
  300. --n_remain;
  301. LOG_DBG("n_remain: %d\n", n_remain);
  302. } else {
  303. // some user input remains from prompt or interaction, forward it to processing
  304. LOG_DBG("embd_inp.size(): %d, n_consumed: %d\n", (int) embd_inp.size(), n_consumed);
  305. while ((int) embd_inp.size() > n_consumed) {
  306. embd.push_back(embd_inp[n_consumed]);
  307. // push the prompt in the sampling context in order to apply repetition penalties later
  308. // for the prompt, we don't apply grammar rules
  309. common_sampler_accept(smpl, embd_inp[n_consumed], false);
  310. ++n_consumed;
  311. if ((int) embd.size() >= params.n_batch) {
  312. break;
  313. }
  314. }
  315. }
  316. // display text
  317. if (input_echo) {
  318. for (auto id : embd) {
  319. const std::string token_str = common_token_to_piece(ctx, id);
  320. LOG("%s", token_str.c_str());
  321. if (embd.size() > 1) {
  322. input_tokens.push_back(id);
  323. } else {
  324. output_tokens.push_back(id);
  325. output_ss << token_str;
  326. }
  327. }
  328. }
  329. // reset color to default if we there is no pending user input
  330. if (input_echo && (int) embd_inp.size() == n_consumed) {
  331. console::set_display(console::reset);
  332. }
  333. // if not currently processing queued inputs;
  334. if ((int) embd_inp.size() <= n_consumed) {
  335. // deal with eot token in infill mode
  336. if ((common_sampler_last(smpl) == llama_vocab_eot(vocab) || is_interacting) && params.interactive){
  337. if (is_interacting && !params.interactive_first) {
  338. // print an eot token
  339. LOG("%s", common_token_to_piece(ctx, llama_vocab_eot(vocab)).c_str());
  340. }
  341. LOG("\n");
  342. console::set_display(console::user_input);
  343. std::string buffer;
  344. std::string line;
  345. bool another_line=true;
  346. // set a new prefix via stdin
  347. do {
  348. another_line = console::readline(line, params.multiline_input);
  349. buffer += line;
  350. } while (another_line);
  351. // check if we got an empty line, if so we use the old input
  352. if (!buffer.empty() && !(buffer.length() == 1 && buffer[0] == '\n')) {
  353. params.input_prefix = buffer;
  354. }
  355. buffer.clear();
  356. // set a new suffix via stdin
  357. do {
  358. another_line = console::readline(line, params.multiline_input);
  359. buffer += line;
  360. } while (another_line);
  361. // check if we got an empty line
  362. if (!buffer.empty() && !(buffer.length() == 1 && buffer[0] == '\n')) {
  363. params.input_suffix = buffer;
  364. }
  365. buffer.clear();
  366. // done taking input, reset color
  367. console::set_display(console::reset);
  368. if (params.escape) {
  369. //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
  370. string_process_escapes(params.input_prefix);
  371. string_process_escapes(params.input_suffix);
  372. }
  373. // tokenize new prefix and suffix
  374. std::vector<llama_token> inp_pfx = common_tokenize(ctx, params.input_prefix, false);
  375. std::vector<llama_token> inp_sfx = common_tokenize(ctx, params.input_suffix, false);
  376. inp_pfx.insert(inp_pfx.begin(), llama_vocab_fim_pre(vocab));
  377. inp_sfx.insert(inp_sfx.begin(), llama_vocab_fim_suf(vocab));
  378. embd_inp = params.spm_infill ? inp_sfx : inp_pfx;
  379. embd_end = params.spm_infill ? inp_pfx : inp_sfx;
  380. if (add_bos) {
  381. embd_inp.insert(embd_inp.begin(), llama_vocab_bos(vocab));
  382. }
  383. embd_inp.insert(embd_inp.end(), embd_end.begin(), embd_end.end());
  384. if (middle_token >= 0) {
  385. embd_inp.push_back(middle_token);
  386. }
  387. embd.clear();
  388. n_remain = params.n_predict;
  389. n_past = 0;
  390. n_consumed = 0;
  391. is_interacting = false;
  392. }
  393. // deal with end of generation tokens in interactive mode
  394. else if (llama_vocab_is_eog(vocab, common_sampler_last(smpl))) {
  395. LOG_DBG("found EOS token\n");
  396. if (params.interactive) {
  397. is_interacting = true;
  398. LOG("\n");
  399. console::set_display(console::user_input);
  400. }
  401. }
  402. if (n_past > 0 && is_interacting && !params.interactive) {
  403. LOG_DBG("waiting for user input\n");
  404. if (params.input_prefix_bos) {
  405. LOG_DBG("adding input prefix BOS token\n");
  406. embd_inp.push_back(llama_vocab_bos(vocab));
  407. }
  408. std::string buffer;
  409. if (!params.input_prefix.empty()) {
  410. LOG_DBG("appending input prefix: '%s'\n", params.input_prefix.c_str());
  411. buffer += params.input_prefix;
  412. LOG("%s", buffer.c_str());
  413. }
  414. std::string line;
  415. bool another_line = true;
  416. do {
  417. another_line = console::readline(line, params.multiline_input);
  418. buffer += line;
  419. } while (another_line);
  420. // done taking input, reset color
  421. console::set_display(console::reset);
  422. // Add tokens to embd only if the input buffer is non-empty
  423. // Entering a empty line lets the user pass control back
  424. if (buffer.length() > 1) {
  425. // append input suffix if any
  426. if (!params.input_suffix.empty()) {
  427. LOG_DBG("appending input suffix: '%s'\n", params.input_suffix.c_str());
  428. buffer += params.input_suffix;
  429. LOG("%s", params.input_suffix.c_str());
  430. }
  431. LOG_DBG("buffer: '%s'\n", buffer.c_str());
  432. const size_t original_size = embd_inp.size();
  433. const auto line_inp = common_tokenize(ctx, buffer, false);
  434. LOG_DBG("input tokens: %s\n", string_from(ctx, line_inp).c_str());
  435. embd_inp.insert(embd_inp.end(), line_inp.begin(), line_inp.end());
  436. for (size_t i = original_size; i < embd_inp.size(); ++i) {
  437. const llama_token token = embd_inp[i];
  438. output_tokens.push_back(token);
  439. output_ss << common_token_to_piece(ctx, token);
  440. }
  441. n_remain -= line_inp.size();
  442. LOG_DBG("n_remain: %d\n", n_remain);
  443. } else {
  444. LOG_DBG("empty line, passing control back\n");
  445. }
  446. input_echo = false; // do not echo this again
  447. }
  448. if (n_past > 0) {
  449. if (is_interacting) {
  450. common_sampler_reset(smpl);
  451. }
  452. is_interacting = false;
  453. }
  454. }
  455. // end of generation
  456. if (!embd.empty() && llama_vocab_is_eog(vocab, embd.back()) && !params.interactive) {
  457. break;
  458. }
  459. // In interactive mode, respect the maximum number of tokens and drop back to user input when reached.
  460. // We skip this logic when n_predict == -1 (infinite) or -2 (stop at context size).
  461. if (params.interactive && n_remain <= 0 && params.n_predict >= 0) {
  462. n_remain = params.n_predict;
  463. is_interacting = true;
  464. }
  465. }
  466. if (!params.interactive && n_remain <= 0) {
  467. LOG("%s", common_token_to_piece(ctx, llama_vocab_eot(vocab)).c_str());
  468. }
  469. LOG("\n");
  470. common_perf_print(ctx, smpl);
  471. common_sampler_free(smpl);
  472. llama_backend_free();
  473. return 0;
  474. }