lookahead.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  1. #include "arg.h"
  2. #include "common.h"
  3. #include "sampling.h"
  4. #include "log.h"
  5. #include "llama.h"
  6. #include <cstdio>
  7. #include <string>
  8. #include <vector>
  9. #include <algorithm>
  10. struct ngram_data {
  11. bool active = false;
  12. llama_seq_id seq_id = -1;
  13. std::vector<int> i_batch;
  14. std::vector<llama_token> tokens;
  15. };
  16. // n-gram container
  17. struct ngram_container {
  18. ngram_container(int n_vocab, int N, int G) {
  19. cnt.resize(n_vocab);
  20. head.resize(n_vocab);
  21. tokens.resize(n_vocab * G * (N - 1));
  22. }
  23. int n_total = 0;
  24. std::vector<int> cnt;
  25. std::vector<int> head;
  26. // [n_vocab][G][N - 1]
  27. // for each token of the vocab, keep a ring-buffer of capacity G of n-grams of size N - 1
  28. std::vector<llama_token> tokens;
  29. };
  30. int main(int argc, char ** argv) {
  31. common_params params;
  32. if (!common_params_parse(argc, argv, params, LLAMA_EXAMPLE_COMMON)) {
  33. return 1;
  34. }
  35. common_init();
  36. const int W = 15; // lookahead window
  37. const int N = 5; // n-gram size
  38. const int G = 15; // max verification n-grams
  39. // init llama.cpp
  40. llama_backend_init();
  41. llama_numa_init(params.numa);
  42. // load the target model
  43. common_init_result llama_init = common_init_from_params(params);
  44. llama_model * model = llama_init.model.get();
  45. llama_context * ctx = llama_init.context.get();
  46. auto * mem = llama_get_memory(ctx);
  47. const llama_vocab * vocab = llama_model_get_vocab(model);
  48. // Tokenize the prompt
  49. std::vector<llama_token> inp;
  50. std::vector<llama_token> all;
  51. inp = common_tokenize(ctx, params.prompt, true, true);
  52. all = inp;
  53. const int max_context_size = llama_n_ctx(ctx);
  54. const int max_tokens_list_size = max_context_size - 4;
  55. if ((int) inp.size() > max_tokens_list_size) {
  56. LOG_ERR("%s: prompt too long (%d tokens, max %d)\n", __func__, (int) inp.size(), max_tokens_list_size);
  57. return 1;
  58. }
  59. LOG("\n\n");
  60. for (auto id : inp) {
  61. LOG("%s", common_token_to_piece(ctx, id).c_str());
  62. }
  63. fflush(stderr);
  64. const int n_input = inp.size();
  65. const auto t_enc_start = ggml_time_us();
  66. // eval the prompt
  67. llama_decode(ctx, llama_batch_get_one( inp.data(), n_input - 1));
  68. llama_decode(ctx, llama_batch_get_one(&inp.back(), 1));
  69. for (int s = 1; s < W + G + 1; ++s) {
  70. llama_memory_seq_cp(mem, 0, s, -1, -1);
  71. }
  72. const auto t_enc_end = ggml_time_us();
  73. int n_predict = 0;
  74. int n_accept = 0;
  75. int n_past = inp.size();
  76. llama_token id = 0;
  77. // used to determine end of generation
  78. bool has_eos = false;
  79. // for each decoded batch, we have at most W + G + 1 distinct sequences:
  80. // seq_id == 0 : the current input token
  81. // seq_id [1, W] : tokens from the past N - 1 Jacobi iterations
  82. // seq_id [W + 1, W + G] : verification n-grams
  83. llama_batch batch = llama_batch_init(params.n_ctx, 0, W + G + 1);
  84. // target model sampling context
  85. struct common_sampler * smpl = common_sampler_init(model, params.sampling);
  86. // verification n-grams
  87. std::vector<ngram_data> ngrams_cur(G);
  88. // tokens for the past N - 1 Jacobi iterations
  89. std::vector<llama_token> tokens_j_prev(W);
  90. std::vector<std::vector<llama_token>> tokens_j(N - 1);
  91. for (int j = 0; j < N - 1; j++) {
  92. tokens_j[j].resize(W);
  93. for (int i = 0; i < W; i++) {
  94. // there are different ways to init these tokens
  95. if (0) {
  96. // initialize randomly from the prompt tokens
  97. tokens_j[j][i] = all[1 + rand() % (all.size() - 1)];
  98. } else {
  99. // initialize with a sequence of increasing numbers
  100. tokens_j[j][i] = 100 + i;
  101. }
  102. }
  103. }
  104. std::vector<llama_seq_id> seq_id_look;
  105. // the input token belongs both to all sequences
  106. std::vector<llama_seq_id> seq_id_all(W + G + 1);
  107. for (int i = 0; i < W + G + 1; i++) {
  108. seq_id_all[i] = i;
  109. }
  110. // here we keep adding new n-grams as we go
  111. ngram_container ngrams_observed(llama_vocab_n_tokens(vocab), N, G);
  112. const auto t_dec_start = ggml_time_us();
  113. // sample first token
  114. {
  115. id = common_sampler_sample(smpl, ctx, 0);
  116. common_sampler_accept(smpl, id, true);
  117. {
  118. const std::string token_str = common_token_to_piece(ctx, id);
  119. LOG("%s", token_str.c_str());
  120. fflush(stdout);
  121. }
  122. }
  123. while (true) {
  124. // build the mask from https://lmsys.org/blog/2023-11-21-lookahead-decoding/
  125. //
  126. // Example for W = 5, N = 4, G = 2:
  127. // (I = input, L = lookahead, V = verification)
  128. //
  129. // Batch: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
  130. // T: -2 -2 -2 -2 -1 -1 -1 -1 -1 0 0 0 0 0 0
  131. // Info: I L L L L L L L L L L L L L L V V V V V V
  132. // Pos: 0 1 2 3 4 1 2 3 4 5 2 3 4 5 6 1 2 3 1 2 3 (+ n_past)
  133. // Logits: 1 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1
  134. // ---------------------------------------------------------------------
  135. // Seq: 0
  136. // 1 1 1
  137. // 2 2 2 2
  138. // 3 3 3 3 3
  139. // 4 4 4 4 4 4
  140. // 5 5 5 5 5 5 5
  141. // 6 6 6 6
  142. // 7 7 7 7
  143. // ---------------------------------------------------------------------
  144. // | | | | | | | | | | |
  145. // V V V V V | | | | | |
  146. // j_tokens | | | | | |
  147. // V V V V V V
  148. // id
  149. {
  150. common_batch_clear(batch);
  151. // current token - first token of the first level
  152. common_batch_add(batch, id, n_past, seq_id_all, true);
  153. // verification n-grams - queue this before the lookahead tokens for less KV cache fragmentation
  154. {
  155. const int g_cur = ngrams_observed.cnt[id];
  156. ngrams_cur.resize(g_cur);
  157. for (int g = 0; g < g_cur; g++) {
  158. ngrams_cur[g].active = true;
  159. ngrams_cur[g].tokens.resize(N);
  160. ngrams_cur[g].i_batch.resize(N);
  161. ngrams_cur[g].seq_id = W + 1 + g;
  162. ngrams_cur[g].i_batch[0] = 0;
  163. ngrams_cur[g].tokens [0] = id;
  164. }
  165. for (int j = 0; j < N - 1; j++) {
  166. for (int g = 0; g < g_cur; g++) {
  167. const int idx = id*(N - 1)*G + g*(N - 1);
  168. const llama_token t = ngrams_observed.tokens[idx + j];
  169. ngrams_cur[g].tokens [j + 1] = t;
  170. ngrams_cur[g].i_batch[j + 1] = batch.n_tokens;
  171. common_batch_add(batch, t, n_past + j + 1, { W + 1 + g }, true);
  172. }
  173. }
  174. }
  175. // fill the remaining W - 1 tokens for the first level
  176. for (int i = 1; i < W; i++) {
  177. seq_id_look.resize(W - i);
  178. for (int j = 0; j < W - i; j++) {
  179. seq_id_look[j] = i + j + 1;
  180. }
  181. common_batch_add(batch, tokens_j[0][i], n_past + i, seq_id_look, false);
  182. }
  183. // fill the rest of the levels
  184. for (int j = 1; j < N - 1; j++) {
  185. for (int i = 0; i < W; i++) {
  186. common_batch_add(batch, tokens_j[j][i], n_past + j + i, { i + 1 }, j == N - 2);
  187. }
  188. }
  189. }
  190. if (llama_decode(ctx, batch) != 0) {
  191. LOG_ERR("\n\n%s: llama_decode failed - increase KV cache size\n", __func__);
  192. return 1;
  193. }
  194. int seq_id_best = 0;
  195. for (int v = 0; v < N; ++v) {
  196. int i_batch = 0;
  197. // if no active ngrams are left, it means the sampled token does not pass the verification
  198. if (v > 0) {
  199. for (int g = 0; g < (int) ngrams_cur.size(); g++) {
  200. if (ngrams_cur[g].active) {
  201. i_batch = ngrams_cur[g].i_batch[v];
  202. seq_id_best = ngrams_cur[g].seq_id;
  203. ++n_accept;
  204. break;
  205. }
  206. }
  207. // no more matches -> create a new batch
  208. if (i_batch == 0) {
  209. break;
  210. }
  211. }
  212. // sample the next token
  213. id = common_sampler_sample(smpl, ctx, i_batch);
  214. common_sampler_accept(smpl, id, true);
  215. // print
  216. {
  217. const std::string token_str = common_token_to_piece(ctx, id);
  218. if (v == 0) {
  219. LOG("%s", token_str.c_str());
  220. } else {
  221. // print light cyan
  222. LOG("\033[0;96m%s\033[0m", token_str.c_str());
  223. }
  224. fflush(stdout);
  225. if (llama_vocab_is_eog(vocab, id)) {
  226. has_eos = true;
  227. }
  228. all.push_back(id);
  229. }
  230. ++n_predict;
  231. ++n_past;
  232. if ((params.n_predict >= 0 && n_predict > params.n_predict) || has_eos) {
  233. break;
  234. }
  235. // verify across active n-grams
  236. for (int g = 0; g < (int) ngrams_cur.size(); g++) {
  237. if (ngrams_cur[g].active) {
  238. if (v == N - 1) {
  239. ngrams_cur[g].active = false;
  240. } else {
  241. if (id != ngrams_cur[g].tokens[v + 1]) {
  242. ngrams_cur[g].active = false;
  243. }
  244. }
  245. }
  246. }
  247. // print known n-grams starting with token id (debug)
  248. if (0 && v == 0) {
  249. if (ngrams_observed.cnt[id] > 0) {
  250. LOG("\n - %d n-grams starting with '%s'\n", ngrams_observed.cnt[id], common_token_to_piece(ctx, id).c_str());
  251. }
  252. for (int i = 0; i < ngrams_observed.cnt[id]; i++) {
  253. LOG(" - ngram %2d: ", i);
  254. const int idx = id*(N - 1)*G + i*(N - 1);
  255. for (int j = 0; j < N - 1; j++) {
  256. const std::string token_str = common_token_to_piece(ctx, ngrams_observed.tokens[idx + j]);
  257. LOG("%s", token_str.c_str());
  258. }
  259. LOG("\n");
  260. }
  261. }
  262. // update lookahead tokens
  263. {
  264. for (int i = 0; i < W; i++) {
  265. tokens_j_prev[i] = tokens_j[0][i];
  266. }
  267. for (int j = 0; j < N - 2; j++) {
  268. tokens_j[j] = tokens_j[j + 1];
  269. }
  270. if (v == 0) {
  271. // sample from the last level
  272. for (int i = 0; i < W; i++) {
  273. tokens_j[N - 2][i] = common_sampler_sample(smpl, ctx, ngrams_cur.size()*(N-1) + W*(N - 2) + i);
  274. }
  275. } else {
  276. for (int i = 0; i < W; i++) {
  277. // there are different ways to init these tokens
  278. if (0) {
  279. // random init
  280. tokens_j[N - 2][i] = all[1 + rand() % (all.size() - 1)];
  281. } else {
  282. // init from the previous level
  283. tokens_j[N - 2][i] = tokens_j[0][i];
  284. }
  285. }
  286. }
  287. }
  288. // update observed ngrams
  289. if (v == 0) {
  290. // the first token of the n-gram is determined by the index in the container so it is not stored
  291. std::vector<llama_token> ngram(N - 1);
  292. // n-gram generation
  293. // ref: https://github.com/hao-ai-lab/LookaheadDecoding/issues/14#issuecomment-1826198518
  294. for (int f = 0; f < W; ++f) {
  295. const int ft = tokens_j_prev[f]; // first token of the n-gram
  296. for (int j = 0; j < N - 1; ++j) {
  297. ngram[j] = tokens_j[j][f];
  298. }
  299. // filter-out repeating n-grams
  300. {
  301. bool is_unique = true;
  302. for (int k = 0; k < ngrams_observed.cnt[ft]; ++k) {
  303. const int idx = ft*(N - 1)*G + k*(N - 1);
  304. bool is_match = true;
  305. for (int j = 0; j < N - 1; ++j) {
  306. if (ngrams_observed.tokens[idx + j] != ngram[j]) {
  307. is_match = false;
  308. break;
  309. }
  310. }
  311. if (is_match) {
  312. is_unique = false;
  313. break;
  314. }
  315. }
  316. if (!is_unique) {
  317. continue;
  318. }
  319. }
  320. const int head = ngrams_observed.head[ft];
  321. const int idx = ft*(N - 1)*G + head*(N - 1);
  322. for (int i = 0; i < N - 1; i++) {
  323. ngrams_observed.tokens[idx + i] = ngram[i];
  324. }
  325. ngrams_observed.cnt[ft] = std::min(G, ngrams_observed.cnt[ft] + 1);
  326. ngrams_observed.head[ft] = (head + 1) % G;
  327. ngrams_observed.n_total++;
  328. }
  329. }
  330. }
  331. if ((params.n_predict >= 0 && n_predict > params.n_predict) || has_eos) {
  332. break;
  333. }
  334. // KV cache management
  335. // if no verification token matched, we simply remove all cells from this batch -> no fragmentation
  336. llama_memory_seq_rm(mem, -1, n_past, -1);
  337. if (seq_id_best != 0) {
  338. // if a verification token matched, we keep the best sequence and remove the rest
  339. // this leads to some KV cache fragmentation
  340. llama_memory_seq_keep(mem, seq_id_best);
  341. llama_memory_seq_cp (mem, seq_id_best, 0, -1, -1);
  342. llama_memory_seq_rm (mem, seq_id_best, -1, -1);
  343. for (int s = 1; s < W + G + 1; ++s) {
  344. llama_memory_seq_cp(mem, 0, s, -1, -1);
  345. }
  346. }
  347. }
  348. auto t_dec_end = ggml_time_us();
  349. LOG("\n\n");
  350. LOG_INF("encoded %4d tokens in %8.3f seconds, speed: %8.3f t/s\n", n_input, (t_enc_end - t_enc_start) / 1e6f, inp.size() / ((t_enc_end - t_enc_start) / 1e6f));
  351. LOG_INF("decoded %4d tokens in %8.3f seconds, speed: %8.3f t/s\n", n_predict, (t_dec_end - t_dec_start) / 1e6f, n_predict / ((t_dec_end - t_dec_start) / 1e6f));
  352. LOG_INF("\n");
  353. LOG_INF("W = %2d\n", W);
  354. LOG_INF("N = %2d\n", N);
  355. LOG_INF("G = %2d\n", G);
  356. LOG_INF("\n");
  357. LOG_INF("n_predict = %d\n", n_predict);
  358. LOG_INF("n_accept = %d\n", n_accept);
  359. LOG_INF("\n");
  360. common_perf_print(ctx, smpl);
  361. common_sampler_free(smpl);
  362. llama_batch_free(batch);
  363. llama_backend_free();
  364. LOG("\n\n");
  365. return 0;
  366. }