[Bug] prefix-cache-hit prefill reads wrong KV rows #22
All Vouch review confidence checks passed
Residual risk 0.05 = Change Risk (0.27) × (1 − Review Confidence (0.83)).
Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.27 · 17 lines diff across 1 files
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.89 · 3 substantive comment(s)
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 35%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size
diff_size
0.173
Real PR Conversation Timeline
4 items
reproduce scripts
modal_run.py
import pathlib
import subprocess
import sys
import modal
REPO_URL = "https://github.com/Future-Outlier/ssd"
PY = "3.11"
THIS_DIR = pathlib.Path(__file__).parent # anchor: works no matter where you `modal run` from
REPO_ROOT = THIS_DIR.parent.parent # local checkout: has pyproject.toml + uv.lock
app = modal.App("ssd-bug-repro")
vol = modal.Volume.from_name("ssd-hf-cache", create_if_missing=True)
image = (
modal.Image.from_registry("nvidia/cuda:12.8.1-devel-ubuntu22.04", add_python=PY)
.apt_install("git", "libnuma1") # sgl_kernel's common_ops.so links libnuma.so.1
# Deps from the repo's own uv.lock (uv sync --frozen). uv_sync does NOT
# install the ssd project itself — code is cloned per-ref at runtime.
.uv_sync(uv_project_dir=str(REPO_ROOT))
.add_local_dir(str(THIS_DIR), remote_path="/scripts")
)
ENV = {
"SSD_HF_CACHE": "/vol/hub",
"SSD_DATASET_DIR": "/tmp",
"SSD_CUDA_ARCH": "9.0",
"HF_HOME": "/vol/hf_home",
"HF_HUB_ENABLE_HF_TRANSFER": "1",
"TRITON_CACHE_DIR": "/vol/triton_cache",
"TORCHINDUCTOR_CACHE_DIR": "/vol/inductor_cache",
"FLASHINFER_WORKSPACE_BASE": "/vol/flashinfer",
}
MODELS = ["Qwen/Qwen3-0.6B"] # ungated (no HF approval needed); repo supports qwen3 natively
@app.function(
image=image, gpu="H100", timeout=1800, volumes={"/vol": vol},
secrets=[modal.Secret.from_name("huggingface")],
)
def run_script(ref: str, script: str) -> tuple[str, int]:
import os
os.environ.update(ENV)
from huggingface_hub import snapshot_download
for repo in MODELS: # idempotent: cached in the Volume after first run
print(f"[{ref}] downloading {repo} (silent, ~1-2 min first time)...", flush=True)
snapshot_download(repo, cache_dir=ENV["SSD_HF_CACHE"])
vol.commit()
print(f"[{ref}] cloning repo @ {ref}...", flush=True)
subprocess.run(["git", "clone", "--quiet", REPO_URL, "/repo"], check=True)
subprocess.run(["git", "-C", "/repo", "checkout", "--quiet", ref], check=True)
print(f"[{ref}] launching {script} (engine init + first-time JIT may take minutes)...", flush=True)
env = os.environ.copy()
env["PYTHONPATH"] = "/repo" # scripts import ssd from the cloned ref
# Stream every line live, exactly once (shows up in your terminal via modal run).
proc = subprocess.Popen(
[sys.executable, "-u", f"/scripts/{script}"], # the uv_sync env's interpreter
env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True,
)
for line in proc.stdout:
print(f"[{ref}] {line}", end="", flush=True)
return ref, proc.wait()
@app.local_entrypoint()
def main(script: str = "repro_a1.py", buggy_ref: str = "main", fixed_ref: str = "fix-a1"):
# pass --fixed-ref - (or the same ref) to run only the buggy ref
refs = [buggy_ref] if fixed_ref in ("-", "", buggy_ref) else [buggy_ref, fixed_ref]
results = [run_script.remote(r, script) for r in refs]
print("\n" + "#" * 72)
for ref, code in results:
# contract: 0 = clean, 3 = divergence (bug reproduced), anything else = crash
verdict = {0: "clean", 3: "bug reproduced"}.get(code, f"ERROR {code} — script crashed, read log above")
print(f"### ref={ref} exit={code} ({verdict})")
print("Expected: buggy ref -> exit 3, fixed ref -> exit 0.")
repro_a1.py
import argparse
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", ".."))
def find_snapshot(base):
for root, _, files in os.walk(base):
if "config.json" in files:
return root
raise FileNotFoundError(f"no config.json under {base}")
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--model", default=None)
ap.add_argument("--gen", type=int, default=64)
args = ap.parse_args()
os.environ.setdefault("SSD_DATASET_DIR", "/tmp") # ssd.paths import-time check
from ssd import LLM, SamplingParams
from ssd.engine.block_manager import BlockManager
from transformers import AutoTokenizer
# Per-request cache usage trace: proves the hit path ran (expect 256 on B run2).
orig_allocate = BlockManager.allocate
def traced_allocate(self, seq):
orig_allocate(self, seq)
print(f"[cache-trace] seq{seq.seq_id}: prompt={seq.num_prompt_tokens} "
f"cached={seq.num_cached_tokens} blocks={seq.block_table}", flush=True)
BlockManager.allocate = traced_allocate
model = args.model or find_snapshot(os.path.join(
os.environ["SSD_HF_CACHE"], "models--Qwen--Qwen3-0.6B"))
tok = AutoTokenizer.from_pretrained(model)
a = tok.encode("zebra quantum umbrella cathedral " * 120)[:300] # displacer
b = tok.encode("The theory of general relativity states " * 100)[:400]
assert min(len(a), len(b)) >= 257 # >= 1 full block + a tail => hit path
sp = SamplingParams(temperature=0.0, ignore_eos=True, max_new_tokens=args.gen)
llm = LLM(model, max_model_len=2048)
outputs, _ = llm.generate([a, b, b], [sp, sp, sp], use_tqdm=False)
r0, r1, r2 = outputs[0]["token_ids"], outputs[1]["token_ids"], outputs[2]["token_ids"]
print(f"\nA run0 (cold prefill) : {tok.decode(r0)!r}")
print(f"\nB run1 (cold prefill) : {tok.decode(r1)!r}")
print(f"B run2 (prefix-cache hit): {tok.decode(r2)!r}")
if r1 == r2:
print("PASS: identical greedy outputs -> hit-path prefill is consistent.")
os._exit(0) # bypass LLMEngine's atexit os._exit(0)
i = next(i for i, (x, y) in enumerate(zip(r1, r2)) if x != y)
print(f"FAIL: outputs diverge at token {i} (same engine, same prompt, temp=0).")
os._exit(3) # distinct from a crash's exit 1
if __name__ == "__main__":
main()
cc @tanishqkumar @JiangJiaWei1103 to take a look, tks!
cu_seqlens_q=context.cu_seqlens_q, max_seqlen_q=context.max_seqlen_q,
softmax_scale=self.scale, causal=True,
nit: can we put this to the end? just follow the API param order and more aligned with flash_attn_varlen_func.
JiangJiaWei1103
Future-Outlier
fixes https://github.com/tanishqkumar/ssd/issues/23
Problem
When a prefill batch contains a prefix-cache hit, the attention layer substitutes the entire per-layer paged K/V cache tensors for the fresh k/v tensors but does not pass the block table to the kernel.
The kernel therefore treats the attention layer’s paged KV cache as contiguous memory and reads the wrong physical KV rows, silently producing incorrect outputs.
Solution
use the function flash_attn_with_kvcache to pass block table to the attention kernel
Evidence (Modal H100, Qwen3-0.6B)
Before (main branch):
<img width="976" height="635" alt="image" src="https://github.com/user-attachments/assets/2fceadd3-575c-45f5-b3d4-07d03e1b3f8b" />
After (this branch):
<img width="1000" height="617" alt="image" src="https://github.com/user-attachments/assets/7c1f828e-b5d7-44c0-9496-8933f7829aff" />
reproduce script
https://github.com/tanishqkumar/ssd/pull/22#issuecomment-5126128102