summaryrefslogtreecommitdiff
path: root/examples/speculative
diff options
context:
space:
mode:
authorGeorgi Gerganov <ggerganov@gmail.com>2023-10-18 16:21:57 +0300
committerGitHub <noreply@github.com>2023-10-18 16:21:57 +0300
commit0e89203b517c95ec6675eda75d200a60d1e8921d (patch)
tree3aba40ef0362d061f240bd43c52e86a8f728f89d /examples/speculative
parentc67fe68e417f766970fb1feaf2e66458aa24116a (diff)
speculative : add tree-based sampling example (#3624)
* sampling : one sequence per sampling context ggml-ci * speculative : add tree-based sampling support ggml-ci * speculative : reuse the n_parallel CLI param * speculative : refactor sampling * examples : fix build after sampling refactoring ggml-ci * batched : fix n_seq_id * sampling : fix malloc ggml-ci * swift : fix build ggml-ci * swift : try to fix build ggml-ci * prompts : add assistant.txt * common : add llama_batch_add() and llama_batch_clear() helpers * speculative : minor refactor ggml-ci * minor : comments + rename ggml-ci * speculative : fix off-by-one for n_drafted * speculative : fix the n_drafted fix + p constants
Diffstat (limited to 'examples/speculative')
-rw-r--r--examples/speculative/speculative.cpp367
1 files changed, 239 insertions, 128 deletions
diff --git a/examples/speculative/speculative.cpp b/examples/speculative/speculative.cpp
index 018dbf9a..53f42fad 100644
--- a/examples/speculative/speculative.cpp
+++ b/examples/speculative/speculative.cpp
@@ -2,13 +2,25 @@
#include "common.h"
#include "llama.h"
-#include "grammar-parser.h"
#include <cmath>
#include <cstdio>
#include <string>
#include <vector>
+struct seq_draft {
+ bool active = false;
+ bool drafting = false;
+ bool skip = false;
+
+ int i_batch_dft = 0;
+ std::vector<int> i_batch_tgt;
+
+ std::vector<llama_token> tokens;
+
+ struct llama_sampling_context * ctx_sampling;
+};
+
int main(int argc, char ** argv) {
gpt_params params;
@@ -21,6 +33,13 @@ int main(int argc, char ** argv) {
return 1;
}
+ // max number of parallel drafting sequences (i.e. tree branches)
+ const int n_seq_dft = params.n_parallel;
+
+ // TODO: make this configurable
+ const float p_accept = 0.4f;
+ const float p_split = 0.3f;
+
#ifndef LOG_DISABLE_LOGS
log_set_target(log_filename_generator("speculative", "log"));
LOG_TEE("Log start\n");
@@ -77,8 +96,6 @@ int main(int argc, char ** argv) {
const auto t_enc_end = ggml_time_us();
// the 2 models should have the same vocab
- const int n_ctx = llama_n_ctx(ctx_tgt);
- const int n_vocab = llama_n_vocab(model_tgt);
//GGML_ASSERT(n_vocab == llama_n_vocab(model_dft));
// how many tokens to draft each time
@@ -91,60 +108,58 @@ int main(int argc, char ** argv) {
int n_past_tgt = inp.size();
int n_past_dft = inp.size();
- std::vector<llama_token> drafted;
-
- std::vector<llama_token> last_tokens(n_ctx);
- std::fill(last_tokens.begin(), last_tokens.end(), 0);
-
- for (auto & id : inp) {
- last_tokens.erase(last_tokens.begin());
- last_tokens.push_back(id);
- }
-
- std::vector<llama_token_data> candidates;
- candidates.reserve(n_vocab);
-
// used to determine end of generation
bool has_eos = false;
- // grammar stuff
- struct llama_grammar * grammar_dft = NULL;
- struct llama_grammar * grammar_tgt = NULL;
+ // target model sampling context
+ struct llama_sampling_context * ctx_sampling = llama_sampling_init(params);
- grammar_parser::parse_state parsed_grammar;
+ // draft sequence data
+ std::vector<seq_draft> drafts(n_seq_dft);
- // if requested - load the grammar, error checking is omitted for brevity
- if (!params.grammar.empty()) {
- parsed_grammar = grammar_parser::parse(params.grammar.c_str());
- // will be empty (default) if there are parse errors
- if (parsed_grammar.rules.empty()) {
- return 1;
- }
+ params.grammar.clear(); // the draft samplers will copy the target sampler's grammar
+ params.sampling_params.temp = 1.0f; // the draft samplers use default temperature
- std::vector<const llama_grammar_element *> grammar_rules(parsed_grammar.c_rules());
- grammar_tgt = llama_grammar_init(grammar_rules.data(), grammar_rules.size(), parsed_grammar.symbol_ids.at("root"));
+ for (int s = 0; s < n_seq_dft; ++s) {
+ drafts[s].ctx_sampling = llama_sampling_init(params);
}
- llama_sampling_context ctx_sampling = llama_sampling_context_init(params, grammar_tgt);
+ llama_batch batch_dft = llama_batch_init(params.n_ctx, 0, 1);
+ llama_batch batch_tgt = llama_batch_init(params.n_ctx, 0, n_seq_dft);
const auto t_dec_start = ggml_time_us();
+ // sample from the last token of the prompt
+ drafts[0].i_batch_tgt.resize(1);
+ drafts[0].i_batch_tgt[0] = 0;
+
while (true) {
- LOG("drafted: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx_dft, drafted));
+ // print current draft sequences
+ for (int s = 0; s < n_seq_dft; ++s) {
+ if (!drafts[s].active) {
+ continue;
+ }
+
+ const auto & tokens = drafts[s].tokens;
- int i_dft = 0;
+ LOG("draft %d: %s\n", s, LOG_TOKENS_TOSTR_PRETTY(ctx_dft, tokens).c_str());
+ }
+
+ int i_dft = 0;
+ int s_keep = 0;
while (true) {
+ 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]);
+
// sample from the target model
- llama_token id = llama_sampling_sample(ctx_tgt, NULL, ctx_sampling, last_tokens, candidates, i_dft);
+ llama_token id = llama_sampling_sample(ctx_sampling, ctx_tgt, NULL, drafts[s_keep].i_batch_tgt[i_dft]);
- // remember which tokens were sampled - used for repetition penalties during sampling
- last_tokens.erase(last_tokens.begin());
- last_tokens.push_back(id);
+ llama_sampling_accept(ctx_sampling, ctx_tgt, id);
//LOG("last: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx_tgt, last_tokens));
const std::string token_str = llama_token_to_piece(ctx_tgt, id);
+
printf("%s", token_str.c_str());
fflush(stdout);
@@ -154,53 +169,67 @@ int main(int argc, char ** argv) {
++n_predict;
- // check if the draft matches the target
- if (i_dft < (int) drafted.size() && id == drafted[i_dft]) {
- LOG("the sampled target token matches the %dth drafted token (%d, '%s') - accepted\n", i_dft, id, token_str.c_str());
- ++n_accept;
- ++n_past_tgt;
- ++n_past_dft;
- ++i_dft;
+ // check if the target token matches any of the drafts
+ {
+ bool matches = false;
- continue;
- }
+ for (int s = 0; s < n_seq_dft; ++s) {
+ if (!drafts[s].active) {
+ continue;
+ }
+
+ if (i_dft < (int) drafts[s].tokens.size() && id == drafts[s].tokens[i_dft]) {
+ 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());
+
+ s_keep = s;
+ matches = true;
+ } else {
+ drafts[s].active = false;
+ }
+ }
- // the drafted token was rejected or we are out of drafted tokens
+ if (matches) {
+ ++n_accept;
+ ++n_past_tgt;
+ ++n_past_dft;
+ ++i_dft;
- if (i_dft < (int) drafted.size()) {
- LOG("the %dth drafted token (%d, '%s') does not match the sampled target token (%d, '%s') - rejected\n",
- i_dft, drafted[i_dft], llama_token_to_piece(ctx_dft, drafted[i_dft]).c_str(), id, token_str.c_str());
- } else {
- LOG("out of drafted tokens\n");
+ continue;
+ }
}
- llama_kv_cache_seq_rm(ctx_dft, 0, n_past_dft, -1);
- llama_decode(ctx_dft, llama_batch_get_one(&id, 1, n_past_dft, 0));
- ++n_past_dft;
+ LOG("the sampled target token (%d, '%s') did not match, or we ran out of drafted tokens\n", id, token_str.c_str());
- // heuristic for n_draft
+ // TODO: simplify
{
- const int n_draft_cur = (int) drafted.size();
- const bool all_accepted = i_dft == n_draft_cur;
-
- LOG("n_draft = %d\n", n_draft);
- LOG("n_draft_cur = %d\n", n_draft_cur);
- LOG("i_dft = %d\n", i_dft);
- LOG("all_accepted = %d\n", all_accepted);
-
- if (all_accepted && n_draft == n_draft_cur) {
- LOG(" - max drafted tokens accepted - n_draft += 8\n");
- n_draft = std::min(30, n_draft + 8);
- } else if (all_accepted) {
- LOG(" - partially drafted tokens accepted - no change\n");
- } else {
- LOG(" - drafted token rejected - n_draft -= 1\n");
- n_draft = std::max(2, n_draft - 1);
- }
+ LOG("keeping sequence %d\n", s_keep);
+
+ llama_kv_cache_seq_keep(ctx_dft, s_keep);
+ llama_kv_cache_seq_cp (ctx_dft, s_keep, 0, -1, -1);
+ llama_kv_cache_seq_keep(ctx_dft, 0);
+
+ llama_kv_cache_seq_rm (ctx_tgt, s_keep, n_past_tgt, -1);
+ llama_kv_cache_seq_keep(ctx_tgt, s_keep);
+ llama_kv_cache_seq_cp (ctx_tgt, s_keep, 0, -1, -1);
+ llama_kv_cache_seq_keep(ctx_tgt, 0);
}
- drafted.clear();
- drafted.push_back(id);
+ for (int s = 0; s < n_seq_dft; ++s) {
+ drafts[s].active = false;
+ drafts[s].tokens.clear();
+ drafts[s].i_batch_tgt.clear();
+ }
+ // note: will be erased after the speculation phase
+ drafts[0].tokens.push_back(id);
+ drafts[0].i_batch_tgt.push_back(0);
+
+ llama_batch_clear(batch_dft);
+ llama_batch_add (batch_dft, id, n_past_dft, { 0 }, true);
+
+ llama_kv_cache_seq_rm(ctx_dft, 0, n_past_dft, -1);
+ llama_decode (ctx_dft, batch_dft);
+
+ ++n_past_dft;
break;
}
@@ -209,78 +238,158 @@ int main(int argc, char ** argv) {
break;
}
- if (grammar_tgt) {
- if (grammar_dft) {
- llama_grammar_free(grammar_dft);
- }
- // Note: Hardcoded to sequence id 0, if this ever supports parallel generation
- // that will need to change.
- auto it = ctx_sampling.sequence_contexts.find(0);
- GGML_ASSERT(it != ctx_sampling.sequence_contexts.end());
- // This is necessary because each sequence id in sequence_contexts
- // uses a copy of the original grammar.
- grammar_dft = llama_grammar_copy(it->second.grammar);
-
- LOG("copied target grammar to draft grammar\n");
- }
+ llama_sampling_cp(ctx_sampling, drafts[0].ctx_sampling);
- // sample n_draft tokens from the draft model using greedy decoding
+ int n_seq_cur = 1;
int n_past_cur = n_past_dft;
+
+ for (int s = 0; s < n_seq_dft; ++s) {
+ drafts[s].active = false;
+ drafts[s].drafting = false;
+ }
+ drafts[0].active = true;
+ drafts[0].drafting = true;
+ drafts[0].i_batch_dft = 0;
+
+ llama_batch_clear(batch_tgt);
+ llama_batch_add (batch_tgt, drafts[0].tokens[0], n_past_tgt, { 0 }, true);
+
+ // sample n_draft tokens from the draft model using tree-based sampling
for (int i = 0; i < n_draft; ++i) {
- float * logits = llama_get_logits(ctx_dft);
+ batch_dft.n_tokens = 0;
- candidates.clear();
- for (llama_token token_id = 0; token_id < n_vocab; token_id++) {
- candidates.emplace_back(llama_token_data{token_id, logits[token_id], 0.0f});
+ for (int s = 0; s < n_seq_dft; ++s) {
+ drafts[s].skip = false;
}
- llama_token_data_array cur_p = { candidates.data(), candidates.size(), false };
+ for (int s = 0; s < n_seq_dft; ++s) {
+ if (!drafts[s].drafting || drafts[s].skip) {
+ continue;
+ }
- if (grammar_dft != NULL) {
- llama_sample_grammar(ctx_dft, &cur_p, grammar_dft);
- }
+ llama_sampling_sample(drafts[s].ctx_sampling, ctx_dft, NULL, drafts[s].i_batch_dft);
+
+ const auto & cur_p = drafts[s].ctx_sampling->cur;
+
+ for (int k = 0; k < std::min(n_seq_dft + 3, (int) cur_p.size()); ++k) {
+ LOG(" - draft candidate %3d for seq %3d, pos %3d: %6d (%8.3f) '%s'\n",
+ k, s, i, cur_p[k].id, cur_p[k].p, llama_token_to_piece(ctx_dft, cur_p[k].id).c_str());
+ }
+
+ if (cur_p[0].p < p_accept) {
+ LOG("stopping drafting for seq %3d, probability too low: %.3f < 2*%.3f\n", s, cur_p[0].p, cur_p[1].p);
+ drafts[s].drafting = false;
+ continue;
+ }
+
+ std::vector<int> sa(1, s);
+
+ // attempt to split the branch if the probability is high enough
+ for (int f = 1; f < 8; ++f) {
+ if (n_seq_cur < n_seq_dft && cur_p[f].p > p_split) {
+ LOG("splitting seq %3d into %3d\n", s, n_seq_cur);
+
+ llama_kv_cache_seq_rm(ctx_dft, n_seq_cur, -1, -1);
+ llama_kv_cache_seq_cp(ctx_dft, s, n_seq_cur, -1, -1);
+
+ // all previous tokens from this branch are now also part of the new branch
+ for (int t = 0; t < batch_tgt.n_tokens; ++t) {
+ for (int p = 0; p < batch_tgt.n_seq_id[t]; ++p) {
+ if (batch_tgt.seq_id[t][p] == s) {
+ batch_tgt.seq_id[t][batch_tgt.n_seq_id[t]] = n_seq_cur;
+ batch_tgt.n_seq_id[t]++;
+ break;
+ }
+ }
+ }
+
+ // copy the draft state
+ drafts[n_seq_cur].active = true;
+ drafts[n_seq_cur].drafting = true;
+ drafts[n_seq_cur].skip = true;
+
+ drafts[n_seq_cur].tokens = drafts[s].tokens;
+ drafts[n_seq_cur].i_batch_dft = drafts[s].i_batch_dft;
+ drafts[n_seq_cur].i_batch_tgt = drafts[s].i_batch_tgt;
+
+ llama_sampling_cp(drafts[s].ctx_sampling, drafts[n_seq_cur].ctx_sampling);
+
+ sa.push_back(n_seq_cur);
+
+ n_seq_cur++;
+ } else {
+ break;
+ }
+ }
+
+ // add drafted token for each sequence
+ for (int is = 0; is < (int) sa.size(); ++is) {
+ const llama_token id = cur_p[is].id;
+
+ const int s = sa[is];
+
+ llama_sampling_accept(drafts[s].ctx_sampling, ctx_dft, id);
- // computes softmax and sorts the candidates
- llama_sample_softmax(ctx_dft, &cur_p);
+ drafts[s].tokens.push_back(id);
- for (int i = 0; i < 3; ++i) {
- LOG(" - draft candidate %3d: %6d (%8.3f) '%s'\n", i, cur_p.data[i].id, cur_p.data[i].p, llama_token_to_piece(ctx_dft, cur_p.data[i].id).c_str());
+ // add unique drafted tokens to the target batch
+ drafts[s].i_batch_tgt.push_back(batch_tgt.n_tokens);
+
+ llama_batch_add(batch_tgt, id, n_past_tgt + i + 1, { s }, true);
+
+ // no need to evaluate the last drafted token, since we won't use the result
+ if (batch_tgt.n_tokens > n_draft) {
+ drafts[s].drafting = false;
+ continue;
+ }
+
+ // add the token to the batch for batched decoding with the draft model
+ drafts[s].i_batch_dft = batch_dft.n_tokens;
+
+ llama_batch_add(batch_dft, id, n_past_cur, { s }, true);
+ }
}
- // TODO: better logic?
- if (cur_p.data[0].p < 2*cur_p.data[1].p) {
- LOG("stopping drafting, probability too low: %.3f < 2*%.3f\n", cur_p.data[0].p, cur_p.data[1].p);
+ // no sequence is drafting anymore
+ if (batch_dft.n_tokens == 0) {
break;
}
- // drafted token
- const llama_token id = cur_p.data[0].id;
-
- drafted.push_back(id);
+ // evaluate the drafted tokens on the draft model
+ llama_decode(ctx_dft, batch_dft);
+ ++n_past_cur;
++n_drafted;
- // no need to evaluate the last drafted token, since we won't use the result
- if (i == n_draft - 1) {
+ if (batch_tgt.n_tokens > n_draft) {
break;
}
+ }
- // evaluate the drafted token on the draft model
- llama_kv_cache_seq_rm(ctx_dft, 0, n_past_cur, -1);
- llama_decode(ctx_dft, llama_batch_get_one(&drafted.back(), 1, n_past_cur, 0));
- ++n_past_cur;
+ // account for the last drafted token that we didn't evaluate
+ if (batch_tgt.n_tokens > n_draft) {
+ ++n_drafted;
+ }
- if (grammar_dft != NULL) {
- llama_grammar_accept_token(ctx_dft, grammar_dft, id);
+ // evaluate the target model on the drafted tokens
+ {
+ llama_kv_cache_seq_keep(ctx_tgt, 0);
+ for (int s = 1; s < n_seq_dft; ++s) {
+ llama_kv_cache_seq_cp(ctx_tgt, 0, s, -1, -1);
}
+
+ //LOG("target batch: %s\n", LOG_BATCH_TOSTR_PRETTY(ctx_tgt, batch_tgt));
+ llama_decode(ctx_tgt, batch_tgt);
+ ++n_past_tgt;
}
- // evaluate the target model on the drafted tokens
- llama_kv_cache_seq_rm(ctx_tgt, 0, n_past_tgt, -1);
- llama_decode(ctx_tgt, llama_batch_get_one(drafted.data(), drafted.size(), n_past_tgt, 0));
- ++n_past_tgt;
+ // the first token is always proposed by the traget model before the speculation loop so we erase it here
+ for (int s = 0; s < n_seq_dft; ++s) {
+ if (!drafts[s].active) {
+ continue;
+ }
- // the first token is always proposed by the traget model before the speculation loop
- drafted.erase(drafted.begin());
+ drafts[s].tokens.erase(drafts[s].tokens.begin());
+ }
}
auto t_dec_end = ggml_time_us();
@@ -288,9 +397,8 @@ int main(int argc, char ** argv) {
LOG_TEE("\n\n");
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));
- 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));
+ 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));
- // TODO: make sure these numbers are computed correctly
LOG_TEE("\n");
LOG_TEE("n_draft = %d\n", n_draft);
LOG_TEE("n_predict = %d\n", n_predict);
@@ -304,16 +412,19 @@ int main(int argc, char ** argv) {
LOG_TEE("\ntarget:\n");
llama_print_timings(ctx_tgt);
+ llama_sampling_free(ctx_sampling);
+ for (int s = 0; s < n_seq_dft; ++s) {
+ llama_sampling_free(drafts[s].ctx_sampling);
+ }
+
+ llama_batch_free(batch_dft);
+
llama_free(ctx_tgt);
llama_free_model(model_tgt);
llama_free(ctx_dft);
llama_free_model(model_dft);
- if (grammar_dft != NULL) {
- llama_grammar_free(grammar_dft);
- llama_grammar_free(grammar_tgt);
- }
llama_backend_free();
fprintf(stderr, "\n\n");