test: verify DSpark device KV rollback

This commit is contained in:
Constantin committed 2026-11-03 13:56:46 -05:00
1 parent e14463b8eb
commit c96cfc9e7b
8 files changed
+418 -11

No files matched your search

+100
View File
@@ -0,0 +1,100 @@
#!/usr/bin/env python3
"""Exercise the compile-time-only direct KV rollback observer against a live Spark server.
Build the server with -DRAD_ENABLE_KV_ROLLBACK_TEST_HOOK=ON and set
RADIANCE_TEST_KV_ROLLBACK_REPORT in that server's environment to the same report path supplied
here. This script sends a real greedy completion; it does not synthesize KV data.
"""
import argparse
import json
from pathlib import Path
import sys
import time
import urllib.error
import urllib.request
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--url", required=True, help="server base URL, e.g. http://127.0.0.1:8080")
parser.add_argument("--model", required=True)
parser.add_argument("--report", required=True, type=Path,
help="same path configured in server's RADIANCE_TEST_KV_ROLLBACK_REPORT")
parser.add_argument("--prompt", default=("Write a detailed, varied explanation of why "
"forest ecosystems change over time. " * 20))
parser.add_argument("--max-tokens", type=int, default=128)
parser.add_argument("--timeout", type=float, default=180.0)
args = parser.parse_args()
if args.report.exists():
parser.error(f"report path already exists; choose a fresh path: {args.report}")
args.report.parent.mkdir(parents=True, exist_ok=True)
evidence = None
endpoint = args.url.rstrip("/") + "/v1/chat/completions"
for attempt in range(8):
prompt = args.prompt + f"\nVariation {attempt + 1}: use a distinct example."
body = json.dumps({"model": args.model, "messages": [{"role": "user", "content": prompt}],
"temperature": 0, "max_tokens": args.max_tokens,
"reasoning_effort": "none", "stream": False}).encode()
request = urllib.request.Request(endpoint, body, {"Content-Type": "application/json"})
try:
with urllib.request.urlopen(request, timeout=args.timeout) as response:
result = json.loads(response.read())
if not result.get("choices"):
raise RuntimeError("server returned no completion choices")
except (urllib.error.URLError, TimeoutError, RuntimeError, json.JSONDecodeError) as exc:
print(f"request {attempt + 1} failed: {exc}", file=sys.stderr)
return 1
deadline = time.monotonic() + 5
while time.monotonic() < deadline:
if args.report.exists():
try:
candidate = json.loads(args.report.read_text())
except (OSError, json.JSONDecodeError):
time.sleep(0.05)
continue
if candidate.get("next_greedy_decode_observed"):
evidence = candidate
break
time.sleep(0.05)
if evidence is not None:
break
if evidence is None:
print("no completed direct KV observer report; a partial depth-7 rollback followed by "
"the next greedy decode was not observed", file=sys.stderr)
return 1
required = {
"partial_rejection_observed": evidence.get("partial_rejection_observed") is True,
"depth_7": evidence.get("proposals") == 7 and 0 < evidence.get("accepted", 0) < 7,
"rollback_length": evidence.get("prefix_tokens_after") == evidence.get("rollback_to_tokens"),
"bytes_equal": evidence.get("bytes_equal") is True,
"mapping_equal": evidence.get("mapping_equal") is True,
"physical_slot_mapping": len(evidence.get("logical_blocks", [])) > 0 and
len(evidence.get("logical_blocks", [])) ==
len(evidence.get("physical_slots", [])) and
evidence.get("logical_blocks") ==
sorted(set(evidence.get("logical_blocks", []))) and
len(evidence.get("physical_slots", [])) ==
len(set(evidence.get("physical_slots", []))),
"all_complete_prefix_blocks": evidence.get("block_size", 0) > 0 and
evidence.get("prefix_tokens_before_verify", 0) >=
evidence.get("first_block_pos", 0) and
len(evidence.get("logical_blocks", [])) ==
(evidence.get("prefix_tokens_before_verify", 0) -
evidence.get("first_block_pos", 0)) //
evidence.get("block_size", 1),
"snapshot_geometry": evidence.get("layers", 0) > 0 and
evidence.get("bytes_per_layer", 0) * evidence.get("layers", 0) *
len(evidence.get("logical_blocks", [])) ==
evidence.get("committed_prefix_bytes", 0),
"negative_control": evidence.get("negative_control_detected") is True,
"next_greedy_decode": evidence.get("next_greedy_decode_observed") is True and
isinstance(evidence.get("next_greedy_token"), int) and
evidence.get("next_greedy_token") >= 0,
}
print(json.dumps({"checks": required, "evidence": evidence}, indent=2))
return 0 if all(required.values()) else 1
if __name__ == "__main__":
raise SystemExit(main())
+32 -11
View File
@@ -252,6 +252,23 @@ def stop_sequence_observed(unstopped: dict[str, Any], stopped: dict[str, Any], m
return bool(found) and stopped["finish_reason"] == "stop" and stopped["content"] == before_marker
def observed_draft_token_total(trials: list[dict[str, Any]]) -> int:
return sum(int(trial["draft_tokens"]) for trial in trials)
def seeded_sample_reproduced(first: dict[str, Any], repeat: dict[str, Any]) -> bool:
"""Equal empty responses do not establish seeded sampling reproducibility."""
content = first.get("content")
count = first.get("completion_tokens")
repeat_count = repeat.get("completion_tokens")
finish = first.get("finish_reason")
return (isinstance(content, str) and bool(content.strip()) and
content == repeat.get("content") and
finish in ("stop", "length") and finish == repeat.get("finish_reason") and
type(count) is int and count > 0 and
type(repeat_count) is int and count == repeat_count)
def calibrated_rollover_prompt(base: str, model: str, api_key: str | None,
timeout: float, target: int = 480) -> tuple[str, int]:
"""Find a repeated prompt below the 512 boundary using response usage (no tokenizer guess)."""
@@ -392,14 +409,14 @@ def run(args: argparse.Namespace) -> dict[str, Any]:
eos = chat_request(on_url, args.model,
[{"role": "user", "content": "Reply with exactly OK and then end the turn."}],
api_key=args.api_key, timeout=args.timeout, temperature=0, seed=61,
max_tokens=24)
max_tokens=24, reasoning_effort="none")
stop_prompt = [{"role": "user", "content": "Write exactly DS_STOP_6f41 and nothing after it."}]
unstopped = chat_request(on_url, args.model, stop_prompt,
api_key=args.api_key, timeout=args.timeout, temperature=0, seed=67,
max_tokens=24)
max_tokens=24, reasoning_effort="none")
stopped = chat_request(on_url, args.model, stop_prompt,
api_key=args.api_key, timeout=args.timeout, temperature=0, seed=67,
max_tokens=24, stop=["DS_STOP_6f41"])
max_tokens=24, stop=["DS_STOP_6f41"], reasoning_effort="none")
result["scenarios"]["eos_and_stop"] = {"eos": eos, "without_stop": unstopped, "stop": stopped}
require(result, "natural_end_of_turn", eos["finish_reason"] == "stop",
f"finish_reason={eos['finish_reason']}")
@@ -425,13 +442,17 @@ def run(args: argparse.Namespace) -> dict[str, Any]:
seeded_body = [{"role": "user", "content": "Write a short, varied sentence about a comet."}]
seeded_a = chat_request(on_url, args.model, seeded_body, api_key=args.api_key, timeout=args.timeout,
temperature=0.75, seed=99173, max_tokens=32)
temperature=0.75, seed=99173, max_tokens=32, reasoning_effort="none")
seeded_b = chat_request(on_url, args.model, seeded_body, api_key=args.api_key, timeout=args.timeout,
temperature=0.75, seed=99173, max_tokens=32)
temperature=0.75, seed=99173, max_tokens=32, reasoning_effort="none")
same = seeded_a["content"] == seeded_b["content"]
result["scenarios"]["seeded_sampling"] = {"first": seeded_a, "repeat": seeded_b, "identical": same}
require(result, "seed_reproduces_sample", same,
f"first={seeded_a['content']!r}, repeat={seeded_b['content']!r}")
reproduced = seeded_sample_reproduced(seeded_a, seeded_b)
result["scenarios"]["seeded_sampling"] = {"first": seeded_a, "repeat": seeded_b,
"identical": same, "valid_reproduction": reproduced}
require(result, "seed_reproduces_sample", reproduced,
f"first={seeded_a['content']!r}, repeat={seeded_b['content']!r}, "
f"finish={seeded_a['finish_reason']!r}/{seeded_b['finish_reason']!r}, "
f"completion_tokens={seeded_a['completion_tokens']!r}/{seeded_b['completion_tokens']!r}")
# Exercise concurrent batching, then look for unaccepted proposals. Aggregate per-request
# counters cannot establish whether any single verify was partially accepted.
@@ -467,9 +488,9 @@ def run(args: argparse.Namespace) -> dict[str, Any]:
"draft_accepted": accepted, "unaccepted_proposals": rejected})
result["scenarios"]["unaccepted_proposals"] = {"trials": rejection_trials,
"observed": any_rejection}
require(result, "draft_proposals_are_observed",
any(t["draft_tokens"] > 0 for t in rejection_trials),
"no draft_tokens_total increase; confirm DSpark is enabled on this server")
draft_tokens_observed = observed_draft_token_total(rejection_trials)
require(result, "draft_proposals_are_observed", draft_tokens_observed > 0,
f"draft_tokens_total delta={draft_tokens_observed}")
if not args.allow_unobserved_rejection:
require(result, "unaccepted_proposals_are_observed", any_rejection,
f"trials={len(rejection_trials)}; per-trial deltas are recorded")