speculative.cpp 9.1 KB

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