speculative.cpp 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. #include "speculative.h"
  2. #include "log.h"
  3. #include "common.h"
  4. #include "sampling.h"
  5. #include <cstring>
  6. #define SPEC_VOCAB_MAX_SIZE_DIFFERENCE 128
  7. #define SPEC_VOCAB_CHECK_START_TOKEN_ID 5
  8. struct common_speculative {
  9. struct llama_context * ctx;
  10. struct common_sampler * smpl;
  11. llama_batch batch;
  12. llama_tokens prompt;
  13. };
  14. struct common_speculative * common_speculative_init(
  15. struct llama_context * ctx_dft) {
  16. auto * result = new common_speculative {
  17. /* .ctx = */ ctx_dft,
  18. /* .smpl = */ nullptr,
  19. /* .batch = */ llama_batch_init(llama_n_batch(ctx_dft), 0, 1),
  20. /* .prompt = */ {},
  21. };
  22. // TODO: optimize or pass from outside?
  23. #if 0
  24. {
  25. common_params_sampling params;
  26. params.no_perf = false;
  27. params.top_k = 40;
  28. params.top_p = 0.9;
  29. params.samplers = {
  30. COMMON_SAMPLER_TYPE_TOP_K,
  31. COMMON_SAMPLER_TYPE_TOP_P,
  32. COMMON_SAMPLER_TYPE_INFILL,
  33. };
  34. result->smpl = common_sampler_init(llama_get_model(ctx_dft), params);
  35. }
  36. #else
  37. {
  38. common_params_sampling params;
  39. params.no_perf = false;
  40. params.top_k = 10;
  41. params.samplers = {
  42. COMMON_SAMPLER_TYPE_TOP_K,
  43. };
  44. result->smpl = common_sampler_init(llama_get_model(ctx_dft), params);
  45. }
  46. #endif
  47. return result;
  48. }
  49. void common_speculative_free(struct common_speculative * spec) {
  50. if (spec == nullptr) {
  51. return;
  52. }
  53. common_sampler_free(spec->smpl);
  54. llama_batch_free(spec->batch);
  55. delete spec;
  56. }
  57. bool common_speculative_are_compatible(
  58. const struct llama_context * ctx_tgt,
  59. const struct llama_context * ctx_dft) {
  60. const struct llama_model * model_tgt = llama_get_model(ctx_tgt);
  61. const struct llama_model * model_dft = llama_get_model(ctx_dft);
  62. const bool vocab_type_tgt = llama_vocab_type(model_tgt);
  63. LOG_DBG("%s: vocab_type tgt: %d\n", __func__, vocab_type_tgt);
  64. const bool vocab_type_dft = llama_vocab_type(model_dft);
  65. LOG_DBG("%s: vocab_type dft: %d\n", __func__, vocab_type_dft);
  66. if (vocab_type_tgt != vocab_type_dft) {
  67. LOG_ERR("%s: draft model vocab type must match target model to use speculation but "
  68. "vocab_type_dft = %d while vocab_type_tgt = %d\n", __func__, vocab_type_dft, vocab_type_tgt);
  69. return false;
  70. }
  71. if (llama_add_bos_token(model_tgt) != llama_add_bos_token(model_dft) ||
  72. llama_add_eos_token(model_tgt) != llama_add_eos_token(model_dft) ||
  73. llama_token_bos(model_tgt) != llama_token_bos(model_dft) ||
  74. llama_token_eos(model_tgt) != llama_token_eos(model_dft)) {
  75. LOG_ERR("%s: draft model special tokens must match target model to use speculation\n", __func__);
  76. LOG_ERR("%s: tgt: bos = %d (%d), eos = %d (%d)\n", __func__, llama_token_bos(model_tgt), llama_add_bos_token(model_tgt), llama_token_eos(model_tgt), llama_add_eos_token(model_tgt));
  77. LOG_ERR("%s: dft: bos = %d (%d), eos = %d (%d)\n", __func__, llama_token_bos(model_dft), llama_add_bos_token(model_dft), llama_token_eos(model_dft), llama_add_eos_token(model_dft));
  78. return false;
  79. }
  80. {
  81. const int n_vocab_tgt = llama_n_vocab(model_tgt);
  82. const int n_vocab_dft = llama_n_vocab(model_dft);
  83. const int vocab_diff = std::abs(n_vocab_tgt - n_vocab_dft);
  84. if (vocab_diff > SPEC_VOCAB_MAX_SIZE_DIFFERENCE) {
  85. LOG_ERR("%s: draft model vocab must closely match target model to use speculation but "
  86. "target vocab size %d does not match draft vocab size %d - difference %d, max allowed %d\n",
  87. __func__, n_vocab_tgt, llama_n_vocab(model_dft), vocab_diff, SPEC_VOCAB_MAX_SIZE_DIFFERENCE);
  88. return false;
  89. }
  90. for (int i = SPEC_VOCAB_CHECK_START_TOKEN_ID; i < std::min(n_vocab_tgt, n_vocab_dft); ++i) {
  91. const char * token_text_tgt = llama_token_get_text(model_tgt, i);
  92. const char * token_text_dft = llama_token_get_text(model_dft, i);
  93. if (std::strcmp(token_text_tgt, token_text_dft) != 0) {
  94. LOG_ERR("%s: draft model vocab must match target model to use speculation but "
  95. "token %d content differs - target '%s', draft '%s'\n", __func__, i,
  96. common_token_to_piece(ctx_tgt, i).c_str(),
  97. common_token_to_piece(ctx_dft, i).c_str());
  98. return false;
  99. }
  100. }
  101. }
  102. return true;
  103. }
  104. llama_tokens common_speculative_gen_draft(
  105. struct common_speculative * spec,
  106. struct common_speculative_params params,
  107. const llama_tokens & prompt_tgt,
  108. llama_token id_last) {
  109. auto & batch = spec->batch;
  110. auto & ctx = spec->ctx;
  111. auto & smpl = spec->smpl;
  112. auto & prompt = spec->prompt;
  113. int reuse_i = 0;
  114. int reuse_n = 0;
  115. const int n_ctx = llama_n_ctx(ctx) - params.n_draft;
  116. const int i_start = std::max<int>(0, (int) prompt_tgt.size() - n_ctx);
  117. // reuse as much as possible from the old draft context
  118. // ideally, the draft context should be as big as the target context and we will always reuse the entire prompt
  119. for (int i = 0; i < (int) prompt.size(); ++i) {
  120. int cur = 0;
  121. while (i_start + cur < (int) prompt_tgt.size() &&
  122. i + cur < (int) prompt.size() &&
  123. prompt_tgt[i_start + cur] == prompt[i + cur]) {
  124. cur++;
  125. }
  126. if ((cur >= params.n_reuse || n_ctx >= (int) prompt_tgt.size()) && cur > reuse_n) {
  127. reuse_i = i;
  128. reuse_n = cur;
  129. }
  130. }
  131. LOG_DBG("%s: reuse_i = %d, reuse_n = %d, prompt = %d\n", __func__, reuse_i, reuse_n, (int) prompt.size());
  132. llama_tokens result;
  133. result.reserve(params.n_draft);
  134. if (reuse_n == 0) {
  135. llama_kv_cache_clear(ctx);
  136. prompt.clear();
  137. } else {
  138. // this happens when a previous draft has been discarded (for example, due to being too small), but the
  139. // target model agreed with it. in this case, we simply pass back the previous results to save compute
  140. if (reuse_i + reuse_n < (int) prompt.size() && prompt[reuse_i + reuse_n] == id_last) {
  141. for (int i = reuse_i + reuse_n + 1; i < (int) prompt.size(); ++i) {
  142. result.push_back(prompt[i]);
  143. if (params.n_draft <= (int) result.size()) {
  144. break;
  145. }
  146. }
  147. return result;
  148. }
  149. if (reuse_i > 0) {
  150. llama_kv_cache_seq_rm (ctx, 0, 0, reuse_i);
  151. llama_kv_cache_seq_add(ctx, 0, reuse_i, -1, -reuse_i);
  152. prompt.erase(prompt.begin(), prompt.begin() + reuse_i);
  153. }
  154. if (reuse_n < (int) prompt.size()) {
  155. llama_kv_cache_seq_rm (ctx, 0, reuse_n, -1);
  156. prompt.erase(prompt.begin() + reuse_n, prompt.end());
  157. }
  158. }
  159. // prepare a batch to evaluate any new tokens in the prompt
  160. common_batch_clear(batch);
  161. for (size_t i = i_start + reuse_n; i < prompt_tgt.size(); ++i) {
  162. //LOG_DBG("i = %d, i_start = %d, reuse_n = %d, i - i_start = %d, id = %6d\n", i, i_start, reuse_n, i - i_start, prompt_tgt[i]);
  163. common_batch_add(batch, prompt_tgt[i], i - i_start, { 0 }, false);
  164. prompt.push_back(prompt_tgt[i]);
  165. }
  166. // we should rarely end-up here during normal decoding
  167. if (batch.n_tokens > 0) {
  168. //LOG_DBG("%s: draft prompt batch: %s\n", __func__, string_from(ctx, batch).c_str());
  169. llama_decode(ctx, batch);
  170. }
  171. const llama_pos n_past = prompt.size();
  172. LOG_DBG("%s: n_past = %d\n", __func__, n_past);
  173. common_batch_clear(batch);
  174. common_batch_add (batch, id_last, n_past, { 0 }, true);
  175. prompt.push_back(id_last);
  176. //LOG_DBG("%s: draft prompt: %s\n", __func__, string_from(ctx, prompt).c_str());
  177. llama_decode(ctx, batch);
  178. common_sampler_reset(smpl);
  179. // sample n_draft tokens from the draft model
  180. for (int i = 0; i < params.n_draft; ++i) {
  181. common_batch_clear(batch);
  182. common_sampler_sample(smpl, ctx, 0, true);
  183. const auto * cur_p = common_sampler_get_candidates(smpl);
  184. for (int k = 0; k < std::min(3, (int) cur_p->size); ++k) {
  185. LOG_DBG(" - draft candidate %3d, pos %3d: %6d (%8.3f) '%s'\n",
  186. k, i, cur_p->data[k].id, cur_p->data[k].p, common_token_to_piece(ctx, cur_p->data[k].id).c_str());
  187. }
  188. // add drafted token for each sequence
  189. const llama_token id = cur_p->data[0].id;
  190. // only collect very high-confidence draft tokens
  191. if (cur_p->data[0].p < params.p_min) {
  192. break;
  193. }
  194. common_sampler_accept(smpl, id, true);
  195. result.push_back(id);
  196. if (params.n_draft <= (int) result.size()) {
  197. break;
  198. }
  199. common_batch_add(batch, id, n_past + i + 1, { 0 }, true);
  200. // evaluate the drafted tokens on the draft model
  201. llama_decode(ctx, batch);
  202. prompt.push_back(id);
  203. }
  204. return result;
  205. }