1
0

speculative.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648
  1. #include "arg.h"
  2. #include "common.h"
  3. #include "sampling.h"
  4. #include "log.h"
  5. #include "llama.h"
  6. #include <algorithm>
  7. #include <cstdio>
  8. #include <cstring>
  9. #include <random>
  10. #include <set>
  11. #include <string>
  12. #include <vector>
  13. #define SPEC_VOCAB_MAX_SIZE_DIFFERENCE 128
  14. #define SPEC_VOCAB_CHECK_START_TOKEN_ID 5
  15. struct seq_draft {
  16. bool active = false;
  17. bool drafting = false;
  18. bool skip = false;
  19. int i_batch_dft = 0;
  20. std::vector<int> i_batch_tgt;
  21. std::vector<llama_token> tokens;
  22. std::vector<std::vector<llama_token_data>> dists;
  23. struct common_sampler * smpl = nullptr;
  24. };
  25. int main(int argc, char ** argv) {
  26. common_params params;
  27. // needed to get candidate probs even for temp <= 0.0
  28. params.sampling.n_probs = 128;
  29. if (!common_params_parse(argc, argv, params, LLAMA_EXAMPLE_SPECULATIVE)) {
  30. return 1;
  31. }
  32. if (params.n_predict < -1) {
  33. LOG_ERR("%s: --n-predict must be >= -1\n", __func__);
  34. return 1;
  35. }
  36. common_init();
  37. if (params.speculative.model.path.empty()) {
  38. LOG_ERR("%s: --model-draft is required\n", __func__);
  39. return 1;
  40. }
  41. // max number of parallel drafting sequences (i.e. tree branches)
  42. const int n_seq_dft = params.n_parallel;
  43. // probability threshold for splitting a draft branch (only for n_seq_dft > 1)
  44. const float p_draft_split = params.speculative.p_split;
  45. std::default_random_engine rng(params.sampling.seed == LLAMA_DEFAULT_SEED ? std::random_device()() : params.sampling.seed);
  46. std::uniform_real_distribution<> u_dist;
  47. // init llama.cpp
  48. llama_backend_init();
  49. llama_numa_init(params.numa);
  50. llama_model * model_tgt = NULL;
  51. llama_model * model_dft = NULL;
  52. llama_context * ctx_tgt = NULL;
  53. llama_context * ctx_dft = NULL;
  54. // load the target model
  55. auto llama_init_tgt = common_init_from_params(params);
  56. model_tgt = llama_init_tgt->model();
  57. ctx_tgt = llama_init_tgt->context();
  58. // load the draft model
  59. params.devices = params.speculative.devices;
  60. params.model = params.speculative.model;
  61. params.n_gpu_layers = params.speculative.n_gpu_layers;
  62. if (params.speculative.cpuparams.n_threads > 0) {
  63. params.cpuparams.n_threads = params.speculative.cpuparams.n_threads;
  64. }
  65. params.cpuparams_batch.n_threads = params.speculative.cpuparams_batch.n_threads;
  66. params.tensor_buft_overrides = params.speculative.tensor_buft_overrides;
  67. auto llama_init_dft = common_init_from_params(params);
  68. model_dft = llama_init_dft->model();
  69. ctx_dft = llama_init_dft->context();
  70. const llama_vocab * vocab_tgt = llama_model_get_vocab(model_tgt);
  71. const llama_vocab * vocab_dft = llama_model_get_vocab(model_dft);
  72. const bool vocab_type_tgt = llama_vocab_type(vocab_tgt);
  73. LOG_DBG("vocab_type tgt: %d\n", vocab_type_tgt);
  74. const bool vocab_type_dft = llama_vocab_type(vocab_dft);
  75. LOG_DBG("vocab_type dft: %d\n", vocab_type_dft);
  76. if (vocab_type_tgt != vocab_type_dft) {
  77. LOG_ERR("%s: draft model vocab type must match target model to use speculation but ", __func__);
  78. LOG_ERR("vocab_type_dft = %d while vocab_type_tgt = %d\n", vocab_type_dft, vocab_type_tgt);
  79. return 1;
  80. }
  81. if (
  82. llama_vocab_get_add_bos(vocab_tgt) != llama_vocab_get_add_bos(vocab_dft) ||
  83. llama_vocab_get_add_eos(vocab_tgt) != llama_vocab_get_add_eos(vocab_dft) ||
  84. llama_vocab_bos(vocab_tgt) != llama_vocab_bos(vocab_dft) ||
  85. llama_vocab_eos(vocab_tgt) != llama_vocab_eos(vocab_dft)
  86. ) {
  87. LOG_ERR("%s: draft model special tokens must match target model to use speculation\n", __func__);
  88. return 1;
  89. }
  90. {
  91. const int n_vocab_tgt = llama_vocab_n_tokens(vocab_tgt);
  92. const int n_vocab_dft = llama_vocab_n_tokens(vocab_dft);
  93. const int vocab_diff = n_vocab_tgt > n_vocab_dft
  94. ? n_vocab_tgt - n_vocab_dft
  95. : n_vocab_dft - n_vocab_tgt;
  96. if (vocab_diff > SPEC_VOCAB_MAX_SIZE_DIFFERENCE) {
  97. LOG_ERR("%s: draft model vocab must closely match target model to use speculation but ", __func__);
  98. LOG_ERR("target vocab size %d does not match draft vocab size %d - difference %d, max allowed %d\n",
  99. n_vocab_tgt, llama_vocab_n_tokens(vocab_dft), vocab_diff, SPEC_VOCAB_MAX_SIZE_DIFFERENCE);
  100. return 1;
  101. }
  102. for (int i = SPEC_VOCAB_CHECK_START_TOKEN_ID; i < std::min(n_vocab_tgt, n_vocab_dft); ++i) {
  103. const char * token_text_tgt = llama_vocab_get_text(vocab_tgt, i);
  104. const char * token_text_dft = llama_vocab_get_text(vocab_dft, i);
  105. if (std::strcmp(token_text_tgt, token_text_dft) != 0) {
  106. LOG_ERR("%s: draft model vocab must match target model to use speculation but ", __func__);
  107. LOG_ERR("token %d content differs - target '%s', draft '%s'\n", i,
  108. common_token_to_piece(ctx_tgt, i).c_str(),
  109. common_token_to_piece(ctx_dft, i).c_str());
  110. return 1;
  111. }
  112. }
  113. }
  114. auto * mem_tgt = llama_get_memory(ctx_tgt);
  115. auto * mem_dft = llama_get_memory(ctx_dft);
  116. // Tokenize the prompt
  117. std::vector<llama_token> inp;
  118. inp = common_tokenize(ctx_tgt, params.prompt, true, true);
  119. const int max_context_size = llama_n_ctx(ctx_tgt);
  120. const int max_tokens_list_size = max_context_size - 4;
  121. if ((int) inp.size() > max_tokens_list_size) {
  122. LOG_ERR("%s: prompt too long (%d tokens, max %d)\n", __func__, (int) inp.size(), max_tokens_list_size);
  123. return 1;
  124. }
  125. LOG("\n\n");
  126. for (auto id : inp) {
  127. LOG("%s", common_token_to_piece(ctx_tgt, id).c_str());
  128. }
  129. const int n_input = inp.size();
  130. const auto t_enc_start = ggml_time_us();
  131. // eval the prompt with both models
  132. llama_decode(ctx_tgt, llama_batch_get_one( inp.data(), n_input - 1));
  133. llama_decode(ctx_tgt, llama_batch_get_one(&inp.back(), 1));
  134. llama_decode(ctx_dft, llama_batch_get_one( inp.data(), n_input));
  135. const auto t_enc_end = ggml_time_us();
  136. // the 2 models should have the same vocab
  137. //GGML_ASSERT(n_vocab == llama_vocab_n_tokens(model_dft));
  138. // how many tokens to draft each time
  139. int n_draft = params.speculative.n_max;
  140. int n_predict = 0;
  141. int n_drafted = 0;
  142. int n_accept = 0;
  143. int n_past_tgt = inp.size();
  144. int n_past_dft = inp.size();
  145. // used to determine end of generation
  146. bool has_eos = false;
  147. // target model sampling context (reuse the llama_context's sampling instance)
  148. struct common_sampler * smpl = common_sampler_init(model_tgt, params.sampling);
  149. // draft sequence data
  150. std::vector<seq_draft> drafts(n_seq_dft);
  151. for (int s = 0; s < n_seq_dft; ++s) {
  152. // allocate llama_sampler for each draft sequence
  153. drafts[s].smpl = common_sampler_init(model_dft, params.sampling);
  154. }
  155. llama_batch batch_dft = llama_batch_init(llama_n_batch(ctx_dft), 0, 1);
  156. llama_batch batch_tgt = llama_batch_init(llama_n_batch(ctx_tgt), 0, n_seq_dft);
  157. const auto t_dec_start = ggml_time_us();
  158. // sample from the last token of the prompt
  159. drafts[0].i_batch_tgt.resize(1);
  160. drafts[0].i_batch_tgt[0] = 0;
  161. while (true) {
  162. std::set<int> active_seqs = {};
  163. // print current draft sequences
  164. for (int s = 0; s < n_seq_dft; ++s) {
  165. if (!drafts[s].active) {
  166. continue;
  167. }
  168. active_seqs.insert(s);
  169. const auto & tokens = drafts[s].tokens;
  170. LOG_DBG("draft %d: %s\n", s, string_from(ctx_dft, tokens).c_str());
  171. }
  172. int i_dft = 0;
  173. int s_keep = 0;
  174. llama_token token_id;
  175. std::string token_str;
  176. // loop until we fail to accept a drafted token or we run out of drafted tokens
  177. while (true) {
  178. // check if the target token matches any of the drafts
  179. // for stochastic sampling, attempt to match the token with the drafted tokens
  180. {
  181. bool accept = false;
  182. if (params.sampling.temp > 0) {
  183. // stochastic verification
  184. common_sampler_sample(smpl, ctx_tgt, drafts[s_keep].i_batch_tgt[i_dft], true);
  185. auto & dist_tgt = *common_sampler_get_candidates(smpl, true);
  186. float p_tgt = 0.0f;
  187. float p_dft = 0.0f;
  188. while (active_seqs.size() > 0) {
  189. // randomly select a sequence to verify from active sequences
  190. std::uniform_int_distribution<unsigned int> u_int_dist(0, active_seqs.size() - 1);
  191. int s = *std::next(active_seqs.begin(), u_int_dist(rng));
  192. if (i_dft >= (int) drafts[s].tokens.size()) {
  193. drafts[s].active = false;
  194. active_seqs.erase(s);
  195. continue;
  196. }
  197. if (accept) {
  198. // if we already accepted a token, we can skip the rest
  199. if (drafts[s].tokens[i_dft] != drafts[s_keep].tokens[i_dft]) {
  200. drafts[s].active = false;
  201. active_seqs.erase(s);
  202. }
  203. continue;
  204. }
  205. LOG_DBG("verifying sequence #%d at pos #%d from %d active sequence(s)\n", s, i_dft, (int) active_seqs.size());
  206. float r = u_dist(rng);
  207. llama_token_data_array dist_dft = { drafts[s].dists[i_dft].data() , drafts[s].dists[i_dft].size(), LLAMA_TOKEN_NULL, true };
  208. //GGML_ASSERT(dist_tgt.size <= dist_dft.size);
  209. // acquire the token probabilities assigned by the draft and target models
  210. for (size_t i = 0; i < dist_tgt.size; i++) {
  211. if (dist_tgt.data[i].id == drafts[s].tokens[i_dft]) {
  212. p_tgt = dist_tgt.data[i].p;
  213. break;
  214. }
  215. }
  216. for (size_t i = 0; i < dist_dft.size; i++) {
  217. if (dist_dft.data[i].id == drafts[s].tokens[i_dft]) {
  218. p_dft = dist_dft.data[i].p;
  219. break;
  220. }
  221. }
  222. LOG_DBG("r = %f, p_dft = %f, p_tgt = %f\n", r, p_dft, p_tgt);
  223. if (r <= p_tgt / p_dft) {
  224. s_keep = s;
  225. accept = true;
  226. token_id = drafts[s].tokens[i_dft];
  227. token_str = common_token_to_piece(ctx_tgt, token_id);
  228. common_sampler_accept(smpl, token_id, true);
  229. LOG_DBG("draft token %d of sequence %d (%d, '%s') accepted\n", i_dft, s, token_id, token_str.c_str());
  230. break;
  231. } else {
  232. LOG_DBG("draft token %d of sequence %d (%d, '%s') rejected\n", i_dft, s, drafts[s].tokens[i_dft], common_token_to_piece(ctx_tgt, drafts[s].tokens[i_dft]).c_str());
  233. drafts[s].active = false;
  234. // calculate residual probability
  235. GGML_ASSERT(dist_tgt.sorted);
  236. GGML_ASSERT(dist_dft.sorted);
  237. // sort dist by id
  238. std::sort(dist_tgt.data, dist_tgt.data + dist_tgt.size, [](const llama_token_data &a, const llama_token_data &b) {
  239. return a.id < b.id;
  240. });
  241. std::sort(dist_dft.data, dist_dft.data + dist_dft.size, [](const llama_token_data &a, const llama_token_data &b) {
  242. return a.id < b.id;
  243. });
  244. float sum_probs = 0.0f;
  245. for (size_t i = 0; i < dist_tgt.size; i++) {
  246. if (i < dist_dft.size) {
  247. dist_tgt.data[i].p = std::max(0.0f, dist_tgt.data[i].p - dist_dft.data[i].p);
  248. } else {
  249. dist_tgt.data[i].p = std::max(0.0f, dist_tgt.data[i].p);
  250. }
  251. sum_probs += dist_tgt.data[i].p;
  252. }
  253. for (size_t i = 0; i < dist_tgt.size; i++) {
  254. dist_tgt.data[i].p /= sum_probs;
  255. }
  256. // sort dist_tgt by p desc
  257. std::sort(dist_tgt.data, dist_tgt.data + dist_tgt.size, [](const llama_token_data &a, const llama_token_data &b) {
  258. return a.p > b.p;
  259. });
  260. }
  261. active_seqs.erase(s);
  262. for (int i = 0; i < n_seq_dft; i++) {
  263. if (i == s) {
  264. continue;
  265. }
  266. if (drafts[i].active && drafts[i].tokens[i_dft] == drafts[s].tokens[i_dft]) {
  267. // synchronize active status for sequences with the same drafted token
  268. drafts[i].active = drafts[i].active && accept;
  269. if (!drafts[i].active) {
  270. active_seqs.erase(s);
  271. }
  272. }
  273. }
  274. }
  275. if (!accept) {
  276. // all drafted tokens were rejected
  277. // sample from the target model
  278. LOG_DBG("all drafted tokens were rejected, sampling from residual distribution\n");
  279. std::vector<float> probs(dist_tgt.size);
  280. for (size_t i = 0; i < dist_tgt.size; ++i) {
  281. probs[i] = dist_tgt.data[i].p;
  282. }
  283. std::discrete_distribution<> dist(probs.begin(), probs.end());
  284. const int idx = dist(rng);
  285. token_id = dist_tgt.data[idx].id;
  286. common_sampler_accept(smpl, token_id, true);
  287. token_str = common_token_to_piece(ctx_tgt, token_id);
  288. }
  289. } else {
  290. // greedy verification
  291. // sample from the target model
  292. LOG_DBG("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]);
  293. token_id = common_sampler_sample(smpl, ctx_tgt, drafts[s_keep].i_batch_tgt[i_dft]);
  294. common_sampler_accept(smpl, token_id, true);
  295. token_str = common_token_to_piece(ctx_tgt, token_id);
  296. for (int s = 0; s < n_seq_dft; ++s) {
  297. if (!drafts[s].active) {
  298. continue;
  299. }
  300. if (i_dft < (int) drafts[s].tokens.size() && token_id == drafts[s].tokens[i_dft]) {
  301. LOG_DBG("the sampled target token matches the %dth drafted token of sequence %d (%d, '%s') - accepted\n", i_dft, s, token_id, token_str.c_str());
  302. s_keep = s;
  303. accept = true;
  304. } else {
  305. drafts[s].active = false;
  306. }
  307. }
  308. }
  309. if (llama_vocab_is_eog(vocab_tgt, token_id)) {
  310. has_eos = true;
  311. }
  312. ++n_predict;
  313. if (accept) {
  314. ++n_accept;
  315. ++n_past_tgt;
  316. ++n_past_dft;
  317. ++i_dft;
  318. if (params.use_color) {
  319. // Color token according to its origin sequence
  320. LOG("\u001b[%dm%s\u001b[37m", (36 - s_keep % 6), token_str.c_str());
  321. } else {
  322. LOG("%s", token_str.c_str());
  323. }
  324. continue;
  325. } else {
  326. LOG("%s", token_str.c_str());
  327. break;
  328. }
  329. }
  330. }
  331. {
  332. LOG_DBG("the sampled target token (%d, '%s') did not match, or we ran out of drafted tokens\n", token_id, token_str.c_str());
  333. // TODO: simplify
  334. {
  335. LOG_DBG("keeping sequence %d, n_past_tgt = %d, n_past_dft = %d\n", s_keep, n_past_tgt, n_past_dft);
  336. llama_memory_seq_keep(mem_dft, s_keep);
  337. llama_memory_seq_cp (mem_dft, s_keep, 0, -1, -1);
  338. llama_memory_seq_keep(mem_dft, 0);
  339. llama_memory_seq_rm (mem_tgt, s_keep, n_past_tgt, -1);
  340. llama_memory_seq_keep(mem_tgt, s_keep);
  341. llama_memory_seq_cp (mem_tgt, s_keep, 0, -1, -1);
  342. llama_memory_seq_keep(mem_tgt, 0);
  343. }
  344. for (int s = 0; s < n_seq_dft; ++s) {
  345. drafts[s].active = false;
  346. drafts[s].tokens.clear();
  347. drafts[s].i_batch_tgt.clear();
  348. drafts[s].dists.clear();
  349. }
  350. // note: will be erased after the speculation phase
  351. drafts[0].tokens.push_back(token_id);
  352. drafts[0].dists.push_back(std::vector<llama_token_data>());
  353. drafts[0].i_batch_tgt.push_back(0);
  354. common_batch_clear(batch_dft);
  355. common_batch_add (batch_dft, token_id, n_past_dft, { 0 }, true);
  356. llama_memory_seq_rm(mem_dft, 0, n_past_dft, -1);
  357. // LOG_DBG("dft batch: %s\n", LOG_BATCH_TOSTR_PRETTY(ctx_dft, batch_dft).c_str());
  358. llama_decode(ctx_dft, batch_dft);
  359. ++n_past_dft;
  360. }
  361. if ((params.n_predict >= 0 && n_predict > params.n_predict) || has_eos) {
  362. break;
  363. }
  364. if (drafts[0].smpl) {
  365. common_sampler_free(drafts[0].smpl);
  366. }
  367. drafts[0].smpl = common_sampler_clone(smpl);
  368. int n_seq_cur = 1;
  369. int n_past_cur = n_past_dft;
  370. for (int s = 0; s < n_seq_dft; ++s) {
  371. drafts[s].active = false;
  372. drafts[s].drafting = false;
  373. }
  374. drafts[0].active = true;
  375. drafts[0].drafting = true;
  376. drafts[0].i_batch_dft = 0;
  377. common_batch_clear(batch_tgt);
  378. common_batch_add (batch_tgt, drafts[0].tokens[0], n_past_tgt, { 0 }, true);
  379. // sample n_draft tokens from the draft model using tree-based sampling
  380. for (int i = 0; i < n_draft; ++i) {
  381. batch_dft.n_tokens = 0;
  382. for (int s = 0; s < n_seq_dft; ++s) {
  383. drafts[s].skip = false;
  384. }
  385. for (int s = 0; s < n_seq_dft; ++s) {
  386. if (!drafts[s].drafting || drafts[s].skip) {
  387. continue;
  388. }
  389. common_sampler_sample(drafts[s].smpl, ctx_dft, drafts[s].i_batch_dft, true);
  390. const auto * cur_p = common_sampler_get_candidates(drafts[s].smpl, true);
  391. for (int k = 0; k < std::min(n_seq_dft + 3, (int) cur_p->size); ++k) {
  392. LOG_DBG(" - draft candidate %3d for seq %3d, pos %3d: %6d (%8.3f) '%s'\n",
  393. k, s, i, cur_p->data[k].id, cur_p->data[k].p, common_token_to_piece(ctx_dft, cur_p->data[k].id).c_str());
  394. }
  395. std::vector<int> sa(1, s);
  396. // attempt to split the branch if the probability is high enough
  397. for (int f = 1; f < 8; ++f) {
  398. if (n_seq_cur < n_seq_dft && cur_p->data[f].p > p_draft_split) {
  399. LOG_DBG("splitting seq %3d into %3d\n", s, n_seq_cur);
  400. llama_memory_seq_rm(mem_dft, n_seq_cur, -1, -1);
  401. llama_memory_seq_cp(mem_dft, s, n_seq_cur, -1, -1);
  402. // all previous tokens from this branch are now also part of the new branch
  403. for (int t = 0; t < batch_tgt.n_tokens; ++t) {
  404. for (int p = 0; p < batch_tgt.n_seq_id[t]; ++p) {
  405. if (batch_tgt.seq_id[t][p] == s) {
  406. batch_tgt.seq_id[t][batch_tgt.n_seq_id[t]] = n_seq_cur;
  407. batch_tgt.n_seq_id[t]++;
  408. break;
  409. }
  410. }
  411. }
  412. // copy the draft state
  413. drafts[n_seq_cur].active = true;
  414. drafts[n_seq_cur].drafting = true;
  415. drafts[n_seq_cur].skip = true;
  416. drafts[n_seq_cur].tokens = drafts[s].tokens;
  417. drafts[n_seq_cur].dists = drafts[s].dists;
  418. drafts[n_seq_cur].i_batch_dft = drafts[s].i_batch_dft;
  419. drafts[n_seq_cur].i_batch_tgt = drafts[s].i_batch_tgt;
  420. if (drafts[n_seq_cur].smpl) {
  421. common_sampler_free(drafts[n_seq_cur].smpl);
  422. }
  423. drafts[n_seq_cur].smpl = common_sampler_clone(drafts[s].smpl);
  424. sa.push_back(n_seq_cur);
  425. n_seq_cur++;
  426. } else {
  427. break;
  428. }
  429. }
  430. // add drafted token for each sequence
  431. for (int is = 0; is < (int) sa.size(); ++is) {
  432. const llama_token id = cur_p->data[is].id;
  433. const int s = sa[is];
  434. common_sampler_accept(drafts[s].smpl, id, true);
  435. drafts[s].tokens.push_back(id);
  436. // save cur_p.data into drafts[s].dists
  437. drafts[s].dists.push_back({cur_p->data, cur_p->data + cur_p->size});
  438. // add unique drafted tokens to the target batch
  439. drafts[s].i_batch_tgt.push_back(batch_tgt.n_tokens);
  440. common_batch_add(batch_tgt, id, n_past_tgt + i + 1, { s }, true);
  441. // add the token to the batch for batched decoding with the draft model
  442. drafts[s].i_batch_dft = batch_dft.n_tokens;
  443. common_batch_add(batch_dft, id, n_past_cur, { s }, true);
  444. if (batch_tgt.n_tokens > n_draft) {
  445. drafts[s].drafting = false;
  446. }
  447. }
  448. }
  449. // no sequence is drafting anymore
  450. if (batch_dft.n_tokens == 0) {
  451. break;
  452. }
  453. // evaluate the drafted tokens on the draft model
  454. llama_decode(ctx_dft, batch_dft);
  455. ++n_past_cur;
  456. ++n_drafted;
  457. if (batch_tgt.n_tokens > n_draft) {
  458. break;
  459. }
  460. }
  461. // evaluate the target model on the drafted tokens
  462. {
  463. llama_memory_seq_keep(mem_tgt, 0);
  464. for (int s = 1; s < n_seq_dft; ++s) {
  465. llama_memory_seq_cp(mem_tgt, 0, s, -1, -1);
  466. }
  467. // LOG_DBG("target batch: %s\n", LOG_BATCH_TOSTR_PRETTY(ctx_tgt, batch_tgt).c_str());
  468. llama_decode(ctx_tgt, batch_tgt);
  469. ++n_past_tgt;
  470. }
  471. // the first token is always proposed by the target model before the speculation loop so we erase it here
  472. for (int s = 0; s < n_seq_dft; ++s) {
  473. if (!drafts[s].active) {
  474. continue;
  475. }
  476. drafts[s].tokens.erase(drafts[s].tokens.begin());
  477. drafts[s].dists.erase(drafts[s].dists.begin());
  478. }
  479. }
  480. auto t_dec_end = ggml_time_us();
  481. LOG("\n\n");
  482. LOG_INF("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));
  483. LOG_INF("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));
  484. LOG_INF("\n");
  485. LOG_INF("n_draft = %d\n", n_draft);
  486. LOG_INF("n_predict = %d\n", n_predict);
  487. LOG_INF("n_drafted = %d\n", n_drafted);
  488. LOG_INF("n_accept = %d\n", n_accept);
  489. LOG_INF("accept = %.3f%%\n", 100.0f * n_accept / n_drafted);
  490. LOG_INF("\n");
  491. LOG_INF("draft:\n\n");
  492. // TODO: print sampling/grammar timings for all drafts
  493. llama_perf_context_print(ctx_dft);
  494. LOG_INF("\n");
  495. LOG_INF("target:\n\n");
  496. common_perf_print(ctx_tgt, smpl);
  497. common_sampler_free(smpl);
  498. for (int s = 0; s < n_seq_dft; ++s) {
  499. common_sampler_free(drafts[s].smpl);
  500. }
  501. llama_batch_free(batch_dft);
  502. llama_backend_free();
  503. LOG("\n\n");
  504. return 0;
  505. }