diff --git a/simulation/ai-polygon/continuous_pipeline.py b/simulation/ai-polygon/continuous_pipeline.py index 4d0a903e..0fc4e20f 100644 --- a/simulation/ai-polygon/continuous_pipeline.py +++ b/simulation/ai-polygon/continuous_pipeline.py @@ -15,6 +15,7 @@ from pathlib import Path from navigation_client import NavigationClient from realtime_ai import EvidenceWriter +from k1link.simulation.ai_polygon.perception_evidence import archive_perception class ContinuousPipeline: @@ -187,6 +188,7 @@ class ContinuousPipeline: if extra is not None: Image.fromarray(extra["rgb"]).save( self.directory/f"{frame:08d}.supplement.jpg", quality=90) + exact_evidence = archive_perception(self.directory, result) journal.write(json.dumps(dict(frame_id=frame, captured_at=observation["captured_at"], completed_at=result["completed_at"], started_at=started, module_ms=result["module_ms"], semantic_observations=result["semantic_observations"], @@ -196,7 +198,8 @@ class ContinuousPipeline: for view in result.get("detection_views", [])], sensor_timing_ms=observation.get("sensor_timing_ms"), acquisition_age_ms=(started-observation["captured_at"])*1000, - archive_ms=(self.clock()-now)*1000, view="body-forward"))+"\n") + archive_ms=(self.clock()-now)*1000, view="body-forward", + exact_evidence=exact_evidence))+"\n") journal.flush() self.writer.submit(frame, archive) # The writer owns this stream until the final outstanding packet. diff --git a/simulation/ai-polygon/sam3/server.py b/simulation/ai-polygon/sam3/server.py index 171c6691..5715a6e0 100644 --- a/simulation/ai-polygon/sam3/server.py +++ b/simulation/ai-polygon/sam3/server.py @@ -11,7 +11,9 @@ from PIL import Image import sam3.model_builder as builder from sam3.model.sam3_image_processor import Sam3Processor -from k1link.simulation.ai_polygon.concept_surfaces import PROMPTS, concept_rasters +from k1link.simulation.ai_polygon.concept_surfaces import ( + PROMPTS, FixedConceptTextEncoder, concept_rasters, +) def load_exact(model, path): @@ -51,6 +53,10 @@ def main(): or any(type(x) not in (int, float) or not 0 < x < 1 for x in thresholds.values())): raise ValueError("Invalid concept confidence thresholds") + # Encoding depends only on these fixed prompts and the immutable weights. + # Warmup below populates the bounded cache under the same inference/autocast + # context as live frames. Image features and masks are never cached. + model.backbone.forward_text = FixedConceptTextEncoder(model.backbone.forward_text, "cuda") processor = Sam3Processor(model, device="cuda", confidence_threshold=min(thresholds.values())) def infer(rgb): diff --git a/src/k1link/simulation/ai_polygon/composition.py b/src/k1link/simulation/ai_polygon/composition.py index 587c860c..a5f3a902 100644 --- a/src/k1link/simulation/ai_polygon/composition.py +++ b/src/k1link/simulation/ai_polygon/composition.py @@ -34,6 +34,8 @@ def registry(adapter_root: Path) -> ModuleRegistry: "run_inputs.py", "camera_optics.py", "sensor_mounts.py", + "perception_evidence.py", + "evidence_arrays.py", )}, **{name: hashlib.sha256((adapter_root / name).read_bytes()).hexdigest() for name in ("continuous_composition.py", "continuous_pipeline.py", "process_pipeline.py", "urban_crossing.py")}, diff --git a/src/k1link/simulation/ai_polygon/concept_surfaces.py b/src/k1link/simulation/ai_polygon/concept_surfaces.py index a5d05cf3..b459122f 100644 --- a/src/k1link/simulation/ai_polygon/concept_surfaces.py +++ b/src/k1link/simulation/ai_polygon/concept_surfaces.py @@ -31,3 +31,26 @@ def concept_rasters(masks): labels = np.asarray(Image.fromarray(labels).crop((100, 0, 700, 600)).resize( (512, 512), Image.Resampling.NEAREST)) return labels, np.isin(labels, (1, 2, 3)), labels != 0 + + +class FixedConceptTextEncoder: + """Cache the four image-independent prompts for one immutable model instance. + + The pinned processor still owns prompt setup and grounding. A fresh mapping + prevents it from changing the cache's keys; its feature tensors are read-only + inputs to the pinned grounding model. Model recreation destroys this cache. + """ + + def __init__(self, encode, device): + self.encode = encode + self.device = device + self.features = {} + + def __call__(self, prompts, *, device): + if (not isinstance(prompts, list) or len(prompts) != 1 + or prompts[0] not in PROMPTS or device != self.device): + raise ValueError("Unexpected fixed concept text request") + prompt = prompts[0] + if prompt not in self.features: + self.features[prompt] = dict(self.encode(prompts, device=device)) + return dict(self.features[prompt]) diff --git a/src/k1link/simulation/ai_polygon/perception_evidence.py b/src/k1link/simulation/ai_polygon/perception_evidence.py new file mode 100644 index 00000000..0fee63e5 --- /dev/null +++ b/src/k1link/simulation/ai_polygon/perception_evidence.py @@ -0,0 +1,49 @@ +"""Exact provider input and distinct surface outputs for causal offline replay.""" + +import hashlib +import json +from pathlib import Path + +import numpy as np + +from .evidence_arrays import save_arrays + + +def archive_perception(directory, result): + """Called only by the existing bounded writer, after perception publication.""" + records = [] + for role, view in (("task", result), ("supplement", result.get("supplement"))): + if view is None: + continue + rgb = np.asarray(view["rgb"]) + if rgb.dtype != np.uint8 or rgb.shape != (600, 800, 3): + raise ValueError("Expected exact 800x600 RGB provider input") + values, observation = view["values"], view["observation"] + arrays = { + "rgb": rgb, + "labels": values["segmentation.labels"], + "known": values["segmentation.known"], + "candidate_surface": values["segmentation.surface"], + "permitted_surface": values["navigation.surface"], + "crossing_mask": values["source.crossing-mask"], + } + if any(np.asarray(a).shape != (512, 512) for k, a in arrays.items() if k != "rgb"): + raise ValueError("Surface evidence does not match the provider raster") + metadata = dict( + schema_version="missioncore.perception-evidence/v1", + frame_id=view["frame_id"], role=role, + captured_at=observation["captured_at"], + simulation_time_ns=observation["simulation_time_ns"], + pose=observation["pose"], calibration=observation["calibration"], + crossing=values["source.crossing-admission"], + rgb_sha256=hashlib.sha256(rgb.tobytes()).hexdigest(), + rgb_layout="RGB uint8 HWC; exact provider input, before lossy preview encoding", + ) + path = Path(directory) / f"{view['frame_id']:08d}.{role}.perception.npz" + save_arrays(path, **arrays, + metadata_json=json.dumps(metadata, sort_keys=True, allow_nan=False)) + with path.open("rb") as stream: + digest = hashlib.file_digest(stream, "sha256").hexdigest() + records.append(dict(role=role, file=path.name, sha256=digest, + rgb_sha256=metadata["rgb_sha256"])) + return records diff --git a/tests/test_ai_polygon_perception_evidence.py b/tests/test_ai_polygon_perception_evidence.py new file mode 100644 index 00000000..7fdd90a1 --- /dev/null +++ b/tests/test_ai_polygon_perception_evidence.py @@ -0,0 +1,89 @@ +import hashlib +import json + +import numpy as np +import pytest + +from k1link.simulation.ai_polygon.concept_surfaces import PROMPTS, FixedConceptTextEncoder +from k1link.simulation.ai_polygon.perception_evidence import archive_perception + + +def test_fixed_text_cache_is_bounded_to_model_prompts_and_keeps_prompt_identity(): + calls = [] + + def encode(prompts, *, device): + calls.append((tuple(prompts), device)) + return {"language_features": np.array([PROMPTS.index(prompts[0])])} + + cached = FixedConceptTextEncoder(encode, "cuda") + for prompt in (*PROMPTS, *reversed(PROMPTS), *PROMPTS): + result = cached([prompt], device="cuda") + assert result["language_features"].tolist() == [PROMPTS.index(prompt)] + result.clear() # Processor-owned mapping must not erase cached keys. + assert calls == [((prompt,), "cuda") for prompt in PROMPTS] + for prompts, device in [(["asphalt"], "cuda"), (["sidewalk", "wall"], "cuda"), + (["sidewalk"], "cpu")]: + with pytest.raises(ValueError, match="Unexpected fixed"): + cached(prompts, device=device) + assert len(calls) == 4 + # A replacement model owns new features, never a process-global text cache. + other = FixedConceptTextEncoder(lambda *a, **k: {"language_features": [99]}, "cuda") + assert other(["sidewalk"], device="cuda")["language_features"] == [99] + + +def view(frame, seed, yaw): + rng = np.random.default_rng(seed) + labels = rng.integers(0, 6, (512, 512), dtype=np.uint8) + candidate = np.isin(labels, [1, 2, 3]) + return { + "frame_id": frame, + "rgb": rng.integers(0, 256, (600, 800, 3), dtype=np.uint8), + "observation": { + "captured_at": 123.5, "simulation_time_ns": 78000000000, + "pose": [1, 2, .37, 0, 0, 0, 1], + "calibration": {"view_yaw_degrees": yaw}, + }, + "values": { + "segmentation.labels": labels, + "segmentation.known": labels != 0, + "segmentation.surface": candidate, + "navigation.surface": candidate & (labels == 1), + "source.crossing-mask": np.zeros_like(candidate), + "source.crossing-admission": {"state": "sidewalk", "admitted": False}, + }, + } + + +def test_exact_evidence_round_trips_input_and_distinguishes_candidate_from_permission(tmp_path): + original = view(2359, 2359, 0) + extra = view(2359, 2360, 90) + original["supplement"] = extra + records = archive_perception(tmp_path, original) + assert [r["role"] for r in records] == ["task", "supplement"] + for result, receipt in zip((original, extra), records, strict=True): + path = tmp_path / receipt["file"] + assert hashlib.sha256(path.read_bytes()).hexdigest() == receipt["sha256"] + with np.load(path, allow_pickle=False) as saved: + assert saved["rgb"].dtype == np.uint8 + assert saved["rgb"].tobytes() == result["rgb"].tobytes() + assert hashlib.sha256(saved["rgb"].tobytes()).hexdigest() == receipt["rgb_sha256"] + for key, port in (("labels", "segmentation.labels"), ("known", "segmentation.known"), + ("candidate_surface", "segmentation.surface"), + ("permitted_surface", "navigation.surface")): + np.testing.assert_array_equal(saved[key], result["values"][port]) + assert (np.count_nonzero(saved["candidate_surface"]) + > np.count_nonzero(saved["permitted_surface"])) + metadata = json.loads(str(saved["metadata_json"])) + assert metadata["frame_id"] == 2359 + assert metadata["captured_at"] == result["observation"]["captured_at"] + assert metadata["simulation_time_ns"] == 78000000000 + assert metadata["calibration"] == result["observation"]["calibration"] + assert metadata["rgb_sha256"] == receipt["rgb_sha256"] + + +def test_perception_evidence_rejects_preview_resolution(tmp_path): + result = view(1, 2, 0) + result["rgb"] = result["rgb"][::2, ::2] + with pytest.raises(ValueError, match="exact 800x600"): + archive_perception(tmp_path, result) + assert not list(tmp_path.iterdir())