test: publish reproducible KVC1 verification suite
Browse filesAdds the 23 unit/schema/tensor tests and pinned Python runtime dependencies used by the exact-model parity milestone.
Files changed (5)
- README.md+1
- requirements.txtAdded+3
- tests/test_kvcache.pyAdded+196
- tests/test_schemas.pyAdded+147
- tests/test_torch_kvcache.pyAdded+77
56 unmodified lines57585960616256 unmodified lines- `validation/qwen25-05b-parity.receipt.json`: measured parity result.- `schemas/`: portable capability packet, translator registry, and software-runevaluation contracts.- `translation/bridge-contract.schema.json`: cross-family translator receipt.- `capability-packs/analytics-hotshot.domcap.json`: optional operating sidecar.56 unmodified lines5758596061626356 unmodified lines- `validation/qwen25-05b-parity.receipt.json`: measured parity result.- `schemas/`: portable capability packet, translator registry, and software-runevaluation contracts.- `tests/`: the 23-test container, schema, and tensor-adapter suite.- `translation/bridge-contract.schema.json`: cross-family translator receipt.- `capability-packs/analytics-hotshot.domcap.json`: optional operating sidecar.
123jsonschema==4.23.0torch==2.10.0transformers==5.0.0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196from __future__ import annotations
import jsonfrom pathlib import Pathimport tempfileimport unittest
import kvcache
def metadata() -> dict[str, object]: return { "model_revision": "tiny-lab-model@0123456789abcdef", "tokenizer_sha256": "7f" * 32, "rope_theta": 10_000.0, "layers": 4, "kv_heads": 2, "head_dim": 8, "dtype": "f16", "layout": "layer-major-k-then-v", "sequence_start": 0, "sequence_length": 37, }
def tensor_metadata() -> dict[str, object]: value = metadata() value.update({ "layers": 1, "kv_heads": 1, "head_dim": 2, "sequence_length": 2, "tensor_manifest": { "version": 1, "byte_order": "little", "batch_size": 1, "cache_class": "dynamic", "attention_type": "causal", "tensors": [ { "name": "layer.0.key", "kind": "key", "layer": 0, "shape": [1, 1, 2, 2], "strides": [8, 8, 4, 2], "offset": 0, "nbytes": 8, "dtype": "f16", }, { "name": "layer.0.value", "kind": "value", "layer": 0, "shape": [1, 1, 2, 2], "strides": [8, 8, 4, 2], "offset": 8, "nbytes": 8, "dtype": "f16", }, ], }, }) return value
class CacheTests(unittest.TestCase): def test_round_trip_tensor_manifest_with_exact_payload_size(self) -> None: with tempfile.TemporaryDirectory() as root: path = Path(root) / "real-tensors.kvc" payload = bytes(range(16)) kvcache.write_cache(path, tensor_metadata(), payload) self.assertEqual((tensor_metadata(), payload), kvcache.read_cache(path, tensor_metadata())) receipt = kvcache.inspect_cache(path) self.assertTrue(receipt["tensor_manifest_verified"]) self.assertEqual(2, receipt["tensor_count"])
def test_rejects_tensor_manifest_payload_size_mismatch(self) -> None: with tempfile.TemporaryDirectory() as root: path = Path(root) / "wrong-size.kvc" with self.assertRaisesRegex(kvcache.CacheFormatError, "tensor manifest declares 16 payload bytes"): kvcache.write_cache(path, tensor_metadata(), b"too short") self.assertFalse(path.exists())
def test_rejects_non_contiguous_tensor_offsets(self) -> None: value = tensor_metadata() value["tensor_manifest"]["tensors"][1]["offset"] = 9 # type: ignore[index] with tempfile.TemporaryDirectory() as root: with self.assertRaisesRegex(kvcache.CacheFormatError, "contiguous"): kvcache.write_cache(Path(root) / "gap.kvc", value, bytes(17))
def test_rejects_tensor_shape_that_disagrees_with_cache_identity(self) -> None: value = tensor_metadata() value["tensor_manifest"]["tensors"][0]["shape"] = [1, 1, 1, 4] # type: ignore[index] with tempfile.TemporaryDirectory() as root: with self.assertRaisesRegex(kvcache.CacheFormatError, "shape must equal"): kvcache.write_cache(Path(root) / "wrong-shape.kvc", value, bytes(16))
def test_rejects_non_contiguous_tensor_strides(self) -> None: value = tensor_metadata() value["tensor_manifest"]["tensors"][0]["strides"] = [1, 1, 1, 1] # type: ignore[index] with tempfile.TemporaryDirectory() as root: with self.assertRaisesRegex(kvcache.CacheFormatError, "C-contiguous byte strides"): kvcache.write_cache(Path(root) / "wrong-strides.kvc", value, bytes(16))
def test_legacy_payload_remains_inspectable_but_is_not_tensor_verified(self) -> None: with tempfile.TemporaryDirectory() as root: path = Path(root) / "legacy.kvc" kvcache.write_cache(path, metadata(), b"legacy") receipt = kvcache.inspect_cache(path) self.assertNotIn("tensor_manifest_verified", receipt) self.assertNotIn("tensor_count", receipt)
def test_round_trip_raw_tensor_bytes(self) -> None: with tempfile.TemporaryDirectory() as root: path = Path(root) / "idea.kvc" payload = bytes(range(255)) kvcache.write_cache(path, metadata(), payload) self.assertEqual((metadata(), payload), kvcache.read_cache(path, metadata()))
def test_inspection_receipt(self) -> None: with tempfile.TemporaryDirectory() as root: path = Path(root) / "idea.kvc" kvcache.write_cache(path, metadata(), b"kv") receipt = kvcache.inspect_cache(path) self.assertEqual("KVC1", receipt["format"]) self.assertEqual(2, receipt["payload_bytes"]) json.dumps(receipt)
def test_rejects_wrong_model(self) -> None: with tempfile.TemporaryDirectory() as root: path = Path(root) / "idea.kvc" kvcache.write_cache(path, metadata(), b"kv") wrong = metadata() wrong["model_revision"] = "other@revision" with self.assertRaises(kvcache.CacheCompatibilityError): kvcache.read_cache(path, wrong)
def test_rejects_wrong_position(self) -> None: with tempfile.TemporaryDirectory() as root: path = Path(root) / "idea.kvc" kvcache.write_cache(path, metadata(), b"kv") wrong = metadata() wrong["sequence_start"] = 10 with self.assertRaises(kvcache.CacheCompatibilityError): kvcache.read_cache(path, wrong)
def test_expected_identity_keyword_accepts_a_valid_subset(self) -> None: with tempfile.TemporaryDirectory() as root: path = Path(root) / "idea.kvc" kvcache.write_cache(path, metadata(), b"kv") self.assertEqual( (metadata(), b"kv"), kvcache.read_cache( path, expected_identity={"model_revision": metadata()["model_revision"]}, ), ) with self.assertRaises(kvcache.CacheCompatibilityError): kvcache.read_cache(path, expected_identity={"dtype": "bf16"})
def test_rejects_corruption(self) -> None: with tempfile.TemporaryDirectory() as root: path = Path(root) / "idea.kvc" kvcache.write_cache(path, metadata(), b"kv") raw = bytearray(path.read_bytes()) raw[-1] ^= 1 path.write_bytes(raw) with self.assertRaises(kvcache.CacheFormatError): kvcache.read_cache(path)
def test_rejects_truncation(self) -> None: with tempfile.TemporaryDirectory() as root: path = Path(root) / "idea.kvc" kvcache.write_cache(path, metadata(), b"kv") path.write_bytes(path.read_bytes()[:-1]) with self.assertRaises(kvcache.CacheFormatError): kvcache.read_cache(path)
def test_rejects_incomplete_identity(self) -> None: value = metadata() value.pop("tokenizer_sha256") with tempfile.TemporaryDirectory() as root: with self.assertRaises(kvcache.CacheFormatError): kvcache.write_cache(Path(root) / "idea.kvc", value, b"kv")
def test_atomic_replacement(self) -> None: with tempfile.TemporaryDirectory() as root: path = Path(root) / "idea.kvc" kvcache.write_cache(path, metadata(), b"first") kvcache.write_cache(path, metadata(), b"second") self.assertEqual(b"second", kvcache.read_cache(path)[1]) self.assertEqual([], list(Path(root).glob("*.tmp")))
if __name__ == "__main__": unittest.main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147from __future__ import annotations
import jsonfrom pathlib import Pathimport unittest
from jsonschema import Draft202012Validator, ValidationError
ROOT = Path(__file__).resolve().parents[1]
def load_schema(name: str) -> dict[str, object]: return json.loads((ROOT / "schemas" / name).read_text(encoding="utf-8"))
def sha(character: str = "a") -> str: return character * 64
class PortableSchemaTests(unittest.TestCase): def test_all_schemas_are_valid_draft_2020_12(self) -> None: for name in ( "capability-packet-1.schema.json", "kvbridge-registry-1.schema.json", "software-run-1.schema.json", ): with self.subTest(name=name): Draft202012Validator.check_schema(load_schema(name))
def test_capability_packet_supports_a_text_only_fallback(self) -> None: packet = { "schema": "CAPABILITY_PACKET_1", "packet_id": "regex-repair-001", "task": { "objective": "Repair the escaping bug.", "constraints": ["Do not broaden the public API."], "done_conditions": ["All regex fixtures pass."], }, "evidence": [{"uri": "repo://src/parser.ts", "sha256": sha(), "kind": "source"}], "tools": [{"name": "read_file", "schema_sha256": sha("b")}], "evaluations": [{"name": "regex-fixtures", "kind": "test", "command_id": "test:regex"}], "text_handoff": "Preserve literal backslashes before expanding groups.", "artifacts": [], } Draft202012Validator(load_schema("capability-packet-1.schema.json")).validate(packet)
def test_capability_packet_rejects_executable_tool_bodies(self) -> None: packet = { "schema": "CAPABILITY_PACKET_1", "packet_id": "unsafe", "task": {"objective": "x", "constraints": [], "done_conditions": ["y"]}, "evidence": [], "tools": [{"name": "shell", "schema_sha256": sha(), "code": "rm -rf /"}], "evaluations": [], "text_handoff": "x", "artifacts": [], } with self.assertRaises(ValidationError): Draft202012Validator(load_schema("capability-packet-1.schema.json")).validate(packet)
def test_directional_translator_registry_entry_is_valid(self) -> None: entry = { "schema": "KVBRIDGE_REGISTRY_1", "source": {"model": "org/qwen-source", "revision": "abc", "tokenizer_sha256": sha()}, "target": {"model": "org/qwen-target", "revision": "def", "tokenizer_sha256": sha("b")}, "translator": { "direction": "source_to_target", "kind": "head_matched_affine", "revision": "translator-v1", "artifact_sha256": sha("c"), "training_data_digest": sha("d"), }, "validity": { "prefix_token_min": 64, "prefix_token_max": 1024, "task_classes": ["code_plan"], "status": "shadow", }, "evaluation": { "dataset_version": "coding-fixtures-v1", "native_context_retention": 0.91, "text_plan_delta": 0.04, "capability_delta": 0.02, "mapper_bytes": 1048576, "latency_ms": 7.5, }, } Draft202012Validator(load_schema("kvbridge-registry-1.schema.json")).validate(entry) entry["translator"]["direction"] = "bidirectional" with self.assertRaises(ValidationError): Draft202012Validator(load_schema("kvbridge-registry-1.schema.json")).validate(entry)
def test_software_run_requires_deterministic_check_receipts(self) -> None: run = { "schema": "SOFTWARE_RUN_1", "identity": { "run_id": "run-1", "mission_id": "mission-1", "stage": "implementation", "attempt": 1, "harness": "colibri", "adapter_revision": "adapter-v1", }, "workspace": { "repository": "ShoeGun/ShoeGun.github.io", "base_commit": "abc123", "worktree_digest": sha(), "task_class": "one-file-repair", }, "model": { "route": "small-executor", "model_revision": "qwen@abc", "tokenizer_sha256": sha("b"), "quantization": "q4", "context_limit": 32768, "input_tokens": 1200, "output_tokens": 300, "cached_tokens": 0, }, "retrieval": {"index_revision": "index-v1", "queries": ["parser escape"], "selected": []}, "handoff": { "packet_sha256": sha("c"), "source_kvc1_sha256": None, "target_kvc1_sha256": None, "translator_revision": None, "cache_sequence_length": 0, }, "trajectory": {"tool_calls": [], "protocol_errors": 0, "policy_violations": 0, "retries": 0}, "outcome": { "patch_sha256": sha("d"), "changed_files": ["src/parser.ts"], "checks": [{"name": "unit", "status": "passed", "receipt_sha256": sha("e")}], "artifact_receipts": [], "human_repair_count": 0, "status": "passed", }, } validator = Draft202012Validator(load_schema("software-run-1.schema.json")) validator.validate(run) run["outcome"]["checks"] = [] with self.assertRaises(ValidationError): validator.validate(run)
if __name__ == "__main__": unittest.main()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677from __future__ import annotations
from pathlib import Pathimport tempfileimport unittest
import torch
import torch_kvcache
class Layer: def __init__(self, keys: torch.Tensor, values: torch.Tensor) -> None: self.keys = keys self.values = values
class Cache: def __init__(self, layers: list[Layer]) -> None: self.layers = layers
class TorchCacheTests(unittest.TestCase): def test_dynamic_cache_tensor_round_trip(self) -> None: layers = [] for layer in range(2): base = torch.arange(24, dtype=torch.float32).reshape(1, 2, 3, 4) + layer * 100 layers.append(Layer(base, base + 50)) with tempfile.TemporaryDirectory() as root: path = Path(root) / "torch.kvc" metadata = torch_kvcache.write_dynamic_cache( path, Cache(layers), model_revision="Qwen/Qwen2.5-0.5B-Instruct@revision", tokenizer_sha256="a" * 64, rope_theta=1_000_000.0, ) restored, restored_metadata = torch_kvcache.read_dynamic_cache( path, expected_identity={"model_revision": metadata["model_revision"]}, ) self.assertEqual(metadata, restored_metadata) self.assertEqual(2, len(restored.layers)) for expected, actual in zip(layers, restored.layers, strict=True): self.assertTrue(torch.equal(expected.keys, actual.keys)) self.assertTrue(torch.equal(expected.values, actual.values))
def test_rejects_mixed_tensor_shapes(self) -> None: layer = Layer( torch.zeros((1, 2, 3, 4), dtype=torch.float32), torch.zeros((1, 2, 2, 6), dtype=torch.float32), ) with tempfile.TemporaryDirectory() as root: with self.assertRaisesRegex(ValueError, "same shape"): torch_kvcache.write_dynamic_cache( Path(root) / "mixed.kvc", Cache([layer]), model_revision="model@revision", tokenizer_sha256="b" * 64, rope_theta=10_000.0, )
def test_rejects_unsupported_tensor_dtype(self) -> None: tensor = torch.zeros((1, 1, 2, 2), dtype=torch.float64) with tempfile.TemporaryDirectory() as root: with self.assertRaisesRegex(ValueError, "unsupported torch cache dtype"): torch_kvcache.write_dynamic_cache( Path(root) / "f64.kvc", Cache([Layer(tensor, tensor)]), model_revision="model@revision", tokenizer_sha256="c" * 64, rope_theta=10_000.0, )
if __name__ == "__main__": unittest.main()README.md+1
requirements.txtAdded+3
tests/test_kvcache.pyAdded+196
tests/test_schemas.pyAdded+147
tests/test_torch_kvcache.pyAdded+77