"""Regression test: the same state requested three or more times across batches must keep working from the prefix cache and give the same logits as a cache-less engine. Before the fix the second cache hit raised KeyError: 0. python -m verdin.tests.test_cache_reuse [--device cpu|cuda] """ import argparse import tempfile from pathlib import Path import torch from verdin.core import Verdin from verdin.tests.make_tiny import make_tiny_checkpoint def main(): ap = argparse.ArgumentParser() ap.add_argument("--device", default="cpu") ap.add_argument("--tokenizer", help="tokenizer.json for the random tiny checkpoint") a = ap.parse_args() model = make_tiny_checkpoint(Path(tempfile.mkdtemp(prefix="verdin-tiny-")), a.tokenizer) state = {"dialogue": " ".join(f"turn {i}: the user asks about bus {i % 7} to city {i % 5}." for i in range(80))} qs = [{"intent": {"type": "choice", "instructions": f"Which intent is active for service {k}?", "criteria": {"FindBus": "FindBus", "BuyBusTicket": "BuyBusTicket", "NONE": "none"}}} for k in range(5)] cached = Verdin.from_pretrained(model, backend="cpu" if a.device == "cpu" else "cuda", device=a.device, dtype="fp32", prefix_cache=4, prefix_cache_min_tokens=0) plain = Verdin.from_pretrained(model, backend="cpu" if a.device == "cpu" else "cuda", device=a.device, dtype="fp32", prefix_cache=0) worst = 0.0 # schema-first puts the questions into the state segment, so only an identical request reuses the cached prefix # (benchmark rows often repeat whole requests): 1 miss + 4 hits on the same request, one request per batch for k in range(5): x = cached.decide(state, qs[0]); y = plain.decide(state, qs[0]) px = x["intent"]["probabilities"]; py = y["intent"]["probabilities"] worst = max(worst, max(abs(px[o] - py[o]) for o in px)) assert worst < 1e-5, worst print(f"cache reuse x5: OK (max |dp| vs no cache {worst:.1e})") if __name__ == "__main__": main()