speculative-simple.cpp 8.7 KB

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