diff --git a/common/sampling.cpp b/common/sampling.cpp index 078bfd984f42..09d38d0a74c6 100644 --- a/common/sampling.cpp +++ b/common/sampling.cpp @@ -125,6 +125,13 @@ struct common_sampler { // for rejection sampling; independent of the draft, or the target distribution is not preserved std::mt19937 rng; + // Fast-path direct argmax when the sampler chain is mathematically identical to pure greedy + // (no grammar, no reasoning budget, no penalties/DRY/XTC/infill, temp <= 0, small logit_bias list e.g. ignore_eos). + bool fast_greedy = false; + bool fast_greedy_has_pos_bias = false; + std::vector fast_greedy_biases; + uint64_t fast_greedy_hits = 0; + void reset() { prev.clear(); @@ -439,16 +446,57 @@ struct common_sampler * common_sampler_init( params.backend_sampling = false; } + // Determine whether the sampler chain is mathematically identical to pure greedy argmax + bool is_fast_greedy = false; + bool fg_has_pos_bias = false; + std::vector fg_biases; + if (params.mirostat == 0 && params.n_probs == 0 && !grmr && !rbudget && !params.samplers.empty()) { + fg_biases = params.logit_bias; + int32_t n_suppress = 0; + const llama_token * suppress = llama_vocab_get_suppress_tokens(vocab, &n_suppress); + for (int32_t i = 0; i < n_suppress; ++i) { + fg_biases.push_back({ suppress[i], -INFINITY }); + } + for (const auto & b : fg_biases) { + if (b.bias > 0.0f) { + fg_has_pos_bias = true; + } + } + const bool small_bias = fg_biases.size() <= 64; + const bool no_penalty = (params.penalty_last_n == 0) || + (params.penalty_repeat == 1.0f && params.penalty_freq == 0.0f && params.penalty_present == 0.0f); + const bool no_dry = (params.dry_multiplier == 0.0f); + const bool no_xtc = (params.xtc_probability == 0.0f); + const bool is_greedy_end = + (params.samplers.back() == COMMON_SAMPLER_TYPE_TEMPERATURE && params.temp <= 0.0f && params.dynatemp_range == 0.0f) || + (params.samplers.back() == COMMON_SAMPLER_TYPE_TOP_K && params.top_k == 1); + bool has_special = false; + for (const auto & cnstr : params.samplers) { + if (cnstr == COMMON_SAMPLER_TYPE_INFILL || cnstr == COMMON_SAMPLER_TYPE_ADAPTIVE_P) { + has_special = true; + break; + } + } + is_fast_greedy = small_bias && no_penalty && no_dry && no_xtc && is_greedy_end && !has_special; + if (!is_fast_greedy) { + fg_biases.clear(); + } + } + auto * result = new common_sampler { - /* .params = */ params, - /* .grmr = */ grmr, - /* .rbudget = */ rbudget, - /* .chain = */ chain, - /* .prev = */ ring_buffer(std::max(32, params.n_prev)), - /* .cur = */ {}, - /* .cur_p = */ {}, + /* .params = */ params, + /* .grmr = */ grmr, + /* .rbudget = */ rbudget, + /* .chain = */ chain, + /* .prev = */ ring_buffer(std::max(32, params.n_prev)), + /* .cur = */ {}, + /* .cur_p = */ {}, // mix it, the chain and the draft are seeded from this one too - /* .rng = */ std::mt19937(llama_sampler_get_seed(chain) ^ 0x9e3779b9u), + /* .rng = */ std::mt19937(llama_sampler_get_seed(chain) ^ 0x9e3779b9u), + /* .fast_greedy = */ is_fast_greedy, + /* .fast_greedy_has_pos_bias = */ fg_has_pos_bias, + /* .fast_greedy_biases = */ std::move(fg_biases), + /* .fast_greedy_hits = */ 0, }; return result; @@ -458,6 +506,14 @@ void common_sampler_free(struct common_sampler * gsmpl) { if (!gsmpl) { return; } + if (gsmpl->fast_greedy_hits > 0) { + const char * st = std::getenv("GGML_AGX_STATS"); + if (st && st[0] && st[0] != '0') { + std::fprintf(stderr, "[common_sampler] fast_greedy_hits=%llu biases=%zu\n", + (unsigned long long) gsmpl->fast_greedy_hits, + gsmpl->fast_greedy_biases.size()); + } + } llama_sampler_free(gsmpl->grmr); llama_sampler_free(gsmpl->rbudget); @@ -532,7 +588,11 @@ struct common_sampler * common_sampler_clone(common_sampler * gsmpl) { /* .prev = */ gsmpl->prev, /* .cur = */ gsmpl->cur, /* .cur_p = */ gsmpl->cur_p, - /* .rng = */ gsmpl->rng, + /* .rng = */ gsmpl->rng, + /* .fast_greedy = */ gsmpl->fast_greedy, + /* .fast_greedy_has_pos_bias = */ gsmpl->fast_greedy_has_pos_bias, + /* .fast_greedy_biases = */ gsmpl->fast_greedy_biases, + /* .fast_greedy_hits = */ 0, }; } @@ -624,6 +684,60 @@ llama_token common_sampler_sample(struct common_sampler * gsmpl, struct llama_co auto & chain = gsmpl->chain; auto & cur_p = gsmpl->cur_p; // initialized by set_logits + // Fast-path pure greedy argmax directly over logits (skips allocating/sorting n_vocab llama_token_data structs) + if (gsmpl->fast_greedy && !grammar_should_apply(gsmpl)) { + id = llama_get_sampled_token_ith(ctx, idx); + if (id != LLAMA_TOKEN_NULL) { + return id; + } + const float * logits = llama_get_logits_ith(ctx, idx); + if (logits) { + const llama_model * model = llama_get_model(ctx); + const llama_vocab * vocab = llama_model_get_vocab(model); + const int n_vocab = llama_vocab_n_tokens(vocab); + if (n_vocab > 0) { + int best_id = 0; + float best_v = logits[0]; + for (int i = 1; i < n_vocab; ++i) { + const float v = logits[i]; + if (v > best_v) { + best_v = v; + best_id = i; + } + } + // Verify bias list (e.g. ignore_eos={EOG,-INF}): if no positive bias and best_id is unbiased, done! + bool need_bias_rescan = false; + if (!gsmpl->fast_greedy_biases.empty()) { + for (const auto & b : gsmpl->fast_greedy_biases) { + if (b.token == best_id) { + need_bias_rescan = true; + break; + } + } + if (!need_bias_rescan && gsmpl->fast_greedy_has_pos_bias) { + for (const auto & b : gsmpl->fast_greedy_biases) { + if (b.token >= 0 && b.token < n_vocab) { + const float bv = logits[b.token] + b.bias; + if (bv > best_v || (bv == best_v && b.token < best_id)) { + best_v = bv; + best_id = b.token; + } + } + } + } + } + if (!need_bias_rescan) { + gsmpl->fast_greedy_hits++; + gsmpl->cur.resize(1); + gsmpl->cur[0] = llama_token_data { best_id, best_v, 1.0f }; + cur_p = { gsmpl->cur.data(), 1, 0, true }; + return best_id; + } + // Rare case (0.1%): argmax hit a biased/EOG token -> fall through to standard chain + } + } + } + gsmpl->set_logits(ctx, idx); // Check if a backend sampler has already sampled a token in which case we diff --git a/common/speculative.cpp b/common/speculative.cpp index db54aef53086..1bfd9dd94b44 100644 --- a/common/speculative.cpp +++ b/common/speculative.cpp @@ -11,8 +11,10 @@ #include "sampling.h" #include +#include #include #include +#include #include #include #include @@ -30,6 +32,19 @@ #define SPEC_VOCAB_MAX_SIZE_DIFFERENCE 128 #define SPEC_VOCAB_CHECK_START_TOKEN_ID 5 +bool common_speculative_timer_enabled() { + static const bool enabled = []() { + const char * e = std::getenv("GGML_AGX_SPEC_TIMER"); + return e && e[0] != '\0' && e[0] != '0'; + }(); + return enabled; +} + +common_speculative_round_timing & common_speculative_round_timing_state() { + static thread_local common_speculative_round_timing st; + return st; +} + // 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( @@ -212,9 +227,15 @@ struct common_speculative_impl { virtual void accept(llama_seq_id seq_id, uint16_t n_accepted, bool is_other) = 0; + // (optional) reset per-seq transient state at request/slot boundary + virtual void reset(llama_seq_id /*seq_id*/) {} + // (optional) serialize/restore per-seq internal state (e.g. eagle3's deferred boundary). virtual bool get_state(llama_seq_id /*seq_id*/, std::vector & /*data*/) const { return false; } virtual void set_state(llama_seq_id /*seq_id*/, const std::vector & /*data*/) {} + + // (optional) emit per-position acceptance stats ([DSPARK_POS]) on request completion + virtual void print_pos_stats(llama_seq_id /*seq_id*/) const {} }; struct common_speculative_impl_draft_simple : public common_speculative_impl { @@ -1213,6 +1234,15 @@ struct common_speculative_impl_draft_dflash : public common_speculative_impl { const int32_t n_ubatch = (int32_t) llama_n_ubatch(ctx_dft); + const bool spec_timer = common_speculative_timer_enabled(); + auto & st = common_speculative_round_timing_state(); + if (spec_timer) { + st.inj_prep_us = 0; + st.inj_decode_us = 0; + st.inj_store_us = 0; + st.inj_dev_feat = use_dev_features ? 1 : 0; + } + for (llama_seq_id seq_id = 0; seq_id < (llama_seq_id) n_seq; ++seq_id) { if (i_batch_beg[seq_id] < 0) { continue; @@ -1230,6 +1260,7 @@ struct common_speculative_impl_draft_dflash : public common_speculative_impl { const int32_t n_chunk = std::min(n_ubatch, n_rows - offset); if (use_dev_features) { + const int64_t t0 = spec_timer ? ggml_time_us() : 0; // the features are the target batch rows in the target's device buffer batch_inject.clear(); for (int32_t i = 0; i < n_chunk; ++i) { @@ -1238,6 +1269,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_row(row, pos_arr, seq_id, false); } + const int64_t t1 = spec_timer ? ggml_time_us() : 0; const int32_t rc = llama_process(ctx_dft, LLAMA_PROCESS_TYPE_DECODE, batch_inject.get()); if (rc != 0) { @@ -1245,10 +1277,18 @@ struct common_speculative_impl_draft_dflash : public common_speculative_impl { __func__, rc, (int) n_chunk, (int) offset); return false; } + const int64_t t2 = spec_timer ? ggml_time_us() : 0; store_context_features(seq_id, n_chunk); + if (spec_timer) { + const int64_t t3 = ggml_time_us(); + st.inj_prep_us += (t1 - t0); + st.inj_decode_us += (t2 - t1); + st.inj_store_us += (t3 - t2); + } continue; } + const int64_t t0 = spec_timer ? ggml_time_us() : 0; // gather target features per extract layer; the fused decode encodes and // injects them into the K/V cache at the target positions features_buf.resize((size_t) n_chunk * n_embd_enc); @@ -1270,13 +1310,21 @@ 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 int64_t t1 = spec_timer ? ggml_time_us() : 0; const int32_t rc = llama_process(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); return false; } + const int64_t t2 = spec_timer ? ggml_time_us() : 0; store_context_features(seq_id, n_chunk); + if (spec_timer) { + const int64_t t3 = ggml_time_us(); + st.inj_prep_us += (t1 - t0); + st.inj_decode_us += (t2 - t1); + st.inj_store_us += (t3 - t2); + } } } @@ -1370,6 +1418,1043 @@ struct common_speculative_impl_draft_dflash : public common_speculative_impl { } }; +// Cost-calibrated, CDM-replay-aware dynamic draft-width planner for DSpark (Wave 40). +// Maintains per-sequence: +// 1. Online confidence calibration p(slot, conf) via hierarchical binned EMA +// plus a sequence-level geometric acceptance rate estimator p_hat, updated from +// observed (slot, conf, accepted) outcomes on each verified round. +// 2. Online steady-state round wall-time table round_ms[0..K_MAX] updated via EMA +// from measured [draft -> accept] wall-clock duration on CDM-replay-hit rounds +// (skipping M-switch rounds so replay misses never pollute round_ms[k]). +// 3. Sticky regime width active_k (starts at min(3, n_max) so low-acceptance prose +// never pays M=8 warmup or replay-miss thrashing) with hysteresis + a one-time +// 2-round high-width probe on high-acceptance sequences to measure true M=n_max+1 +// latency automatically across context lengths (1k..32k) and hardware/kernel builds. +// 4. Per-round throughput-maximizing width selection with explicit CDM replay-miss +// switch penalty (2 * k_switch_ms for single-round early trim in wide regimes). +struct dspark_width_planner { + static constexpr int32_t K_MAX = 16; + static constexpr int32_t N_BINS = 8; + static constexpr float k_cal_decay = 0.94f; + static constexpr float k_bin_decay = 0.94f; + static constexpr float k_slot_decay = 0.95f; + static constexpr float k_seq_decay = 0.94f; + static constexpr float k_bin_prior_w = 2.0f; + static constexpr float k_slot_prior_w = 6.0f; + static constexpr float k_switch_ms = 3.5f; // Legacy 1-slot CDM replay miss cost (when GGML_AGX_CDM_CACHE_M8=0) + static constexpr float k_hyst_ratio = 1.06f; // Legacy hysteresis ratio (when GGML_AGX_CDM_CACHE_M8=0) + + static uint32_t w46_dspark_mask() { + static const uint32_t mask = []() -> uint32_t { + const char * v = std::getenv("GGML_AGX_W46_DSPARK"); + if (!v || !v[0]) { + return 0x3u; // Bit 0: Wave 46 Planner v3, Bit 1: agx-moe s6_m48_dedup + } + return (uint32_t) std::strtoul(v, nullptr, 0); + }(); + return mask; + } + + // Wave 55 DSpark Acceptance Yield & Planner bitmask (0x00 = exact 476147701 behavior): + // Bit 0 (0x01): Unbiased decayed-prior seq_p_hat() (fixes permanent +3.25/+5.0 downward bias) + // Bit 1 (0x02): 3-tier silicon-calibrated sticky regime {3, 5, 7} (removes p_hat>=0.85 ceiling) + // Bit 2 (0x04): Bypass recovery grace + confirmation guard (stops Code 1k false k=0 lock-in) + // Bit 3 (0x08): Proportional context-length latency scaling for unvisited widths (fixes 16k/32k round_ms[0]/7) + static uint32_t w55_dspark_mask() { + static const uint32_t mask = []() -> uint32_t { + const char * v = std::getenv("GGML_AGX_W55_DSPARK"); + if (!v || !v[0]) { + return 0x0Fu; + } + return (uint32_t) std::strtoul(v, nullptr, 0); + }(); + return mask; + } + + static bool w55_unbiased_p_hat() { return (w55_dspark_mask() & 0x01u) != 0u; } + static bool w55_multi_width() { return (w55_dspark_mask() & 0x02u) != 0u; } + static bool w55_bypass_guard() { return (w55_dspark_mask() & 0x04u) != 0u; } + static bool w55_prop_lat_scale() { return (w55_dspark_mask() & 0x08u) != 0u; } + + // Wave 61: Silicon-calibrated priors + empirical survival curve (eliminates Jensen bias on bursty code) + // + 3-tier {3,5,7} regime selector with faster warmup & direct 3->7 jump (default ON; set 0 for W55 baseline). + static bool w61_planner_enabled() { + static const bool enabled = []() { + const char * v = std::getenv("GGML_AGX_W61_PLANNER"); + if (!v || !v[0]) { + return true; + } + return std::atoi(v) != 0; + }(); + return enabled; + } + + // Wave 62: Surgical fixes on top of W61 planner (default ON when W61_PLANNER=1; set 0 for exact W61 A/B): + // 1. Additive context-length latency shift for delta > 0 (j >= 1) + round_ms[0] >= priors[0] floor + // (prevents 32k round_ms[7] inflation and 1k round_ms[0] underflow). + // 2. Sustained-low bypass gate (n_rounds >= 8 fast / >= 12 std, p_hat < 0.36) + n_acc >= 1 probe grace + // (stops novel_4096 & code_16384 hard-opening false k=0 lock-in while unseen_prose_1 still bypasses). + static bool w62_planner_enabled() { + static const bool enabled = []() { + const char * v = std::getenv("GGML_AGX_W62_PLANNER"); + if (!v || !v[0]) { + return true; + } + return std::atoi(v) != 0; + }(); + return enabled; + } + + static bool planner_v3_enabled() { + return (w46_dspark_mask() & 0x1u) != 0u; + } + + static bool cdm_cache_m8_enabled() { + static const bool enabled = []() { + const char * v = std::getenv("GGML_AGX_CDM_CACHE_M8"); + if (v && v[0] == '0') { + return false; + } + return planner_v3_enabled(); + }(); + return enabled; + } + + // Non-uniform confidence bin upper edges (finer resolution in [0.60, 1.0]) + static constexpr float k_bin_edges[N_BINS] = { + 0.25f, 0.45f, 0.60f, 0.72f, 0.82f, 0.90f, 0.96f, 1.01f + }; + + // Initial round latency prior (ms) for k = 0..7 (trunk verify M = 1..8), + // seeded from Wave 40 Phase 0 wall-clock measurements (d1k, oQ4e-match, F16 KV). + // Online EMA adapts this automatically to context length (1k..32k) and hardware. + static constexpr float k_default_round_ms[8] = { + 15.50f, 19.67f, 23.34f, 25.76f, 32.83f, 36.59f, 37.25f, 39.55f + }; + + // Wave 46 recalibrated priors (d1k, oQ4e-match, F16 KV, with s6_m48_dedup): + // round_ms[0] = true no-draft Plain M=1 wall-clock (12.4 ms); + // round_ms[1..7] = DSpark draft (~2.5 ms) + target verify M=2..8. + static constexpr float k_v3_round_ms[8] = { + 12.40f, 18.50f, 22.00f, 23.90f, 27.50f, 29.80f, 31.80f, 33.80f + }; + + // Wave 55 silicon-calibrated priors (Wave 53 476147701 Suite A 1k F16 KV truth): + // M=1: 12.14, M=2: 19.51, M=4: 24.07, M=8: 33.97 (interpolated M=3,5,6,7). + static constexpr float k_v55_round_ms[8] = { + 12.14f, 19.51f, 21.80f, 24.07f, 26.55f, 29.00f, 31.50f, 33.97f + }; + + // Wave 61 silicon-calibrated priors (48403d708 F16 KV short-ctx truth: M=1 ~12.85, M=4 ~24.0, M=8 ~32.0): + static constexpr float k_v61_round_ms[8] = { + 12.85f, 19.20f, 21.60f, 24.00f, 26.00f, 28.00f, 30.00f, 32.00f + }; + + static const float * active_priors() { + if (!planner_v3_enabled()) { + return k_default_round_ms; + } + if (w61_planner_enabled()) { + return k_v61_round_ms; + } + return w55_multi_width() ? k_v55_round_ms : k_v3_round_ms; + } + + // Calibration state + float cal_acc = 0.0f; + float cal_pred = 0.0f; + float bin_acc[N_BINS] = {}; + float bin_tot[N_BINS] = {}; + float slot_acc[K_MAX] = {}; + float slot_pred[K_MAX] = {}; + + // Sequence-level geometric acceptance rate estimator + float seq_ema_acc = 0.0f; + float seq_ema_trials = 0.0f; + + // Wave 61: per-position empirical survival EMA P(n_acc >= i+1) for non-parametric E[tokens(k)] + float surv_ema[K_MAX] = {}; + float surv_obs_ema[K_MAX] = {}; + + // Latency model state: steady-state CDM-replay-hit round wall-time (ms) + float round_ms[K_MAX + 1] = {}; + uint32_t obs_count[K_MAX + 1] = {}; + + // Last drafted round state (for calibration + latency update in accept()) + int64_t last_draft_start_us = 0; + int32_t last_k = 0; + int32_t prev_executed_k = -1; + bool last_single_seq = false; + float last_conf[K_MAX] = {}; + + // Sticky regime width (also drives agx_set_dspark_active_drafts Markov early-stop cap) + int32_t active_k = 3; + int32_t steady_rounds = 0; + uint32_t n_rounds = 0; + uint32_t warmed_k_mask = 0u; + bool probed_high = false; + int32_t probe_rem = 0; + + // Wave 46 Planner v3: true k=0 Plain M=1 bypass + online draft latency tracking + float draft_ms_ema = 2.50f; + int32_t bypass_rem = 0; + int32_t bypass_len = 8; + int32_t bypass_grace = 0; + bool last_was_bypass = false; + bool probe_after_bypass = false; + int64_t last_bypass_us = 0; + uint32_t bypass_streak = 0; + + // Diagnostic stats (for SPC_DBG / LLAMA_DSPARK_PLANNER_DEBUG) + uint32_t k_hist[K_MAX + 1] = {}; + uint32_t n_switches = 0; + + void reset(int32_t n_max_cfg) { + cal_acc = 0.0f; + cal_pred = 0.0f; + if (w55_unbiased_p_hat()) { + // Decayed prior: starts at 1.30 / 2.0 = 0.65 and decays naturally to zero bias + seq_ema_acc = 1.30f; + seq_ema_trials = 2.00f; + } else { + seq_ema_acc = 0.0f; + seq_ema_trials = 0.0f; + } + std::memset(bin_acc, 0, sizeof(bin_acc)); + std::memset(bin_tot, 0, sizeof(bin_tot)); + std::memset(slot_acc, 0, sizeof(slot_acc)); + std::memset(slot_pred, 0, sizeof(slot_pred)); + std::memset(surv_ema, 0, sizeof(surv_ema)); + std::memset(surv_obs_ema, 0, sizeof(surv_obs_ema)); + std::memset(obs_count, 0, sizeof(obs_count)); + std::memset(last_conf, 0, sizeof(last_conf)); + std::memset(k_hist, 0, sizeof(k_hist)); + + const float * priors = active_priors(); + for (int32_t k = 0; k <= K_MAX; ++k) { + if (k < 8) { + round_ms[k] = priors[k]; + } else { + round_ms[k] = priors[7] + 2.0f * (float) (k - 7); + } + } + + last_draft_start_us = 0; + last_k = 0; + prev_executed_k = -1; + last_single_seq = false; + // Start at min(3, n_max_cfg) so prose pays zero M=8 warmup or CDM replay misses + active_k = std::clamp(std::min(3, n_max_cfg), 1, K_MAX); + steady_rounds = 0; + n_rounds = 0; + warmed_k_mask = 0u; + probed_high = false; + probe_rem = 0; + draft_ms_ema = 2.50f; + bypass_rem = 0; + bypass_len = 8; + bypass_grace = 0; + last_was_bypass = false; + probe_after_bypass = false; + last_bypass_us = 0; + bypass_streak = 0; + n_switches = 0; + } + + // Wave 46 Planner v3: called at entry of draft() before building ctx_dft batch. + // Returns true if this sequence should bypass DSpark completely (k=0, Plain M=1 verify, + // skipping llama_process(ctx_dft)). Also updates true round_ms[0] from consecutive bypass rounds. + bool on_draft_entry(int64_t t_now_us, bool single_seq, int32_t n_min) { + if (!planner_v3_enabled()) { + return false; + } + if (last_was_bypass && single_seq && bypass_streak >= 1u && last_bypass_us > 0 && t_now_us > last_bypass_us) { + const float obs_ms = (float) (t_now_us - last_bypass_us) * 1e-3f; + if (obs_ms >= 3.0f && obs_ms <= 200.0f && (obs_count[0] == 0 || obs_ms <= 3.0f * round_ms[0])) { + const float alpha = (obs_count[0] == 0) ? 0.70f : ((obs_count[0] < 3) ? 0.35f : 0.15f); + round_ms[0] += alpha * (obs_ms - round_ms[0]); + obs_count[0]++; + if (round_ms[0] > round_ms[1] - 0.5f) { + round_ms[0] = std::max(1.0f, round_ms[1] - 0.5f); + } + } + } + if (bypass_rem > 0 && n_min <= 0) { + bypass_rem--; + last_was_bypass = true; + last_bypass_us = t_now_us; + bypass_streak++; + last_k = 0; + k_hist[0]++; + return true; + } + last_was_bypass = false; + last_bypass_us = 0; + bypass_streak = 0; + return false; + } + + void observe_draft_ms(float d_ms) { + if (d_ms >= 0.2f && d_ms <= 50.0f) { + draft_ms_ema = 0.85f * draft_ms_ema + 0.15f * d_ms; + } + } + + static int32_t bin_of(float c) { + for (int32_t b = 0; b < N_BINS - 1; ++b) { + if (c < k_bin_edges[b]) { + return b; + } + } + return N_BINS - 1; + } + + float seq_p_hat() const { + if (w55_unbiased_p_hat()) { + return std::clamp(seq_ema_acc / std::max(seq_ema_trials, 1e-3f), 0.15f, 0.98f); + } + return std::clamp((seq_ema_acc + 3.25f) / (seq_ema_trials + 5.0f), 0.15f, 0.98f); + } + + float predict_bin_prob(float c) const { + const float c_clamped = std::clamp(c, 0.01f, 0.995f); + // Sequence-level calibration multiplier (shrinks toward 0.90 prior on round 0) + const float r_seq = std::clamp((cal_acc + 1.35f) / (cal_pred + 1.50f), 0.25f, 1.15f); + const float prior_p = std::clamp(c_clamped * r_seq, 0.02f, 0.99f); + const int32_t b = bin_of(c_clamped); + return (bin_acc[b] + k_bin_prior_w * prior_p) / (bin_tot[b] + k_bin_prior_w); + } + + float predict_prob(int32_t slot, float c) const { + const float p_bin = predict_bin_prob(c); + const int32_t s = std::clamp(slot, 0, K_MAX - 1); + const float r_slot = std::clamp((slot_acc[s] + k_slot_prior_w) / (slot_pred[s] + k_slot_prior_w), 0.55f, 1.15f); + const float p_slot = std::clamp(p_bin * r_slot, 0.01f, 0.995f); + return std::clamp(0.75f * p_slot + 0.25f * seq_p_hat(), 0.02f, 0.995f); + } + + static double expected_tokens_regime(int32_t k, float p_hat) { + double surv = 1.0; + double exp_tok = 1.0; + for (int32_t j = 0; j < k; ++j) { + surv *= (double) p_hat; + exp_tok += surv; + } + return exp_tok; + } + + // Wave 61: Non-parametric empirical survival curve for observed slots [0..obs_max] + // plus conditional tail continuation p_tail for wider unobserved slots (eliminates + // Jensen's inequality underestimation on bursty code/repetitive text). + double expected_tokens_w61(int32_t k, float p_hat) const { + k = std::clamp(k, 0, K_MAX); + if (k == 0) { + return 1.0; + } + int32_t last_obs = -1; + for (int32_t j = 0; j < K_MAX; ++j) { + if (surv_obs_ema[j] >= 1.5f) { + last_obs = j; + } else { + break; + } + } + if (last_obs < 1) { + return expected_tokens_regime(k, p_hat); + } + const float s_last = std::clamp(surv_ema[last_obs] / surv_obs_ema[last_obs], 0.0f, 0.99f); + const float s_prev = std::clamp(surv_ema[last_obs - 1] / surv_obs_ema[last_obs - 1], 0.0f, 0.99f); + const float p_cond = (s_prev > 0.08f) ? std::clamp(s_last / s_prev, 0.15f, 0.92f) : p_hat; + const float p_tail = 0.65f * p_cond + 0.35f * p_hat; + + double exp_tok = 1.0; + double surv = 1.0; + for (int32_t j = 0; j < k; ++j) { + if (j <= last_obs) { + surv = (double) std::clamp(surv_ema[j] / surv_obs_ema[j], 0.0f, 0.99f); + } else { + surv *= (double) p_tail; + } + exp_tok += surv; + } + return exp_tok; + } + + int32_t select_width(const float * raw_conf, int32_t n_avail, int32_t n_min) const { + n_avail = std::clamp(n_avail, 0, K_MAX); + if (n_avail == 0) { + return 0; + } + // During a high-width latency probe, keep full width for a clean steady-state sample + if (probe_rem > 0) { + return n_avail; + } + + const bool m8_cache = cdm_cache_m8_enabled(); + const bool v3 = planner_v3_enabled(); + if (v3) { + // Wave 46 v3.1: llama_decode pays ~4-5 ms CPU graph-rebuild/alloc whenever M changes! + // Keep steady-state regimes (sw=0) for active_k <= 3, and only trim wide regimes + // when a single-round drop beats the real 2 * 4.5 ms switch cost. + if (active_k <= 3) { + return n_avail; + } + const int32_t k_lo = std::max(n_min, std::min(3, n_avail)); + double best_tps = -1.0; + int32_t best_k = n_avail; + double surv = 1.0; + double exp_tok = 1.0; + for (int32_t k = 1; k <= n_avail; ++k) { + const float p_i = predict_prob(k - 1, raw_conf[k - 1]); + surv *= (double) p_i; + exp_tok += surv; + if (k < k_lo) { + continue; + } + const float sw_pen = (k != n_avail) ? 9.0f : 0.0f; + const double tps = exp_tok / (double) std::max(round_ms[k] + sw_pen, 0.5f); + if (tps > best_tps) { + best_tps = tps; + best_k = k; + } + } + return best_k; + } + if (!m8_cache && active_k <= 3) { + // Legacy 1-slot CDM mode: avoid replay thrashing in narrow regimes + return n_avail; + } + + const int32_t k_lo = std::max(n_min, std::min(3, n_avail)); + + double best_tps = -1.0; + int32_t best_k = n_avail; + + double surv = 1.0; + double exp_tok = 1.0; + for (int32_t k = 1; k <= n_avail; ++k) { + const float p_i = predict_prob(k - 1, raw_conf[k - 1]); + surv *= (double) p_i; + exp_tok += surv; + if (k < k_lo) { + continue; + } + float sw_pen = 0.0f; + if (!m8_cache) { + sw_pen = (k != n_avail) ? (2.0f * k_switch_ms) : 0.0f; + } else if (k != n_avail && k < 32 && (warmed_k_mask & (1u << k)) == 0u) { + // Amortized one-time cold-slot warmup guard (0.0 ms once warmed!) + sw_pen = 0.35f; + } + const double tps = exp_tok / (double) std::max(round_ms[k] + sw_pen, 0.5f); + if (tps > best_tps) { + best_tps = tps; + best_k = k; + } + } + + return best_k; + } + + void record_draft(int32_t k_chosen, const float * raw_conf, int64_t t_start_us, bool single_seq) { + last_k = std::clamp(k_chosen, 0, K_MAX); + last_draft_start_us = t_start_us; + last_single_seq = single_seq; + for (int32_t i = 0; i < last_k; ++i) { + last_conf[i] = std::clamp(raw_conf[i], 0.01f, 0.995f); + } + k_hist[last_k]++; + } + + void observe_accept(int32_t n_accepted, int64_t t_now_us, int32_t n_max_cfg, int32_t n_min_cfg = 0) { + const int32_t k = last_k; + const int64_t t_start = last_draft_start_us; + const bool single_seq = last_single_seq; + last_k = 0; + last_draft_start_us = 0; + last_single_seq = false; + + if (k <= 0 || k > K_MAX) { + return; + } + + const bool is_switch = (prev_executed_k > 0 && k != prev_executed_k); + if (is_switch) { + n_switches++; + steady_rounds = 0; + } else { + steady_rounds++; + } + prev_executed_k = k; + n_rounds++; + + // 1. Update confidence calibration + sequence-level geometric acceptance rate + const int32_t n_acc = std::clamp(n_accepted, 0, k); + const int32_t n_tested = std::min(n_acc + 1, k); + seq_ema_acc = k_seq_decay * seq_ema_acc + (float) n_acc; + seq_ema_trials = k_seq_decay * seq_ema_trials + (float) n_tested; + + for (int32_t i = 0; i < k; ++i) { + surv_ema[i] = k_seq_decay * surv_ema[i] + ((i < n_acc) ? 1.0f : 0.0f); + surv_obs_ema[i] = k_seq_decay * surv_obs_ema[i] + 1.0f; + } + + for (int32_t i = 0; i < n_tested; ++i) { + const float c = std::clamp(last_conf[i], 0.01f, 0.995f); + const float outcome = (i < n_acc) ? 1.0f : 0.0f; + const float p_bin = predict_bin_prob(c); + const int32_t b = bin_of(c); + + cal_acc = k_cal_decay * cal_acc + outcome; + cal_pred = k_cal_decay * cal_pred + c; + bin_acc[b] = k_bin_decay * bin_acc[b] + outcome; + bin_tot[b] = k_bin_decay * bin_tot[b] + 1.0f; + slot_acc[i] = k_slot_decay * slot_acc[i] + outcome; + slot_pred[i] = k_slot_decay * slot_pred[i] + p_bin; + } + + const bool m8_cache = cdm_cache_m8_enabled(); + const bool is_cold_k = (k < 32) && ((warmed_k_mask & (1u << k)) == 0u); + if (k < 32) { + warmed_k_mask |= (1u << k); + } + + // 2. Update steady-state round latency model: + // Skip switch rounds AND cold-k warmup rounds (round 0 pays ~16ms cold CDM encode; + // M switches pay ~4-5ms host graph rebuild) so round_ms[k] tracks true steady-state! + static const uint32_t w49_host_mask = []() -> uint32_t { + const char * e = std::getenv("GGML_AGX_W49_HOST"); + if (!e || !*e) return 0x0Du; + return static_cast(std::strtoul(e, nullptr, 0)); + }(); + const bool w49_lat_fix = (w49_host_mask & 0x04u) != 0u; + const bool skip_lat_sample = w49_lat_fix + ? (is_switch || is_cold_k) + : (planner_v3_enabled() ? is_switch : (m8_cache ? is_cold_k : is_switch)); + const float * priors = active_priors(); + auto prior_val = [&](int32_t j) -> float { + return (j < 8) ? priors[j] : (priors[7] + 2.0f * (float) (j - 7)); + }; + auto prior_floor = [&](int32_t j) -> float { + if (!w49_lat_fix) return 1.0f; + return std::max(1.0f, 0.65f * prior_val(j)); + }; + if (single_seq && !skip_lat_sample && t_start > 0 && t_now_us > t_start) { + const float obs_ms = (float) (t_now_us - t_start) * 1e-3f; + const float cur_ms = round_ms[k]; + if (obs_ms >= 1.0f && obs_ms <= 500.0f && (obs_count[k] == 0 || obs_ms <= 3.0f * cur_ms)) { + const float alpha = (obs_count[k] == 0) ? (w49_lat_fix ? 0.55f : 0.85f) : ((obs_count[k] < 3) ? 0.35f : 0.15f); + const float delta = obs_ms - cur_ms; + round_ms[k] = std::max(prior_floor(k), round_ms[k] + alpha * delta); + obs_count[k]++; + + // Coupled shift for unvisited widths: + // - W62: for long-context positive delta > 0, use additive KV scaling (ratio=1.0 for j>=1, + // 0.75 for j==0) so 8k/16k/32k don't inflate round_ms[7] or under-shift round_ms[0]; + // for delta <= 0 (1k fast path), keep proportional scaling and never push unvisited + // round_ms[0] below its 1k silicon prior floor. + // - W55 bit 3: legacy proportional scaling. + const bool w62_lat = w61_planner_enabled() && w62_planner_enabled(); + const float pk = std::max(prior_val(k), 1.0f); + for (int32_t j = 0; j <= K_MAX; ++j) { + if (j == k) { + continue; + } + if (w62_lat && delta > 0.0f) { + const float ratio = (j == 0) ? 0.75f : 1.00f; + const float c_alpha = (obs_count[j] == 0) ? std::min(alpha, 0.55f) : 0.02f; + round_ms[j] = std::max(prior_floor(j), round_ms[j] + c_alpha * delta * ratio); + } else if (w55_prop_lat_scale()) { + const float ratio = std::clamp(prior_val(j) / pk, 0.45f, 1.65f); + const float c_alpha = (obs_count[j] == 0) ? std::min(alpha, 0.55f) : 0.02f; + const float floor_j = (w62_lat && j == 0 && obs_count[0] == 0) ? prior_val(0) : prior_floor(j); + round_ms[j] = std::max(floor_j, round_ms[j] + c_alpha * delta * ratio); + } else { + const float dist = (float) std::abs(j - k); + const float c_alpha = (obs_count[j] == 0) ? (std::min(alpha, 0.35f) / (1.0f + 0.50f * dist)) : 0.02f; + round_ms[j] = std::max(prior_floor(j), round_ms[j] + c_alpha * delta); + } + } + + // Enforce strict monotonicity round_ms[j] <= round_ms[j+1] - 0.05f around k + for (int32_t j = k - 1; j >= 0; --j) { + if (round_ms[j] > round_ms[j + 1] - 0.05f) { + round_ms[j] = std::max(prior_floor(j), round_ms[j + 1] - 0.05f); + } + } + for (int32_t j = k + 1; j <= K_MAX; ++j) { + if (round_ms[j] < round_ms[j - 1] + 0.05f) { + round_ms[j] = round_ms[j - 1] + 0.05f; + } + } + } + } + + // 3. Regime update (drives agx_set_dspark_active_drafts Markov early-stop cap + k=0 bypass) + const int32_t cap_max = std::clamp(n_max_cfg, 1, K_MAX); + const float p_hat = seq_p_hat(); + const bool v3 = planner_v3_enabled(); + + if (v3) { + const bool w61 = w61_planner_enabled(); + const bool w62 = w61 && w62_planner_enabled(); + const int32_t k_mid = std::min(3, cap_max); + const double tps_0 = 1.0 / (double) std::max(round_ms[0], 0.5f); + auto exp_tok_fn = [&](int32_t kc) -> double { + return w61 ? expected_tokens_w61(kc, p_hat) : expected_tokens_regime(kc, p_hat); + }; + double best_draft_tps = -1.0; + for (int32_t kc = k_mid; kc <= cap_max; ++kc) { + const double tps = exp_tok_fn(kc) / (double) std::max(round_ms[kc], 0.5f); + if (tps > best_draft_tps) { + best_draft_tps = tps; + } + } + // True k=0 Plain M=1 bypass: + // - W55 Bit 2 (w55_bypass_guard): adds recovery grace window (4 rounds on n_acc>=2, + // 1 confirmation round on n_acc==1) so short hard prefixes on Code 1k/16k never + // lock into exponential bypass while true prose (unseen_prose_1) still hits bypass. + // - W62: gates k=0 bypass to genuinely dead speculation (n_rounds>=12, p_hat<0.20, 1.10x margin) + // and grants 2-round probe grace on any n_acc>=1, because Wave 61/62 M=4 (k=3) beats Plain M=1 + // down to ~30% acceptance once round-trip M-switch cost is included (recovers novel_1024, + // novel_4096, unseen_prose_1, and code_16384 from false k=0 bypass lock-in). + if (w55_bypass_guard()) { + const bool from_probe = probe_after_bypass; + probe_after_bypass = false; + if (from_probe && (n_acc >= 2 || n_acc >= active_k)) { + bypass_grace = 4; + bypass_len = 10; + } else if (from_probe && n_acc == 1 && (w62 || p_hat >= 0.35f)) { + bypass_grace = w62 ? 2 : 1; + bypass_len = std::min(bypass_len, 12); + } else if (bypass_grace > 0) { + bypass_grace--; + } + const bool fast_prose_byp = w62 ? (n_rounds >= 12u && p_hat < 0.20f) : (n_rounds >= 5u && p_hat < 0.28f); + const bool std_prose_byp = w62 ? false : (n_rounds >= 8u && p_hat < 0.44f); + const double byp_margin = w62 ? 1.10 : 1.04; + if (bypass_grace == 0 && n_min_cfg <= 0 && (fast_prose_byp || std_prose_byp) && tps_0 > best_draft_tps * byp_margin) { + bypass_rem = fast_prose_byp ? std::max(bypass_len, 16) : std::max(bypass_len, 10); + if ((w49_host_mask & 0x08u) != 0u) { + bypass_len = std::min(bypass_rem * 2, fast_prose_byp ? 64 : 32); + } else { + bypass_len = std::min(bypass_rem + 4, fast_prose_byp ? 24 : 18); + } + probe_after_bypass = true; + active_k = k_mid; + steady_rounds = 0; + return; + } + if (bypass_grace == 0) { + bypass_len = 10; + } + } else { + const bool probe_recovered = probe_after_bypass && (n_acc >= 2); + const bool fast_prose_byp = (n_rounds >= 4u && p_hat < 0.35f); + const bool std_prose_byp = (n_rounds >= 8u && p_hat < 0.44f); + if (!probe_recovered && n_min_cfg <= 0 && (fast_prose_byp || std_prose_byp) && tps_0 > best_draft_tps * 1.04) { + bypass_rem = fast_prose_byp ? std::max(bypass_len, 16) : bypass_len; + if ((w49_host_mask & 0x08u) != 0u) { + bypass_len = std::min(bypass_rem * 2, fast_prose_byp ? 64 : 32); + } else { + bypass_len = std::min(bypass_rem + 4, fast_prose_byp ? 24 : 18); + } + probe_after_bypass = true; + active_k = k_mid; + steady_rounds = 0; + return; + } + bypass_len = 10; + probe_after_bypass = false; + } + + if (w61) { + // Wave 61: 3-tier silicon-calibrated sticky regime selector {k_mid=3, k_wide=5, cap_max=7} + // using non-parametric empirical survival + conditional tail extrapolation. + if (probe_rem > 0) { + probe_rem--; + if (probe_rem > 0) { + return; + } + } else if (n_rounds < 4u || steady_rounds < ((active_k > k_mid) ? 2 : 3)) { + return; + } + + const int32_t k_wide = std::min(5, cap_max); + const int32_t cands[3] = { k_mid, k_wide, cap_max }; + const double tps_cur = exp_tok_fn(active_k) / (double) std::max(round_ms[active_k], 0.5f); + double best_tps = tps_cur; + int32_t best_k = active_k; + for (int32_t ci = 0; ci < 3; ++ci) { + const int32_t kc = cands[ci]; + if (kc == active_k) { + continue; + } + const double tps_c = exp_tok_fn(kc) / (double) std::max(round_ms[kc], 0.5f); + if (kc > active_k && active_k > k_mid && steady_rounds < 4) { + continue; // Avoid double-promoting k=5 -> k=7 immediately after entering k=5 + } + const double hyst = (kc < active_k) ? 1.02 : 1.03; + if (tps_c > tps_cur * hyst && tps_c > best_tps) { + best_tps = tps_c; + best_k = kc; + } + } + if (best_k != active_k) { + active_k = best_k; + steady_rounds = 0; + if (best_k > k_mid && obs_count[best_k] == 0) { + probe_rem = 2; + } + } + return; + } + + if (w55_multi_width()) { + // Wave 55 Bit 1: 3-tier silicon-calibrated sticky regime selector {k_mid=3, k_wide=5, cap_max=7}. + // Require n_rounds >= 6 and >= 6% throughput win to promote (amortizes ~20ms cold-M switch cost). + if (probe_rem > 0) { + probe_rem--; + if (probe_rem > 0) { + return; + } + } else if (n_rounds < 6u || steady_rounds < ((active_k > k_mid) ? 2 : 4)) { + return; + } + + const int32_t k_wide = std::min(5, cap_max); + const int32_t cands[3] = { k_mid, k_wide, cap_max }; + const double tps_cur = expected_tokens_regime(active_k, p_hat) / (double) std::max(round_ms[active_k], 0.5f); + double best_tps = tps_cur; + int32_t best_k = active_k; + for (int32_t ci = 0; ci < 3; ++ci) { + const int32_t kc = cands[ci]; + if (kc == active_k) { + continue; + } + const double tps_c = expected_tokens_regime(kc, p_hat) / (double) std::max(round_ms[kc], 0.5f); + if (kc > active_k && active_k > k_mid && steady_rounds < 6) { + continue; // Avoid double-promoting k=3 -> k=5 -> k=7 within a few rounds + } + const double hyst = (kc < active_k) ? 1.02 : 1.06; + if (tps_c > tps_cur * hyst && tps_c > best_tps) { + best_tps = tps_c; + best_k = kc; + } + } + if (best_k != active_k) { + active_k = best_k; + steady_rounds = 0; + if (best_k > k_mid && obs_count[best_k] == 0) { + probe_rem = 2; + } + } + return; + } + + // Legacy Wave 46 sticky 2-regime selector (k_mid=3 vs cap_max=7): + if (probe_rem > 0) { + probe_rem--; + if (probe_rem > 0) { + return; + } + } else if (!probed_high && cap_max > active_k && n_rounds >= 6u && p_hat >= 0.85f) { + const float opt_ms = round_ms[active_k] + 2.2f * (float) (cap_max - active_k); + const double tps_cur = expected_tokens_regime(active_k, p_hat) / (double) std::max(round_ms[active_k], 0.5f); + const double tps_opt = expected_tokens_regime(cap_max, p_hat) / (double) std::max(opt_ms, 0.5f); + if (tps_opt > tps_cur * 1.04) { + probed_high = true; + active_k = cap_max; + probe_rem = 2; + return; + } + } else if (steady_rounds < ((active_k > k_mid) ? 2 : 4)) { + return; + } + + const double tps_cur = expected_tokens_regime(active_k, p_hat) / (double) std::max(round_ms[active_k], 0.5f); + const int32_t alt_k = (active_k == k_mid) ? cap_max : k_mid; + if (alt_k != active_k) { + const double tps_alt = expected_tokens_regime(alt_k, p_hat) / (double) std::max(round_ms[alt_k], 0.5f); + const double hyst = (alt_k < active_k) ? 1.02 : 1.05; + if (tps_alt > tps_cur * hyst && (alt_k < active_k || p_hat >= 0.85f)) { + active_k = alt_k; + steady_rounds = 0; + } + } + return; + } + + const float hyst_ratio = m8_cache ? 1.03f : k_hyst_ratio; + const int32_t cooldown_rnd = m8_cache ? 2 : 6; + const uint32_t probe_min_r = m8_cache ? 3u : 6u; + const float probe_min_p = m8_cache ? 0.78f : 0.82f; + // Only allow stepping down below 3 when acceptance is genuinely low (< 0.45) + const int32_t k_lo = std::min(cap_max, (p_hat < 0.45f) ? 2 : 3); + + if (probe_rem > 0) { + probe_rem--; + if (probe_rem > 0) { + return; // complete 2-round probe (1 cold fill + 1 steady-state sample) before re-evaluating + } + } else if (!probed_high && cap_max > active_k && n_rounds >= probe_min_r && p_hat >= probe_min_p) { + // Only probe cap_max if it could plausibly beat active_k under an optimistic fast-M8 slope + const float opt_ms = round_ms[active_k] + 1.5f * (float) (cap_max - active_k); + const double tps_cur = expected_tokens_regime(active_k, p_hat) / (double) std::max(round_ms[active_k], 0.5f); + const double tps_opt = expected_tokens_regime(cap_max, p_hat) / (double) std::max(opt_ms, 0.5f); + if (tps_opt > tps_cur * (double) hyst_ratio) { + probed_high = true; + active_k = cap_max; + probe_rem = 2; + return; + } + } else if (steady_rounds < cooldown_rnd) { + return; + } + + const double tps_cur = expected_tokens_regime(active_k, p_hat) / (double) std::max(round_ms[active_k], 0.5f); + double best_tps = tps_cur; + int32_t best_k = active_k; + for (int32_t kc = k_lo; kc <= cap_max; ++kc) { + const double tps = expected_tokens_regime(kc, p_hat) / (double) std::max(round_ms[kc], 0.5f); + if (tps > best_tps) { + best_tps = tps; + best_k = kc; + } + } + if (best_k != active_k && best_tps > tps_cur * (double) hyst_ratio) { + active_k = best_k; + steady_rounds = 0; + } + } + + // Effective drafter Markov cap for the upcoming round + int32_t get_draft_cap(int32_t n_max_cfg) const { + return std::clamp(active_k, 1, std::clamp(n_max_cfg, 1, K_MAX)); + } + + static float candidate_top1_prob(const llama_token_data_array * cur_p) { + if (!cur_p || cur_p->size == 0) { + return 0.5f; + } + const float p = cur_p->data[0].p; + if (p > 0.0f && p <= 1.0f) { + return p; + } + // fallback: softmax over available candidate logits + float max_l = cur_p->data[0].logit; + for (size_t k = 1; k < cur_p->size; ++k) { + max_l = std::max(max_l, cur_p->data[k].logit); + } + double sum = 0.0; + for (size_t k = 0; k < cur_p->size; ++k) { + sum += std::exp((double) (cur_p->data[k].logit - max_l)); + } + return sum > 0.0 ? (float) (std::exp((double) (cur_p->data[0].logit - max_l)) / sum) : 0.5f; + } +}; + +// Wave 61: Zero-cost (< 5 us) CPU prompt/history copy proposer for DSpark. +// Indexes every committed 4-gram into a 4-way 8192-bucket L2-resident hash table. +// When the trailing N >= 5 tokens (or N >= 4 during an active copy streak) match an +// earlier span in the prompt or generated history, proposes up to n_max verbatim tokens +// directly and skips the ~3 ms DSpark GPU forward pass completely (100% lossless in greedy mode). +struct dspark_copy_proposer { + static constexpr uint32_t TABLE_BITS = 13u; + static constexpr uint32_t TABLE_SIZE = 1u << TABLE_BITS; + static constexpr uint32_t TABLE_MASK = TABLE_SIZE - 1u; + static constexpr uint32_t EMPTY_POS = 0xFFFFFFFFu; + static constexpr int32_t WAYS = 4; + + std::vector history; + std::vector> table; + llama_tokens last_draft; + + bool synced = false; + bool cur_inserted = false; + bool last_was_copy = false; + bool in_copy_streak = false; + int32_t copy_cooldown = 0; + float copy_acc_ema = 0.85f; + float copy_tr_ema = 1.00f; + + uint32_t n_copy_rounds = 0; + uint32_t n_copy_drafted = 0; + uint32_t n_copy_accepted = 0; + + static inline uint32_t hash4(llama_token t0, llama_token t1, llama_token t2, llama_token t3) { + uint64_t h = (uint64_t) (uint32_t) t0 * 0x9E3779B185EBCA87ull; + h ^= (uint64_t) (uint32_t) t1 * 0xC2B2AE3D27D4EB4Full; + h = (h ^ (h >> 27)) * 0x94D049BB133111EBull; + h ^= (uint64_t) (uint32_t) t2 * 0x165667B19E3779F9ull; + h = (h ^ (h >> 31)) * 0xD6E8FEB86659FD93ull; + h ^= (uint64_t) (uint32_t) t3 * 0xA0761D6478BD642Full; + return (uint32_t) ((h ^ (h >> 32)) & (uint64_t) TABLE_MASK); + } + + inline void insert_pos(uint32_t end_pos) { + if (end_pos < 3u || end_pos >= history.size()) { + return; + } + const uint32_t b = hash4(history[end_pos - 3u], history[end_pos - 2u], history[end_pos - 1u], history[end_pos]); + auto & slot = table[b]; + slot[3] = slot[2]; + slot[2] = slot[1]; + slot[1] = slot[0]; + slot[0] = end_pos; + } + + void reset(const llama_tokens & prompt) { + if (table.size() != TABLE_SIZE) { + table.resize(TABLE_SIZE); + } + for (auto & slot : table) { + slot.fill(EMPTY_POS); + } + history = prompt; + const size_t n = history.size(); + for (size_t i = 3; i < n; ++i) { + insert_pos((uint32_t) i); + } + last_draft.clear(); + synced = true; + cur_inserted = true; + last_was_copy = false; + in_copy_streak = false; + copy_cooldown = 0; + copy_acc_ema = 0.85f; + copy_tr_ema = 1.00f; + n_copy_rounds = 0; + n_copy_drafted = 0; + n_copy_accepted = 0; + } + + void on_draft_begin(llama_pos pos0, llama_token id_last) { + if (!synced || pos0 < 0) { + synced = false; + return; + } + const size_t p0 = (size_t) pos0; + if (history.size() == p0) { + history.push_back(id_last); + cur_inserted = false; + } else if (history.size() > p0) { + // Checkpoint rollback/truncation: resync tail cleanly + history.resize(p0); + history.push_back(id_last); + cur_inserted = false; + } else { + synced = false; + } + } + + void insert_cur() { + if (synced && !cur_inserted && history.size() >= 4u) { + insert_pos((uint32_t) (history.size() - 1u)); + cur_inserted = true; + } + } + + bool propose(int32_t n_max, const llama_vocab * vocab, llama_tokens & out) { + if (!synced || n_max < 2 || history.size() < 9u) { + insert_cur(); + return false; + } + const uint32_t cur = (uint32_t) (history.size() - 1u); + const uint32_t b = hash4(history[cur - 3u], history[cur - 2u], history[cur - 1u], history[cur]); + const auto & slot = table[b]; + + const int32_t min_len = in_copy_streak ? 5 : (copy_cooldown > 0 ? 10 : 8); + int32_t best_len = 0; + uint32_t best_pos = EMPTY_POS; + + for (int32_t w = 0; w < WAYS; ++w) { + const uint32_t cand = slot[w]; + if (cand == EMPTY_POS || cand < 3u || cand + 2u > cur) { + continue; + } + if (history[cand] != history[cur] || + history[cand - 1u] != history[cur - 1u] || + history[cand - 2u] != history[cur - 2u] || + history[cand - 3u] != history[cur - 3u]) { + continue; + } + int32_t mlen = 4; + const int32_t max_back = (int32_t) std::min(16u, cand + 1u); + while (mlen < max_back && history[cand - (uint32_t) mlen] == history[cur - (uint32_t) mlen]) { + mlen++; + } + if (mlen > best_len || (mlen == best_len && (best_pos == EMPTY_POS || cand > best_pos))) { + best_len = mlen; + best_pos = cand; + } + } + + insert_cur(); + + if (best_pos == EMPTY_POS || best_len < min_len) { + return false; + } + + const int32_t k_copy = std::min(n_max, (int32_t) (cur - best_pos)); + if (k_copy < 2) { + return false; + } + + out.clear(); + out.reserve((size_t) k_copy); + for (int32_t j = 0; j < k_copy; ++j) { + const llama_token tok = history[best_pos + 1u + (uint32_t) j]; + out.push_back(tok); + if (vocab && llama_vocab_is_eog(vocab, tok)) { + break; + } + } + + last_draft = out; + last_was_copy = true; + return !out.empty(); + } + + void record_dspark_draft(const llama_tokens & draft) { + last_draft = draft; + last_was_copy = false; + } + + bool on_accept(uint16_t n_accepted) { + const size_t n_add = std::min((size_t) n_accepted, last_draft.size()); + if (synced) { + for (size_t j = 0; j < n_add; ++j) { + history.push_back(last_draft[j]); + insert_pos((uint32_t) (history.size() - 1u)); + } + } + const bool was_copy = last_was_copy; + if (was_copy) { + n_copy_rounds++; + n_copy_drafted += (uint32_t) last_draft.size(); + n_copy_accepted += (uint32_t) n_add; + in_copy_streak = (n_add >= 3u); + const float n_tr = (float) std::min(n_add + 1u, last_draft.size()); + copy_acc_ema = 0.85f * copy_acc_ema + (float) n_add; + copy_tr_ema = 0.85f * copy_tr_ema + n_tr; + if (n_add == 0u && (copy_acc_ema / std::max(copy_tr_ema, 1e-3f)) < 0.45f) { + copy_cooldown = 8; + } else if (copy_cooldown > 0) { + copy_cooldown--; + } + } else { + in_copy_streak = false; + if (copy_cooldown > 0) { + copy_cooldown--; + } + } + last_draft.clear(); + last_was_copy = false; + return was_copy; + } +}; + // DSpark: a semi-autoregressive Markov head (+ Confidence head) on the block, anchor-first block layout struct common_speculative_impl_draft_dspark final : public common_speculative_impl_draft_dflash { // bonus anchor (SpecForge exports) when false: slot 0 is a bonus token, not a prediction slot @@ -1377,7 +2462,11 @@ struct common_speculative_impl_draft_dspark final : public common_speculative_im // the Markov head reads the context state of the last committed token (Inkling2 f_rnn) // it comes back from the injection as h_nextn, kept for the last ctx_rows positions of each sequence - bool has_markov_context = false; + bool has_markov_context = false; + bool has_confidence_head = false; + bool planner_enabled = true; + bool planner_debug = false; + int32_t fixed_n = 0; size_t ctx_rows = 0; std::vector ctx_embd; std::vector ctx_pos; @@ -1388,6 +2477,45 @@ struct common_speculative_impl_draft_dspark final : public common_speculative_im std::vector draw_rng; std::vector draw_seed; // the seed each generator was last seeded with (-1: reseed) + // Wave 40: per-sequence cost-calibrated dynamic draft-width planner (active when planner_enabled && params.n_max >= 2) + std::vector planners; + + // Wave 61: opt-in zero-cost CPU prompt-copy proposer (LLAMA_DSPARK_COPY_PROPOSER=1) + bool copy_proposer_enabled = false; + std::vector copy_proposers; + + // Legacy per-sequence adaptive draft length state (used when LLAMA_DSPARK_PLANNER=0 && params.n_max >= 3): + // exponentially decayed (accepted, trials) sums estimate per-token acceptance probability p + // without denominator-shrinkage bias when cur_n_max steps down from 3 to 2; mapped back to + // the equivalent n_max=3 acceptance rate (p + p^2 + p^3)/3 for hysteresis gating. + static constexpr float k_adapt_decay = 0.96f; + static constexpr float k_adapt_init_acc = 0.80f; // prior: 1.0 trial at p=0.80 => r3 ~= 0.65 + static constexpr float k_adapt_init_tr = 1.00f; + static constexpr float k_adapt_lo = 0.45f; // step down >=3 -> 2 below this equivalent r3 + static constexpr float k_adapt_hi = 0.52f; // step up 2 -> 3 above this equivalent r3 + static constexpr int32_t k_adapt_min_round = 4; // warmup rounds before allowing step-down + + std::vector adapt_ema_acc; + std::vector adapt_ema_trials; + std::vector adapt_n_rounds; + std::vector adapt_cur_n_max; + std::vector adapt_n_draft_last; + + // Wave 60: per-request per-position acceptance stats (acc_pos[1..7]) + bool pos_stats_enabled = false; + std::vector pos_rounds; + mutable std::vector pos_printed_rounds; + std::vector> pos_acc; + + // Wave 63: opt-in per-round DSpark trace (LLAMA_DSPARK_TRACE=1) + bool trace_enabled = false; + std::vector trace_pos0; + std::vector trace_id_last; + std::vector trace_draft; + + using agx_set_active_drafts_fn = void (*)(uint32_t); + agx_set_active_drafts_fn agx_set_active_drafts = nullptr; + common_speculative_impl_draft_dspark(const common_params_speculative & params, uint32_t n_seq) : common_speculative_impl_draft_dflash(params, n_seq, COMMON_SPECULATIVE_TYPE_DRAFT_DSPARK) { @@ -1401,6 +2529,33 @@ struct common_speculative_impl_draft_dspark final : public common_speculative_im if (llama_model_meta_val_str(model_dft, "dflash.has_markov_context", buf, sizeof(buf)) >= 0) { has_markov_context = std::strcmp(buf, "true") == 0; } + if (llama_model_meta_val_str(model_dft, "dflash.has_confidence_head", buf, sizeof(buf)) >= 0) { + has_confidence_head = std::strcmp(buf, "true") == 0; + } else { + has_confidence_head = !has_markov_context; + } + } + + if (const char * env = getenv("LLAMA_DSPARK_PLANNER")) { + planner_enabled = atoi(env) != 0; + } + if (const char * env = getenv("LLAMA_DSPARK_PLANNER_DEBUG")) { + planner_debug = atoi(env) != 0; + } + if (const char * env = getenv("LLAMA_DSPARK_POS_STATS")) { + pos_stats_enabled = atoi(env) != 0; + } + if (planner_debug) { + pos_stats_enabled = true; + } + if (const char * env = getenv("LLAMA_DSPARK_FIXED_N")) { + fixed_n = std::max(0, atoi(env)); + } + if (const char * env = getenv("LLAMA_DSPARK_COPY_PROPOSER")) { + copy_proposer_enabled = atoi(env) != 0; + } + if (const char * env = getenv("LLAMA_DSPARK_TRACE")) { + trace_enabled = atoi(env) != 0; } if (has_markov_context) { @@ -1422,8 +2577,15 @@ struct common_speculative_impl_draft_dspark final : public common_speculative_im } } - LOG_INF("%s: - sample_from_anchor=%s, has_markov_context=%s\n", __func__, - sample_from_anchor ? "true" : "false", has_markov_context ? "true" : "false"); + LOG_INF("%s: - sample_from_anchor=%s, has_markov_context=%s, has_confidence_head=%s, planner=%s, w61_planner=%s, w62_planner=%s, copy_proposer=%s, fixed_n=%d\n", __func__, + sample_from_anchor ? "true" : "false", + has_markov_context ? "true" : "false", + has_confidence_head ? "true" : "false", + planner_enabled ? "true" : "false", + dspark_width_planner::w61_planner_enabled() ? "true" : "false", + (dspark_width_planner::w61_planner_enabled() && dspark_width_planner::w62_planner_enabled()) ? "true" : "false", + copy_proposer_enabled ? "true" : "false", + fixed_n); // anchor-first DSpark yields a full block_size draft tokens // the context state is read back from h_nextn at every injected row @@ -1433,15 +2595,62 @@ struct common_speculative_impl_draft_dspark final : public common_speculative_im /* .dev_features = */ true, /* .nextn_masked = */ !has_markov_context, }); + + adapt_ema_acc .assign(n_seq, k_adapt_init_acc); + adapt_ema_trials .assign(n_seq, k_adapt_init_tr); + + if (ggml_backend_reg_t agx_reg = ggml_backend_reg_by_name("AGX")) { + void * fn_p = ggml_backend_reg_get_proc_address(agx_reg, "agx_set_dspark_active_drafts"); + if (fn_p) { + std::memcpy(&agx_set_active_drafts, &fn_p, sizeof(agx_set_active_drafts)); + } + } + adapt_n_rounds .assign(n_seq, 0); + adapt_cur_n_max .assign(n_seq, this->params.n_max); + adapt_n_draft_last.assign(n_seq, 0); + + pos_rounds .assign(n_seq, 0u); + pos_printed_rounds.assign(n_seq, 0u); + pos_acc .assign(n_seq, {}); + if (trace_enabled) { + trace_pos0 .assign(n_seq, -1); + trace_id_last.assign(n_seq, LLAMA_TOKEN_NULL); + trace_draft .assign(n_seq, {}); + } + + planners.resize(n_seq); + for (uint32_t s = 0; s < n_seq; ++s) { + planners[s].reset(this->params.n_max); + } + if (copy_proposer_enabled) { + copy_proposers.resize(n_seq); + } } protected: + void reset_adaptive(llama_seq_id seq_id) { + adapt_ema_acc [seq_id] = k_adapt_init_acc; + adapt_ema_trials [seq_id] = k_adapt_init_tr; + adapt_n_rounds [seq_id] = 0; + adapt_cur_n_max [seq_id] = params.n_max; + adapt_n_draft_last[seq_id] = 0; + pos_rounds [seq_id] = 0u; + pos_printed_rounds[seq_id] = 0u; + pos_acc [seq_id].fill(0u); + if (seq_id >= 0 && seq_id < (llama_seq_id) planners.size()) { + planners[seq_id].reset(params.n_max); + } + } void store_context_features(llama_seq_id seq_id, int32_t n_chunk) override { if (!has_markov_context) { return; } const float * state = llama_get_embeddings_nextn(params.ctx_dft); if (!state) { + if (trace_enabled) { + std::fprintf(stderr, "[DSPARK_TRACE] seq=%d store_context_features: llama_get_embeddings_nextn returned NULL (n_chunk=%d)\n", + (int) seq_id, (int) n_chunk); + } return; } const llama_pos pos_min = std::max(0, batch_inject.tokens.back().pos[0] - block_size); @@ -1466,16 +2675,52 @@ struct common_speculative_impl_draft_dspark final : public common_speculative_im } public: - void begin(llama_seq_id seq_id, const llama_tokens & prompt) override { - // the markov context draws: reseed per request rather than per round, or two identical requests differ - if (has_markov_context && seq_id >= 0 && seq_id < (llama_seq_id) n_seq) { + void reset(llama_seq_id seq_id) override { + if (seq_id < 0 || seq_id >= (llama_seq_id) n_seq) { + return; + } + if (has_markov_context) { draw_seed[seq_id] = -1; + if (ctx_rows > 0) { + const size_t base = (size_t) seq_id * ctx_rows; + if (base + ctx_rows <= ctx_pos.size()) { + std::fill(ctx_pos.begin() + base, ctx_pos.begin() + base + ctx_rows, (llama_pos) -1); + } + } + } + reset_adaptive(seq_id); + if (copy_proposer_enabled && seq_id < (llama_seq_id) copy_proposers.size()) { + copy_proposers[seq_id].reset({}); + } + } + + void begin(llama_seq_id seq_id, const llama_tokens & prompt) override { + if (seq_id >= 0 && seq_id < (llama_seq_id) n_seq) { + // the markov context draws: reseed per request rather than per round, or two identical requests differ + if (has_markov_context) { + draw_seed[seq_id] = -1; + } + reset_adaptive(seq_id); + if (copy_proposer_enabled && seq_id < (llama_seq_id) copy_proposers.size()) { + copy_proposers[seq_id].reset(prompt); + } } common_speculative_impl_draft_dflash::begin(seq_id, prompt); } void draft(common_speculative_draft_params_vec & dparams) override { + const bool spec_timer = common_speculative_timer_enabled(); + auto & st = common_speculative_round_timing_state(); + const int64_t t_d0 = spec_timer ? ggml_time_us() : 0; + if (spec_timer) { + st.dft_prep_us = 0; + st.dft_decode_us = 0; + st.dft_sample_us = 0; + } + if (params.n_max <= 0) { + return; + } auto & ctx_dft = params.ctx_dft; batch.clear(); @@ -1488,15 +2733,58 @@ struct common_speculative_impl_draft_dspark final : public common_speculative_im block_state.clear(); + const bool use_planner = (fixed_n <= 0) && planner_enabled && params.n_max >= 2; + int32_t n_drafting_req = 0; + for (llama_seq_id seq_id = 0; seq_id < (llama_seq_id) n_seq; ++seq_id) { + if (dparams[seq_id].drafting) { + n_drafting_req++; + } + } + const bool req_single_seq = (n_drafting_req == 1); + const int64_t t_entry_us = use_planner ? ggml_time_us() : 0; + + const llama_vocab * vocab_copy = copy_proposer_enabled ? llama_model_get_vocab(llama_get_model(ctx_dft)) : nullptr; + for (llama_seq_id seq_id = 0; seq_id < (llama_seq_id) n_seq; ++seq_id) { auto & dp = dparams[seq_id]; if (!dp.drafting) { continue; } + adapt_n_draft_last[seq_id] = 0; + if (trace_enabled) { + trace_pos0[seq_id] = dp.pos0; + trace_id_last[seq_id] = dp.id_last; + trace_draft[seq_id].clear(); + } + + if (copy_proposer_enabled) { + copy_proposers[seq_id].on_draft_begin(dp.pos0, dp.id_last); + const bool prob_reject = has_markov_context && params.probabilistic && dp.result_q && dp.temp > 0.0f; + if (fixed_n <= 0 && !prob_reject) { + int32_t n_copy_max = params.n_max; + if (dp.n_max > 0) { + n_copy_max = std::min(n_copy_max, dp.n_max); + } + if (copy_proposers[seq_id].propose(n_copy_max, vocab_copy, *dp.result)) { + adapt_n_draft_last[seq_id] = (int32_t) dp.result->size(); + continue; // Wave 61: zero-cost CPU prompt-copy hit (skips ctx_dft!) + } + } else { + copy_proposers[seq_id].insert_cur(); + } + } + + if (use_planner && planners[seq_id].on_draft_entry(t_entry_us, req_single_seq, params.n_min)) { + continue; // Wave 46 Planner v3: k=0 Plain M=1 bypass (skips ctx_dft!) + } // the Markov head reads the context state of the token before the block, no draft without it const float * state = has_markov_context ? get_context_state(seq_id, dp.pos0 - 1) : nullptr; if (has_markov_context && !state) { + if (trace_enabled) { + std::fprintf(stderr, "[DSPARK_TRACE] seq=%d skip draft: missing context state for pos0-1=%d\n", + (int) seq_id, (int) (dp.pos0 - 1)); + } continue; } @@ -1512,11 +2800,17 @@ struct common_speculative_impl_draft_dspark final : public common_speculative_im const int32_t n = (int32_t) dp.pos0; + // keep the draft batch shape fixed at params.n_max so DSpark graph replay stays cached; + // adaptive truncation below limits only the tokens returned to the target verifier const int32_t n_draft = params.n_max; const int32_t n_block_tokens = n_draft + (sample_from_anchor ? 0 : 1); // all blocks share one decode: a block that does not fit in the draft context fails every sequence's draft if ((uint64_t) dp.pos0 + n_block_tokens > llama_n_ctx_seq(ctx_dft)) { + if (trace_enabled) { + std::fprintf(stderr, "[DSPARK_TRACE] seq=%d skip draft: pos0(%d)+blk(%d) > n_ctx_seq(%u)\n", + (int) seq_id, (int) dp.pos0, (int) n_block_tokens, (unsigned) llama_n_ctx_seq(ctx_dft)); + } continue; } @@ -1548,13 +2842,63 @@ struct common_speculative_impl_draft_dspark final : public common_speculative_im return; } + int32_t n_active_seqs = 0; + for (llama_seq_id seq_id = 0; seq_id < (llama_seq_id) n_seq; ++seq_id) { + if (i_block_beg[seq_id] >= 0) { + n_active_seqs++; + } + } + const bool single_seq = (n_active_seqs == 1); + + const int32_t i_draft_beg = sample_from_anchor ? 0 : 1; + if (agx_set_active_drafts) { + uint32_t max_draft_end = 0; + for (llama_seq_id seq_id = 0; seq_id < (llama_seq_id) n_seq; ++seq_id) { + if (i_block_beg[seq_id] < 0) { + continue; + } + const int32_t req_cap = (fixed_n > 0) + ? fixed_n + : (use_planner + ? planners[seq_id].get_draft_cap(params.n_max) + : adapt_cur_n_max[seq_id]); + const int32_t n_draft_cur = std::clamp(req_cap, 0, n_block[seq_id] - i_draft_beg); + max_draft_end = std::max(max_draft_end, (uint32_t) (i_draft_beg + n_draft_cur)); + } + agx_set_active_drafts(max_draft_end); + } + + const int64_t t_draft_start_us = (use_planner || spec_timer) ? ggml_time_us() : 0; + if (spec_timer) { + st.dft_prep_us = t_draft_start_us - t_d0; + } + // decode all sequence's noise block in a single batch int ret = llama_process(ctx_dft, LLAMA_PROCESS_TYPE_DECODE, batch.get()); + const int64_t t_draft_dec_end_us = (use_planner || spec_timer) ? ggml_time_us() : 0; + if (spec_timer) { + st.dft_decode_us = t_draft_dec_end_us - t_draft_start_us; + } if (ret != 0) { + if (trace_enabled) { + std::fprintf(stderr, "[DSPARK_TRACE] draft llama_process(ctx_dft) failed ret=%d\n", ret); + } LOG_WRN("%s: llama_process returned %d\n", __func__, ret); return; } + if (use_planner && single_seq && t_draft_start_us > 0) { + const float d_ms = (float) (t_draft_dec_end_us - t_draft_start_us) * 1e-3f; + for (llama_seq_id seq_id = 0; seq_id < (llama_seq_id) n_seq; ++seq_id) { + if (i_block_beg[seq_id] >= 0) { + planners[seq_id].observe_draft_ms(d_ms); + break; + } + } + } + + const llama_vocab * vocab_dft = use_planner ? llama_model_get_vocab(llama_get_model(ctx_dft)) : nullptr; + for (llama_seq_id seq_id = 0; seq_id < (llama_seq_id) n_seq; ++seq_id) { if (i_block_beg[seq_id] < 0) { continue; @@ -1569,60 +2913,242 @@ struct common_speculative_impl_draft_dspark final : public common_speculative_im auto & result = *dp.result; // bonus-anchor drafts read the mask positions only, like DFlash - const int32_t i_draft_beg = sample_from_anchor ? 0 : 1; + const int32_t req_cap = (fixed_n > 0) + ? fixed_n + : (use_planner + ? planners[seq_id].get_draft_cap(params.n_max) + : adapt_cur_n_max[seq_id]); + const int32_t n_draft_cur = std::clamp(req_cap, 0, n_block_tokens - i_draft_beg); + const int32_t i_draft_end = i_draft_beg + n_draft_cur; + + float raw_conf[dspark_width_planner::K_MAX] = {}; + int32_t n_conf = 0; if (sampled[seq_id]) { // the tokens the graph drew, and the distribution q each one was drawn from const float * draws = llama_get_embeddings_nextn(ctx_dft); GGML_ASSERT(draws && "DSpark draws missing from h_nextn"); - for (int32_t i = i_draft_beg; i < n_block_tokens; ++i) { + for (int32_t i = i_draft_beg; i < i_draft_end; ++i) { const float * row = draws + (size_t) (beg + i) * n_embd_dec; const int32_t n_cand = (int32_t) row[1]; + const llama_token drawn_id = (llama_token) row[0]; + float p_draw = (n_cand > 0) ? row[2 + n_cand] : 0.5f; auto & q = dp.result_q->emplace_back(); q.reserve(n_cand); for (int32_t k = 0; k < n_cand; ++k) { + const llama_token cid = (llama_token) row[2 + k]; const float p = row[2 + n_cand + k]; - q.push_back({ (llama_token) row[2 + k], std::log(p), p }); + q.push_back({ cid, std::log(p), p }); + if (cid == drawn_id) { + p_draw = p; + } + } + result.push_back(drawn_id); + if (n_conf < dspark_width_planner::K_MAX) { + raw_conf[n_conf++] = std::clamp(p_draw, 0.01f, 0.995f); + } + if (use_planner && vocab_dft && llama_vocab_is_eog(vocab_dft, drawn_id)) { + break; + } + } + } else { + // DSpark: read from the first draft slot, truncate below the confidence threshold + const float * conf = (fixed_n <= 0 && has_confidence_head && (use_planner || params.p_min > 0.0f)) + ? llama_get_embeddings_nextn(ctx_dft) + : nullptr; + for (int32_t i = i_draft_beg; i < i_draft_end; ++i) { + const int32_t idx = beg + i; + + if (conf && params.p_min > 0.0f && conf[(size_t) idx * n_embd_dec] < params.p_min) { + break; } - result.push_back((llama_token) row[0]); + + common_sampler_sample(smpl, ctx_dft, idx, true); + + const auto * cur_p = common_sampler_get_candidates(smpl, true); + + for (int k = 0; k < std::min(3, (int) cur_p->size); ++k) { + LOG_DBG(" - seq_id %d, draft candidate %3d, pos %3d: %6d (%8.3f) '%s'\n", + seq_id, k, i, cur_p->data[k].id, cur_p->data[k].p, + common_token_to_piece(ctx_dft, cur_p->data[k].id).c_str()); + } + + const llama_token id = cur_p->data[0].id; + + common_sampler_accept(smpl, id, true); + + result.push_back(id); + if (n_conf < dspark_width_planner::K_MAX) { + const float c_i = conf + ? conf[(size_t) idx * n_embd_dec] + : dspark_width_planner::candidate_top1_prob(cur_p); + raw_conf[n_conf++] = std::clamp(c_i, 0.01f, 0.995f); + } + if (use_planner && vocab_dft && llama_vocab_is_eog(vocab_dft, id)) { + break; + } + } + } + + if (use_planner) { + int32_t n_avail = (int32_t) result.size(); + if (dp.n_max > 0) { + n_avail = std::min(n_avail, dp.n_max); + } + const int32_t k_star = planners[seq_id].select_width(raw_conf, n_avail, params.n_min); + result.resize((size_t) k_star); + if (sampled[seq_id] && dp.result_q) { + dp.result_q->resize((size_t) k_star); + } + planners[seq_id].record_draft(k_star, raw_conf, t_draft_start_us, single_seq); + adapt_n_draft_last[seq_id] = k_star; + + if (planner_debug && ((planners[seq_id].n_rounds % 8u) == 0u || planners[seq_id].n_rounds <= 4u)) { + const auto & pl = planners[seq_id]; + const float r_seq = (pl.cal_acc + 1.35f) / (pl.cal_pred + 1.50f); + LOG_INF("dspark-planner seq=%d rnd=%u k*=%d act=%d sw=%u p_hat=%.3f r_seq=%.3f w55=0x%x ms=[%.1f,%.1f,%.1f,%.1f,%.1f,%.1f,%.1f,%.1f] hist=[%u,%u,%u,%u,%u,%u,%u,%u]\n", + (int) seq_id, pl.n_rounds, (int) k_star, (int) pl.active_k, pl.n_switches, + (double) pl.seq_p_hat(), (double) r_seq, (unsigned) dspark_width_planner::w55_dspark_mask(), + (double) pl.round_ms[0], (double) pl.round_ms[1], (double) pl.round_ms[2], (double) pl.round_ms[3], + (double) pl.round_ms[4], (double) pl.round_ms[5], (double) pl.round_ms[6], (double) pl.round_ms[7], + pl.k_hist[0], pl.k_hist[1], pl.k_hist[2], pl.k_hist[3], + pl.k_hist[4], pl.k_hist[5], pl.k_hist[6], pl.k_hist[7]); } - if (result.size() < (size_t) params.n_min) { + } else { + if (fixed_n <= 0 && result.size() < (size_t) params.n_min) { result.clear(); - dp.result_q->clear(); + if (sampled[seq_id] && dp.result_q) { + dp.result_q->clear(); + } } - continue; + adapt_n_draft_last[seq_id] = dp.n_max > 0 + ? std::min((int32_t) result.size(), dp.n_max) + : (int32_t) result.size(); } - // DSpark: read from the first draft slot, truncate below the confidence threshold - const float * conf = params.p_min > 0.0f ? llama_get_embeddings_nextn(ctx_dft) : nullptr; - for (int32_t i = i_draft_beg; i < n_block_tokens; ++i) { - const int32_t idx = beg + i; + if (copy_proposer_enabled) { + copy_proposers[seq_id].record_dspark_draft(result); + } + if (trace_enabled) { + trace_pos0[seq_id] = dp.pos0; + trace_id_last[seq_id] = dp.id_last; + trace_draft[seq_id] = result; + } + } + if (spec_timer) { + st.dft_sample_us = ggml_time_us() - t_draft_dec_end_us; + } + } - if (conf && conf[(size_t) idx * n_embd_dec] < params.p_min) { - break; - } + void accept(llama_seq_id seq_id, uint16_t n_accepted, bool is_other) override { + if (is_other || seq_id < 0 || seq_id >= (llama_seq_id) n_seq) { + return; + } - common_sampler_sample(smpl, ctx_dft, idx, true); + pos_rounds[seq_id]++; + for (uint32_t i = 0; i < 7u && i < (uint32_t) n_accepted; ++i) { + pos_acc[seq_id][i]++; + } - const auto * cur_p = common_sampler_get_candidates(smpl, true); + if (trace_enabled) { + const auto & d = trace_draft[seq_id]; + const int32_t k_dft = (int32_t) d.size(); + const int32_t first_rej = ((int32_t) n_accepted < k_dft) ? (int32_t) n_accepted : -1; + std::fprintf(stderr, "[DSPARK_TRACE] seq=%d rnd=%u pos=%d id=%d k=%d acc=%u first_rej=%d draft=[", + (int) seq_id, pos_rounds[seq_id], (int) trace_pos0[seq_id], (int) trace_id_last[seq_id], + k_dft, (unsigned) n_accepted, first_rej); + for (int32_t j = 0; j < k_dft; ++j) { + std::fprintf(stderr, "%s%d", j > 0 ? "," : "", (int) d[j]); + } + std::fprintf(stderr, "]\n"); + std::fflush(stderr); + } - for (int k = 0; k < std::min(3, (int) cur_p->size); ++k) { - LOG_DBG(" - seq_id %d, draft candidate %3d, pos %3d: %6d (%8.3f) '%s'\n", - seq_id, k, i, cur_p->data[k].id, cur_p->data[k].p, - common_token_to_piece(ctx_dft, cur_p->data[k].id).c_str()); - } + if (copy_proposer_enabled && seq_id < (llama_seq_id) copy_proposers.size()) { + const bool was_copy = copy_proposers[seq_id].on_accept(n_accepted); + if (was_copy) { + adapt_n_draft_last[seq_id] = 0; + return; + } + } - const llama_token id = cur_p->data[0].id; + if (fixed_n > 0) { + adapt_n_draft_last[seq_id] = 0; + return; + } - common_sampler_accept(smpl, id, true); + if (planner_enabled && params.n_max >= 2) { + planners[seq_id].observe_accept((int32_t) n_accepted, ggml_time_us(), params.n_max, params.n_min); + adapt_n_draft_last[seq_id] = 0; + return; + } - result.push_back(id); + const int32_t n_drafted = adapt_n_draft_last[seq_id]; + adapt_n_draft_last[seq_id] = 0; + + if (params.n_max < 3 || n_drafted <= 0) { + return; + } + + const int32_t n_acc = std::min(n_accepted, n_drafted); + const int32_t n_trials = std::min(n_acc + 1, n_drafted); + + adapt_ema_acc [seq_id] = k_adapt_decay * adapt_ema_acc [seq_id] + (float) n_acc; + adapt_ema_trials[seq_id] = k_adapt_decay * adapt_ema_trials[seq_id] + (float) n_trials; + adapt_n_rounds [seq_id]++; + + const float p_hat = adapt_ema_acc[seq_id] / adapt_ema_trials[seq_id]; + const float accept_ema = (p_hat + p_hat * p_hat + p_hat * p_hat * p_hat) * (1.0f / 3.0f); + + if (adapt_n_rounds[seq_id] >= k_adapt_min_round) { + int32_t & cur = adapt_cur_n_max[seq_id]; + if (cur >= 3 && accept_ema < k_adapt_lo) { + const int32_t next = std::min(params.n_max, std::max(2, params.n_min)); + if (next != cur) { + SPC_DBG("dspark adaptive n_max seq=%d: %d -> %d (ema=%.3f, p_hat=%.3f, rounds=%d)\n", + (int) seq_id, (int) cur, (int) next, (double) accept_ema, (double) p_hat, (int) adapt_n_rounds[seq_id]); + cur = next; + } + } else if (cur == 2 && accept_ema > k_adapt_hi) { + const int32_t next = std::min(3, params.n_max); + if (next != cur) { + SPC_DBG("dspark adaptive n_max seq=%d: %d -> %d (ema=%.3f, p_hat=%.3f, rounds=%d)\n", + (int) seq_id, (int) cur, (int) next, (double) accept_ema, (double) p_hat, (int) adapt_n_rounds[seq_id]); + cur = next; + } } + } + } - if (result.size() < (size_t) params.n_min) { - result.clear(); + void print_pos_stats(llama_seq_id seq_id) const override { + if (!pos_stats_enabled) { + return; + } + const llama_seq_id s_beg = (seq_id >= 0 && seq_id < (llama_seq_id) n_seq) ? seq_id : 0; + const llama_seq_id s_end = (seq_id >= 0 && seq_id < (llama_seq_id) n_seq) ? (seq_id + 1) : (llama_seq_id) n_seq; + for (llama_seq_id s = s_beg; s < s_end; ++s) { + const uint32_t r = pos_rounds[s]; + if (r == 0u || r == pos_printed_rounds[s]) { + continue; } + pos_printed_rounds[s] = r; + const auto & c = pos_acc[s]; + const double inv_r = 1.0 / (double) r; + std::fprintf(stderr, + "[DSPARK_POS] rounds=%u pos_acc=[%u,%u,%u,%u,%u,%u,%u] " + "p=[%.3f,%.3f,%.3f,%.3f,%.3f,%.3f,%.3f]\n", + r, c[0], c[1], c[2], c[3], c[4], c[5], c[6], + c[0] * inv_r, c[1] * inv_r, c[2] * inv_r, c[3] * inv_r, + c[4] * inv_r, c[5] * inv_r, c[6] * inv_r); + if (copy_proposer_enabled && s < (llama_seq_id) copy_proposers.size() && copy_proposers[s].n_copy_rounds > 0u) { + const auto & cp = copy_proposers[s]; + const double pct = cp.n_copy_drafted > 0u ? (100.0 * (double) cp.n_copy_accepted / (double) cp.n_copy_drafted) : 0.0; + std::fprintf(stderr, + "[DSPARK_COPY] rounds=%u acc=%u/%u (%.1f%%)\n", + cp.n_copy_rounds, cp.n_copy_accepted, cp.n_copy_drafted, pct); + } + std::fflush(stderr); } } }; @@ -3547,6 +5073,26 @@ void common_speculative_begin(common_speculative * spec, llama_seq_id seq_id, co } } +void common_speculative_reset(common_speculative * spec, llama_seq_id seq_id) { + if (spec == nullptr) { + return; + } + + const llama_seq_id n_seq = (llama_seq_id) spec->dparams.size(); + const llama_seq_id s_beg = (seq_id >= 0 && seq_id < n_seq) ? seq_id : 0; + const llama_seq_id s_end = (seq_id >= 0 && seq_id < n_seq) ? (seq_id + 1) : n_seq; + + for (llama_seq_id s = s_beg; s < s_end; ++s) { + spec->dparams[s].drafting = false; + if (s < (llama_seq_id) spec->impl_last.size()) { + spec->impl_last[s] = nullptr; + } + for (auto & impl : spec->impls) { + impl->reset(s); + } + } +} + bool common_speculative_process(common_speculative * spec, const common_batch & batch) { bool result = true; @@ -3712,6 +5258,19 @@ void common_speculative_set_state(common_speculative * spec, llama_seq_id seq_id } } +bool common_speculative_needs_prompt(const common_speculative * spec) { + if (!spec || spec->impls.empty()) { + return true; + } + for (const auto & impl : spec->impls) { + if (impl->type != COMMON_SPECULATIVE_TYPE_DRAFT_DFLASH && + impl->type != COMMON_SPECULATIVE_TYPE_DRAFT_DSPARK) { + return true; + } + } + return false; +} + void common_speculative_print_stats(const common_speculative * spec) { if (spec == nullptr) { return; @@ -3756,4 +5315,14 @@ void common_speculative_print_stats(const common_speculative * spec) { str_stats.c_str(), str_perf.c_str()); } + common_speculative_print_pos_stats(spec, -1); +} + +void common_speculative_print_pos_stats(const common_speculative * spec, llama_seq_id seq_id) { + if (spec == nullptr) { + return; + } + for (const auto & impl : spec->impls) { + impl->print_pos_stats(seq_id); + } } diff --git a/common/speculative.h b/common/speculative.h index 949114f35609..86d0afe72905 100644 --- a/common/speculative.h +++ b/common/speculative.h @@ -86,6 +86,9 @@ common_speculative_draft_params & common_speculative_get_draft_params(common_spe // optionally call once at the beginning of a new generation void common_speculative_begin(common_speculative * spec, llama_seq_id seq_id, const llama_tokens & prompt); +// reset per-sequence transient speculative state (planner, cached features, last impl) at request/slot boundaries +void common_speculative_reset(common_speculative * spec, llama_seq_id seq_id = -1); + // process the batch and update the internal state of the speculative context bool common_speculative_process(common_speculative * spec, const common_batch & batch); @@ -102,6 +105,24 @@ 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); +// print per-position DSpark acceptance stats ([DSPARK_POS]) when LLAMA_DSPARK_POS_STATS=1 or LLAMA_DSPARK_PLANNER_DEBUG=1 +void common_speculative_print_pos_stats(const common_speculative * spec, llama_seq_id seq_id = -1); + +// Wave 50: opt-in per-round speculative phase timer (GGML_AGX_SPEC_TIMER=1) +struct common_speculative_round_timing { + int64_t dft_prep_us = 0; + int64_t dft_decode_us = 0; + int64_t dft_sample_us = 0; + int64_t inj_prep_us = 0; + int64_t inj_decode_us = 0; + int64_t inj_store_us = 0; + int32_t inj_dev_feat = 0; +}; + +bool common_speculative_timer_enabled(); +common_speculative_round_timing & common_speculative_round_timing_state(); +bool common_speculative_needs_prompt(const common_speculative * spec); + struct common_speculative_deleter { void operator()(common_speculative * s) { common_speculative_free(s); } }; diff --git a/ggml/CMakeLists.txt b/ggml/CMakeLists.txt index 2970eebf1bcd..7a498c370e9b 100644 --- a/ggml/CMakeLists.txt +++ b/ggml/CMakeLists.txt @@ -238,6 +238,8 @@ option(GGML_ZDNN "ggml: use zDNN" option(GGML_VIRTGPU "ggml: use the VirtGPU/Virglrenderer API Remoting frontend" OFF) option(GGML_VIRTGPU_BACKEND "ggml: build the VirtGPU/Virglrenderer API Remoting backend" OFF) option(GGML_METAL "ggml: use Metal" ${GGML_METAL_DEFAULT}) +option(GGML_AGX "ggml: use bare-metal Apple Silicon AGX3 (drm_asahi)" OFF) +option(GGML_AGX_DEBUG "ggml: enable AGX3 backend debug output" OFF) option(GGML_METAL_NDEBUG "ggml: disable Metal debugging" OFF) option(GGML_METAL_SHADER_DEBUG "ggml: compile Metal with -fno-fast-math" OFF) option(GGML_METAL_EMBED_LIBRARY "ggml: embed Metal library" ${GGML_METAL}) @@ -339,6 +341,7 @@ set(GGML_PUBLIC_HEADERS include/ggml-cuda.h include/ggml-opt.h include/ggml-metal.h + include/ggml-agx.h include/ggml-rpc.h include/ggml-virtgpu.h include/ggml-sycl.h diff --git a/ggml/include/ggml-agx.h b/ggml/include/ggml-agx.h new file mode 100644 index 000000000000..081a8d900a0a --- /dev/null +++ b/ggml/include/ggml-agx.h @@ -0,0 +1,32 @@ +#pragma once + +#include "ggml.h" +#include "ggml-backend.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define GGML_AGX_NAME "AGX" +#define GGML_AGX_MAX_DEVICES 4 + +// Backend API (bare-metal Apple Silicon AGX3 via Linux drm_asahi) +GGML_BACKEND_API ggml_backend_t ggml_backend_agx_init(size_t dev_num); +GGML_BACKEND_API bool ggml_backend_is_agx(ggml_backend_t backend); + +GGML_BACKEND_API int ggml_backend_agx_get_device_count(void); +GGML_BACKEND_API void ggml_backend_agx_get_device_description(int device, char * description, size_t description_size); +GGML_BACKEND_API void ggml_backend_agx_get_device_memory(int device, size_t * free, size_t * total); + +// Default SLC-aware unified memory buffer type (AGX0) +GGML_BACKEND_API ggml_backend_buffer_type_t ggml_backend_agx_buffer_type(size_t dev_num); +// Repacked 128B cache-line-aligned super-tile weight buffer type (AGX0_Repack) +GGML_BACKEND_API ggml_backend_buffer_type_t ggml_backend_agx_repack_buffer_type(size_t dev_num); +// Pinned host-visible coherent buffer type +GGML_BACKEND_API ggml_backend_buffer_type_t ggml_backend_agx_host_buffer_type(void); + +GGML_BACKEND_API ggml_backend_reg_t ggml_backend_agx_reg(void); + +#ifdef __cplusplus +} +#endif diff --git a/ggml/include/ggml.h b/ggml/include/ggml.h index 0007fa18f80e..a613c2a3f434 100644 --- a/ggml/include/ggml.h +++ b/ggml/include/ggml.h @@ -2301,6 +2301,19 @@ extern "C" { struct ggml_tensor * table, struct ggml_tensor * indices); + GGML_API bool ggml_flash_attn_ext_has_banded_rel_bias(const struct ggml_tensor * a); + + // Banded relative-position bias with O(n_kv) packed positions instead of O(n_kv * n_tokens * n_head) kq_b: + // table : F32 [eff_rows, n_head, n_tokens * n_stream] + // pos_info : I32 [n_stream * n_kv + n_tokens * n_stream + n_stream * ceil(n_kv / 64) * 2] + // layout: [cell_pos | q_pos | tile64_minmax] + // extent : maximum valid relative distance (d in [0, min(extent, eff_rows)) adds table[d], else 0) + GGML_API void ggml_flash_attn_ext_add_banded_rel_bias( + struct ggml_tensor * a, + struct ggml_tensor * table, + struct ggml_tensor * pos_info, + int32_t extent); + // TODO: needs to be adapted to ggml_flash_attn_ext GGML_API struct ggml_tensor * ggml_flash_attn_back( struct ggml_context * ctx, diff --git a/ggml/src/CMakeLists.txt b/ggml/src/CMakeLists.txt index 74ddb51ca88e..c694fd620db4 100644 --- a/ggml/src/CMakeLists.txt +++ b/ggml/src/CMakeLists.txt @@ -596,6 +596,7 @@ elseif (GGML_CPU) ggml_add_cpu_backend_variant_impl("") endif() +ggml_add_backend(AGX) ggml_add_backend(BLAS) ggml_add_backend(CANN) ggml_add_backend(CUDA) diff --git a/ggml/src/ggml-agx/CMakeLists.txt b/ggml/src/ggml-agx/CMakeLists.txt new file mode 100644 index 000000000000..637f498b5735 --- /dev/null +++ b/ggml/src/ggml-agx/CMakeLists.txt @@ -0,0 +1,55 @@ +find_package(Threads REQUIRED) + +set(GGML_AGX_SOURCES + ggml-agx.cpp + agx-common.h + agx-drm.h + agx-drm.cpp + agx-cdm.h + agx-cdm.cpp + agx-compiler.h + agx-compiler.cpp +) + +# Modular Pillars 2, 3, 4/5: included automatically when present on disk so +# Pillar 1/4/6 builds cleanly standalone and seamlessly links all pillars once landed. +set(GGML_AGX_OPTIONAL_SOURCES + agx-repack.cpp + agx-gemm.cpp + agx-inkling2-discover.cpp + agx-inkling2-dspark.cpp + agx-inkling2-target.cpp + agx-graph-exec.cpp + agx-kv-hybrid.cpp + agx-moe.cpp +) + +foreach(_agx_src ${GGML_AGX_OPTIONAL_SOURCES}) + if (EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/${_agx_src}") + list(APPEND GGML_AGX_SOURCES "${_agx_src}") + message(STATUS "ggml-agx: including ${_agx_src}") + endif() +endforeach() + +ggml_add_backend_library(ggml-agx + ../../include/ggml-agx.h + ${GGML_AGX_SOURCES} +) + +target_include_directories(ggml-agx PRIVATE + ${CMAKE_CURRENT_SOURCE_DIR} + ${CMAKE_CURRENT_SOURCE_DIR}/kernels +) + +target_compile_definitions(ggml-agx PRIVATE + GGML_AGX_KERNEL_DIR="${CMAKE_CURRENT_SOURCE_DIR}/kernels" +) + +if (GGML_AGX_DEBUG) + target_compile_definitions(ggml-agx PRIVATE GGML_AGX_DEBUG=1) +endif() + +target_link_libraries(ggml-agx PRIVATE + Threads::Threads + ${CMAKE_DL_LIBS} +) diff --git a/ggml/src/ggml-agx/DESIGN.md b/ggml/src/ggml-agx/DESIGN.md new file mode 100644 index 000000000000..87efa5a45cbf --- /dev/null +++ b/ggml/src/ggml-agx/DESIGN.md @@ -0,0 +1,30 @@ +# `ggml-agx`: Bare-Metal Apple Silicon AGX3 Backend for `ggml` / `llama.cpp` + +## Goal +Build a first-class, bare-metal Linux Apple Silicon GPU backend (`GGML_AGX`, `ggml/src/ggml-agx/`) targeting **M4 Max 40-core GPU (`J616c` / `T6041`, AGX3, 64 GB LPDDR5X-8533 @ 546 GB/s theoretical / ~505 GB/s physical ceiling)** directly over Linux `drm_asahi` (`include/drm-uapi/asahi_drm.h`) + Borealis/AGX3 ISA, bypassing generic Vulkan/SPIR-V dispatch & barrier overhead to push **Inkling 2 Mini** (26.4B-A3.4B, 3x looped middle 12 layers = 48 passes, NVFP4 + Q8_0/MXFP8 + DSpark MTP) as close as physically possible to the AGX3 hardware roofline. + +Full reference specification from the shared architecture brief: `/home/astaff/m4-rig/var/pr-prep/ggml-agx-gemini-share.md`. +Reference Mesa/Borealis/`drm_asahi` source tree on this host (read-only reference): `/home/astaff/m4-rig/var/pr-prep/mesa-s24` (`include/drm-uapi/asahi_drm.h`, `src/asahi/lib/`, `src/asahi/compiler/`, `src/asahi/vulkan/`). + +## Six Architectural Pillars + +1. **Pillar 1 — Direct `drm_asahi` UAPI Runtime & Native AGX3 ISA / Borealis Kernel Pipeline (`ggml-agx` Backend):** + - Direct `/dev/dri/renderD*` `DRM_IOCTL_ASAHI_*` device, VM, BO, queue, and CDM (`Command Data Master`) compute command stream submission (`ggml-agx-drm.{h,cpp}`), with optional Borealis compiler linkage or pre-assembled/JIT AGX3 binary shader emission (`<= 96` 32-bit GPRs/lane discipline for 20–32 simdgroups/core occupancy; predicated execution without warp-divergence cleanup splits; direct-register `simdgroup_matrix` 8x8 FMA). +2. **Pillar 2 — Zero-Loss Cache-Line-Aligned Repacking (`AGX_NVFP4` & `Q8_0`/`MXFP8`) + Branchless GPR Decode:** + - 128-byte cache-line-aligned super-tiles matched to 32-lane AGX simdgroups (`uint4` 16B coalesced weight load + `ushort`/`uint` scale load) and branchless bitwise `E2M1 -> FP16` normal-exponent shift decode (FTZ-safe on AGX coopmat, zero LUT bank conflicts) + `Q8_0` / `MXFP8` fast decode. +3. **Pillar 3 — Eliminating the 700+ Dispatch CDM Bottleneck via Persistent / Single-Stream 48-Pass Execution:** + - Collapse Inkling 2 Mini's 48 passes (`0..5`, `6..17 x 3`, `18..23`, LM head + argmax/sampler) into a single pre-recorded CDM submission / persistent 40-core execution loop with 3 fused stages per pass: + 1. `fused_loop_prep_qkv_conv_rope` (depth-mix residual attention + 4x rank-64 cross-pass gates in 32 KB threadgroup SRAM + QKV + dynamic K/V shortconv + L2 clip / Hadamard + KV write + 2304->128 router top-8) + 2. `fused_attn_outgate_proj` (40-pass SWA-1024 ring attention + 8-pass split-K Flash-Decoding + learned sink + rel-pos bias + sigmoid output gate + `W_O`) + 3. `fused_moe_gate_up_situ_down` (GPU-indirect top-8 expert workqueue reading router IDs in SLC, zero host sync) +4. **Pillar 4 — 48 MB SLC Residency & Page-Table / VM Cache Policy Partitioning:** + - Exploit `drm_asahi` VM/BO flags and access patterns so cold 14.7 GB MoE expert pages stream without thrashing SLC while hot activations, cross-pass residuals, SWA-1024 KV ring (~84 MB / hot window), router tables, and DSpark MTP weights stay hot in SLC. +5. **Pillar 5 — GPU-Resident Bitonic/Radix Token-to-Expert Bucketing (`DSpark` `M=4..8` & Prefill `simdgroup_matrix` GEMM):** + - Single-simdgroup bitonic sort deduplicating shared experts across `M=5` speculative verify tokens into predicated width-`M_bucket` vec-mat micro-tiles (each touched expert read once from DRAM), switching to `simdgroup_matrix` 8x8 tiled GEMM when `M_bucket >= 6..8`. +6. **Pillar 6 — TLA+-Verified Sense-Reversing Atomic / CDM `wait_for_idle` Barrier Elision:** + - Formal weak-memory / USC-SLC coherence model + sense-reversing device-scope atomic or minimal CDM barrier transitions across all 48 passes without full dirty-cache DRAM flushes. + +## Hardware & Safety Rules (`AGENTS.md` — Mandatory) +- Target hardware: `m4-nixos` via `ssh -F /home/astaff/m4-rig/config/ssh/m4.conf m4-nixos` (user-space only under `/home/astaff/llama/llama-ggml-agx` and `/tmp/ggml-agx-*`). +- **ALWAYS** wrap every GPU test/benchmark on `m4-nixos` with `su - astaff -s /run/current-system/sw/bin/bash -c "python3 /home/astaff/llama/guarded-run.py