1
0

speculative-simple.cpp 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. #include "arg.h"
  2. #include "common.h"
  3. #include "sampling.h"
  4. #include "speculative.h"
  5. #include "log.h"
  6. #include "llama.h"
  7. #include <cstdio>
  8. #include <cstring>
  9. #include <string>
  10. #include <vector>
  11. int main(int argc, char ** argv) {
  12. common_params params;
  13. if (!common_params_parse(argc, argv, params, LLAMA_EXAMPLE_SPECULATIVE)) {
  14. return 1;
  15. }
  16. if (params.n_predict < -1) {
  17. LOG_ERR("%s: --n-predict must be >= -1\n", __func__);
  18. return 1;
  19. }
  20. common_init();
  21. if (params.speculative.model.empty()) {
  22. LOG_ERR("%s: --model-draft is required\n", __func__);
  23. return 1;
  24. }
  25. // init llama.cpp
  26. llama_backend_init();
  27. llama_numa_init(params.numa);
  28. llama_model * model_tgt = NULL;
  29. //llama_model * model_dft = NULL;
  30. llama_context * ctx_tgt = NULL;
  31. llama_context * ctx_dft = NULL;
  32. // load the target model
  33. common_init_result llama_init_tgt = common_init_from_params(params);
  34. model_tgt = llama_init_tgt.model.get();
  35. ctx_tgt = llama_init_tgt.context.get();
  36. const llama_vocab * vocab = llama_model_get_vocab(model_tgt);
  37. // load the draft model
  38. params.devices = params.speculative.devices;
  39. params.model = params.speculative.model;
  40. params.n_ctx = params.speculative.n_ctx;
  41. params.n_batch = params.speculative.n_ctx > 0 ? params.speculative.n_ctx : params.n_batch;
  42. params.n_gpu_layers = params.speculative.n_gpu_layers;
  43. if (params.speculative.cpuparams.n_threads > 0) {
  44. params.cpuparams.n_threads = params.speculative.cpuparams.n_threads;
  45. }
  46. params.cpuparams_batch.n_threads = params.speculative.cpuparams_batch.n_threads;
  47. common_init_result llama_init_dft = common_init_from_params(params);
  48. //model_dft = llama_init_dft.model.get();
  49. ctx_dft = llama_init_dft.context.get();
  50. if (!common_speculative_are_compatible(ctx_tgt, ctx_dft)) {
  51. return 1;
  52. }
  53. // Tokenize the prompt
  54. std::vector<llama_token> inp;
  55. inp = common_tokenize(ctx_tgt, params.prompt, true, true);
  56. if (llama_n_ctx(ctx_tgt) < (uint32_t) inp.size()) {
  57. LOG_ERR("%s: the prompt exceeds the context size (%d tokens, ctx %d)\n", __func__, (int) inp.size(), llama_n_ctx(ctx_tgt));
  58. return 1;
  59. }
  60. if (llama_n_batch(ctx_tgt) < (uint32_t) inp.size()) {
  61. LOG_ERR("%s: the prompt exceeds the batch size (%d tokens, batch %d)\n", __func__, (int) inp.size(), llama_n_batch(ctx_tgt));
  62. return 1;
  63. }
  64. LOG("\n\n");
  65. for (auto id : inp) {
  66. LOG("%s", common_token_to_piece(ctx_tgt, id).c_str());
  67. }
  68. // how many tokens to draft each time
  69. int n_draft = params.speculative.n_max;
  70. int n_draft_min = params.speculative.n_min;
  71. float p_min = params.speculative.p_min;
  72. int n_predict = 0;
  73. int n_drafted = 0;
  74. int n_accept = 0;
  75. // used to determine end of generation
  76. bool has_eos = false;
  77. // ================================================
  78. // everything until here is standard initialization
  79. // the relevant stuff for speculative decoding starts here
  80. const auto t_enc_start = ggml_time_us();
  81. // target model sampling context
  82. struct common_sampler * smpl = common_sampler_init(model_tgt, params.sampling);
  83. // eval the prompt
  84. llama_decode(ctx_tgt, llama_batch_get_one(inp.data(), inp.size() - 1));
  85. // note: keep the last token separate!
  86. llama_token id_last = inp.back();
  87. // all tokens currently in the target context
  88. llama_tokens prompt_tgt(inp.begin(), inp.end() - 1);
  89. prompt_tgt.reserve(llama_n_ctx(ctx_tgt));
  90. int n_past = inp.size() - 1;
  91. // init the speculator
  92. struct common_speculative_params params_spec;
  93. params_spec.n_draft = n_draft;
  94. params_spec.n_reuse = llama_n_ctx(ctx_dft) - n_draft;
  95. params_spec.p_min = p_min;
  96. struct common_speculative * spec = common_speculative_init(ctx_dft);
  97. llama_batch batch_tgt = llama_batch_init(llama_n_batch(ctx_tgt), 0, 1);
  98. const auto t_enc_end = ggml_time_us();
  99. const auto t_dec_start = ggml_time_us();
  100. while (true) {
  101. // optionally, generate draft tokens that can be appended to the target batch
  102. //
  103. // this is the most important part of the speculation. the more probable tokens that are provided here
  104. // the better the performance will be. in theory, this computation can be performed asynchronously and even
  105. // offloaded to a remote device. it doesn't even have to be based on an LLM. instead, it can provide tokens
  106. // from a cache or lookup tables.
  107. //
  108. llama_tokens draft = common_speculative_gen_draft(spec, params_spec, prompt_tgt, id_last);
  109. //LOG_DBG("draft: %s\n", string_from(ctx_dft, draft).c_str());
  110. // always have a token to evaluate from before - id_last
  111. common_batch_clear(batch_tgt);
  112. common_batch_add (batch_tgt, id_last, n_past++, { 0 }, true);
  113. // evaluate the target model on [id_last, draft0, draft1, ..., draftN-1]
  114. {
  115. // do not waste time on small drafts
  116. if (draft.size() < (size_t) n_draft_min) {
  117. draft.clear();
  118. }
  119. for (size_t i = 0; i < draft.size(); ++i) {
  120. common_batch_add(batch_tgt, draft[i], n_past + i, { 0 }, true);
  121. }
  122. //LOG_DBG("target batch: %s\n", string_from(ctx_tgt, batch_tgt).c_str());
  123. llama_decode(ctx_tgt, batch_tgt);
  124. }
  125. // sample from the full target batch and return the accepted tokens based on the target sampler
  126. //
  127. // for each token to be accepted, the sampler would have to sample that same token
  128. // in such cases, instead of decoding the sampled token as we normally do, we simply continue with the
  129. // available logits from the batch and sample the next token until we run out of logits or the sampler
  130. // disagrees with the draft
  131. //
  132. const auto ids = common_sampler_sample_and_accept_n(smpl, ctx_tgt, draft);
  133. //LOG_DBG("ids: %s\n", string_from(ctx_tgt, ids).c_str());
  134. GGML_ASSERT(ids.size() > 0); // there will always be at least one accepted token
  135. n_past += ids.size() - 1;
  136. n_drafted += draft.size(); // note: we ignore the discarded small drafts
  137. n_accept += ids.size() - 1;
  138. n_predict += ids.size();
  139. // process the accepted tokens and update contexts
  140. //
  141. // this is the standard token post-processing that we normally do
  142. // in this case, we do it for a group of accepted tokens at once
  143. //
  144. for (size_t i = 0; i < ids.size(); ++i) {
  145. prompt_tgt.push_back(id_last);
  146. id_last = ids[i];
  147. if (llama_vocab_is_eog(vocab, id_last)) {
  148. has_eos = true;
  149. break;
  150. }
  151. const std::string token_str = common_token_to_piece(ctx_tgt, id_last);
  152. if (params.use_color && i + 1 < ids.size()) {
  153. LOG("\u001b[%dm%s\u001b[37m", (36 - 0 % 6), token_str.c_str());
  154. } else {
  155. LOG("%s", token_str.c_str());
  156. }
  157. }
  158. LOG_DBG("accepted %d/%d draft tokens, the last target token is: (%d)\n", (int) ids.size() - 1, (int) draft.size(), id_last);
  159. {
  160. LOG_DBG("clear kv cache from any extra tokens, n_past = %d\n", n_past);
  161. llama_kv_cache_seq_rm(ctx_tgt, 0, n_past, -1);
  162. }
  163. if ((params.n_predict >= 0 && n_predict > params.n_predict) || has_eos) {
  164. break;
  165. }
  166. }
  167. auto t_dec_end = ggml_time_us();
  168. const int n_input = inp.size();
  169. LOG("\n\n");
  170. 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));
  171. 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));
  172. LOG_INF("\n");
  173. LOG_INF("n_draft = %d\n", n_draft);
  174. LOG_INF("n_predict = %d\n", n_predict);
  175. LOG_INF("n_drafted = %d\n", n_drafted);
  176. LOG_INF("n_accept = %d\n", n_accept);
  177. LOG_INF("accept = %.3f%%\n", 100.0f * n_accept / n_drafted);
  178. LOG_INF("\n");
  179. LOG_INF("draft:\n\n");
  180. llama_perf_context_print(ctx_dft);
  181. LOG_INF("\n");
  182. LOG_INF("target:\n\n");
  183. common_perf_print(ctx_tgt, smpl);
  184. common_sampler_free(smpl);
  185. common_speculative_free(spec);
  186. llama_backend_free();
  187. LOG("\n\n");
  188. return 0;
  189. }