lookahead.cpp 16 KB

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