From 02cbe94a40a0ae956bd52faabc49bc1240ac08cb Mon Sep 17 00:00:00 2001 From: rafasmour <54501936+rafasmour@users.noreply.github.com> Date: Fri, 4 Dec 2026 11:32:10 +0000 Subject: [PATCH] spec: step timing, single output sync, opt-in backend greedy verify - LLAMA_SPEC_TIMING=1: per-step timers (draft decode/sample, feature reads, inject, verify launch/sync/prepare/accept) and sync counters, per-request summary. - Readers of decode outputs (llama_get_*, common_sampler_sample/prepare) wait for the backend once per computed batch instead of once per read. LLAMA_SPEC_NO_SINGLE_SYNC=1 restores a wait per read. Bit-identical. - LLAMA_SPEC_DEVICE_VERIFY=1 (opt-in): greedy requests in a speculative server register a backend greedy sampler, so the verify decode does not copy the logits of the rows and the host skips the candidate scan. - tests/test-spec-device-verify.cpp Assisted-by: Claude Sonnet 5.5 --- common/sampling.cpp | 88 +++++++++- common/sampling.h | 9 + common/speculative.cpp | 151 ++++++++++++++--- common/speculative.h | 41 +++++ src/llama-context.cpp | 70 ++++++-- src/llama-context.h | 21 +++ src/llama-ext.h | 9 + tests/CMakeLists.txt | 5 + tests/test-spec-device-verify.cpp | 265 ++++++++++++++++++++++++++++++ tools/server/server-context.cpp | 63 ++++++- 10 files changed, 680 insertions(+), 42 deletions(-) create mode 100644 tests/test-spec-device-verify.cpp diff --git a/common/sampling.cpp b/common/sampling.cpp index d640f6ed3e59..9b42439e44eb 100644 --- a/common/sampling.cpp +++ b/common/sampling.cpp @@ -7,6 +7,8 @@ #include "ggml.h" +#include "../src/llama-ext.h" + #include #include #include @@ -263,6 +265,9 @@ struct common_sampler { }; std::vector prepared; + // a backend greedy sampler selects the token of every row (see common_sampler_set_backend_greedy) + bool backend_greedy = false; + void reset() { prev.clear(); @@ -849,7 +854,7 @@ void common_sampler_prepare(struct llama_context * ctx, const std::vectorgrmr || gsmpl->rbudget) { + return false; + } + + const auto & p = gsmpl->params; + + if (p.mirostat != 0 || p.n_probs != 0 || p.samplers.empty() || !p.logit_bias.empty() || p.dynatemp_range != 0.0f) { + return false; + } + + // at temp > 0 the speculative loop verifies by rejection and reads the candidates of the rows + if (!(p.temp <= 0.0f)) { + return false; + } + + // the chain ends in the greedy sampler, see common_sampler_init + const auto last = p.samplers.back(); + if (!((last == COMMON_SAMPLER_TYPE_TEMPERATURE && p.temp == 0.0f) || (last == COMMON_SAMPLER_TYPE_TOP_K && p.top_k == 1))) { + return false; + } + + int32_t n_suppress = 0; + llama_vocab_get_suppress_tokens(llama_model_get_vocab(model), &n_suppress); + if (n_suppress != 0) { + return false; + } + + // the samplers before it must keep the token with the largest logit + for (const auto & cnstr : p.samplers) { + switch (cnstr) { + case COMMON_SAMPLER_TYPE_TOP_K: + case COMMON_SAMPLER_TYPE_TOP_P: + case COMMON_SAMPLER_TYPE_MIN_P: + case COMMON_SAMPLER_TYPE_TOP_N_SIGMA: + case COMMON_SAMPLER_TYPE_TEMPERATURE: + break; + case COMMON_SAMPLER_TYPE_PENALTIES: + if (p.penalty_last_n > 0 && (p.penalty_repeat != 1.0f || p.penalty_freq != 0.0f || p.penalty_present != 0.0f)) { + return false; + } + break; + case COMMON_SAMPLER_TYPE_DRY: + if (p.dry_multiplier != 0.0f && p.dry_penalty_last_n != 0) { + return false; + } + break; + case COMMON_SAMPLER_TYPE_TYPICAL_P: + if (p.typ_p < 1.0f) { + return false; + } + break; + case COMMON_SAMPLER_TYPE_XTC: + if (p.xtc_probability > 0.0f) { + return false; + } + break; + default: + return false; + } + } + + return true; +} + +void common_sampler_set_backend_greedy(struct common_sampler * gsmpl, bool value) { + if (gsmpl) { + gsmpl->backend_greedy = value; + } +} + llama_token common_sampler_sample(struct common_sampler * gsmpl, struct llama_context * ctx, int idx, bool grammar_first) { - llama_synchronize(ctx); + llama_synchronize_outputs(ctx); // start measuring sampling time after the llama_context synchronization in order to not measure any ongoing async operations const auto tm = gsmpl->tm(); + // the backend picked the largest logit of the row: no logits were copied, and there are no candidates to build + if (gsmpl->backend_greedy) { + const llama_token id = llama_get_sampled_token_ith(ctx, idx); + if (id != LLAMA_TOKEN_NULL) { + return id; + } + } + llama_token id = LLAMA_TOKEN_NULL; auto & grmr = gsmpl->grmr; diff --git a/common/sampling.h b/common/sampling.h index abef08e258a6..1ea474d587f3 100644 --- a/common/sampling.h +++ b/common/sampling.h @@ -71,6 +71,15 @@ struct llama_sampler * common_sampler_get(const struct common_sampler * gsmpl); // Returns that number of logits, 0 if the chain needs all the logits. n_suppress is the number of suppressed tokens of the vocabulary. size_t common_sampler_n_preselect(const common_params_sampling & params, size_t n_suppress); +// True if the chain selects the token with the largest logit and nothing else (a greedy request, temp <= 0, no grammar, +// no reasoning budget, no logit bias, no sampler that changes the order of the logits). The token is then the argmax of the logits. +bool common_sampler_is_greedy(const struct common_sampler * gsmpl, const struct llama_model * model); + +// The caller registered a backend greedy sampler (llama_sampler_init_greedy) for the sequence, so common_sampler_sample() +// returns the token the backend selected and leaves the candidates (common_sampler_get_candidates) untouched. +// Only valid if common_sampler_is_greedy(); a row without a backend token falls back to the host as before. +void common_sampler_set_backend_greedy(struct common_sampler * gsmpl, bool value); + // Fills cur with the n largest logits and the tokens with a positive logit bias, in token order. void common_sampler_preselect(const float * logits, int32_t n_vocab, size_t n, const std::vector & logit_bias, std::vector & cur); diff --git a/common/speculative.cpp b/common/speculative.cpp index 60ed79d22803..398375cf4834 100644 --- a/common/speculative.cpp +++ b/common/speculative.cpp @@ -10,6 +10,8 @@ #include "ngram-mod.h" #include "sampling.h" +#include "../src/llama-ext.h" + #include #include #include @@ -19,6 +21,7 @@ #include #include #include +#include #define SPC_DBG(fmt, ...) LOG_DBG("spec %12.*s: " fmt, 12, __func__, __VA_ARGS__) #define SPC_TRC(fmt, ...) LOG_TRC("spec %12.*s: " fmt, 12, __func__, __VA_ARGS__) @@ -30,6 +33,18 @@ #define SPEC_VOCAB_MAX_SIZE_DIFFERENCE 128 #define SPEC_VOCAB_CHECK_START_TOKEN_ID 5 +// llama_process() of the draft context, timed for LLAMA_SPEC_TIMING +static int32_t spec_process_dft(llama_context * ctx, enum llama_process_type type, llama_batch_ext * batch) { + common_spec_scoped_timer tm(COMMON_SPEC_TM_DRAFT_DECODE); + return llama_process(ctx, type, batch); +} + +// common_sampler_sample() on the draft context, timed for LLAMA_SPEC_TIMING +static llama_token spec_sample_dft(common_sampler * smpl, llama_context * ctx, int idx, bool grammar_first) { + common_spec_scoped_timer tm(COMMON_SPEC_TM_DRAFT_SAMPLE); + return common_sampler_sample(smpl, ctx, idx, grammar_first); +} + // Rebuild seq_id's draft sampler at the target's temperature: rejection weighs q against p, so // both have to sample alike. Only temp and seed carry over; the draft keeps its own top_k. static void spec_retune( @@ -346,7 +361,7 @@ struct common_speculative_impl_draft_simple : public common_speculative_impl { return true; } - const int ret = llama_process(ctx_dft, LLAMA_PROCESS_TYPE_DECODE, batch.get()); + const int ret = spec_process_dft(ctx_dft, LLAMA_PROCESS_TYPE_DECODE, batch.get()); if (ret != 0) { SPC_ERR("failed to decode draft batch, ret = %d\n", ret); @@ -393,7 +408,7 @@ struct common_speculative_impl_draft_simple : public common_speculative_impl { batch.add(dp.id_last, dp.pos0, seq_id, true); } - int ret = llama_process(ctx_dft, LLAMA_PROCESS_TYPE_DECODE, batch.get()); + int ret = spec_process_dft(ctx_dft, LLAMA_PROCESS_TYPE_DECODE, batch.get()); if (ret != 0) { SPC_ERR("llama_process returned %d\n", ret); return; @@ -413,7 +428,7 @@ struct common_speculative_impl_draft_simple : public common_speculative_impl { auto * smpl = smpls[seq_id].get(); - const llama_token id_sampled = common_sampler_sample(smpl, ctx_dft, i_batch, true); + const llama_token id_sampled = spec_sample_dft(smpl, ctx_dft, i_batch, true); ++i_batch; const auto * cur_p = common_sampler_get_candidates(smpl, true); @@ -461,7 +476,7 @@ struct common_speculative_impl_draft_simple : public common_speculative_impl { } // evaluate the drafted tokens on the draft model - ret = llama_process(ctx_dft, LLAMA_PROCESS_TYPE_DECODE, batch.get()); + ret = spec_process_dft(ctx_dft, LLAMA_PROCESS_TYPE_DECODE, batch.get()); if (ret != 0) { SPC_ERR("llama_process[%d] returned %d\n", i, ret); break; @@ -695,6 +710,7 @@ struct common_speculative_impl_draft_eagle3 : public common_speculative_impl { features_buf.resize((size_t) n_tokens * n_embd_enc, 0.0f); for (uint32_t k = 0; k < target_layer_ids_n; ++k) { + common_spec_scoped_timer tm_feat(COMMON_SPEC_TM_FEATURES); const float * layer = target_layer_ids[k] < n_layer_tgt ? llama_get_embeddings_layer_inp(ctx_tgt, (uint32_t) target_layer_ids[k]) : llama_get_embeddings_nextn(ctx_tgt); @@ -724,7 +740,7 @@ struct common_speculative_impl_draft_eagle3 : public common_speculative_impl { pos++; } - const int32_t rc = llama_process(ctx_dft, LLAMA_PROCESS_TYPE_ENCODE, batch_enc.get()); + const int32_t rc = spec_process_dft(ctx_dft, LLAMA_PROCESS_TYPE_ENCODE, batch_enc.get()); if (rc != 0) { SPC_ERR("llama_process(ctx_dft) failed rc=%d (n_tokens=%d, offset=%d)\n", rc, (int) n_chunk, (int) i); @@ -793,7 +809,7 @@ struct common_speculative_impl_draft_eagle3 : public common_speculative_impl { } if (batch.size() > 0) { - const int32_t rc = llama_process(ctx_dft, LLAMA_PROCESS_TYPE_DECODE, batch.get()); + const int32_t rc = spec_process_dft(ctx_dft, LLAMA_PROCESS_TYPE_DECODE, batch.get()); if (rc != 0) { SPC_ERR("llama_process(ctx_dft) failed rc=%d (n_tokens=%d, ubatch_pos[0]=%d)\n", rc, (int) batch.size(), (int) batch_in.tokens[0].pos[0]); @@ -841,7 +857,7 @@ struct common_speculative_impl_draft_eagle3 : public common_speculative_impl { return; } - int ret = llama_process(ctx_dft, LLAMA_PROCESS_TYPE_DECODE, batch.get()); + int ret = spec_process_dft(ctx_dft, LLAMA_PROCESS_TYPE_DECODE, batch.get()); if (ret != 0) { SPC_ERR("llama_process returned %d\n", ret); return; @@ -861,7 +877,7 @@ struct common_speculative_impl_draft_eagle3 : public common_speculative_impl { auto * smpl = smpls[seq_id].get(); - common_sampler_sample(smpl, ctx_dft, i_batch, true); + spec_sample_dft(smpl, ctx_dft, i_batch, true); // pre-norm hidden state of this position becomes g_embd for the next step const float * prenorm = llama_get_embeddings_nextn_ith(ctx_dft, i_batch); ++i_batch; @@ -906,7 +922,7 @@ struct common_speculative_impl_draft_eagle3 : public common_speculative_impl { break; } - ret = llama_process(ctx_dft, LLAMA_PROCESS_TYPE_DECODE, batch.get()); + ret = spec_process_dft(ctx_dft, LLAMA_PROCESS_TYPE_DECODE, batch.get()); if (ret != 0) { SPC_ERR("llama_process[%d] returned %d\n", i, ret); break; @@ -1267,7 +1283,7 @@ struct common_speculative_impl_draft_dflash : public common_speculative_impl { if (n_inject == 0) { return true; } - const int32_t rc = llama_process(ctx_dft, LLAMA_PROCESS_TYPE_DECODE, batch_inject.get()); + const int32_t rc = spec_process_dft(ctx_dft, LLAMA_PROCESS_TYPE_DECODE, batch_inject.get()); if (rc != 0) { LOG_ERR("%s: llama_process(ctx_dft) failed rc=%d (n_tokens=%d)\n", __func__, rc, (int) n_inject); return false; @@ -1314,7 +1330,11 @@ struct common_speculative_impl_draft_dflash : public common_speculative_impl { // injects them into the K/V cache at the target positions features_buf.resize((size_t) n_chunk * n_embd_enc); for (uint32_t k = 0; k < target_layer_ids_n; ++k) { - const float * layer = llama_get_embeddings_layer_inp(ctx_tgt, (uint32_t) target_layer_ids[k]); + const float * layer = nullptr; + { + common_spec_scoped_timer tm_feat(COMMON_SPEC_TM_FEATURES); + layer = llama_get_embeddings_layer_inp(ctx_tgt, (uint32_t) target_layer_ids[k]); + } if (!layer) { GGML_ABORT("DFlash: target layer %d input not extracted.", target_layer_ids[k]); } @@ -1331,7 +1351,7 @@ struct common_speculative_impl_draft_dflash : public common_speculative_impl { const llama_pos pos_arr[4] = { p, p, p, 0 }; batch_inject.add_embd({ features_buf.data() + (size_t) i * n_embd_enc, 1, (size_t) n_embd_enc }, pos_arr, seq_id, false); } - const int32_t rc = llama_process(ctx_dft, LLAMA_PROCESS_TYPE_DECODE, batch_inject.get()); + const int32_t rc = spec_process_dft(ctx_dft, LLAMA_PROCESS_TYPE_DECODE, batch_inject.get()); if (rc != 0) { LOG_ERR("%s: llama_process(ctx_dft) failed rc=%d (n_tokens=%d, offset=%d)\n", __func__, rc, (int) n_chunk, (int) offset); @@ -1379,7 +1399,7 @@ struct common_speculative_impl_draft_dflash : public common_speculative_impl { } // decode all sequence's noise block in a single batch - int ret = llama_process(ctx_dft, LLAMA_PROCESS_TYPE_DECODE, batch.get()); + int ret = spec_process_dft(ctx_dft, LLAMA_PROCESS_TYPE_DECODE, batch.get()); if (ret != 0) { LOG_WRN("%s: llama_process returned %d\n", __func__, ret); return; @@ -1402,7 +1422,7 @@ struct common_speculative_impl_draft_dflash : public common_speculative_impl { // greedily read the predicted block at this sequence's noise positions 1..n_block_tokens-1 for (int32_t i = 1; i < n_block_tokens; ++i) { - common_sampler_sample(smpl, ctx_dft, beg + i, true); + spec_sample_dft(smpl, ctx_dft, beg + i, true); const auto * cur_p = common_sampler_get_candidates(smpl, true); @@ -1613,7 +1633,7 @@ struct common_speculative_impl_draft_dspark final : public common_speculative_im } // decode all sequence's noise block in a single batch - int ret = llama_process(ctx_dft, LLAMA_PROCESS_TYPE_DECODE, batch.get()); + int ret = spec_process_dft(ctx_dft, LLAMA_PROCESS_TYPE_DECODE, batch.get()); if (ret != 0) { LOG_WRN("%s: llama_process returned %d\n", __func__, ret); return; @@ -1669,7 +1689,7 @@ struct common_speculative_impl_draft_dspark final : public common_speculative_im break; } - common_sampler_sample(smpl, ctx_dft, idx, true); + spec_sample_dft(smpl, ctx_dft, idx, true); const auto * cur_p = common_sampler_get_candidates(smpl, true); @@ -1760,7 +1780,7 @@ struct common_speculative_impl_draft_dflash2 final : public common_speculative_i } // decode all sequence's noise block in a single batch - int ret = llama_process(ctx_dft, LLAMA_PROCESS_TYPE_DECODE, batch.get()); + int ret = spec_process_dft(ctx_dft, LLAMA_PROCESS_TYPE_DECODE, batch.get()); if (ret != 0) { LOG_WRN("%s: llama_process returned %d\n", __func__, ret); return; @@ -1943,7 +1963,7 @@ struct common_speculative_impl_draft_lilicorr final : public common_speculative_ } // decode all sequence's noise block in a single batch - int ret = llama_process(ctx_dft, LLAMA_PROCESS_TYPE_DECODE, batch.get()); + int ret = spec_process_dft(ctx_dft, LLAMA_PROCESS_TYPE_DECODE, batch.get()); if (ret != 0) { LOG_WRN("%s: llama_process returned %d\n", __func__, ret); return; @@ -2215,7 +2235,11 @@ struct common_speculative_impl_draft_mtp : public common_speculative_impl { } } - const float * h_tgt = dev_rows ? nullptr : llama_get_embeddings_nextn(ctx_tgt); + const float * h_tgt = nullptr; + if (!dev_rows) { + common_spec_scoped_timer tm_feat(COMMON_SPEC_TM_FEATURES); + h_tgt = llama_get_embeddings_nextn(ctx_tgt); + } for (int k = 0; k < n_tokens; ++k) { const auto & t = batch_in.tokens[k]; @@ -2254,7 +2278,7 @@ struct common_speculative_impl_draft_mtp : public common_speculative_impl { llama_set_nextn_layer_offset(ctx_dft, head); } - const int32_t rc = llama_process(ctx_dft, LLAMA_PROCESS_TYPE_DECODE, batch.get()); + const int32_t rc = spec_process_dft(ctx_dft, LLAMA_PROCESS_TYPE_DECODE, batch.get()); if (rc != 0) { SPC_ERR("llama_process(ctx_dft) head=%d failed rc=%d (pos=%d)\n", head, (int) rc, (int) batch_in.tokens[0].pos[0]); @@ -2294,7 +2318,10 @@ struct common_speculative_impl_draft_mtp : public common_speculative_impl { if (dev_rows) { // the rows stay on the device until the next target decode, only the pending row comes to the host verify_row0[seq_id] = h_offset; - llama_get_embeddings_nextn_rows(ctx_tgt, h_offset + h_rows - 1, 1, pending_h[seq_id].data()); + { + common_spec_scoped_timer tm_feat(COMMON_SPEC_TM_FEATURES); + llama_get_embeddings_nextn_rows(ctx_tgt, h_offset + h_rows - 1, 1, pending_h[seq_id].data()); + } continue; } @@ -2374,7 +2401,7 @@ struct common_speculative_impl_draft_mtp : public common_speculative_impl { llama_set_nextn_layer_offset(ctx_dft, i); } - int ret = llama_process(ctx_dft, LLAMA_PROCESS_TYPE_DECODE, batch.get()); + int ret = spec_process_dft(ctx_dft, LLAMA_PROCESS_TYPE_DECODE, batch.get()); if (ret != 0) { SPC_ERR("llama_process[%d] returned %d\n", i, ret); break; @@ -2392,7 +2419,7 @@ struct common_speculative_impl_draft_mtp : public common_speculative_impl { auto * smpl = smpls[seq_id].get(); - const llama_token id_sampled = common_sampler_sample(smpl, ctx_dft, i_last[seq_id], true); + const llama_token id_sampled = spec_sample_dft(smpl, ctx_dft, i_last[seq_id], true); const float * h_row = llama_get_embeddings_nextn_ith(ctx_dft, i_last[seq_id]); const auto * cur_p = common_sampler_get_candidates(smpl, true); @@ -2492,6 +2519,7 @@ struct common_speculative_impl_draft_mtp : public common_speculative_impl { if (dev_rows) { // process() already fetched the last row if (i_h != n_rows - 1) { + common_spec_scoped_timer tm_feat(COMMON_SPEC_TM_FEATURES); llama_get_embeddings_nextn_rows(params.ctx_tgt, verify_row0[seq_id] + i_h, 1, pending_h[seq_id].data()); } return; @@ -3635,6 +3663,8 @@ void common_speculative_begin(common_speculative * spec, llama_seq_id seq_id, co } bool common_speculative_process(common_speculative * spec, const common_batch & batch) { + common_spec_scoped_timer tm_inject(COMMON_SPEC_TM_INJECT); + bool result = true; if (spec == nullptr) { @@ -3648,11 +3678,86 @@ bool common_speculative_process(common_speculative * spec, const common_batch & return result; } +// +// LLAMA_SPEC_TIMING +// + +static int64_t g_spec_tm_us[COMMON_SPEC_TM_COUNT] = {}; +static int64_t g_spec_tm_n [COMMON_SPEC_TM_COUNT] = {}; + +bool common_spec_timing_enabled() { + static const bool enabled = [] { + const char * e = std::getenv("LLAMA_SPEC_TIMING"); + return e && *e && *e != '0'; + }(); + return enabled; +} + +common_spec_scoped_timer::common_spec_scoped_timer(common_spec_tm_id id_) : id(id_), t_start(0) { + if (common_spec_timing_enabled()) { + t_start = ggml_time_us(); + } +} + +common_spec_scoped_timer::~common_spec_scoped_timer() { + if (t_start != 0) { + g_spec_tm_us[id] += ggml_time_us() - t_start; + g_spec_tm_n [id]++; + } +} + +common_spec_timing_snapshot common_spec_timing_get(const llama_context * ctx_tgt, const llama_context * ctx_dft) { + common_spec_timing_snapshot res; + for (int i = 0; i < COMMON_SPEC_TM_COUNT; ++i) { + res.t_us[i] = g_spec_tm_us[i]; + res.n [i] = g_spec_tm_n [i]; + } + for (const llama_context * ctx : { ctx_tgt, ctx_dft }) { + if (ctx) { + uint64_t n = 0, n_skip = 0, t = 0; + llama_get_sync_stats(ctx, &n, &n_skip, &t); + res.n_sync += n; + res.n_sync_skipped += n_skip; + res.t_sync_us += t; + } + } + return res; +} + +void common_spec_timing_print(const char * what, const common_spec_timing_snapshot & from, const common_spec_timing_snapshot & to) { + if (!common_spec_timing_enabled()) { + return; + } + + static const char * names[COMMON_SPEC_TM_COUNT] = { + "draft total", " draft decode (host)", " draft sample/read", " feature reads (host)", " inject (process)", + "verify decode (host launch)", "verify sync (GPU wait)", "verify candidate prepare", "verify sample+accept", + }; + + const int64_t n_steps = std::max(1, to.n[COMMON_SPEC_TM_VERIFY_ACCEPT] - from.n[COMMON_SPEC_TM_VERIFY_ACCEPT]); + + LOG_INF("spec-timing %s: %" PRId64 " verify steps, per step (ms, calls/step):\n", what, n_steps); + for (int i = 0; i < COMMON_SPEC_TM_COUNT; ++i) { + const int64_t t = to.t_us[i] - from.t_us[i]; + const int64_t n = to.n [i] - from.n [i]; + if (n == 0) { + continue; + } + LOG_INF("spec-timing %-28s %8.3f ms (%5.2f calls)\n", names[i], t / 1000.0 / n_steps, (double) n / n_steps); + } + LOG_INF("spec-timing %-28s %8.3f ms (%5.2f waits, %5.2f reads skipped)\n", "llama_synchronize waits", + (to.t_sync_us - from.t_sync_us) / 1000.0 / n_steps, + (double) (to.n_sync - from.n_sync) / n_steps, + (double) (to.n_sync_skipped - from.n_sync_skipped) / n_steps); +} + void common_speculative_draft(common_speculative * spec) { if (spec == nullptr) { return; } + common_spec_scoped_timer tm_draft(COMMON_SPEC_TM_DRAFT); + auto & dparams = spec->dparams; { diff --git a/common/speculative.h b/common/speculative.h index 76cb14307630..48ece244fa59 100644 --- a/common/speculative.h +++ b/common/speculative.h @@ -111,6 +111,47 @@ void common_speculative_set_state(common_speculative * spec, llama_seq_id seq_id // print statistics about the speculative decoding void common_speculative_print_stats(const common_speculative * spec); +// +// per-step timing of the speculative loop, LLAMA_SPEC_TIMING=1 (off: the timers do nothing) +// + +enum common_spec_tm_id { + COMMON_SPEC_TM_DRAFT, // common_speculative_draft(), all drafters, whole call + COMMON_SPEC_TM_DRAFT_DECODE, // llama_process() of the draft context (host time, includes any wait for the previous work) + COMMON_SPEC_TM_DRAFT_SAMPLE, // reading the draft logits / tokens after the draft decode (includes the wait for it) + COMMON_SPEC_TM_FEATURES, // reading the target features / hidden rows on the host (D2H waits included) + COMMON_SPEC_TM_INJECT, // common_speculative_process(): feeding the target features to the drafter + COMMON_SPEC_TM_VERIFY_LAUNCH, // llama_process() of the target verify decode (host time to build and queue the graph) + COMMON_SPEC_TM_VERIFY_SYNC, // llama_synchronize() after the verify decode: waiting for the GPU + COMMON_SPEC_TM_VERIFY_PREPARE, // common_sampler_prepare(): the candidate scan of the verify rows + COMMON_SPEC_TM_VERIFY_ACCEPT, // sampling and accepting the verify rows on the host + COMMON_SPEC_TM_COUNT, +}; + +bool common_spec_timing_enabled(); + +struct common_spec_timing_snapshot { + int64_t t_us[COMMON_SPEC_TM_COUNT] = {}; + int64_t n [COMMON_SPEC_TM_COUNT] = {}; + uint64_t n_sync = 0; // llama_synchronize() calls that waited, target + draft context + uint64_t n_sync_skipped = 0; // output reads that did not wait again + uint64_t t_sync_us = 0; +}; + +struct common_spec_scoped_timer { + common_spec_tm_id id; + int64_t t_start; + + explicit common_spec_scoped_timer(common_spec_tm_id id_); + ~common_spec_scoped_timer(); +}; + +// the totals so far; the sync statistics come from the contexts (may be null) +common_spec_timing_snapshot common_spec_timing_get(const llama_context * ctx_tgt, const llama_context * ctx_dft); + +// log the difference of two snapshots as a per-request summary (the steps are counted by the VERIFY_ACCEPT timer) +void common_spec_timing_print(const char * what, const common_spec_timing_snapshot & from, const common_spec_timing_snapshot & to); + struct common_speculative_deleter { void operator()(common_speculative * s) { common_speculative_free(s); } }; diff --git a/src/llama-context.cpp b/src/llama-context.cpp index 787c8029587b..fc6aab14fe31 100644 --- a/src/llama-context.cpp +++ b/src/llama-context.cpp @@ -945,7 +945,13 @@ void llama_context::synchronize() { return; } - ggml_backend_sched_synchronize(sched.get()); + { + const int64_t t_start = ggml_time_us(); + ggml_backend_sched_synchronize(sched.get()); + t_sync_us += ggml_time_us() - t_start; + n_sync++; + } + outputs_pending = false; // FIXME: if multiple single tokens are evaluated without a synchronization, // the stats will be added to the prompt evaluation stats @@ -974,6 +980,22 @@ void llama_context::synchronize() { t_compute_start_us = 0; } +void llama_context::synchronize_outputs() { + // the outputs of the last decode are ready if nothing was computed since the last synchronize() + if (sync_once && !outputs_pending) { + n_sync_skipped++; + return; + } + + synchronize(); +} + +void llama_context::get_sync_stats(uint64_t * n_sync_out, uint64_t * n_skipped_out, uint64_t * t_sync_us_out) const { + if (n_sync_out) { *n_sync_out = n_sync; } + if (n_skipped_out) { *n_skipped_out = n_sync_skipped; } + if (t_sync_us_out) { *t_sync_us_out = t_sync_us; } +} + const llama_model & llama_context::get_model() const { return model; } @@ -2121,6 +2143,9 @@ int llama_context::encode(const llama_batch_ext & batch_inp) { } } + // the output copies are queued + outputs_pending = true; + return 0; } @@ -2648,6 +2673,9 @@ int llama_context::decode(const llama_batch_ext & batch_inp) { // wait for the computation to finish (automatically done when obtaining the model output) //synchronize(); + // the output copies are queued + outputs_pending = true; + return 0; } @@ -3189,6 +3217,8 @@ ggml_status llama_context::graph_compute( copy_experts.reset(); + outputs_pending = true; + auto status = ggml_backend_sched_graph_compute_async(sched_res(), gf); if (status != GGML_STATUS_SUCCESS) { LLAMA_LOG_ERROR("%s: ggml_backend_sched_graph_compute_async failed with error %d\n", __func__, status); @@ -4746,14 +4776,22 @@ void llama_synchronize(llama_context * ctx) { ctx->synchronize(); } +void llama_synchronize_outputs(llama_context * ctx) { + ctx->synchronize_outputs(); +} + +void llama_get_sync_stats(const llama_context * ctx, uint64_t * n_sync, uint64_t * n_skipped, uint64_t * t_sync_us) { + ctx->get_sync_stats(n_sync, n_skipped, t_sync_us); +} + float * llama_get_logits(llama_context * ctx) { - ctx->synchronize(); + ctx->synchronize_outputs(); return ctx->get_logits(); } float * llama_get_logits_ith(llama_context * ctx, int32_t i) { - ctx->synchronize(); + ctx->synchronize_outputs(); float * res = nullptr; @@ -4767,19 +4805,19 @@ float * llama_get_logits_ith(llama_context * ctx, int32_t i) { } float * llama_get_embeddings(llama_context * ctx) { - ctx->synchronize(); + ctx->synchronize_outputs(); return ctx->get_embeddings(); } float * llama_get_embeddings_ith(llama_context * ctx, int32_t i) { - ctx->synchronize(); + ctx->synchronize_outputs(); return ctx->get_embeddings_ith(i); } float * llama_get_embeddings_seq(llama_context * ctx, llama_seq_id seq_id) { - ctx->synchronize(); + ctx->synchronize_outputs(); return ctx->get_embeddings_seq(seq_id); } @@ -4833,19 +4871,19 @@ llama_memory_t llama_get_memory(const struct llama_context * ctx) { } float * llama_get_embeddings_nextn(llama_context * ctx) { - ctx->synchronize(); + ctx->synchronize_outputs(); return ctx->get_embeddings_nextn(); } float * llama_get_embeddings_nextn_ith(llama_context * ctx, int32_t i) { - ctx->synchronize(); + ctx->synchronize_outputs(); return ctx->get_embeddings_nextn_ith(i); } float * llama_get_embeddings_layer_inp(llama_context * ctx, uint32_t lid) { - ctx->synchronize(); + ctx->synchronize_outputs(); return ctx->get_embeddings_layer_inp(lid); } @@ -4855,43 +4893,43 @@ bool llama_set_sampler(llama_context * ctx, llama_seq_id seq_id, llama_sampler * } llama_token llama_get_sampled_token_ith(llama_context * ctx, int32_t i) { - ctx->synchronize(); + ctx->synchronize_outputs(); return ctx->get_sampled_token_ith(i); } float * llama_get_sampled_probs_ith(llama_context * ctx, int32_t i) { - ctx->synchronize(); + ctx->synchronize_outputs(); return ctx->get_sampled_probs_ith(i); } float * llama_get_sampled_logits_ith(llama_context * ctx, int32_t i) { - ctx->synchronize(); + ctx->synchronize_outputs(); return ctx->get_sampled_logits_ith(i); } llama_token * llama_get_sampled_candidates_ith(llama_context * ctx, int32_t i) { - ctx->synchronize(); + ctx->synchronize_outputs(); return const_cast(ctx->get_sampled_candidates_ith(i)); } uint32_t llama_get_sampled_candidates_count_ith(llama_context * ctx, int32_t i) { - ctx->synchronize(); + ctx->synchronize_outputs(); return static_cast(ctx->get_sampled_candidates_count(i)); } uint32_t llama_get_sampled_logits_count_ith(llama_context * ctx, int32_t i) { - ctx->synchronize(); + ctx->synchronize_outputs(); return static_cast(ctx->get_sampled_logits_count(i)); } uint32_t llama_get_sampled_probs_count_ith(llama_context * ctx, int32_t i) { - ctx->synchronize(); + ctx->synchronize_outputs(); return static_cast(ctx->get_sampled_probs_count(i)); } diff --git a/src/llama-context.h b/src/llama-context.h index 9153cd244a0d..02949e2bdb20 100644 --- a/src/llama-context.h +++ b/src/llama-context.h @@ -13,6 +13,7 @@ #include "ggml-opt.h" #include +#include #include #include @@ -60,6 +61,13 @@ struct llama_context { void synchronize(); + // like synchronize(), for the readers of the decode outputs (logits, embeddings, sampled tokens, ...): + // does nothing if no graph was computed since the last synchronize(), see LLAMA_SPEC_NO_SINGLE_SYNC + void synchronize_outputs(); + + // synchronize() calls that waited / that the output readers skipped, and the time spent waiting + void get_sync_stats(uint64_t * n_sync, uint64_t * n_skipped, uint64_t * t_sync_us) const; + const llama_model & get_model() const; const llama_cparams & get_cparams() const; @@ -531,6 +539,19 @@ struct llama_context { mutable int64_t t_compute_start_us = 0; mutable int64_t n_queued_tokens = 0; + // a graph was computed (or output copies queued) since the last synchronize(), so the outputs may not be ready + bool outputs_pending = false; + + // the output readers synchronize once per computed batch instead of once per read (LLAMA_SPEC_NO_SINGLE_SYNC=1 restores the latter) + const bool sync_once = [] { + const char * e = std::getenv("LLAMA_SPEC_NO_SINGLE_SYNC"); + return !(e && *e && *e != '0'); + }(); + + uint64_t n_sync = 0; + uint64_t n_sync_skipped = 0; + uint64_t t_sync_us = 0; + mutable int32_t n_p_eval = 0; // number of tokens in eval calls for the prompt (with batch size > 1) mutable int32_t n_eval = 0; // number of eval calls diff --git a/src/llama-ext.h b/src/llama-ext.h index a77b2f40948a..cdfbcf841acf 100644 --- a/src/llama-ext.h +++ b/src/llama-ext.h @@ -165,3 +165,12 @@ LLAMA_API uint32_t llama_model_n_tokens_delay(const struct llama_model * model); // each sequence is paired with an unconditional one at n_seq_max / 2 + seq_id, in a unified KV cache LLAMA_API bool llama_model_classifier_free_guidance(const struct llama_model * model); + +// Like llama_synchronize(), for code that is about to read the outputs of the last decode (the sampler, the speculative loop): +// does nothing if no graph was computed since the last wait, so reading the rows of one batch one by one waits once. +// LLAMA_SPEC_NO_SINGLE_SYNC=1 waits on every call, as llama_synchronize() does. +LLAMA_API void llama_synchronize_outputs(struct llama_context * ctx); + +// Output synchronization statistics of a context: llama_synchronize() calls that waited on the backends, reads of the decode +// outputs that found them ready and did not wait again (see LLAMA_SPEC_NO_SINGLE_SYNC), and the time spent waiting. Any pointer may be null. +LLAMA_API void llama_get_sync_stats(const struct llama_context * ctx, uint64_t * n_sync, uint64_t * n_skipped, uint64_t * t_sync_us); diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 531f34c1f28d..8178c6e7b8d0 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -284,6 +284,11 @@ llama_build_and_test(test-speculative-rejection-sampling.cpp ARGS -m "${SPEC_TARGET_DIR}/llama-dense.gguf") set_tests_properties(test-speculative-rejection-sampling PROPERTIES FIXTURES_REQUIRED speculative-model) +# the single output synchronization and the backend greedy verification of the speculative loop +llama_build_and_test(test-spec-device-verify.cpp ARGS + -m "${SPEC_TARGET_DIR}/llama-dense.gguf") +set_tests_properties(test-spec-device-verify PROPERTIES FIXTURES_REQUIRED speculative-model) + # Test context state handling across all architectures, using the generated dummy models llama_test( test-llama-context diff --git a/tests/test-spec-device-verify.cpp b/tests/test-spec-device-verify.cpp new file mode 100644 index 000000000000..d7fe7680a20e --- /dev/null +++ b/tests/test-spec-device-verify.cpp @@ -0,0 +1,265 @@ +#include "sampling.h" +#include "llama.h" +#include "common.h" +#include "arg.h" +#include "log.h" + +#include "../src/llama-ext.h" + +#include +#include +#include +#include + +// Tests the two host round trips of the speculative loop that LLAMA_SPEC_NO_SINGLE_SYNC and LLAMA_SPEC_DEVICE_VERIFY change: +// - the readers of the decode outputs wait for the backend once per batch, and read the same values either way +// - a greedy request verified with a backend argmax accepts the same tokens as the host sampler + +struct run_result { + std::vector host; // host greedy sampling of every output row + std::vector dev; // the same rows with the backend greedy sampler + std::vector accept_host; // common_sampler_sample_and_accept_n with a draft that is right for a few rows + std::vector accept_dev; + std::vector logits; // the logits of the host run, all rows + uint64_t n_sync = 0; + uint64_t n_sync_skipped = 0; +}; + +static const int N_ROWS = 6; + +static bool decode_rows(llama_context * ctx, const llama_tokens & toks) { + llama_memory_clear(llama_get_memory(ctx), true); + + common_batch batch(ctx); + for (size_t i = 0; i < toks.size(); ++i) { + batch.add(toks[i], (llama_pos) i, 0, true); + } + return llama_process(ctx, LLAMA_PROCESS_TYPE_DECODE, batch.get()) == 0; +} + +static common_params_sampling greedy_params() { + common_params_sampling s; + s.samplers = { COMMON_SAMPLER_TYPE_TOP_K, COMMON_SAMPLER_TYPE_TOP_P, COMMON_SAMPLER_TYPE_TEMPERATURE }; + s.temp = 0.0f; + return s; +} + +static int run(common_params & params, run_result & res) { + params.sampling.backend_sampling = false; + params.n_outputs_max_per_seq = N_ROWS; + + auto llama_init = common_init_from_params(params); + + auto * model = llama_init->model(); + auto * ctx = llama_init->context(); + if (!model || !ctx) { + LOG_ERR("failed to initialize the model and context\n"); + return 1; + } + + const int n_vocab = llama_vocab_n_tokens(llama_model_get_vocab(model)); + + const llama_tokens toks = { 1, 2, 3, 1, 2, 3 }; + GGML_ASSERT((int) toks.size() == N_ROWS); + + uint64_t n0 = 0, s0 = 0; + llama_get_sync_stats(ctx, &n0, &s0, nullptr); + + // host sampler + { + if (!decode_rows(ctx, toks)) { + LOG_ERR("decode failed\n"); + return 1; + } + + common_params_sampling sp = greedy_params(); + common_sampler_ptr smpl(common_sampler_init(model, sp)); + if (!common_sampler_is_greedy(smpl.get(), model)) { + LOG_ERR("a greedy request is not detected as greedy\n"); + return 1; + } + + for (int i = 0; i < N_ROWS; ++i) { + res.host.push_back(common_sampler_sample(smpl.get(), ctx, i)); + const float * l = llama_get_logits_ith(ctx, i); + res.logits.insert(res.logits.end(), l, l + n_vocab); + } + + // a draft that matches the first 3 rows + llama_tokens draft(res.host.begin(), res.host.begin() + 3); + draft.push_back((res.host[3] + 1) % n_vocab); + draft.push_back(0); + std::vector idxs = { 0, 1, 2, 3, 4, 5 }; + res.accept_host = common_sampler_sample_and_accept_n(smpl.get(), ctx, idxs, draft); + } + + uint64_t n1 = 0, s1 = 0; + llama_get_sync_stats(ctx, &n1, &s1, nullptr); + res.n_sync = n1 - n0; + res.n_sync_skipped = s1 - s0; + + // backend greedy sampler + { + llama_sampler_ptr chain(llama_sampler_chain_init(llama_sampler_chain_default_params())); + llama_sampler_chain_add(chain.get(), llama_sampler_init_greedy()); + if (!llama_set_sampler(ctx, 0, chain.get())) { + LOG_ERR("the backend greedy sampler was not accepted\n"); + return 1; + } + + if (!decode_rows(ctx, toks)) { + LOG_ERR("decode with the backend sampler failed\n"); + return 1; + } + + common_params_sampling sp = greedy_params(); + common_sampler_ptr smpl(common_sampler_init(model, sp)); + common_sampler_set_backend_greedy(smpl.get(), true); + + for (int i = 0; i < N_ROWS; ++i) { + if (llama_get_sampled_token_ith(ctx, i) == LLAMA_TOKEN_NULL) { + LOG_ERR("row %d has no backend token\n", i); + return 1; + } + res.dev.push_back(common_sampler_sample(smpl.get(), ctx, i)); + } + + llama_tokens draft(res.host.begin(), res.host.begin() + 3); + draft.push_back((res.host[3] + 1) % n_vocab); + draft.push_back(0); + std::vector idxs = { 0, 1, 2, 3, 4, 5 }; + res.accept_dev = common_sampler_sample_and_accept_n(smpl.get(), ctx, idxs, draft); + + llama_set_sampler(ctx, 0, nullptr); + } + + return 0; +} + +static int test_is_greedy(common_params & params) { + auto llama_init = common_init_from_params(params); + auto * model = llama_init->model(); + if (!model) { + return 1; + } + + auto check = [&](const char * name, common_params_sampling sp, bool expect) { + common_sampler_ptr smpl(common_sampler_init(model, sp)); + const bool got = common_sampler_is_greedy(smpl.get(), model); + if (got != expect) { + LOG_ERR("%s: common_sampler_is_greedy = %d, expected %d\n", name, (int) got, (int) expect); + return false; + } + return true; + }; + + bool ok = true; + + // the default chain at temperature 0 + { + common_params_sampling sp; + sp.temp = 0.0f; + ok = check("default chain, temp 0", sp, true) && ok; + sp.temp = 0.8f; + ok = check("default chain, temp 0.8", sp, false) && ok; + } + { + common_params_sampling sp; + sp.temp = 0.0f; + sp.penalty_repeat = 1.1f; + ok = check("repeat penalty", sp, false) && ok; + } + { + common_params_sampling sp; + sp.temp = 0.0f; + sp.n_probs = 5; + ok = check("n_probs", sp, false) && ok; + } + { + common_params_sampling sp; + sp.temp = 0.0f; + sp.logit_bias.push_back({ 1, -10.0f }); + ok = check("logit bias", sp, false) && ok; + } + { + common_params_sampling sp; + sp.temp = 0.0f; + sp.mirostat = 2; + ok = check("mirostat", sp, false) && ok; + } + { + common_params_sampling sp; + sp.temp = 0.0f; + sp.xtc_probability = 0.5f; + ok = check("xtc", sp, false) && ok; + } + + return ok ? 0 : 1; +} + +int main(int argc, char ** argv) { + std::setlocale(LC_NUMERIC, "C"); + + common_params params; + params.n_ctx = 256; + + common_init(); + + if (!common_params_parse(argc, argv, params, LLAMA_EXAMPLE_COMMON)) { + return 1; + } + + llama_backend_init(); + + int rc = 0; + + rc |= test_is_greedy(params); + + run_result a, b; + + unsetenv("LLAMA_SPEC_NO_SINGLE_SYNC"); + rc |= run(params, a); + + setenv("LLAMA_SPEC_NO_SINGLE_SYNC", "1", 1); + rc |= run(params, b); + unsetenv("LLAMA_SPEC_NO_SINGLE_SYNC"); + + if (rc == 0) { + if (a.host != a.dev) { + LOG_ERR("the backend greedy sampler picked other tokens than the host sampler\n"); + rc = 1; + } + if (a.accept_host != a.accept_dev) { + LOG_ERR("the backend greedy sampler accepted other tokens than the host sampler\n"); + rc = 1; + } + // 3 right draft tokens, then the first wrong one is replaced by the target token + if (a.accept_host.size() != 4) { + LOG_ERR("unexpected accept length %zu\n", a.accept_host.size()); + rc = 1; + } + if (a.host != b.host || a.dev != b.dev || a.accept_host != b.accept_host || a.accept_dev != b.accept_dev) { + LOG_ERR("the tokens depend on LLAMA_SPEC_NO_SINGLE_SYNC\n"); + rc = 1; + } + if (a.logits.size() != b.logits.size() || std::memcmp(a.logits.data(), b.logits.data(), a.logits.size()*sizeof(float)) != 0) { + LOG_ERR("the logits depend on LLAMA_SPEC_NO_SINGLE_SYNC\n"); + rc = 1; + } + LOG("single sync: %" PRIu64 " waits, %" PRIu64 " reads skipped; per read: %" PRIu64 " waits, %" PRIu64 " reads skipped\n", + a.n_sync, a.n_sync_skipped, b.n_sync, b.n_sync_skipped); + if (a.n_sync > 2 || a.n_sync_skipped == 0) { + LOG_ERR("the readers of one batch waited %" PRIu64 " times, %" PRIu64 " reads were skipped\n", a.n_sync, a.n_sync_skipped); + rc = 1; + } + if (b.n_sync_skipped != 0 || b.n_sync <= a.n_sync) { + LOG_ERR("LLAMA_SPEC_NO_SINGLE_SYNC=1 did not restore a wait per read\n"); + rc = 1; + } + } + + LOG(rc == 0 ? "\nAll tests passed.\n" : "\nSome tests failed.\n"); + + llama_backend_free(); + return rc; +} diff --git a/tools/server/server-context.cpp b/tools/server/server-context.cpp index 606295d76f77..e8fb5cde8c43 100644 --- a/tools/server/server-context.cpp +++ b/tools/server/server-context.cpp @@ -30,6 +30,7 @@ #include #include #include +#include #include #include #include @@ -310,6 +311,12 @@ struct server_slot { bool spec_is_replay = false; std::mt19937 spec_synth_rng; + // LLAMA_SPEC_TIMING: the totals when the task started, for the per-request summary + common_spec_timing_snapshot spec_tm0; + + // LLAMA_SPEC_DEVICE_VERIFY: the backend greedy sampler registered for this slot's sequence in ctx_tgt, see launch_slot_with_task() + llama_sampler_ptr spec_dev_chain; + // TODO: move members that belong to the task (such as `generated`, `has_new_line`) to task_results_state // see https://github.com/ggml-org/llama.cpp/pull/18283#issuecomment-3710175837 std::unique_ptr task; @@ -822,6 +829,12 @@ struct server_slot { } common_speculative_print_stats(spec); + + if (spec && common_spec_timing_enabled()) { + // the timers are global: with several slots generating at once a step is shared and counted for each of them + common_spec_timing_print(("slot " + std::to_string(id) + " task " + std::to_string(task ? task->id : -1)).c_str(), + spec_tm0, common_spec_timing_get(ctx_tgt, ctx_dft)); + } } json to_json(bool only_metrics = false) const { @@ -1111,6 +1124,12 @@ struct server_context_impl { common_speculative_ptr spec; + // LLAMA_SPEC_DEVICE_VERIFY=1: verify the drafts of greedy requests with a backend argmax (opt-in) + const bool spec_device_verify = [] { + const char * e = std::getenv("LLAMA_SPEC_DEVICE_VERIFY"); + return e && *e && *e != '0'; + }(); + // see common_speculative_n_prompt_tail(), -1 = the drafters read the features of every prompt row int32_t n_spec_prompt_tail = -1; @@ -2068,6 +2087,23 @@ struct server_context_impl { llama_set_sampler(ctx_tgt, slot.id, nullptr); } + // the registration above replaced the sampler of the previous task + slot.spec_dev_chain.reset(); + + // LLAMA_SPEC_DEVICE_VERIFY: a greedy request verifies the draft on the device: the target argmax of every output row is + // selected there, so the logits of the rows are not copied to the host and the host scan of them is skipped. + // The accepted tokens are the same as with the host sampler, unless the two largest logits of a row are exactly equal. + if (!use_backend_sampling && spec && spec_device_verify && task.type != SERVER_TASK_TYPE_TTS && + common_sampler_is_greedy(slot.smpl.get(), model_tgt)) { + llama_sampler_ptr chain(llama_sampler_chain_init(llama_sampler_chain_default_params())); + llama_sampler_chain_add(chain.get(), llama_sampler_init_greedy()); + if (llama_set_sampler(ctx_tgt, slot.id, chain.get())) { + slot.spec_dev_chain = std::move(chain); + common_sampler_set_backend_greedy(slot.smpl.get(), true); + SLT_TRC(slot, "%s", "greedy draft verification on the device\n"); + } + } + SLT_TRC(slot, "sampler chain: %s\n", common_sampler_print(slot.smpl.get()).c_str()); SLT_TRC(slot, "sampler params: \n%s\n", task.params.sampling.print().c_str()); @@ -2086,6 +2122,10 @@ struct server_context_impl { slot.task = std::make_unique(std::move(task)); + if (spec && common_spec_timing_enabled()) { + slot.spec_tm0 = common_spec_timing_get(ctx_tgt, ctx_dft); + } + if (slot.task->type == SERVER_TASK_TYPE_TTS) { slot.state = SLOT_STATE_PROCESSING_PROMPT; } else { @@ -4726,16 +4766,34 @@ struct server_context_impl { // yield to the queue, so we can still handle metrics tasks while decoding // note: the sync is done here too, so that the wait is also covered by the yield + // LLAMA_SPEC_TIMING: time the decodes that verify a draft + bool time_verify = false; + if (spec && common_spec_timing_enabled()) { + for (const auto & s : slots) { + time_verify = time_verify || (!s.spec_draft.empty() && !s.spec_i_batch.empty()); + } + } + int ret = 0; queue_tasks.yield_to_queue([&]() { if (spec_skip) { llama_set_embeddings_layer_inp_skip(ctx_tgt, true); } - ret = llama_process(ctx_tgt, LLAMA_PROCESS_TYPE_DECODE, batch.view.get()); + { + std::optional tm; + if (time_verify) { + tm.emplace(COMMON_SPEC_TM_VERIFY_LAUNCH); + } + ret = llama_process(ctx_tgt, LLAMA_PROCESS_TYPE_DECODE, batch.view.get()); + } if (spec_skip) { llama_set_embeddings_layer_inp_skip(ctx_tgt, false); } if (ret == 0 && has_output) { + std::optional tm; + if (time_verify) { + tm.emplace(COMMON_SPEC_TM_VERIFY_SYNC); + } llama_synchronize(ctx_tgt); } }); @@ -4880,6 +4938,7 @@ struct server_context_impl { } }); if (rows.size() > 1) { + common_spec_scoped_timer tm(COMMON_SPEC_TM_VERIFY_PREPARE); common_sampler_prepare(ctx_tgt, rows, params_base.cpuparams.n_threads); } } @@ -4995,6 +5054,8 @@ struct server_context_impl { GGML_ASSERT(n_draft > 0); + common_spec_scoped_timer tm_accept(COMMON_SPEC_TM_VERIFY_ACCEPT); + // batch indices of the draft tokens, used to get the token probabilities below auto spec_i_batch = std::move(slot.spec_i_batch);