1
0

speculative-simple.cpp 8.6 KB

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