diff --git a/CMakeLists.txt b/CMakeLists.txt index 4c5ca8f..382f44a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -22,6 +22,7 @@ add_library(diffuse src/diffuse-sampler.cpp src/ar-graph.cpp src/ar-sampler.cpp + src/ar-speculative.cpp ) target_include_directories(diffuse PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include diff --git a/include/diffuse.h b/include/diffuse.h index c3fce1a..9e0d36f 100644 --- a/include/diffuse.h +++ b/include/diffuse.h @@ -115,4 +115,41 @@ std::vector ar_generate( const ar_sampler_params & params, ar_token_callback callback = nullptr); +// ═══════════════════════════════════════════════════════════════ +// ── Speculative Decoding API ──────────────────────────────────── +// ═══════════════════════════════════════════════════════════════ + +struct ar_spec_params { + int K = 4; // speculative lookahead (draft tokens per round) +}; + +struct ar_spec_stats { + int total_draft_tokens = 0; + int total_accepted = 0; + int total_generated = 0; + int total_target_batches = 0; + int total_target_decodes = 0; + int total_fast_rejects = 0; + double prefill_ms = 0; + double decode_ms = 0; + + float acceptance_rate() const { + return total_draft_tokens > 0 + ? (float)total_accepted / total_draft_tokens : 0.0f; + } + float tokens_per_target_call() const { + int calls = total_target_batches + total_target_decodes; + return calls > 0 ? (float)total_generated / calls : 1.0f; + } +}; + +std::vector ar_speculative_generate( + diffuse_context * target_ctx, + diffuse_context * draft_ctx, + const std::vector & prompt_tokens, + int max_tokens, + const ar_spec_params & params, + ar_token_callback callback = nullptr, + ar_spec_stats * stats_out = nullptr); + // end of diffuse.h diff --git a/src/ar-graph.cpp b/src/ar-graph.cpp index 16818a6..170090b 100644 --- a/src/ar-graph.cpp +++ b/src/ar-graph.cpp @@ -353,3 +353,21 @@ bool ar_forward_decode( return ar_forward_impl(ctx, &token, 1, cache, logits_out); } + +// ── Public API: Batch forward (no cache reset) ────────────────── +// Used by speculative decoding to verify K candidate tokens at once. +bool ar_forward_batch( + diffuse_context * ctx, + const int32_t * tokens, + int n_tokens, + ar_kv_cache * cache, + float * logits_out) { + + if (!cache || !cache->initialized) { + DIFFUSE_LOG("ar_forward_batch: cache not initialized"); + return false; + } + + DIFFUSE_LOG("ar_forward_batch: %d tokens, n_past=%d", n_tokens, cache->n_past); + return ar_forward_impl(ctx, tokens, n_tokens, cache, logits_out); +} diff --git a/src/ar-graph.h b/src/ar-graph.h index 4431121..47d188e 100644 --- a/src/ar-graph.h +++ b/src/ar-graph.h @@ -27,3 +27,13 @@ bool ar_forward_decode( int32_t token, ar_kv_cache * cache, float * logits_out); + +// Batch: process N tokens with existing KV cache (no reset). +// Used for speculative decoding verification: target verifies K draft tokens at once. +// tokens: [n_tokens], logits_out: [n_tokens * n_vocab] +bool ar_forward_batch( + diffuse_context * ctx, + const int32_t * tokens, + int n_tokens, + ar_kv_cache * cache, + float * logits_out); diff --git a/src/ar-speculative.cpp b/src/ar-speculative.cpp new file mode 100644 index 0000000..375b1a2 --- /dev/null +++ b/src/ar-speculative.cpp @@ -0,0 +1,373 @@ +#include "ar-speculative.h" +#include "ar-graph.h" +#include "diffuse.h" +#include "ggml-cpu.h" + +#include +#include +#include +#include + +// ── Helpers ───────────────────────────────────────────────────── + +static int32_t argmax(const float * logits, int n) { + int best = 0; + float best_val = logits[0]; + for (int i = 1; i < n; i++) { + if (logits[i] > best_val) { + best_val = logits[i]; + best = i; + } + } + return best; +} + +// Qwen2.5 family EOS tokens +static bool is_eos_token(int32_t token) { + return token == 151643 || token == 151645 || token == 151644; +} + +// ── Speculative Generation ────────────────────────────────────── + +std::vector ar_speculative_generate( + diffuse_context * target_ctx, + diffuse_context * draft_ctx, + const std::vector & prompt_tokens, + int max_tokens, + const ar_spec_params & params, + ar_token_callback callback, + ar_spec_stats * stats_out) { + + const auto & t_hp = target_ctx->model->hparams; + const auto & d_hp = draft_ctx->model->hparams; + const int t_vocab = (int)t_hp.n_vocab; + const int d_vocab = (int)d_hp.n_vocab; + const int prompt_len = (int)prompt_tokens.size(); + const int total_ctx = prompt_len + max_tokens + params.K + 4; + const int K = std::max(params.K, 1); + + DIFFUSE_LOG("speculative: target=%dL/%dH/%dKV vocab=%d, draft=%dL/%dH/%dKV vocab=%d, K=%d", + (int)t_hp.n_layer, (int)t_hp.n_head, (int)t_hp.n_head_kv, t_vocab, + (int)d_hp.n_layer, (int)d_hp.n_head, (int)d_hp.n_head_kv, d_vocab, K); + + // ── Init KV caches ────────────────────────────────────────── + ar_kv_cache target_cache, draft_cache; + target_cache.init(total_ctx, (int)t_hp.n_layer, + (int)t_hp.n_embd_head(), (int)t_hp.n_head_kv); + draft_cache.init(total_ctx, (int)d_hp.n_layer, + (int)d_hp.n_embd_head(), (int)d_hp.n_head_kv); + + // ── Persistent threadpools ────────────────────────────────── + { + auto tp = ggml_threadpool_params_default(target_ctx->n_threads); + tp.strict_cpu = true; + tp.prio = GGML_SCHED_PRIO_HIGH; + target_cache.threadpool = ggml_threadpool_new(&tp); + DIFFUSE_LOG(" target: %d threads, %dL, %d KV heads, %d dim", + target_ctx->n_threads, (int)t_hp.n_layer, + (int)t_hp.n_head_kv, (int)t_hp.n_embd_head()); + } + { + auto tp = ggml_threadpool_params_default(draft_ctx->n_threads); + tp.strict_cpu = true; + tp.prio = GGML_SCHED_PRIO_NORMAL; + draft_cache.threadpool = ggml_threadpool_new(&tp); + DIFFUSE_LOG(" draft: %d threads, %dL, %d KV heads, %d dim", + draft_ctx->n_threads, (int)d_hp.n_layer, + (int)d_hp.n_head_kv, (int)d_hp.n_embd_head()); + } + + ar_spec_stats stats = {}; + using clk = std::chrono::steady_clock; + auto gen_start = clk::now(); + + // ── Prefill both models ───────────────────────────────────── + std::vector t_prefill_logits((size_t)prompt_len * t_vocab); + { + // We only need the draft prefill to populate its KV cache, not the logits. + // But ar_forward_prefill requires a logits buffer, so allocate a temp one. + std::vector d_prefill_logits((size_t)prompt_len * d_vocab); + + auto t0 = clk::now(); + if (!ar_forward_prefill(target_ctx, prompt_tokens.data(), prompt_len, + &target_cache, t_prefill_logits.data())) { + DIFFUSE_DIE("speculative: target prefill failed"); + } + if (!ar_forward_prefill(draft_ctx, prompt_tokens.data(), prompt_len, + &draft_cache, d_prefill_logits.data())) { + DIFFUSE_DIE("speculative: draft prefill failed"); + } + auto t1 = clk::now(); + stats.prefill_ms = std::chrono::duration(t1 - t0).count(); + DIFFUSE_LOG(" prefill: %d tokens in %.1f ms (%.1f tok/s)", + prompt_len, stats.prefill_ms, + 1000.0 * prompt_len / std::max(stats.prefill_ms, 0.1)); + } + + // ── Sample first token from target prefill logits ─────────── + std::vector generated; + generated.reserve(max_tokens); + + std::vector prev_target_logits( + t_prefill_logits.data() + (size_t)(prompt_len - 1) * t_vocab, + t_prefill_logits.data() + (size_t)prompt_len * t_vocab); + + // Free prefill buffer (large: prompt_len * vocab * 4 bytes) + t_prefill_logits.clear(); + t_prefill_logits.shrink_to_fit(); + + int32_t first_token = argmax(prev_target_logits.data(), t_vocab); + generated.push_back(first_token); + stats.total_generated++; + + if (callback && !callback(first_token, prompt_len)) { + goto cleanup; + } + if (is_eos_token(first_token)) { + DIFFUSE_LOG(" EOS at first token (%d)", first_token); + goto cleanup; + } + + // ── Decode first token on both models to sync caches ──────── + { + std::vector t_logits(t_vocab); + if (!ar_forward_decode(target_ctx, first_token, + &target_cache, t_logits.data())) { + DIFFUSE_DIE("speculative: target decode first token failed"); + } + prev_target_logits.assign(t_logits.begin(), t_logits.end()); + stats.total_target_decodes++; + } + + { + // Persistent buffer for draft logits (reused across iterations) + std::vector prev_draft_logits(d_vocab); + if (!ar_forward_decode(draft_ctx, first_token, + &draft_cache, prev_draft_logits.data())) { + DIFFUSE_DIE("speculative: draft decode first token failed"); + } + + // ── Main speculative loop ─────────────────────────────── + auto decode_start = clk::now(); + + std::vector draft_logits_buf(d_vocab); + std::vector target_batch_logits; + std::vector candidates; + candidates.reserve(K); + + while ((int)generated.size() < max_tokens) { + int remaining = max_tokens - (int)generated.size(); + int k = std::min(K, remaining); + + int target_P = target_cache.n_past; + int draft_P = draft_cache.n_past; + + // ── Phase 1: Draft generates k candidates ─────────── + candidates.clear(); + { + // First candidate from prev_draft_logits (no decode needed) + candidates.push_back(argmax(prev_draft_logits.data(), d_vocab)); + + // Remaining: decode on draft and sample + for (int i = 1; i < k; i++) { + if (!ar_forward_decode(draft_ctx, candidates[i - 1], + &draft_cache, draft_logits_buf.data())) { + DIFFUSE_LOG("speculative: draft decode failed at candidate %d", i); + goto loop_done; + } + candidates.push_back(argmax(draft_logits_buf.data(), d_vocab)); + } + stats.total_draft_tokens += k; + } + // draft_cache.n_past = draft_P + (k - 1) + // Positions draft_P .. draft_P+k-2 have KV for candidates[0..k-2] + + // ── Phase 2: Target verification ──────────────────── + { + int n_accepted = 0; + int32_t bonus; + + int32_t target_predicted = argmax(prev_target_logits.data(), t_vocab); + + if (target_predicted != candidates[0]) { + // ── Fast path: d1 rejected, skip expensive batch ── + bonus = target_predicted; + n_accepted = 0; + stats.total_fast_rejects++; + } else { + // d1 accepted — batch verify all k candidates + target_batch_logits.resize((size_t)k * t_vocab); + if (!ar_forward_batch(target_ctx, candidates.data(), k, + &target_cache, target_batch_logits.data())) { + DIFFUSE_LOG("speculative: target batch failed"); + goto loop_done; + } + stats.total_target_batches++; + // target_cache.n_past = target_P + k + + n_accepted = 1; + for (int i = 1; i < k; i++) { + float * bl = target_batch_logits.data() + + (size_t)(i - 1) * t_vocab; + if (argmax(bl, t_vocab) == candidates[i]) { + n_accepted++; + } else { + break; + } + } + + // Determine bonus from target logits + if (n_accepted < k) { + bonus = argmax( + target_batch_logits.data() + + (size_t)(n_accepted - 1) * t_vocab, + t_vocab); + } else { + bonus = argmax( + target_batch_logits.data() + + (size_t)(k - 1) * t_vocab, + t_vocab); + } + + // Rollback target cache to accepted prefix + target_cache.n_past = target_P + n_accepted; + } + + stats.total_accepted += n_accepted; + + // ── Output accepted tokens ────────────────────── + for (int i = 0; i < n_accepted; i++) { + if ((int)generated.size() >= max_tokens) goto loop_done; + generated.push_back(candidates[i]); + stats.total_generated++; + if (callback && !callback(candidates[i], + prompt_len + (int)generated.size() - 1)) { + goto loop_done; + } + if (is_eos_token(candidates[i])) { + goto loop_done; + } + } + + // ── Output bonus token ────────────────────────── + if ((int)generated.size() < max_tokens) { + generated.push_back(bonus); + stats.total_generated++; + if (callback && !callback(bonus, + prompt_len + (int)generated.size() - 1)) { + goto loop_done; + } + if (is_eos_token(bonus)) { + goto loop_done; + } + } + + // ── Sync target: decode bonus ─────────────────── + { + std::vector t_logits(t_vocab); + if (!ar_forward_decode(target_ctx, bonus, + &target_cache, t_logits.data())) { + DIFFUSE_LOG("speculative: target decode bonus failed"); + goto loop_done; + } + prev_target_logits.assign(t_logits.begin(), t_logits.end()); + stats.total_target_decodes++; + } + + // ── Sync draft: rollback + decode bonus ───────── + // + // Draft decoded k-1 times → n_past = draft_P + k - 1 + // We need n_past = draft_P + n_accepted, then decode bonus. + // + // Cases: + // n_accepted < k-1 → rollback (set n_past lower) + // n_accepted == k-1 → already correct + // n_accepted == k → need one more decode (candidates[k-1]) + { + int draft_current = draft_P + (k - 1); + int draft_target = draft_P + n_accepted; + + if (draft_current > draft_target) { + // Rollback: discard rejected KV entries + draft_cache.n_past = draft_target; + } else if (draft_current < draft_target) { + // n_accepted == k: decode the last candidate + if (!ar_forward_decode(draft_ctx, candidates[k - 1], + &draft_cache, + draft_logits_buf.data())) { + DIFFUSE_LOG("speculative: draft decode last candidate failed"); + goto loop_done; + } + } + // else: draft_current == draft_target, nothing to do + + // Decode bonus on draft + if (!ar_forward_decode(draft_ctx, bonus, + &draft_cache, + prev_draft_logits.data())) { + DIFFUSE_LOG("speculative: draft decode bonus failed"); + goto loop_done; + } + } + + DIFFUSE_LOG(" spec: k=%d accepted=%d bonus=%d (%.0f%%)", + k, n_accepted, bonus, + k > 0 ? 100.0f * n_accepted / k : 0.0f); + } + } + + loop_done: + auto decode_end = clk::now(); + stats.decode_ms = std::chrono::duration( + decode_end - decode_start).count(); + } + + // ── Report ────────────────────────────────────────────────── + { + auto gen_end = clk::now(); + double total_ms = std::chrono::duration( + gen_end - gen_start).count(); + + DIFFUSE_LOG("=== SPECULATIVE GENERATION COMPLETE ==="); + DIFFUSE_LOG(" prefill: %.1f ms (%d tok, %.1f tok/s)", + stats.prefill_ms, prompt_len, + 1000.0 * prompt_len / std::max(stats.prefill_ms, 0.1)); + DIFFUSE_LOG(" decode: %.1f ms (%d tok, %.2f tok/s)", + stats.decode_ms, stats.total_generated, + stats.total_generated > 0 + ? 1000.0 * stats.total_generated / stats.decode_ms + : 0.0); + DIFFUSE_LOG(" acceptance: %d/%d (%.1f%%)", + stats.total_accepted, stats.total_draft_tokens, + 100.0f * stats.acceptance_rate()); + DIFFUSE_LOG(" fast rejects: %d (d1 mismatch, no batch needed)", + stats.total_fast_rejects); + DIFFUSE_LOG(" target calls: %d batches + %d decodes", + stats.total_target_batches, stats.total_target_decodes); + DIFFUSE_LOG(" effective: %.2f tok/target_call", + stats.tokens_per_target_call()); + DIFFUSE_LOG(" total: %.1f ms", total_ms); + DIFFUSE_LOG(" KV target: %d/%d pos (%.1f MB)", + target_cache.n_past, target_cache.n_ctx_max, + (float)target_cache.total_bytes() / (1024 * 1024)); + DIFFUSE_LOG(" KV draft: %d/%d pos (%.1f MB)", + draft_cache.n_past, draft_cache.n_ctx_max, + (float)draft_cache.total_bytes() / (1024 * 1024)); + } + +cleanup: + if (stats_out) *stats_out = stats; + + if (target_cache.threadpool) { + ggml_threadpool_free(target_cache.threadpool); + target_cache.threadpool = nullptr; + } + if (draft_cache.threadpool) { + ggml_threadpool_free(draft_cache.threadpool); + draft_cache.threadpool = nullptr; + } + target_cache.clear(); + draft_cache.clear(); + + return generated; +} diff --git a/src/ar-speculative.h b/src/ar-speculative.h new file mode 100644 index 0000000..d16105c --- /dev/null +++ b/src/ar-speculative.h @@ -0,0 +1,9 @@ +#pragma once + +// Speculative decoding implementation header. +// Public types (ar_spec_params, ar_spec_stats, ar_speculative_generate) +// are declared in include/diffuse.h. +// This header adds internal includes needed by the implementation. + +#include "diffuse-common.h" +#include "ar-cache.h" diff --git a/tools/ar-cli.cpp b/tools/ar-cli.cpp index 36f62e8..453b522 100644 --- a/tools/ar-cli.cpp +++ b/tools/ar-cli.cpp @@ -26,8 +26,13 @@ static void print_usage(const char * prog) { fprintf(stderr, " --seed INT Random seed (default: 42)\n"); fprintf(stderr, " --tokens IDs Comma-separated pre-tokenized input\n"); fprintf(stderr, " --bind-cores Bind threads to CPU cores (reduces jitter)\n"); + fprintf(stderr, "\nSpeculative decoding:\n"); + fprintf(stderr, " --draft PATH Draft model GGUF (enables speculative decoding)\n"); + fprintf(stderr, " --spec-k INT Speculative lookahead (default: 4)\n"); + fprintf(stderr, " --draft-threads INT Threads for draft model (default: 4)\n"); fprintf(stderr, "\nExample:\n"); fprintf(stderr, " %s -m thrombia-32b-q4.gguf --tokens 151644,8948,198,... -n 512 -t 12\n", prog); + fprintf(stderr, " %s -m thrombia-32b-q4.gguf --draft qwen2.5-0.5b-q4.gguf --spec-k 5 -t 12\n", prog); } static std::vector parse_tokens(const char * str) { @@ -43,10 +48,13 @@ static std::vector parse_tokens(const char * str) { int main(int argc, char ** argv) { std::string model_path; + std::string draft_path; std::string prompt; std::vector input_tokens; int max_tokens = 256; int n_threads = 4; + int draft_threads = 4; + int spec_k = 4; float temperature = 0.0f; float top_p = 0.9f; int top_k = 40; @@ -58,12 +66,18 @@ int main(int argc, char ** argv) { for (int i = 1; i < argc; i++) { if (strcmp(argv[i], "-m") == 0 && i + 1 < argc) { model_path = argv[++i]; + } else if (strcmp(argv[i], "--draft") == 0 && i + 1 < argc) { + draft_path = argv[++i]; } else if (strcmp(argv[i], "-p") == 0 && i + 1 < argc) { prompt = argv[++i]; } else if (strcmp(argv[i], "-n") == 0 && i + 1 < argc) { max_tokens = atoi(argv[++i]); } else if (strcmp(argv[i], "-t") == 0 && i + 1 < argc) { n_threads = atoi(argv[++i]); + } else if (strcmp(argv[i], "--draft-threads") == 0 && i + 1 < argc) { + draft_threads = atoi(argv[++i]); + } else if (strcmp(argv[i], "--spec-k") == 0 && i + 1 < argc) { + spec_k = atoi(argv[++i]); } else if (strcmp(argv[i], "--temp") == 0 && i + 1 < argc) { temperature = atof(argv[++i]); } else if (strcmp(argv[i], "--top-p") == 0 && i + 1 < argc) { @@ -118,14 +132,80 @@ int main(int argc, char ** argv) { #ifdef _OPENMP omp_set_num_threads(n_threads); #endif - // Set environment for child threads (GGML uses pthreads internally) - setenv("OMP_PROC_BIND", "close", 0); // don't override if already set + setenv("OMP_PROC_BIND", "close", 0); setenv("OMP_PLACES", "cores", 0); setenv("GOMP_CPU_AFFINITY", "0-1023", 0); fprintf(stderr, "Thread binding: enabled (%d threads, close/cores)\n", n_threads); } - // Load model + // ── Speculative decoding path ─────────────────────────────── + if (!draft_path.empty()) { + fprintf(stderr, "=== SPECULATIVE DECODING MODE ===\n"); + fprintf(stderr, "Loading target model: %s\n", model_path.c_str()); + diffuse_model * target_model = diffuse_model_load(model_path, n_threads); + if (!target_model) { + fprintf(stderr, "Failed to load target model\n"); + return 1; + } + + fprintf(stderr, "Loading draft model: %s\n", draft_path.c_str()); + diffuse_model * draft_model = diffuse_model_load(draft_path, draft_threads); + if (!draft_model) { + fprintf(stderr, "Failed to load draft model\n"); + diffuse_model_free(target_model); + return 1; + } + + const auto & t_hp = diffuse_model_hparams(target_model); + const auto & d_hp = diffuse_model_hparams(draft_model); + int n_ctx = (int)input_tokens.size() + max_tokens + spec_k + 4; + + fprintf(stderr, "Target: %dL, %d heads, vocab=%d\n", + (int)t_hp.n_layer, (int)t_hp.n_head, (int)t_hp.n_vocab); + fprintf(stderr, "Draft: %dL, %d heads, vocab=%d\n", + (int)d_hp.n_layer, (int)d_hp.n_head, (int)d_hp.n_vocab); + fprintf(stderr, "Prompt: %d tokens, max_generate: %d, K=%d\n", + (int)input_tokens.size(), max_tokens, spec_k); + + diffuse_context * target_ctx = diffuse_context_new(target_model, n_ctx, n_threads); + diffuse_context * draft_ctx = diffuse_context_new(draft_model, n_ctx, draft_threads); + + ar_spec_params sparams; + sparams.K = spec_k; + + ar_spec_stats stats; + + auto result = ar_speculative_generate( + target_ctx, draft_ctx, input_tokens, max_tokens, sparams, + [](int32_t token, int pos) -> bool { + fprintf(stderr, "\r generating... %d tokens", pos); + return true; + }, + &stats); + + fprintf(stderr, "\n\nGenerated %d token IDs:\n", (int)result.size()); + for (size_t i = 0; i < result.size(); i++) { + if (i > 0) printf(","); + printf("%d", result[i]); + } + printf("\n"); + + fprintf(stderr, "\nSpeculative stats:\n"); + fprintf(stderr, " Acceptance rate: %.1f%% (%d/%d)\n", + 100.0f * stats.acceptance_rate(), + stats.total_accepted, stats.total_draft_tokens); + fprintf(stderr, " Tokens/target_call: %.2f\n", + stats.tokens_per_target_call()); + fprintf(stderr, " Fast rejects: %d\n", stats.total_fast_rejects); + + diffuse_context_free(target_ctx); + diffuse_context_free(draft_ctx); + diffuse_model_free(target_model); + diffuse_model_free(draft_model); + return 0; + } + + // ── Standard AR decoding path ─────────────────────────────── fprintf(stderr, "Loading model...\n"); diffuse_model * model = diffuse_model_load(model_path, n_threads); if (!model) { @@ -155,10 +235,8 @@ int main(int argc, char ** argv) { auto result = ar_generate(ctx, input_tokens, max_tokens, sparams, [](int32_t token, int pos) -> bool { - // Streaming: print token IDs as they come - // (decode externally with tokenizer) fprintf(stderr, "\r generating... %d tokens", pos); - return true; // continue + return true; }); fprintf(stderr, "\n\nGenerated %d token IDs:\n", (int)result.size());