speculative.cpp 25 KB

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