speculative.cpp 10 KB

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