speculative.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  1. #include "speculative.h"
  2. #include "ggml.h"
  3. #include "llama.h"
  4. #include "log.h"
  5. #include "common.h"
  6. #include "sampling.h"
  7. #include <cstring>
  8. #include <algorithm>
  9. #include <map>
  10. #define SPEC_VOCAB_MAX_SIZE_DIFFERENCE 128
  11. #define SPEC_VOCAB_CHECK_START_TOKEN_ID 5
  12. struct common_speculative {
  13. struct llama_context * ctx_tgt; // only used for retokenizing from ctx_dft
  14. struct llama_context * ctx_dft;
  15. struct common_sampler * smpl;
  16. llama_batch batch;
  17. llama_tokens prompt_dft;
  18. bool vocab_dft_compatible = true; // whether retokenization is needed
  19. std::map<std::string, std::string> tgt_dft_replacements = {};
  20. };
  21. struct common_speculative * common_speculative_init(
  22. struct llama_context * ctx_tgt,
  23. struct llama_context * ctx_dft) {
  24. auto * result = new common_speculative {
  25. /* .ctx_tgt = */ ctx_tgt,
  26. /* .ctx_dft = */ ctx_dft,
  27. /* .smpl = */ nullptr,
  28. /* .batch = */ llama_batch_init(llama_n_batch(ctx_dft), 0, 1),
  29. /* .prompt_dft = */ {},
  30. /* .vocab_dft_compatible = */ false,
  31. };
  32. // TODO: optimize or pass from outside?
  33. #if 0
  34. {
  35. common_params_sampling params;
  36. params.no_perf = false;
  37. params.top_k = 40;
  38. params.top_p = 0.9;
  39. params.samplers = {
  40. COMMON_SAMPLER_TYPE_TOP_K,
  41. COMMON_SAMPLER_TYPE_TOP_P,
  42. COMMON_SAMPLER_TYPE_INFILL,
  43. };
  44. result->smpl = common_sampler_init(llama_get_model(ctx_dft), params);
  45. }
  46. #else
  47. {
  48. common_params_sampling params;
  49. params.no_perf = false;
  50. params.top_k = 10;
  51. params.samplers = {
  52. COMMON_SAMPLER_TYPE_TOP_K,
  53. };
  54. result->smpl = common_sampler_init(llama_get_model(ctx_dft), params);
  55. }
  56. #endif
  57. result->vocab_dft_compatible = common_speculative_are_compatible(ctx_tgt, ctx_dft);
  58. LOG_DBG("vocab_dft_compatible = %d\n", result->vocab_dft_compatible);
  59. return result;
  60. }
  61. void common_speculative_free(struct common_speculative * spec) {
  62. if (spec == nullptr) {
  63. return;
  64. }
  65. common_sampler_free(spec->smpl);
  66. llama_batch_free(spec->batch);
  67. delete spec;
  68. }
  69. bool common_speculative_are_compatible(
  70. const struct llama_context * ctx_tgt,
  71. const struct llama_context * ctx_dft) {
  72. const struct llama_model * model_tgt = llama_get_model(ctx_tgt);
  73. const struct llama_model * model_dft = llama_get_model(ctx_dft);
  74. const struct llama_vocab * vocab_tgt = llama_model_get_vocab(model_tgt);
  75. const struct llama_vocab * vocab_dft = llama_model_get_vocab(model_dft);
  76. const bool vocab_type_tgt = llama_vocab_type(vocab_tgt);
  77. LOG_DBG("%s: vocab_type tgt: %d\n", __func__, vocab_type_tgt);
  78. const bool vocab_type_dft = llama_vocab_type(vocab_dft);
  79. LOG_DBG("%s: vocab_type dft: %d\n", __func__, vocab_type_dft);
  80. if (vocab_type_tgt != vocab_type_dft) {
  81. LOG_DBG("%s: draft model vocab type must match target model to use speculation but ", __func__);
  82. LOG_DBG("vocab_type_dft = %d while vocab_type_tgt = %d\n", vocab_type_dft, vocab_type_tgt);
  83. return false;
  84. }
  85. if (
  86. llama_vocab_get_add_bos(vocab_tgt) != llama_vocab_get_add_bos(vocab_dft) ||
  87. llama_vocab_get_add_eos(vocab_tgt) != llama_vocab_get_add_eos(vocab_dft) ||
  88. llama_vocab_bos(vocab_tgt) != llama_vocab_bos(vocab_dft) ||
  89. llama_vocab_eos(vocab_tgt) != llama_vocab_eos(vocab_dft)
  90. ) {
  91. LOG_DBG("%s: draft model special tokens must match target model to use speculation\n", __func__);
  92. return false;
  93. }
  94. {
  95. const int n_vocab_tgt = llama_vocab_n_tokens(vocab_tgt);
  96. const int n_vocab_dft = llama_vocab_n_tokens(vocab_dft);
  97. const int vocab_diff = n_vocab_tgt > n_vocab_dft
  98. ? n_vocab_tgt - n_vocab_dft
  99. : n_vocab_dft - n_vocab_tgt;
  100. if (vocab_diff > SPEC_VOCAB_MAX_SIZE_DIFFERENCE) {
  101. LOG_DBG("%s: draft model vocab must closely match target model to use speculation but ", __func__);
  102. LOG_DBG("target vocab size %d does not match draft vocab size %d - difference %d, max allowed %d\n",
  103. n_vocab_tgt, llama_vocab_n_tokens(vocab_dft), vocab_diff, SPEC_VOCAB_MAX_SIZE_DIFFERENCE);
  104. return false;
  105. }
  106. for (int i = SPEC_VOCAB_CHECK_START_TOKEN_ID; i < std::min(n_vocab_tgt, n_vocab_dft); ++i) {
  107. const char * token_text_tgt = llama_vocab_get_text(vocab_tgt, i);
  108. const char * token_text_dft = llama_vocab_get_text(vocab_dft, i);
  109. if (std::strcmp(token_text_tgt, token_text_dft) != 0) {
  110. LOG_DBG("%s: draft model vocab must match target model to use speculation but ", __func__);
  111. LOG_DBG("token %d content differs - target '%s', draft '%s'\n", i,
  112. common_token_to_piece(ctx_tgt, i).c_str(),
  113. common_token_to_piece(ctx_dft, i).c_str());
  114. return false;
  115. }
  116. }
  117. }
  118. return true;
  119. }
  120. void common_speculative_add_replacement_tgt_dft(
  121. struct common_speculative * spec,
  122. const char *source, const char *dest) {
  123. spec->tgt_dft_replacements[source] = dest;
  124. }
  125. static std::string replace_to_dft(
  126. struct common_speculative * spec,
  127. const std::string& input) {
  128. std::string result = input;
  129. for (const auto & pair : spec->tgt_dft_replacements) {
  130. size_t pos = result.find(pair.first);
  131. while (pos != std::string::npos) {
  132. result.replace(pos, pair.first.length(), pair.second);
  133. pos = result.find(pair.first, pos + pair.second.length());
  134. }
  135. }
  136. return result;
  137. }
  138. static std::string replace_to_tgt(
  139. struct common_speculative * spec,
  140. const std::string& input) {
  141. std::string result = input;
  142. for (const auto& pair : spec->tgt_dft_replacements) {
  143. size_t pos = result.find(pair.second);
  144. while (pos != std::string::npos) {
  145. result.replace(pos, pair.second.length(), pair.first);
  146. pos = result.find(pair.second, pos + pair.first.length());
  147. }
  148. }
  149. return result;
  150. }
  151. llama_tokens common_speculative_gen_draft(
  152. struct common_speculative * spec,
  153. struct common_speculative_params params,
  154. const llama_tokens & prompt_tgt_main_model, // specified in target model vocab
  155. llama_token id_last) {
  156. auto & batch = spec->batch;
  157. auto & ctx_tgt = spec->ctx_tgt;
  158. auto & ctx_dft = spec->ctx_dft;
  159. auto & smpl = spec->smpl;
  160. auto & prompt_dft = spec->prompt_dft;
  161. auto * mem_dft = llama_get_memory(ctx_dft);
  162. int reuse_i = 0;
  163. int reuse_n = 0;
  164. const int n_ctx = llama_n_ctx(ctx_dft) - params.n_draft;
  165. llama_tokens prompt_tgt_draft_model;
  166. if (!spec->vocab_dft_compatible) {
  167. std::string text;
  168. text = common_detokenize(ctx_tgt, prompt_tgt_main_model, true);
  169. text = replace_to_dft(spec, text);
  170. LOG_DBG("%s: main->draft detokenized string: '%s'\n", __func__, text.c_str());
  171. prompt_tgt_draft_model = common_tokenize(ctx_dft, text, false, true);
  172. // convert id_last to draft vocab. llama_detokenize is called directly to avoid an allocation
  173. const auto * model_tgt = llama_get_model(ctx_tgt);
  174. const auto * vocab_tgt = llama_model_get_vocab(model_tgt);
  175. int32_t n_chars = llama_detokenize(vocab_tgt, &id_last, 1, nullptr, 0, false, false);
  176. GGML_ASSERT(n_chars < 0 && "failed to detokenize id_last");
  177. text.resize(-n_chars);
  178. llama_detokenize(vocab_tgt, &id_last, 1, text.data(), text.size(), false, false);
  179. text = replace_to_dft(spec, text);
  180. LOG_DBG("main->draft detokenized id_last(%d): '%s'\n", id_last, text.c_str());
  181. id_last = common_tokenize(ctx_dft, text, false, true)[0];
  182. }
  183. // prompt_tgt's tokens will always be compatible with ctx_dft
  184. const llama_tokens &prompt_tgt =
  185. spec->vocab_dft_compatible ? prompt_tgt_main_model : prompt_tgt_draft_model;
  186. const int i_start = std::max<int>(0, (int) prompt_tgt.size() - n_ctx);
  187. // reuse as much as possible from the old draft context
  188. // ideally, the draft context should be as big as the target context and we will always reuse the entire prompt
  189. for (int i = 0; i < (int) prompt_dft.size(); ++i) {
  190. int cur = 0;
  191. while (i_start + cur < (int) prompt_tgt.size() &&
  192. i + cur < (int) prompt_dft.size() &&
  193. prompt_tgt[i_start + cur] == prompt_dft[i + cur]) {
  194. cur++;
  195. }
  196. if ((cur >= params.n_reuse || n_ctx >= (int) prompt_tgt.size()) && cur > reuse_n) {
  197. reuse_i = i;
  198. reuse_n = cur;
  199. }
  200. }
  201. LOG_DBG("%s: reuse_i = %d, reuse_n = %d, prompt = %d\n", __func__, reuse_i, reuse_n, (int) prompt_dft.size());
  202. llama_tokens result;
  203. result.reserve(params.n_draft);
  204. if (reuse_n == 0) {
  205. llama_memory_clear(mem_dft, false);
  206. prompt_dft.clear();
  207. } else {
  208. // this happens when a previous draft has been discarded (for example, due to being too small), but the
  209. // target model agreed with it. in this case, we simply pass back the previous results to save compute
  210. if (reuse_i + reuse_n < (int) prompt_dft.size() && prompt_dft[reuse_i + reuse_n] == id_last) {
  211. for (int i = reuse_i + reuse_n + 1; i < (int) prompt_dft.size(); ++i) {
  212. result.push_back(prompt_dft[i]);
  213. if (params.n_draft <= (int) result.size()) {
  214. break;
  215. }
  216. }
  217. return result;
  218. }
  219. if (reuse_i > 0) {
  220. llama_memory_seq_rm (mem_dft, 0, 0, reuse_i);
  221. llama_memory_seq_add(mem_dft, 0, reuse_i, -1, -reuse_i);
  222. prompt_dft.erase(prompt_dft.begin(), prompt_dft.begin() + reuse_i);
  223. }
  224. if (reuse_n < (int) prompt_dft.size()) {
  225. llama_memory_seq_rm (mem_dft, 0, reuse_n, -1);
  226. prompt_dft.erase(prompt_dft.begin() + reuse_n, prompt_dft.end());
  227. }
  228. }
  229. // prepare a batch to evaluate any new tokens in the prompt
  230. common_batch_clear(batch);
  231. for (size_t i = i_start + reuse_n; i < prompt_tgt.size(); ++i) {
  232. //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]);
  233. common_batch_add(batch, prompt_tgt[i], i - i_start, { 0 }, false);
  234. prompt_dft.push_back(prompt_tgt[i]);
  235. }
  236. // we should rarely end-up here during normal decoding
  237. if (batch.n_tokens > 0) {
  238. //LOG_DBG("%s: draft prompt batch: %s\n", __func__, string_from(ctx, batch).c_str());
  239. llama_decode(ctx_dft, batch);
  240. }
  241. const llama_pos n_past = prompt_dft.size();
  242. LOG_DBG("%s: n_past = %d\n", __func__, n_past);
  243. common_batch_clear(batch);
  244. common_batch_add (batch, id_last, n_past, { 0 }, true);
  245. prompt_dft.push_back(id_last);
  246. LOG_DBG("%s: draft prompt: %s\n", __func__, string_from(ctx_dft, prompt_dft).c_str());
  247. llama_decode(ctx_dft, batch);
  248. common_sampler_reset(smpl);
  249. // sample n_draft tokens from the draft model
  250. for (int i = 0; i < params.n_draft; ++i) {
  251. common_batch_clear(batch);
  252. common_sampler_sample(smpl, ctx_dft, 0, true);
  253. const auto * cur_p = common_sampler_get_candidates(smpl, true);
  254. for (int k = 0; k < std::min(3, (int) cur_p->size); ++k) {
  255. LOG_DBG(" - draft candidate %3d, pos %3d: %6d (%8.3f) '%s'\n",
  256. k, i, cur_p->data[k].id, cur_p->data[k].p, common_token_to_piece(ctx_dft, cur_p->data[k].id).c_str());
  257. }
  258. // add drafted token for each sequence
  259. const llama_token id = cur_p->data[0].id;
  260. common_sampler_accept(smpl, id, true);
  261. result.push_back(id);
  262. if (params.n_draft <= (int) result.size()) {
  263. break;
  264. }
  265. // only collect very high-confidence draft tokens
  266. if (cur_p->data[0].p < params.p_min) {
  267. break;
  268. }
  269. common_batch_add(batch, id, n_past + i + 1, { 0 }, true);
  270. // evaluate the drafted tokens on the draft model
  271. llama_decode(ctx_dft, batch);
  272. prompt_dft.push_back(id);
  273. }
  274. if (!spec->vocab_dft_compatible) {
  275. std::string detokenized = common_detokenize(ctx_dft, result, true);
  276. detokenized = replace_to_tgt(spec, detokenized);
  277. LOG_DBG("draft->main detokenized string: '%s'\n", detokenized.c_str());
  278. result = common_tokenize(ctx_tgt, detokenized, false, true);
  279. if (result.size() > (size_t)params.n_draft) {
  280. result.resize(params.n_draft);
  281. }
  282. }
  283. return result;
  284. }