speculative.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  1. #include "common.h"
  2. #include "llama.h"
  3. #include <cmath>
  4. #include <cstdio>
  5. #include <string>
  6. #include <vector>
  7. #define SPEC_VOCAB_MAX_SIZE_DIFFERENCE 100
  8. #define SPEC_VOCAB_CHECK_START_TOKEN_ID 5
  9. struct seq_draft {
  10. bool active = false;
  11. bool drafting = false;
  12. bool skip = false;
  13. int i_batch_dft = 0;
  14. std::vector<int> i_batch_tgt;
  15. std::vector<llama_token> tokens;
  16. struct llama_sampling_context * ctx_sampling;
  17. };
  18. int main(int argc, char ** argv) {
  19. gpt_params params;
  20. if (gpt_params_parse(argc, argv, params) == false) {
  21. return 1;
  22. }
  23. if (params.model_draft.empty()) {
  24. fprintf(stderr, "%s: error: --model-draft is required\n", __func__);
  25. return 1;
  26. }
  27. // max number of parallel drafting sequences (i.e. tree branches)
  28. const int n_seq_dft = params.n_parallel;
  29. // probability threshold for accepting a token from the draft model
  30. const float p_accept = params.p_accept;
  31. // probability threshold for splitting a draft branch (only for n_seq_dft > 1)
  32. const float p_split = params.p_split;
  33. #ifndef LOG_DISABLE_LOGS
  34. log_set_target(log_filename_generator("speculative", "log"));
  35. LOG_TEE("Log start\n");
  36. log_dump_cmdline(argc, argv);
  37. #endif // LOG_DISABLE_LOGS
  38. // init llama.cpp
  39. llama_backend_init();
  40. llama_numa_init(params.numa);
  41. llama_model * model_tgt = NULL;
  42. llama_model * model_dft = NULL;
  43. llama_context * ctx_tgt = NULL;
  44. llama_context * ctx_dft = NULL;
  45. // load the target model
  46. params.logits_all = true;
  47. std::tie(model_tgt, ctx_tgt) = llama_init_from_gpt_params(params);
  48. // load the draft model
  49. params.model = params.model_draft;
  50. params.n_gpu_layers = params.n_gpu_layers_draft;
  51. if (params.n_threads_draft > 0) {
  52. params.n_threads = params.n_threads_draft;
  53. }
  54. params.n_threads_batch = params.n_threads_batch_draft;
  55. std::tie(model_dft, ctx_dft) = llama_init_from_gpt_params(params);
  56. {
  57. const int n_vocab_tgt = llama_n_vocab(model_tgt);
  58. const int n_vocab_dft = llama_n_vocab(model_dft);
  59. const int vocab_diff = n_vocab_tgt > n_vocab_dft
  60. ? n_vocab_tgt - n_vocab_dft
  61. : n_vocab_dft - n_vocab_tgt;
  62. if (vocab_diff > SPEC_VOCAB_MAX_SIZE_DIFFERENCE) {
  63. fprintf(stderr, "%s: error: draft model vocab must closely match target model to use speculation but ", __func__);
  64. fprintf(stderr, "target vocab size %d does not match draft vocab size %d - difference %d, max allowed %d\n",
  65. n_vocab_tgt, llama_n_vocab(model_dft), vocab_diff, SPEC_VOCAB_MAX_SIZE_DIFFERENCE);
  66. return 1;
  67. }
  68. for (int i = SPEC_VOCAB_CHECK_START_TOKEN_ID; i < std::min(n_vocab_tgt, n_vocab_dft); ++i) {
  69. const char * token_text_tgt = llama_token_get_text(model_tgt, i);
  70. const char * token_text_dft = llama_token_get_text(model_dft, i);
  71. if (std::strcmp(token_text_tgt, token_text_dft) != 0) {
  72. fprintf(stderr, "%s: error: draft model vocab must match target model to use speculation but ", __func__);
  73. fprintf(stderr, "token %d content differs - target '%s', draft '%s'\n", i,
  74. llama_token_to_piece(ctx_tgt, i).c_str(),
  75. llama_token_to_piece(ctx_dft, i).c_str());
  76. return 1;
  77. }
  78. }
  79. }
  80. // Tokenize the prompt
  81. const bool add_bos_tgt = llama_should_add_bos_token(model_tgt);
  82. LOG("add_bos tgt: %d\n", add_bos_tgt);
  83. const bool add_bos_dft = llama_should_add_bos_token(model_dft);
  84. LOG("add_bos dft: %d\n", add_bos_dft);
  85. if (add_bos_tgt != add_bos_dft) {
  86. fprintf(stderr, "%s: error: draft model add_bos must match target model to use speculation but ", __func__);
  87. fprintf(stderr, "add_bos_dft = %d while add_bos_tgt = %d\n", add_bos_dft, add_bos_tgt);
  88. return 1;
  89. }
  90. std::vector<llama_token> inp;
  91. inp = ::llama_tokenize(ctx_tgt, params.prompt, add_bos_tgt, true);
  92. const int max_context_size = llama_n_ctx(ctx_tgt);
  93. const int max_tokens_list_size = max_context_size - 4;
  94. if ((int) inp.size() > max_tokens_list_size) {
  95. fprintf(stderr, "%s: error: prompt too long (%d tokens, max %d)\n", __func__, (int) inp.size(), max_tokens_list_size);
  96. return 1;
  97. }
  98. fprintf(stderr, "\n\n");
  99. for (auto id : inp) {
  100. fprintf(stderr, "%s", llama_token_to_piece(ctx_tgt, id).c_str());
  101. }
  102. fflush(stderr);
  103. const int n_input = inp.size();
  104. const auto t_enc_start = ggml_time_us();
  105. // eval the prompt with both models
  106. llama_decode(ctx_tgt, llama_batch_get_one( inp.data(), n_input - 1, 0, 0));
  107. llama_decode(ctx_tgt, llama_batch_get_one(&inp.back(), 1, n_input - 1, 0));
  108. llama_decode(ctx_dft, llama_batch_get_one( inp.data(), n_input, 0, 0));
  109. const auto t_enc_end = ggml_time_us();
  110. // the 2 models should have the same vocab
  111. //GGML_ASSERT(n_vocab == llama_n_vocab(model_dft));
  112. // how many tokens to draft each time
  113. int n_draft = params.n_draft;
  114. int n_predict = 0;
  115. int n_drafted = 0;
  116. int n_accept = 0;
  117. int n_past_tgt = inp.size();
  118. int n_past_dft = inp.size();
  119. // used to determine end of generation
  120. bool has_eos = false;
  121. // target model sampling context
  122. struct llama_sampling_context * ctx_sampling = llama_sampling_init(params.sparams);
  123. // draft sequence data
  124. std::vector<seq_draft> drafts(n_seq_dft);
  125. params.sparams.grammar.clear(); // the draft samplers will copy the target sampler's grammar
  126. params.sparams.temp = -1.0f; // force greedy sampling with probs for the draft model
  127. for (int s = 0; s < n_seq_dft; ++s) {
  128. drafts[s].ctx_sampling = llama_sampling_init(params.sparams);
  129. }
  130. llama_batch batch_dft = llama_batch_init(params.n_ctx, 0, 1);
  131. llama_batch batch_tgt = llama_batch_init(params.n_ctx, 0, n_seq_dft);
  132. const auto t_dec_start = ggml_time_us();
  133. // sample from the last token of the prompt
  134. drafts[0].i_batch_tgt.resize(1);
  135. drafts[0].i_batch_tgt[0] = 0;
  136. while (true) {
  137. // print current draft sequences
  138. for (int s = 0; s < n_seq_dft; ++s) {
  139. if (!drafts[s].active) {
  140. continue;
  141. }
  142. const auto & tokens = drafts[s].tokens;
  143. LOG("draft %d: %s\n", s, LOG_TOKENS_TOSTR_PRETTY(ctx_dft, tokens).c_str());
  144. }
  145. int i_dft = 0;
  146. int s_keep = 0;
  147. while (true) {
  148. LOG("sampling target: s_keep = %3d, i_dft = %3d, i_batch_tgt = %3d\n", s_keep, i_dft, drafts[s_keep].i_batch_tgt[i_dft]);
  149. // sample from the target model
  150. llama_token id = llama_sampling_sample(ctx_sampling, ctx_tgt, NULL, drafts[s_keep].i_batch_tgt[i_dft]);
  151. llama_sampling_accept(ctx_sampling, ctx_tgt, id, true);
  152. //LOG("last: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx_tgt, ctx_sampling->prev).c_str());
  153. const std::string token_str = llama_token_to_piece(ctx_tgt, id);
  154. if (!params.use_color) {
  155. printf("%s", token_str.c_str());
  156. }
  157. if (id == llama_token_eos(model_tgt)) {
  158. has_eos = true;
  159. }
  160. ++n_predict;
  161. // check if the target token matches any of the drafts
  162. {
  163. bool matches = false;
  164. for (int s = 0; s < n_seq_dft; ++s) {
  165. if (!drafts[s].active) {
  166. continue;
  167. }
  168. if (i_dft < (int) drafts[s].tokens.size() && id == drafts[s].tokens[i_dft]) {
  169. LOG("the sampled target token matches the %dth drafted token of sequence %d (%d, '%s') - accepted\n", i_dft, s, id, token_str.c_str());
  170. s_keep = s;
  171. matches = true;
  172. } else {
  173. drafts[s].active = false;
  174. }
  175. }
  176. if (matches) {
  177. ++n_accept;
  178. ++n_past_tgt;
  179. ++n_past_dft;
  180. ++i_dft;
  181. if (params.use_color) {
  182. // Color token according to its origin sequence
  183. printf("\u001b[%dm%s\u001b[37m", (36 - s_keep % 6), token_str.c_str());
  184. fflush(stdout);
  185. }
  186. continue;
  187. }
  188. }
  189. if (params.use_color) {
  190. printf("%s", token_str.c_str());
  191. }
  192. fflush(stdout);
  193. LOG("the sampled target token (%d, '%s') did not match, or we ran out of drafted tokens\n", id, token_str.c_str());
  194. // TODO: simplify
  195. {
  196. LOG("keeping sequence %d, n_past_tgt = %d, n_past_dft = %d\n", s_keep, n_past_tgt, n_past_dft);
  197. llama_kv_cache_seq_keep(ctx_dft, s_keep);
  198. llama_kv_cache_seq_cp (ctx_dft, s_keep, 0, -1, -1);
  199. llama_kv_cache_seq_keep(ctx_dft, 0);
  200. llama_kv_cache_seq_rm (ctx_tgt, s_keep, n_past_tgt, -1);
  201. llama_kv_cache_seq_keep(ctx_tgt, s_keep);
  202. llama_kv_cache_seq_cp (ctx_tgt, s_keep, 0, -1, -1);
  203. llama_kv_cache_seq_keep(ctx_tgt, 0);
  204. }
  205. for (int s = 0; s < n_seq_dft; ++s) {
  206. drafts[s].active = false;
  207. drafts[s].tokens.clear();
  208. drafts[s].i_batch_tgt.clear();
  209. }
  210. // note: will be erased after the speculation phase
  211. drafts[0].tokens.push_back(id);
  212. drafts[0].i_batch_tgt.push_back(0);
  213. llama_batch_clear(batch_dft);
  214. llama_batch_add (batch_dft, id, n_past_dft, { 0 }, true);
  215. llama_kv_cache_seq_rm(ctx_dft, 0, n_past_dft, -1);
  216. // LOG("dft batch: %s\n", LOG_BATCH_TOSTR_PRETTY(ctx_dft, batch_dft).c_str());
  217. llama_decode (ctx_dft, batch_dft);
  218. ++n_past_dft;
  219. break;
  220. }
  221. if (n_predict > params.n_predict || has_eos) {
  222. break;
  223. }
  224. llama_sampling_cp(ctx_sampling, drafts[0].ctx_sampling);
  225. int n_seq_cur = 1;
  226. int n_past_cur = n_past_dft;
  227. for (int s = 0; s < n_seq_dft; ++s) {
  228. drafts[s].active = false;
  229. drafts[s].drafting = false;
  230. }
  231. drafts[0].active = true;
  232. drafts[0].drafting = true;
  233. drafts[0].i_batch_dft = 0;
  234. llama_batch_clear(batch_tgt);
  235. llama_batch_add (batch_tgt, drafts[0].tokens[0], n_past_tgt, { 0 }, true);
  236. // sample n_draft tokens from the draft model using tree-based sampling
  237. for (int i = 0; i < n_draft; ++i) {
  238. batch_dft.n_tokens = 0;
  239. for (int s = 0; s < n_seq_dft; ++s) {
  240. drafts[s].skip = false;
  241. }
  242. for (int s = 0; s < n_seq_dft; ++s) {
  243. if (!drafts[s].drafting || drafts[s].skip) {
  244. continue;
  245. }
  246. llama_sampling_sample(drafts[s].ctx_sampling, ctx_dft, NULL, drafts[s].i_batch_dft);
  247. const auto & cur_p = drafts[s].ctx_sampling->cur;
  248. for (int k = 0; k < std::min(n_seq_dft + 3, (int) cur_p.size()); ++k) {
  249. LOG(" - draft candidate %3d for seq %3d, pos %3d: %6d (%8.3f) '%s'\n",
  250. k, s, i, cur_p[k].id, cur_p[k].p, llama_token_to_piece(ctx_dft, cur_p[k].id).c_str());
  251. }
  252. if (cur_p[0].p < p_accept) {
  253. LOG("stopping drafting for seq %3d, probability too low: %.3f < %.3f\n", s, cur_p[0].p, p_accept);
  254. drafts[s].drafting = false;
  255. continue;
  256. }
  257. std::vector<int> sa(1, s);
  258. // attempt to split the branch if the probability is high enough
  259. for (int f = 1; f < 8; ++f) {
  260. if (n_seq_cur < n_seq_dft && cur_p[f].p > p_split) {
  261. LOG("splitting seq %3d into %3d\n", s, n_seq_cur);
  262. llama_kv_cache_seq_rm(ctx_dft, n_seq_cur, -1, -1);
  263. llama_kv_cache_seq_cp(ctx_dft, s, n_seq_cur, -1, -1);
  264. // all previous tokens from this branch are now also part of the new branch
  265. for (int t = 0; t < batch_tgt.n_tokens; ++t) {
  266. for (int p = 0; p < batch_tgt.n_seq_id[t]; ++p) {
  267. if (batch_tgt.seq_id[t][p] == s) {
  268. batch_tgt.seq_id[t][batch_tgt.n_seq_id[t]] = n_seq_cur;
  269. batch_tgt.n_seq_id[t]++;
  270. break;
  271. }
  272. }
  273. }
  274. // copy the draft state
  275. drafts[n_seq_cur].active = true;
  276. drafts[n_seq_cur].drafting = true;
  277. drafts[n_seq_cur].skip = true;
  278. drafts[n_seq_cur].tokens = drafts[s].tokens;
  279. drafts[n_seq_cur].i_batch_dft = drafts[s].i_batch_dft;
  280. drafts[n_seq_cur].i_batch_tgt = drafts[s].i_batch_tgt;
  281. llama_sampling_cp(drafts[s].ctx_sampling, drafts[n_seq_cur].ctx_sampling);
  282. sa.push_back(n_seq_cur);
  283. n_seq_cur++;
  284. } else {
  285. break;
  286. }
  287. }
  288. // add drafted token for each sequence
  289. for (int is = 0; is < (int) sa.size(); ++is) {
  290. const llama_token id = cur_p[is].id;
  291. const int s = sa[is];
  292. llama_sampling_accept(drafts[s].ctx_sampling, ctx_dft, id, true);
  293. drafts[s].tokens.push_back(id);
  294. // add unique drafted tokens to the target batch
  295. drafts[s].i_batch_tgt.push_back(batch_tgt.n_tokens);
  296. llama_batch_add(batch_tgt, id, n_past_tgt + i + 1, { s }, true);
  297. // add the token to the batch for batched decoding with the draft model
  298. drafts[s].i_batch_dft = batch_dft.n_tokens;
  299. llama_batch_add(batch_dft, id, n_past_cur, { s }, true);
  300. if (batch_tgt.n_tokens > n_draft) {
  301. drafts[s].drafting = false;
  302. }
  303. }
  304. }
  305. // no sequence is drafting anymore
  306. if (batch_dft.n_tokens == 0) {
  307. break;
  308. }
  309. // evaluate the drafted tokens on the draft model
  310. llama_decode(ctx_dft, batch_dft);
  311. ++n_past_cur;
  312. ++n_drafted;
  313. if (batch_tgt.n_tokens > n_draft) {
  314. break;
  315. }
  316. }
  317. // evaluate the target model on the drafted tokens
  318. {
  319. llama_kv_cache_seq_keep(ctx_tgt, 0);
  320. for (int s = 1; s < n_seq_dft; ++s) {
  321. llama_kv_cache_seq_cp(ctx_tgt, 0, s, -1, -1);
  322. }
  323. // LOG("target batch: %s\n", LOG_BATCH_TOSTR_PRETTY(ctx_tgt, batch_tgt).c_str());
  324. llama_decode(ctx_tgt, batch_tgt);
  325. ++n_past_tgt;
  326. }
  327. // the first token is always proposed by the target model before the speculation loop so we erase it here
  328. for (int s = 0; s < n_seq_dft; ++s) {
  329. if (!drafts[s].active) {
  330. continue;
  331. }
  332. drafts[s].tokens.erase(drafts[s].tokens.begin());
  333. }
  334. }
  335. auto t_dec_end = ggml_time_us();
  336. LOG_TEE("\n\n");
  337. 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));
  338. 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));
  339. LOG_TEE("\n");
  340. LOG_TEE("n_draft = %d\n", n_draft);
  341. LOG_TEE("n_predict = %d\n", n_predict);
  342. LOG_TEE("n_drafted = %d\n", n_drafted);
  343. LOG_TEE("n_accept = %d\n", n_accept);
  344. LOG_TEE("accept = %.3f%%\n", 100.0f * n_accept / n_drafted);
  345. LOG_TEE("\ndraft:\n");
  346. llama_print_timings(ctx_dft);
  347. LOG_TEE("\ntarget:\n");
  348. llama_print_timings(ctx_tgt);
  349. llama_sampling_free(ctx_sampling);
  350. for (int s = 0; s < n_seq_dft; ++s) {
  351. llama_sampling_free(drafts[s].ctx_sampling);
  352. }
  353. llama_batch_free(batch_dft);
  354. llama_free(ctx_tgt);
  355. llama_free_model(model_tgt);
  356. llama_free(ctx_dft);
  357. llama_free_model(model_dft);
  358. llama_backend_free();
  359. fprintf(stderr, "\n\n");
  360. return 0;
  361. }