lookahead.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  1. #include "common.h"
  2. #include "llama.h"
  3. #include <cstdio>
  4. #include <string>
  5. #include <vector>
  6. struct ngram_data {
  7. bool active = false;
  8. llama_seq_id seq_id = -1;
  9. std::vector<int> i_batch;
  10. std::vector<llama_token> tokens;
  11. };
  12. // n-gram container
  13. struct ngram_container {
  14. ngram_container(int n_vocab, int N, int G) {
  15. cnt.resize(n_vocab);
  16. head.resize(n_vocab);
  17. tokens.resize(n_vocab * G * (N - 1));
  18. }
  19. int n_total = 0;
  20. std::vector<int> cnt;
  21. std::vector<int> head;
  22. // [n_vocab][G][N - 1]
  23. // for each token of the vocab, keep a ring-buffer of capacity G of n-grams of size N - 1
  24. std::vector<llama_token> tokens;
  25. };
  26. int main(int argc, char ** argv) {
  27. gpt_params params;
  28. if (!gpt_params_parse(argc, argv, params)) {
  29. gpt_params_print_usage(argc, argv, params);
  30. return 1;
  31. }
  32. const int W = 15; // lookahead window
  33. const int N = 5; // n-gram size
  34. const int G = 15; // max verification n-grams
  35. const bool dump_kv_cache = params.dump_kv_cache;
  36. #ifndef LOG_DISABLE_LOGS
  37. log_set_target(log_filename_generator("lookahead", "log"));
  38. LOG_TEE("Log start\n");
  39. log_dump_cmdline(argc, argv);
  40. #endif // LOG_DISABLE_LOGS
  41. // init llama.cpp
  42. llama_backend_init();
  43. llama_numa_init(params.numa);
  44. // load the target model
  45. llama_init_result llama_init = llama_init_from_gpt_params(params);
  46. llama_model * model = llama_init.model;
  47. llama_context * ctx = llama_init.context;
  48. // Tokenize the prompt
  49. std::vector<llama_token> inp;
  50. std::vector<llama_token> all;
  51. inp = ::llama_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. fprintf(stderr, "%s: error: prompt too long (%d tokens, max %d)\n", __func__, (int) inp.size(), max_tokens_list_size);
  57. return 1;
  58. }
  59. fprintf(stderr, "\n\n");
  60. for (auto id : inp) {
  61. fprintf(stderr, "%s", llama_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, 0, 0));
  68. llama_decode(ctx, llama_batch_get_one(&inp.back(), 1, n_input - 1, 0));
  69. for (int s = 1; s < W + G + 1; ++s) {
  70. llama_kv_cache_seq_cp(ctx, 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 gpt_sampler * smpl = gpt_sampler_init(model, params.sparams);
  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_n_vocab(model), N, G);
  112. // debug
  113. struct llama_kv_cache_view kvc_view = llama_kv_cache_view_init(ctx, W + G + 1);
  114. const auto t_dec_start = ggml_time_us();
  115. // sample first token
  116. {
  117. id = gpt_sampler_sample(smpl, ctx, 0);
  118. gpt_sampler_accept(smpl, id, true);
  119. {
  120. const std::string token_str = llama_token_to_piece(ctx, id);
  121. printf("%s", token_str.c_str());
  122. fflush(stdout);
  123. }
  124. }
  125. while (true) {
  126. // debug
  127. if (dump_kv_cache) {
  128. llama_kv_cache_view_update(ctx, &kvc_view);
  129. llama_kv_cache_dump_view_seqs(kvc_view, 40);
  130. }
  131. // build the mask from https://lmsys.org/blog/2023-11-21-lookahead-decoding/
  132. //
  133. // Example for W = 5, N = 4, G = 2:
  134. // (I = input, L = lookahead, V = verification)
  135. //
  136. // Batch: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
  137. // T: -2 -2 -2 -2 -1 -1 -1 -1 -1 0 0 0 0 0 0
  138. // Info: I L L L L L L L L L L L L L L V V V V V V
  139. // Pos: 0 1 2 3 4 1 2 3 4 5 2 3 4 5 6 1 2 3 1 2 3 (+ n_past)
  140. // Logits: 1 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1
  141. // ---------------------------------------------------------------------
  142. // Seq: 0
  143. // 1 1 1
  144. // 2 2 2 2
  145. // 3 3 3 3 3
  146. // 4 4 4 4 4 4
  147. // 5 5 5 5 5 5 5
  148. // 6 6 6 6
  149. // 7 7 7 7
  150. // ---------------------------------------------------------------------
  151. // | | | | | | | | | | |
  152. // V V V V V | | | | | |
  153. // j_tokens | | | | | |
  154. // V V V V V V
  155. // id
  156. {
  157. llama_batch_clear(batch);
  158. // current token - first token of the first level
  159. llama_batch_add(batch, id, n_past, seq_id_all, true);
  160. // verification n-grams - queue this before the lookahead tokens for less KV cache fragmentation
  161. {
  162. const int g_cur = ngrams_observed.cnt[id];
  163. ngrams_cur.resize(g_cur);
  164. for (int g = 0; g < g_cur; g++) {
  165. ngrams_cur[g].active = true;
  166. ngrams_cur[g].tokens.resize(N);
  167. ngrams_cur[g].i_batch.resize(N);
  168. ngrams_cur[g].seq_id = W + 1 + g;
  169. ngrams_cur[g].i_batch[0] = 0;
  170. ngrams_cur[g].tokens [0] = id;
  171. }
  172. for (int j = 0; j < N - 1; j++) {
  173. for (int g = 0; g < g_cur; g++) {
  174. const int idx = id*(N - 1)*G + g*(N - 1);
  175. const llama_token t = ngrams_observed.tokens[idx + j];
  176. ngrams_cur[g].tokens [j + 1] = t;
  177. ngrams_cur[g].i_batch[j + 1] = batch.n_tokens;
  178. llama_batch_add(batch, t, n_past + j + 1, { W + 1 + g }, true);
  179. }
  180. }
  181. }
  182. // fill the remaining W - 1 tokens for the first level
  183. for (int i = 1; i < W; i++) {
  184. seq_id_look.resize(W - i);
  185. for (int j = 0; j < W - i; j++) {
  186. seq_id_look[j] = i + j + 1;
  187. }
  188. llama_batch_add(batch, tokens_j[0][i], n_past + i, seq_id_look, false);
  189. }
  190. // fill the rest of the levels
  191. for (int j = 1; j < N - 1; j++) {
  192. for (int i = 0; i < W; i++) {
  193. llama_batch_add(batch, tokens_j[j][i], n_past + j + i, { i + 1 }, j == N - 2);
  194. }
  195. }
  196. }
  197. if (llama_decode(ctx, batch) != 0) {
  198. fprintf(stderr, "\n\n%s: error: llama_decode failed - increase KV cache size\n", __func__);
  199. return 1;
  200. }
  201. int seq_id_best = 0;
  202. for (int v = 0; v < N; ++v) {
  203. int i_batch = 0;
  204. // if no active ngrams are left, it means the sampled token does not pass the verification
  205. if (v > 0) {
  206. for (int g = 0; g < (int) ngrams_cur.size(); g++) {
  207. if (ngrams_cur[g].active) {
  208. i_batch = ngrams_cur[g].i_batch[v];
  209. seq_id_best = ngrams_cur[g].seq_id;
  210. ++n_accept;
  211. break;
  212. }
  213. }
  214. // no more matches -> create a new batch
  215. if (i_batch == 0) {
  216. break;
  217. }
  218. }
  219. // sample the next token
  220. id = gpt_sampler_sample(smpl, ctx, i_batch);
  221. gpt_sampler_accept(smpl, id, true);
  222. // print
  223. {
  224. const std::string token_str = llama_token_to_piece(ctx, id);
  225. if (v == 0) {
  226. printf("%s", token_str.c_str());
  227. } else {
  228. // print light cyan
  229. printf("\033[0;96m%s\033[0m", token_str.c_str());
  230. }
  231. fflush(stdout);
  232. if (llama_token_is_eog(model, id)) {
  233. has_eos = true;
  234. }
  235. all.push_back(id);
  236. }
  237. ++n_predict;
  238. ++n_past;
  239. if ((params.n_predict >= 0 && n_predict > params.n_predict) || has_eos) {
  240. break;
  241. }
  242. // verify across active n-grams
  243. for (int g = 0; g < (int) ngrams_cur.size(); g++) {
  244. if (ngrams_cur[g].active) {
  245. if (v == N - 1) {
  246. ngrams_cur[g].active = false;
  247. } else {
  248. if (id != ngrams_cur[g].tokens[v + 1]) {
  249. ngrams_cur[g].active = false;
  250. }
  251. }
  252. }
  253. }
  254. // print known n-grams starting with token id (debug)
  255. if (0 && v == 0) {
  256. if (ngrams_observed.cnt[id] > 0) {
  257. printf("\n - %d n-grams starting with '%s'\n", ngrams_observed.cnt[id], llama_token_to_piece(ctx, id).c_str());
  258. }
  259. for (int i = 0; i < ngrams_observed.cnt[id]; i++) {
  260. printf(" - ngram %2d: ", i);
  261. const int idx = id*(N - 1)*G + i*(N - 1);
  262. for (int j = 0; j < N - 1; j++) {
  263. const std::string token_str = llama_token_to_piece(ctx, ngrams_observed.tokens[idx + j]);
  264. printf("%s", token_str.c_str());
  265. }
  266. printf("\n");
  267. }
  268. }
  269. // update lookahead tokens
  270. {
  271. for (int i = 0; i < W; i++) {
  272. tokens_j_prev[i] = tokens_j[0][i];
  273. }
  274. for (int j = 0; j < N - 2; j++) {
  275. tokens_j[j] = tokens_j[j + 1];
  276. }
  277. if (v == 0) {
  278. // sample from the last level
  279. for (int i = 0; i < W; i++) {
  280. tokens_j[N - 2][i] = gpt_sampler_sample(smpl, ctx, ngrams_cur.size()*(N-1) + W*(N - 2) + i);
  281. }
  282. } else {
  283. for (int i = 0; i < W; i++) {
  284. // there are different ways to init these tokens
  285. if (0) {
  286. // random init
  287. tokens_j[N - 2][i] = all[1 + rand() % (all.size() - 1)];
  288. } else {
  289. // init from the previous level
  290. tokens_j[N - 2][i] = tokens_j[0][i];
  291. }
  292. }
  293. }
  294. }
  295. // update observed ngrams
  296. if (v == 0) {
  297. // the first token of the n-gram is determined by the index in the container so it is not stored
  298. std::vector<llama_token> ngram(N - 1);
  299. // n-gram generation
  300. // ref: https://github.com/hao-ai-lab/LookaheadDecoding/issues/14#issuecomment-1826198518
  301. for (int f = 0; f < W; ++f) {
  302. const int ft = tokens_j_prev[f]; // first token of the n-gram
  303. for (int j = 0; j < N - 1; ++j) {
  304. ngram[j] = tokens_j[j][f];
  305. }
  306. // filter-out repeating n-grams
  307. {
  308. bool is_unique = true;
  309. for (int k = 0; k < ngrams_observed.cnt[ft]; ++k) {
  310. const int idx = ft*(N - 1)*G + k*(N - 1);
  311. bool is_match = true;
  312. for (int j = 0; j < N - 1; ++j) {
  313. if (ngrams_observed.tokens[idx + j] != ngram[j]) {
  314. is_match = false;
  315. break;
  316. }
  317. }
  318. if (is_match) {
  319. is_unique = false;
  320. break;
  321. }
  322. }
  323. if (!is_unique) {
  324. continue;
  325. }
  326. }
  327. const int head = ngrams_observed.head[ft];
  328. const int idx = ft*(N - 1)*G + head*(N - 1);
  329. for (int i = 0; i < N - 1; i++) {
  330. ngrams_observed.tokens[idx + i] = ngram[i];
  331. }
  332. ngrams_observed.cnt[ft] = std::min(G, ngrams_observed.cnt[ft] + 1);
  333. ngrams_observed.head[ft] = (head + 1) % G;
  334. ngrams_observed.n_total++;
  335. }
  336. }
  337. }
  338. if ((params.n_predict >= 0 && n_predict > params.n_predict) || has_eos) {
  339. break;
  340. }
  341. // KV cache management
  342. // if no verification token matched, we simply remove all cells from this batch -> no fragmentation
  343. llama_kv_cache_seq_rm(ctx, -1, n_past, -1);
  344. if (seq_id_best != 0) {
  345. // if a verification token matched, we keep the best sequence and remove the rest
  346. // this leads to some KV cache fragmentation
  347. llama_kv_cache_seq_keep(ctx, seq_id_best);
  348. llama_kv_cache_seq_cp (ctx, seq_id_best, 0, -1, -1);
  349. llama_kv_cache_seq_rm (ctx, seq_id_best, -1, -1);
  350. for (int s = 1; s < W + G + 1; ++s) {
  351. llama_kv_cache_seq_cp(ctx, 0, s, -1, -1);
  352. }
  353. }
  354. }
  355. auto t_dec_end = ggml_time_us();
  356. LOG_TEE("\n\n");
  357. LOG_TEE("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));
  358. LOG_TEE("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));
  359. LOG_TEE("\n");
  360. LOG_TEE("W = %2d\n", W);
  361. LOG_TEE("N = %2d\n", N);
  362. LOG_TEE("G = %2d\n", G);
  363. LOG_TEE("\n");
  364. LOG_TEE("n_predict = %d\n", n_predict);
  365. LOG_TEE("n_accept = %d\n", n_accept);
  366. LOG_TEE("\n");
  367. gpt_perf_print(ctx, smpl);
  368. gpt_sampler_free(smpl);
  369. llama_kv_cache_view_free(&kvc_view);
  370. llama_batch_free(batch);
  371. llama_free(ctx);
  372. llama_free_model(model);
  373. llama_backend_free();
  374. fprintf(stderr, "\n\n");
  375. return 0;
  376. }