speculative.cpp 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  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 struct llama_vocab * vocab_tgt = llama_model_get_vocab(model_tgt);
  63. const struct llama_vocab * vocab_dft = llama_model_get_vocab(model_dft);
  64. const bool vocab_type_tgt = llama_vocab_type(vocab_tgt);
  65. LOG_DBG("%s: vocab_type tgt: %d\n", __func__, vocab_type_tgt);
  66. const bool vocab_type_dft = llama_vocab_type(vocab_dft);
  67. LOG_DBG("%s: vocab_type dft: %d\n", __func__, vocab_type_dft);
  68. if (vocab_type_tgt != vocab_type_dft) {
  69. LOG_ERR("%s: draft model vocab type must match target model to use speculation but "
  70. "vocab_type_dft = %d while vocab_type_tgt = %d\n", __func__, vocab_type_dft, vocab_type_tgt);
  71. return false;
  72. }
  73. if (llama_vocab_get_add_bos(vocab_tgt) != llama_vocab_get_add_bos(vocab_dft) ||
  74. llama_vocab_get_add_eos(vocab_tgt) != llama_vocab_get_add_eos(vocab_dft) ||
  75. llama_vocab_bos(vocab_tgt) != llama_vocab_bos(vocab_dft) ||
  76. llama_vocab_eos(vocab_tgt) != llama_vocab_eos(vocab_dft)) {
  77. LOG_ERR("%s: draft vocab special tokens must match target vocab to use speculation\n", __func__);
  78. 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));
  79. 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));
  80. return false;
  81. }
  82. {
  83. const int n_vocab_tgt = llama_vocab_n_tokens(vocab_tgt);
  84. const int n_vocab_dft = llama_vocab_n_tokens(vocab_dft);
  85. const int vocab_diff = std::abs(n_vocab_tgt - n_vocab_dft);
  86. if (vocab_diff > SPEC_VOCAB_MAX_SIZE_DIFFERENCE) {
  87. LOG_ERR("%s: draft model vocab must closely match target model to use speculation but "
  88. "target vocab size %d does not match draft vocab size %d - difference %d, max allowed %d\n",
  89. __func__, n_vocab_tgt, llama_vocab_n_tokens(vocab_dft), vocab_diff, SPEC_VOCAB_MAX_SIZE_DIFFERENCE);
  90. return false;
  91. }
  92. for (int i = SPEC_VOCAB_CHECK_START_TOKEN_ID; i < std::min(n_vocab_tgt, n_vocab_dft); ++i) {
  93. const char * token_text_tgt = llama_vocab_get_text(vocab_tgt, i);
  94. const char * token_text_dft = llama_vocab_get_text(vocab_dft, i);
  95. if (std::strcmp(token_text_tgt, token_text_dft) != 0) {
  96. LOG_ERR("%s: draft vocab vocab must match target vocab to use speculation but "
  97. "token %d content differs - target '%s', draft '%s'\n", __func__, i,
  98. common_token_to_piece(ctx_tgt, i).c_str(),
  99. common_token_to_piece(ctx_dft, i).c_str());
  100. return false;
  101. }
  102. }
  103. }
  104. return true;
  105. }
  106. llama_tokens common_speculative_gen_draft(
  107. struct common_speculative * spec,
  108. struct common_speculative_params params,
  109. const llama_tokens & prompt_tgt,
  110. llama_token id_last) {
  111. auto & batch = spec->batch;
  112. auto & ctx = spec->ctx;
  113. auto & smpl = spec->smpl;
  114. auto & prompt = spec->prompt;
  115. int reuse_i = 0;
  116. int reuse_n = 0;
  117. const int n_ctx = llama_n_ctx(ctx) - params.n_draft;
  118. const int i_start = std::max<int>(0, (int) prompt_tgt.size() - n_ctx);
  119. // reuse as much as possible from the old draft context
  120. // ideally, the draft context should be as big as the target context and we will always reuse the entire prompt
  121. for (int i = 0; i < (int) prompt.size(); ++i) {
  122. int cur = 0;
  123. while (i_start + cur < (int) prompt_tgt.size() &&
  124. i + cur < (int) prompt.size() &&
  125. prompt_tgt[i_start + cur] == prompt[i + cur]) {
  126. cur++;
  127. }
  128. if ((cur >= params.n_reuse || n_ctx >= (int) prompt_tgt.size()) && cur > reuse_n) {
  129. reuse_i = i;
  130. reuse_n = cur;
  131. }
  132. }
  133. LOG_DBG("%s: reuse_i = %d, reuse_n = %d, prompt = %d\n", __func__, reuse_i, reuse_n, (int) prompt.size());
  134. llama_tokens result;
  135. result.reserve(params.n_draft);
  136. if (reuse_n == 0) {
  137. llama_kv_cache_clear(ctx);
  138. prompt.clear();
  139. } else {
  140. // this happens when a previous draft has been discarded (for example, due to being too small), but the
  141. // target model agreed with it. in this case, we simply pass back the previous results to save compute
  142. if (reuse_i + reuse_n < (int) prompt.size() && prompt[reuse_i + reuse_n] == id_last) {
  143. for (int i = reuse_i + reuse_n + 1; i < (int) prompt.size(); ++i) {
  144. result.push_back(prompt[i]);
  145. if (params.n_draft <= (int) result.size()) {
  146. break;
  147. }
  148. }
  149. return result;
  150. }
  151. if (reuse_i > 0) {
  152. llama_kv_cache_seq_rm (ctx, 0, 0, reuse_i);
  153. llama_kv_cache_seq_add(ctx, 0, reuse_i, -1, -reuse_i);
  154. prompt.erase(prompt.begin(), prompt.begin() + reuse_i);
  155. }
  156. if (reuse_n < (int) prompt.size()) {
  157. llama_kv_cache_seq_rm (ctx, 0, reuse_n, -1);
  158. prompt.erase(prompt.begin() + reuse_n, prompt.end());
  159. }
  160. }
  161. // prepare a batch to evaluate any new tokens in the prompt
  162. common_batch_clear(batch);
  163. for (size_t i = i_start + reuse_n; i < prompt_tgt.size(); ++i) {
  164. //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]);
  165. common_batch_add(batch, prompt_tgt[i], i - i_start, { 0 }, false);
  166. prompt.push_back(prompt_tgt[i]);
  167. }
  168. // we should rarely end-up here during normal decoding
  169. if (batch.n_tokens > 0) {
  170. //LOG_DBG("%s: draft prompt batch: %s\n", __func__, string_from(ctx, batch).c_str());
  171. llama_decode(ctx, batch);
  172. }
  173. const llama_pos n_past = prompt.size();
  174. LOG_DBG("%s: n_past = %d\n", __func__, n_past);
  175. common_batch_clear(batch);
  176. common_batch_add (batch, id_last, n_past, { 0 }, true);
  177. prompt.push_back(id_last);
  178. //LOG_DBG("%s: draft prompt: %s\n", __func__, string_from(ctx, prompt).c_str());
  179. llama_decode(ctx, batch);
  180. common_sampler_reset(smpl);
  181. // sample n_draft tokens from the draft model
  182. for (int i = 0; i < params.n_draft; ++i) {
  183. common_batch_clear(batch);
  184. common_sampler_sample(smpl, ctx, 0, true);
  185. const auto * cur_p = common_sampler_get_candidates(smpl);
  186. for (int k = 0; k < std::min(3, (int) cur_p->size); ++k) {
  187. LOG_DBG(" - draft candidate %3d, pos %3d: %6d (%8.3f) '%s'\n",
  188. k, i, cur_p->data[k].id, cur_p->data[k].p, common_token_to_piece(ctx, cur_p->data[k].id).c_str());
  189. }
  190. // add drafted token for each sequence
  191. const llama_token id = cur_p->data[0].id;
  192. // only collect very high-confidence draft tokens
  193. if (cur_p->data[0].p < params.p_min) {
  194. break;
  195. }
  196. common_sampler_accept(smpl, id, true);
  197. result.push_back(id);
  198. if (params.n_draft <= (int) result.size()) {
  199. break;
  200. }
  201. common_batch_add(batch, id, n_past + i + 1, { 0 }, true);
  202. // evaluate the drafted tokens on the draft model
  203. llama_decode(ctx, batch);
  204. prompt.push_back(id);
  205. }
  206. return result;
  207. }