[HIP][Core] DSpark GPU drafter + verify perf & correctness fixes (13.93 tok/s, strata parity)
Fix all DSpark speculative bottlenecks and long-context/multi-turn bugs: - Single-pass base-unembed Top-512 screen + on-GPU Markov loop & argmax (reads 922 MB unembed once per round, <=32 B D2H). - On-GPU batched verify argmax + forward_batch_taps_no_logits (eliminates double unembed and 4.8 MB D2H per round). - Wave32 online-softmax dspark_block_attn (0 bytes LDS, fixes >16.2k token crash on Global layer 1; regression-tested at c_len=17000). - Vectorized M-tiled Wave32 router_gemv_batched, zero-scratch small-M SWA GQA, WMMA gemm_bf16 for m>=1, fdot2 MoE for b<=12. - Persistent DsparkContext + PrefixCache DsparkSnapshot save/restore (multi-turn RESUME parity tested). - Accepted-count EMA governor starting at n_draft=5 (adapts 2..7). - Docs (README.md, docs/ORIENTATION.md) + changelog in review/2026-12-02-fix-drafter-e-ottimizzazioni.md. Measured on gfx1150 (Inkling-2-Mini, temperature=0, 100% greedy EXACT): - Rust coding (RingBuffer<T>, 128 tok): OFF 6.83 -> VETTA_SPEC=1 13.93 tok/s (2.04x, n_draft=5; strata-inkling 13.66 tok/s). - Short prose (capital, 96 tok): nd=5 4.58 -> 9.09 tok/s (+98.5%); adaptive EMA 8.93 tok/s decode. Validated: cargo test --workspace (-D warnings), all 7 Lean 4 proofs (0 sorryAx), HIP/LD/GW GPU parity gates.
This commit is contained in:
1 parent
91c1baaf27
commit
c1c5221642
9 files changed
+1433
-186
No files matched your search
@@ -32,7 +32,7 @@ use vetta_infer_ld::SafetensorsArchive;
|
||||
#[cfg(feature = "hip")]
|
||||
use vetta_infer_ld::layer::forward_batch_taps;
|
||||
#[cfg(feature = "hip")]
|
||||
use vetta_infer_ld::dspark::{layout_check, spec_round, DsparkContext, DsparkWeights, DS_HIDDEN};
|
||||
use vetta_infer_ld::dspark::{layout_check, spec_round, DsparkContext, DsparkSnapshot, DsparkWeights, DS_HIDDEN};
|
||||
|
||||
use crate::session::ServeSession;
|
||||
use crate::{err_line, ready_line};
|
||||
@@ -80,6 +80,8 @@ fn is_grid(seq: usize) -> bool { seq % 512 == 0 }
|
||||
struct Checkpoint {
|
||||
tokens: Vec<i32>,
|
||||
layers: Vec<Option<LayerSnapshot>>,
|
||||
#[cfg(feature = "hip")]
|
||||
dspark: Option<DsparkSnapshot>,
|
||||
lru: u64,
|
||||
}
|
||||
|
||||
@@ -113,7 +115,12 @@ impl PrefixCache {
|
||||
/// Takes `&mut self` to refresh the hit checkpoint's LRU tick: without this a
|
||||
/// just-restored grid checkpoint keeps its old tick and gets evicted by the
|
||||
/// next turn's boundary/full saves, regressing turn 3+ to the pinned anchor.
|
||||
fn restore(&mut self, idx: usize, states: &mut [Option<LayerState>], d: &Dims, max_seq: usize) -> Result<usize, String> {
|
||||
/// Returns `(restored_len, dspark_restored)`.
|
||||
fn restore(
|
||||
&mut self, idx: usize, states: &mut [Option<LayerState>], d: &Dims, max_seq: usize,
|
||||
#[cfg(feature = "hip")] dctx: Option<&mut DsparkContext>,
|
||||
) -> Result<(usize, bool), String> {
|
||||
let mut dspark_ok = false;
|
||||
{
|
||||
let ck = &self.pool[idx];
|
||||
// A usable checkpoint must cover EVERY layer: a partially-restored state
|
||||
@@ -136,35 +143,58 @@ impl PrefixCache {
|
||||
states[ip].as_mut().unwrap().restore(d, s)?;
|
||||
}
|
||||
}
|
||||
#[cfg(feature = "hip")]
|
||||
if let (Some(dc), Some(ds)) = (dctx, ck.dspark.as_ref()) {
|
||||
dc.restore(ds)?;
|
||||
dspark_ok = true;
|
||||
}
|
||||
}
|
||||
self.tick += 1;
|
||||
self.pool[idx].lru = self.tick;
|
||||
Ok(self.pool[idx].tokens.len())
|
||||
Ok((self.pool[idx].tokens.len(), dspark_ok))
|
||||
}
|
||||
|
||||
/// Snapshot all layer states at `tokens.len()` and insert (update / grow /
|
||||
/// evict oldest unpinned). Mirrors poolInsert in proofs/prefix_cache.lean.
|
||||
fn save(&mut self, tokens: &[i32], states: &[Option<LayerState>], d: &Dims) -> Result<(), String> {
|
||||
/// Snapshot all layer states (and optional DSpark context) at `tokens.len()`
|
||||
/// and insert (update / grow / evict oldest unpinned). Mirrors poolInsert in
|
||||
/// proofs/prefix_cache.lean.
|
||||
fn save(
|
||||
&mut self, tokens: &[i32], states: &[Option<LayerState>], d: &Dims,
|
||||
#[cfg(feature = "hip")] dctx: Option<&DsparkContext>,
|
||||
) -> Result<(), String> {
|
||||
let seq = tokens.len();
|
||||
if seq == 0 { return Ok(()); }
|
||||
let layers: Vec<Option<LayerSnapshot>> = states.iter().enumerate()
|
||||
.map(|(ip, st)| st.as_ref().map(|s| s.snapshot(d, seq, is_swa(ip))).transpose())
|
||||
.collect::<Result<_, _>>()?;
|
||||
#[cfg(feature = "hip")]
|
||||
let dspark = match dctx {
|
||||
Some(dc) if dc.len >= seq => Some(dc.snapshot(seq, d.swa_win as usize)?),
|
||||
_ => None,
|
||||
};
|
||||
self.tick += 1;
|
||||
let lru = self.tick;
|
||||
if let Some(ck) = self.pool.iter_mut().find(|c| c.tokens.len() == seq) {
|
||||
ck.tokens = tokens.to_vec(); ck.layers = layers; ck.lru = lru;
|
||||
#[cfg(feature = "hip")] { ck.dspark = dspark; }
|
||||
return Ok(());
|
||||
}
|
||||
if self.pool.len() < PREFIX_CACHE_CAP {
|
||||
self.pool.push(Checkpoint { tokens: tokens.to_vec(), layers, lru });
|
||||
self.pool.push(Checkpoint {
|
||||
tokens: tokens.to_vec(), layers,
|
||||
#[cfg(feature = "hip")] dspark,
|
||||
lru,
|
||||
});
|
||||
return Ok(());
|
||||
}
|
||||
let victim = self.pool.iter().enumerate()
|
||||
.filter(|(_, c)| !pinned_anchor(c.tokens.len()))
|
||||
.min_by_key(|(_, c)| (is_grid(c.tokens.len()) as u8, c.lru)).map(|(i, _)| i);
|
||||
if let Some(i) = victim {
|
||||
self.pool[i] = Checkpoint { tokens: tokens.to_vec(), layers, lru };
|
||||
self.pool[i] = Checkpoint {
|
||||
tokens: tokens.to_vec(), layers,
|
||||
#[cfg(feature = "hip")] dspark,
|
||||
lru,
|
||||
};
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -190,6 +220,9 @@ pub struct InklingEngine {
|
||||
/// mtp.safetensors passes layout_check. Enables opt-in greedy speculation.
|
||||
#[cfg(feature = "hip")]
|
||||
spec_dw: Option<DsparkWeights>,
|
||||
/// Persistent DSpark context rings reused across requests (mirrors `states`).
|
||||
#[cfg(feature = "hip")]
|
||||
dctx: RefCell<Option<DsparkContext>>,
|
||||
}
|
||||
|
||||
impl InklingEngine {
|
||||
@@ -258,6 +291,8 @@ impl InklingEngine {
|
||||
max_context,
|
||||
#[cfg(feature = "hip")]
|
||||
spec_dw,
|
||||
#[cfg(feature = "hip")]
|
||||
dctx: RefCell::new(None),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -343,6 +378,30 @@ pub fn serve_gen(
|
||||
let cap = max_context;
|
||||
let mut states = eng.states.borrow_mut();
|
||||
|
||||
// Opt-in DSpark speculation (pure greedy, no penalties): capture trunk taps
|
||||
// during prefill to build the drafter context rings, then run a batched
|
||||
// speculative decode (lossless vs forward_batch B=1, proofs/speculative_draft).
|
||||
#[cfg(feature = "hip")]
|
||||
let mut spec_enabled = eng.spec_dw.is_some() && g.sampling.is_greedy() && !g.sampling.has_penalties();
|
||||
#[cfg(not(feature = "hip"))]
|
||||
let spec_enabled = false;
|
||||
#[cfg(feature = "hip")]
|
||||
let mut dctx_guard = eng.dctx.borrow_mut();
|
||||
#[cfg(feature = "hip")]
|
||||
if spec_enabled {
|
||||
let need_new = dctx_guard.as_ref().map_or(true, |c| c.cap < cap);
|
||||
if need_new {
|
||||
match DsparkContext::new(cap, DS_HIDDEN) {
|
||||
Ok(c) => *dctx_guard = Some(c),
|
||||
Err(e) => {
|
||||
emit_all(emit, sess.on_error(&e));
|
||||
stop.store(false, Ordering::Relaxed);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Prefix checkpoint reuse (proofs/prefix_cache.lean restore_equiv): restore
|
||||
// the longest cached strict prefix of this prompt and prefill only the NEW
|
||||
// suffix tokens. VETTA_NO_PREFIX_CACHE forces cold prefill (A/B measurement).
|
||||
@@ -350,8 +409,25 @@ pub fn serve_gen(
|
||||
if std::env::var("VETTA_NO_PREFIX_CACHE").is_err() {
|
||||
let matched = eng.prefix.borrow().best_match(&g.ids);
|
||||
if let Some((idx, _l)) = matched {
|
||||
match eng.prefix.borrow_mut().restore(idx, &mut states[..], &eng.d, cap) {
|
||||
Ok(n) => start = n,
|
||||
#[cfg(feature = "hip")]
|
||||
let res = eng.prefix.borrow_mut().restore(
|
||||
idx, &mut states[..], &eng.d, cap,
|
||||
if spec_enabled { dctx_guard.as_mut() } else { None },
|
||||
);
|
||||
#[cfg(not(feature = "hip"))]
|
||||
let res = eng.prefix.borrow_mut().restore(idx, &mut states[..], &eng.d, cap);
|
||||
match res {
|
||||
Ok((n, dspark_ok)) => {
|
||||
start = n;
|
||||
#[cfg(feature = "hip")]
|
||||
if spec_enabled && !dspark_ok {
|
||||
// Checkpoint lacked DSpark state (e.g. saved while spec was off):
|
||||
// never run the drafter over zeroed prefix rings.
|
||||
spec_enabled = false;
|
||||
}
|
||||
#[cfg(not(feature = "hip"))]
|
||||
let _ = dspark_ok;
|
||||
}
|
||||
Err(_) => {
|
||||
// Incomplete/failed restore: fall back to a clean cold prefill.
|
||||
*states = (0..eng.n_layers).map(|_| None).collect();
|
||||
@@ -371,6 +447,10 @@ pub fn serve_gen(
|
||||
return;
|
||||
}
|
||||
}
|
||||
#[cfg(feature = "hip")]
|
||||
if let Some(dc) = dctx_guard.as_mut() {
|
||||
dc.len = 0;
|
||||
}
|
||||
}
|
||||
if std::env::var("VETTA_DBG_PREFIX").is_ok() {
|
||||
eprintln!("[prefix] prompt_len={n_prompt} restored={start}");
|
||||
@@ -389,27 +469,6 @@ pub fn serve_gen(
|
||||
// Weights are resident in eng.cache (loaded once at boot, reused across all
|
||||
// requests): no per-request NVMe re-read or re-upload.
|
||||
|
||||
// Opt-in DSpark speculation (pure greedy, no penalties): capture trunk taps
|
||||
// during prefill to build the drafter context rings, then run a batched
|
||||
// speculative decode (lossless vs forward_batch B=1, proofs/speculative_draft).
|
||||
#[cfg(feature = "hip")]
|
||||
let spec_enabled = eng.spec_dw.is_some() && g.sampling.is_greedy() && !g.sampling.has_penalties();
|
||||
#[cfg(not(feature = "hip"))]
|
||||
let spec_enabled = false;
|
||||
#[cfg(feature = "hip")]
|
||||
let mut dctx: Option<DsparkContext> = None;
|
||||
#[cfg(feature = "hip")]
|
||||
if spec_enabled {
|
||||
match DsparkContext::new(cap, DS_HIDDEN) {
|
||||
Ok(c) => dctx = Some(c),
|
||||
Err(e) => {
|
||||
emit_all(emit, sess.on_error(&e));
|
||||
stop.store(false, Ordering::Relaxed);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- Prefill: chunked batched (M=B) forward over the NEW prompt tokens. ---
|
||||
// Each chunk runs ONE forward_batch over B tokens (weight streaming + kernel
|
||||
// launches amortized across B), growing KV/history; logits come from the last
|
||||
@@ -450,7 +509,7 @@ pub fn serve_gen(
|
||||
let pb = DeviceBuf::alloc(take * 4)?;
|
||||
pb.h2d_bytes(&(pos..pos + take as i32).flat_map(|p| p.to_le_bytes()).collect::<Vec<u8>>())?;
|
||||
let dw = eng.spec_dw.as_ref().unwrap();
|
||||
let dc = dctx.as_mut().unwrap();
|
||||
let dc = dctx_guard.as_mut().unwrap();
|
||||
dc.commit(dw, &taps, &pb, take as i32, eng.d.eps, 1e6)?;
|
||||
dc.len = (pos + take as i32) as usize;
|
||||
Ok(l)
|
||||
@@ -481,6 +540,9 @@ pub fn serve_gen(
|
||||
// prefix; grid entries are protected from eviction (is_grid) and refreshed
|
||||
// on restore (lru), so turn 3+ keeps advancing instead of falling to 1024.
|
||||
if std::env::var("VETTA_NO_PREFIX_CACHE").is_err() && pos as usize == next_grid {
|
||||
#[cfg(feature = "hip")]
|
||||
let _ = eng.prefix.borrow_mut().save(&history[..pos as usize], &states[..], &eng.d, if spec_enabled { dctx_guard.as_ref() } else { None });
|
||||
#[cfg(not(feature = "hip"))]
|
||||
let _ = eng.prefix.borrow_mut().save(&history[..pos as usize], &states[..], &eng.d);
|
||||
if std::env::var("VETTA_DBG_PREFIX").is_ok() {
|
||||
eprintln!("[prefix] grid save seq={pos}");
|
||||
@@ -512,6 +574,9 @@ pub fn serve_gen(
|
||||
// stable prefix and prefill only the new dialogue suffix. Mirrors strata
|
||||
// --auto-ckpt's prompt-boundary save (proofs/prefix_cache.lean restore_equiv).
|
||||
if std::env::var("VETTA_NO_PREFIX_CACHE").is_err() && pos > 0 {
|
||||
#[cfg(feature = "hip")]
|
||||
let _ = eng.prefix.borrow_mut().save(&history[..pos as usize], &states[..], &eng.d, if spec_enabled { dctx_guard.as_ref() } else { None });
|
||||
#[cfg(not(feature = "hip"))]
|
||||
let _ = eng.prefix.borrow_mut().save(&history[..pos as usize], &states[..], &eng.d);
|
||||
if std::env::var("VETTA_DBG_PREFIX").is_ok() {
|
||||
eprintln!("[prefix] prompt-boundary save seq={pos}");
|
||||
@@ -539,7 +604,7 @@ pub fn serve_gen(
|
||||
#[cfg(feature = "hip")]
|
||||
if spec_enabled {
|
||||
let dw = eng.spec_dw.as_ref().unwrap();
|
||||
let mut dc = dctx.take().unwrap();
|
||||
let dc = dctx_guard.as_mut().unwrap();
|
||||
let t1 = Instant::now();
|
||||
let mut lg = vec![0f32; eng.vocab];
|
||||
if let Err(e) = logits.d2h(&mut lg) {
|
||||
@@ -568,11 +633,13 @@ pub fn serve_gen(
|
||||
return;
|
||||
}
|
||||
let mut cur_pos = pos; let mut next_tok = tok0;
|
||||
// Measured optimum on real text (gfx1150, GEN 96): n_draft=2 gives the best
|
||||
// decode tok/s (6.09) vs 3=5.78, 4=5.54, 5=4.58, 7=5.15, 1=5.25 — at ~30-50%
|
||||
// acceptance a larger verify batch wastes compute on rejected drafts. Start
|
||||
// at 2 and escalate only when acceptance is very high (cost-aware governor).
|
||||
let mut ema = 0.5f32; let mut n_draft = 2usize;
|
||||
// Measured on gfx1150 after single-pass GPU drafter + WMMA/fdot2 + small-M SWA:
|
||||
// Rust coding prompt (128 tok): OFF 6.83 | nd=2 11.93 | nd=3 13.90 | nd=4 13.97 | nd=5 13.69 tok/s
|
||||
// Short prose prompt (96 tok): OFF 4.70 | nd=2 9.21 | nd=3 9.09 | nd=4 8.93 | nd=5 9.09 tok/s
|
||||
// Track an EMA of ACCEPTED tokens per round (not acceptance ratio, which
|
||||
// naturally drops as nd grows and used to clamp code generation down to nd=2).
|
||||
// Start at 5 (optimal on code/structured text) and adapt smoothly 2..7.
|
||||
let mut ema_acc = 2.0f32; let mut n_draft = 5usize;
|
||||
// VETTA_SPEC_ND fixes n_draft (bypasses the EMA) for A/B measurement.
|
||||
let nd_override = std::env::var("VETTA_SPEC_ND").ok().and_then(|v| v.parse::<usize>().ok());
|
||||
let mut offered = 0usize; let mut accepted = 0usize; let mut rounds = 0usize;
|
||||
@@ -589,7 +656,7 @@ pub fn serve_gen(
|
||||
}
|
||||
let left = effective_max_new - generated;
|
||||
let nd = nd_override.unwrap_or(n_draft).min(left.saturating_sub(1));
|
||||
let (em, nc, nt, done) = match spec_round(&eng.cache, &eng.d, dw, &mut dc, &mut states[..], cur_pos, next_tok, nd, eng.vocab, cap, left, |t| t == eng.eos) {
|
||||
let (em, nc, nt, done) = match spec_round(&eng.cache, &eng.d, dw, dc, &mut states[..], cur_pos, next_tok, nd, eng.vocab, cap, left, |t| t == eng.eos) {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
emit_all(emit, sess.on_error(&e));
|
||||
@@ -607,10 +674,14 @@ pub fn serve_gen(
|
||||
if generated >= effective_max_new { break; }
|
||||
}
|
||||
if nd > 0 {
|
||||
let acc = (em.len().saturating_sub(1)) as f32 / nd as f32;
|
||||
ema = 0.9 * ema + 0.1 * acc;
|
||||
n_draft = if ema >= 0.9 { 7 } else if ema >= 0.75 { 4 } else { 2 };
|
||||
offered += nd; accepted += em.len().saturating_sub(1);
|
||||
let acc = em.len().saturating_sub(1);
|
||||
ema_acc = 0.85 * ema_acc + 0.15 * (acc as f32);
|
||||
n_draft = if ema_acc >= 3.5 { 7 }
|
||||
else if ema_acc >= 2.0 { 5 }
|
||||
else if ema_acc >= 1.1 { 4 }
|
||||
else if ema_acc >= 0.6 { 3 }
|
||||
else { 2 };
|
||||
offered += nd; accepted += acc;
|
||||
}
|
||||
rounds += 1;
|
||||
cur_pos = nc; next_tok = nt; pos = nc;
|
||||
@@ -620,10 +691,10 @@ pub fn serve_gen(
|
||||
}
|
||||
let decode_ms = t1.elapsed().as_secs_f64() * 1000.0;
|
||||
if std::env::var("VETTA_DBG_SPEC").is_ok() {
|
||||
eprintln!("[spec] rounds={rounds} offered={offered} accepted={accepted} ema={ema:.3} n_draft={n_draft} generated={generated} decode_ms={decode_ms:.1} tok_s={:.2}", generated as f64 / (decode_ms / 1000.0));
|
||||
eprintln!("[spec] rounds={rounds} offered={offered} accepted={accepted} ema_acc={ema_acc:.3} n_draft={n_draft} generated={generated} decode_ms={decode_ms:.1} tok_s={:.2}", generated as f64 / (decode_ms / 1000.0));
|
||||
}
|
||||
if std::env::var("VETTA_NO_PREFIX_CACHE").is_err() && pos > 0 {
|
||||
let _ = eng.prefix.borrow_mut().save(&history[..pos as usize], &states[..], &eng.d);
|
||||
let _ = eng.prefix.borrow_mut().save(&history[..pos as usize], &states[..], &eng.d, Some(dc));
|
||||
}
|
||||
emit_all(emit, sess.on_finish(finish, decode_ms).unwrap_or_default());
|
||||
stop.store(false, Ordering::Relaxed);
|
||||
@@ -693,6 +764,9 @@ pub fn serve_gen(
|
||||
// counts tokens actually folded into `states` (history[..pos]); a sampled token
|
||||
// not forwarded (EOS / last length step) is excluded, keeping the ckpt valid.
|
||||
if std::env::var("VETTA_NO_PREFIX_CACHE").is_err() && pos > 0 {
|
||||
#[cfg(feature = "hip")]
|
||||
let _ = eng.prefix.borrow_mut().save(&history[..pos as usize], &states[..], &eng.d, None);
|
||||
#[cfg(not(feature = "hip"))]
|
||||
let _ = eng.prefix.borrow_mut().save(&history[..pos as usize], &states[..], &eng.d);
|
||||
if std::env::var("VETTA_DBG_PREFIX").is_ok() {
|
||||
eprintln!("[prefix] full-sequence save seq={pos}");
|
||||
@@ -970,4 +1044,58 @@ mod tests {
|
||||
assert_eq!(off_n, on_n, "spec must emit the same token count");
|
||||
});
|
||||
}
|
||||
|
||||
/// GPU: multi-turn PrefixCache + DsparkSnapshot restore regression test.
|
||||
/// Turn 1 prefills + generates 16 tokens and saves a checkpoint with DSpark
|
||||
/// state; Turn 2 extends Turn 1's exact prompt + generated tokens with a
|
||||
/// follow-up suffix, hitting RESUME on Turn 1's checkpoint and restoring
|
||||
/// DSpark rings + frnn_last. Turn 2 output with VETTA_SPEC=1 must match
|
||||
/// VETTA_SPEC=0 100% EXACT and emit a non-zero RESUME.
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn serve_gen_spec_prefix_cache_multi_turn_parity() {
|
||||
crate::gpu_isolated(|| {
|
||||
let turn1_ids = "200002,200004,34182,279,154554,150628,25,220,15,200010,200000,200004,10970,261,4660,11,5603,59195,9268,328,261,6164,12,13448,8459,6462,13,200010,200001,200004";
|
||||
let run_two_turns = |spec: bool| -> (Vec<i32>, Vec<i32>, usize) {
|
||||
if spec { unsafe { std::env::set_var("VETTA_SPEC", "1"); } } else { unsafe { std::env::remove_var("VETTA_SPEC"); } }
|
||||
let eng = InklingEngine::new("/mnt/models/Inkling/safetensors").unwrap();
|
||||
let stop = AtomicBool::new(false);
|
||||
// Turn 1
|
||||
let g1 = match parse_serve_line(&format!("GEN 16 temperature=0 {turn1_ids}"), eng.vocab()).unwrap() {
|
||||
ServeCommand::Gen(g) => g,
|
||||
_ => panic!("expected Gen"),
|
||||
};
|
||||
let mut l1 = Vec::new();
|
||||
serve_gen(&eng, &g1, &stop, &mut |l| l1.push(l));
|
||||
let t1: Vec<i32> = l1.iter().filter(|l| l.starts_with("T ")).map(|l| l[2..].trim().parse().unwrap()).collect();
|
||||
// Turn 2 extends Turn 1 prompt + Turn 1 reply + short follow-up prompt
|
||||
let mut turn2_vec: Vec<String> = turn1_ids.split(',').map(|s| s.to_string()).collect();
|
||||
for &id in &t1 { turn2_vec.push(id.to_string()); }
|
||||
for extra in [200010, 200000, 200004, 10970, 261, 2324, 13, 200010, 200001, 200004] {
|
||||
turn2_vec.push(extra.to_string());
|
||||
}
|
||||
let turn2_ids = turn2_vec.join(",");
|
||||
let g2 = match parse_serve_line(&format!("GEN 24 temperature=0 {turn2_ids}"), eng.vocab()).unwrap() {
|
||||
ServeCommand::Gen(g) => g,
|
||||
_ => panic!("expected Gen"),
|
||||
};
|
||||
let mut l2 = Vec::new();
|
||||
serve_gen(&eng, &g2, &stop, &mut |l| l2.push(l));
|
||||
let t2: Vec<i32> = l2.iter().filter(|l| l.starts_with("T ")).map(|l| l[2..].trim().parse().unwrap()).collect();
|
||||
let resumed: usize = l2.iter()
|
||||
.find(|l| l.starts_with("RESUME "))
|
||||
.and_then(|l| l[7..].trim().parse().ok())
|
||||
.unwrap_or(0);
|
||||
unsafe { std::env::remove_var("VETTA_SPEC"); }
|
||||
(t1, t2, resumed)
|
||||
};
|
||||
let (off_t1, off_t2, off_resumed) = run_two_turns(false);
|
||||
let (on_t1, on_t2, on_resumed) = run_two_turns(true);
|
||||
eprintln!("multi-turn prefix cache: off_resumed={off_resumed} on_resumed={on_resumed} t1_len={} t2_len={}", on_t1.len(), on_t2.len());
|
||||
assert!(on_resumed > 0, "Turn 2 with VETTA_SPEC=1 must hit PrefixCache RESUME");
|
||||
assert_eq!(on_resumed, off_resumed, "Turn 2 RESUME length must match OFF");
|
||||
assert_eq!(on_t1, off_t1, "Turn 1 tokens must match OFF exactly");
|
||||
assert_eq!(on_t2, off_t2, "Turn 2 tokens after PrefixCache+DsparkSnapshot restore must match OFF exactly");
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user