speculative.cpp 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. #include "build-info.h"
  2. #include "common.h"
  3. #include "llama.h"
  4. #include "grammar-parser.h"
  5. #include <cmath>
  6. #include <cstdio>
  7. #include <string>
  8. #include <vector>
  9. int main(int argc, char ** argv) {
  10. gpt_params params;
  11. if (gpt_params_parse(argc, argv, params) == false) {
  12. return 1;
  13. }
  14. if (params.model_draft.empty()) {
  15. fprintf(stderr, "%s: error: --model-draft is required\n", __func__);
  16. return 1;
  17. }
  18. #ifndef LOG_DISABLE_LOGS
  19. log_set_target(log_filename_generator("speculative", "log"));
  20. LOG_TEE("Log start\n");
  21. log_dump_cmdline(argc, argv);
  22. #endif // LOG_DISABLE_LOGS
  23. // init llama.cpp
  24. llama_backend_init(params.numa);
  25. llama_model * model_tgt = NULL;
  26. llama_model * model_dft = NULL;
  27. llama_context * ctx_tgt = NULL;
  28. llama_context * ctx_dft = NULL;
  29. // load the target model
  30. params.perplexity = true; // HACK: enable logits_all = true
  31. std::tie(model_tgt, ctx_tgt) = llama_init_from_gpt_params(params);
  32. // load the draft model
  33. params.model = params.model_draft;
  34. std::tie(model_dft, ctx_dft) = llama_init_from_gpt_params(params);
  35. // tokenize the prompt
  36. std::vector<llama_token> inp;
  37. inp = ::llama_tokenize(ctx_tgt, params.prompt, true);
  38. const int max_context_size = llama_n_ctx(ctx_tgt);
  39. const int max_tokens_list_size = max_context_size - 4;
  40. if ((int) inp.size() > max_tokens_list_size) {
  41. fprintf(stderr, "%s: error: prompt too long (%d tokens, max %d)\n", __func__, (int) inp.size(), max_tokens_list_size);
  42. return 1;
  43. }
  44. fprintf(stderr, "\n\n");
  45. for (auto id : inp) {
  46. fprintf(stderr, "%s", llama_token_to_piece(ctx_tgt, id).c_str());
  47. }
  48. fflush(stderr);
  49. const int n_input = inp.size();
  50. const auto t_enc_start = ggml_time_us();
  51. // eval the prompt with both models
  52. llama_eval(ctx_tgt, inp.data(), int(inp.size() - 1), 0, params.n_threads);
  53. llama_eval(ctx_tgt, &inp.back(), 1, inp.size() - 1, params.n_threads);
  54. llama_eval(ctx_dft, inp.data(), int(inp.size()), 0, params.n_threads);
  55. const auto t_enc_end = ggml_time_us();
  56. // the 2 models should have the same vocab
  57. const int n_ctx = llama_n_ctx(ctx_tgt);
  58. const int n_vocab = llama_n_vocab(ctx_tgt);
  59. //GGML_ASSERT(n_vocab == llama_n_vocab(ctx_dft));
  60. // how many tokens to draft each time
  61. const int n_draft = params.n_draft;
  62. int n_predict = 0;
  63. int n_drafted = 0;
  64. int n_accept = 0;
  65. int n_past_tgt = inp.size();
  66. int n_past_dft = inp.size();
  67. std::vector<llama_token> drafted;
  68. std::vector<llama_token> last_tokens(n_ctx);
  69. std::fill(last_tokens.begin(), last_tokens.end(), 0);
  70. for (auto & id : inp) {
  71. last_tokens.erase(last_tokens.begin());
  72. last_tokens.push_back(id);
  73. }
  74. std::vector<llama_token_data> candidates;
  75. candidates.reserve(n_vocab);
  76. // used to determine end of generation
  77. bool has_eos = false;
  78. // grammar stuff
  79. struct llama_grammar * grammar_dft = NULL;
  80. struct llama_grammar * grammar_tgt = NULL;
  81. grammar_parser::parse_state parsed_grammar;
  82. // if requested - load the grammar, error checking is omitted for brevity
  83. if (!params.grammar.empty()) {
  84. parsed_grammar = grammar_parser::parse(params.grammar.c_str());
  85. // will be empty (default) if there are parse errors
  86. if (parsed_grammar.rules.empty()) {
  87. return 1;
  88. }
  89. std::vector<const llama_grammar_element *> grammar_rules(parsed_grammar.c_rules());
  90. grammar_tgt = llama_grammar_init(grammar_rules.data(), grammar_rules.size(), parsed_grammar.symbol_ids.at("root"));
  91. }
  92. const auto t_dec_start = ggml_time_us();
  93. while (true) {
  94. LOG("drafted: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx_dft, drafted));
  95. int i_dft = 0;
  96. while (true) {
  97. // sample from the target model
  98. const llama_token id = llama_sample_token(ctx_tgt, NULL, grammar_tgt, params, last_tokens, candidates, i_dft);
  99. // remember which tokens were sampled - used for repetition penalties during sampling
  100. last_tokens.erase(last_tokens.begin());
  101. last_tokens.push_back(id);
  102. //LOG("last: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx_tgt, last_tokens));
  103. const std::string token_str = llama_token_to_piece(ctx_tgt, id);
  104. printf("%s", token_str.c_str());
  105. fflush(stdout);
  106. if (id == llama_token_eos(ctx_tgt)) {
  107. has_eos = true;
  108. }
  109. ++n_predict;
  110. // check if the draft matches the target
  111. if (i_dft < (int) drafted.size() && id == drafted[i_dft]) {
  112. LOG("the sampled target token matches the %dth drafted token (%d, '%s') - accepted\n", i_dft, id, token_str.c_str());
  113. ++n_accept;
  114. ++n_past_tgt;
  115. ++n_past_dft;
  116. ++i_dft;
  117. continue;
  118. }
  119. // the drafted token was rejected or we are out of drafted tokens
  120. if (i_dft < (int) drafted.size()) {
  121. LOG("the %dth drafted token (%d, '%s') does not match the sampled target token (%d, '%s') - rejected\n",
  122. i_dft, drafted[i_dft], llama_token_to_piece(ctx_dft, drafted[i_dft]).c_str(), id, token_str.c_str());
  123. } else {
  124. LOG("out of drafted tokens\n");
  125. }
  126. llama_eval(ctx_dft, &id, 1, n_past_dft, params.n_threads);
  127. ++n_past_dft;
  128. drafted.clear();
  129. drafted.push_back(id);
  130. break;
  131. }
  132. if (n_predict > params.n_predict || has_eos) {
  133. break;
  134. }
  135. if (grammar_tgt) {
  136. if (grammar_dft) {
  137. llama_grammar_free(grammar_dft);
  138. }
  139. grammar_dft = llama_grammar_copy(grammar_tgt);
  140. LOG("copied target grammar to draft grammar\n");
  141. }
  142. // sample n_draft tokens from the draft model using greedy decoding
  143. int n_past_cur = n_past_dft;
  144. for (int i = 0; i < n_draft; ++i) {
  145. float * logits = llama_get_logits(ctx_dft);
  146. candidates.clear();
  147. for (llama_token token_id = 0; token_id < n_vocab; token_id++) {
  148. candidates.emplace_back(llama_token_data{token_id, logits[token_id], 0.0f});
  149. }
  150. llama_token_data_array cur_p = { candidates.data(), candidates.size(), false };
  151. if (grammar_dft != NULL) {
  152. llama_sample_grammar(ctx_dft, &cur_p, grammar_dft);
  153. }
  154. // computes softmax and sorts the candidates
  155. llama_sample_softmax(ctx_dft, &cur_p);
  156. for (int i = 0; i < 3; ++i) {
  157. LOG(" - draft candidate %3d: %6d (%8.3f) '%s'\n", i, cur_p.data[i].id, cur_p.data[i].p, llama_token_to_piece(ctx_dft, cur_p.data[i].id).c_str());
  158. }
  159. // TODO: better logic?
  160. if (cur_p.data[0].p < 2*cur_p.data[1].p) {
  161. LOG("stopping drafting, probability too low: %.3f < 2*%.3f\n", cur_p.data[0].p, cur_p.data[1].p);
  162. break;
  163. }
  164. // drafted token
  165. const llama_token id = cur_p.data[0].id;
  166. drafted.push_back(id);
  167. ++n_drafted;
  168. // no need to evaluate the last drafted token, since we won't use the result
  169. if (i == n_draft - 1) {
  170. break;
  171. }
  172. // evaluate the drafted token on the draft model
  173. llama_eval(ctx_dft, &drafted.back(), 1, n_past_cur, params.n_threads);
  174. ++n_past_cur;
  175. if (grammar_dft != NULL) {
  176. llama_grammar_accept_token(ctx_dft, grammar_dft, id);
  177. }
  178. }
  179. // evaluate the target model on the drafted tokens
  180. llama_eval(ctx_tgt, drafted.data(), drafted.size(), n_past_tgt, params.n_threads);
  181. ++n_past_tgt;
  182. // the first token is always proposed by the traget model before the speculation loop
  183. drafted.erase(drafted.begin());
  184. }
  185. auto t_dec_end = ggml_time_us();
  186. LOG_TEE("\n\n");
  187. 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));
  188. 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));
  189. // TODO: make sure these numbers are computed correctly
  190. LOG_TEE("\n");
  191. LOG_TEE("n_draft = %d\n", n_draft);
  192. LOG_TEE("n_predict = %d\n", n_predict);
  193. LOG_TEE("n_drafted = %d\n", n_drafted);
  194. LOG_TEE("n_accept = %d\n", n_accept);
  195. LOG_TEE("accept = %.3f%%\n", 100.0f * n_accept / n_drafted);
  196. LOG_TEE("\ndraft:\n");
  197. llama_print_timings(ctx_dft);
  198. LOG_TEE("\ntarget:\n");
  199. llama_print_timings(ctx_tgt);
  200. llama_free(ctx_tgt);
  201. llama_free_model(model_tgt);
  202. llama_free(ctx_dft);
  203. llama_free_model(model_dft);
  204. if (grammar_dft != NULL) {
  205. llama_grammar_free(grammar_dft);
  206. llama_grammar_free(grammar_tgt);
  207. }
  208. llama_backend_free();
  209. fprintf(stderr, "\n\n");
  210. return 0;
  211. }