1
0

speculative.cpp 9.1 KB

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