Publish fresh front perception before supplementary neural views
This commit is contained in:
@@ -97,44 +97,58 @@ class ContinuousComposition(ComposedInference):
|
||||
processing_ms=(time.monotonic() - started) * 1000,
|
||||
module_ms={self.segmenter_id: segment_ms, "simulation-rf-detr": detector_ms})
|
||||
|
||||
def perceive(self, observation, frame_id):
|
||||
def perceive(self, observation, frame_id, *, publish_front=None, latest_sensor=None):
|
||||
request = getattr(self, "recovery_view_request", None)
|
||||
front = self.perceive_view(observation, frame_id, 0)
|
||||
front["semantic_observations"] = [front["samples"]]
|
||||
front["detection_views"] = [front.copy()]
|
||||
cached = getattr(self, "recovery_detection_view", None)
|
||||
if cached and time.monotonic()-cached["observation"]["captured_at"] <= 2:
|
||||
front["detection_views"].append(cached)
|
||||
yaw = request["yaw_degrees"] if request else self.supplement_yaw
|
||||
if request and yaw == 0:
|
||||
front["recovery_view"] = request
|
||||
front["recovery_observation"] = observation
|
||||
yaw = None
|
||||
changed = request and request != getattr(self, "last_recovery_view_request", None)
|
||||
if yaw is not None and (changed or time.monotonic() - self.last_supplement >= 1):
|
||||
# One bounded supplementary crop, never a full panorama inference.
|
||||
# Keep the same perspective distribution as the task view. A
|
||||
# down-looking crop requires separate model qualification.
|
||||
# Publish the completed front before another neural pass. Never
|
||||
# mutate a packet already visible to navigation/control threads.
|
||||
if publish_front is not None and not publish_front(front):
|
||||
return front
|
||||
packet = latest_sensor() if latest_sensor is not None else (frame_id, observation)
|
||||
if packet is None:
|
||||
return front # Pause/reset invalidated this capture epoch.
|
||||
extra_frame, extra_observation = packet
|
||||
# A supplementary pass starts from the latest captured panorama;
|
||||
# its pose/time must never be borrowed from the earlier front view.
|
||||
self.last_supplement = time.monotonic()
|
||||
self.last_recovery_view_request = request
|
||||
extra = self.perceive_view(observation, frame_id, yaw, detect=bool(request))
|
||||
front["semantic_observations"].append(extra["samples"])
|
||||
front["supplement"] = extra
|
||||
extra = self.perceive_view(extra_observation, extra_frame, yaw, detect=bool(request))
|
||||
front = {**front, "semantic_observations": [front["samples"], extra["samples"]],
|
||||
"supplement": extra, "detection_views": [front["detection_views"][0]]}
|
||||
if request:
|
||||
self.recovery_detection_view = extra
|
||||
front["recovery_view"] = request
|
||||
extra = getattr(self, "recovery_detection_view", None)
|
||||
if extra and time.monotonic()-extra["observation"]["captured_at"] <= 2:
|
||||
front["detection_views"].append(extra)
|
||||
front["recovery_observation"] = extra_observation
|
||||
front["detection_views"].append(extra)
|
||||
elif cached and time.monotonic()-cached["observation"]["captured_at"] <= 2:
|
||||
front["detection_views"].append(cached)
|
||||
return front
|
||||
|
||||
def navigate_latest(self, observation, perception, observation_id):
|
||||
camera = perception["observation"]
|
||||
recovery = self.mission.recovery
|
||||
recovery.observe_view(perception.get("recovery_view"), camera["pose"],
|
||||
camera["simulation_time_ns"] / 1e9)
|
||||
recovery_camera = perception.get("recovery_observation", camera)
|
||||
recovery.observe_view(perception.get("recovery_view"), recovery_camera["pose"],
|
||||
recovery_camera["simulation_time_ns"] / 1e9)
|
||||
self.source.lens_depths = camera["lens_depths"]
|
||||
values = {
|
||||
**self.static_values, **perception["values"],
|
||||
"source.execution-inputs": self.inputs,
|
||||
"source.camera.rgb": perception["rgb"],
|
||||
"source.camera.calibration": camera["calibration"],
|
||||
"source.camera.lens-depths": camera["lens_depths"],
|
||||
"source.lidar": observation["points"],
|
||||
"source.range-rays": observation.get("range_rays", {}),
|
||||
"source.pose": observation["pose"],
|
||||
@@ -142,6 +156,7 @@ class ContinuousComposition(ComposedInference):
|
||||
"source.semantic-observation": perception["semantic_observations"],
|
||||
"source.detection-views": [
|
||||
dict(calibration=view["observation"]["calibration"],
|
||||
lens_depths=view["observation"]["lens_depths"],
|
||||
boxes=view["values"]["detection.boxes"],
|
||||
objects=view["values"].get("detection.objects", []),
|
||||
surface=view["values"]["navigation.surface"])
|
||||
|
||||
@@ -154,6 +154,21 @@ class ContinuousPipeline:
|
||||
return None
|
||||
return ((*self.sensor[:2], self.perception_revision), self.sensor, self.perception)
|
||||
|
||||
def publish_perception(self, epoch, result):
|
||||
with self.condition:
|
||||
if not self.current(epoch):
|
||||
return False
|
||||
self.perception = (epoch, result)
|
||||
self.perception_revision += 1
|
||||
self.condition.notify_all()
|
||||
return True
|
||||
|
||||
def latest_sensor(self, epoch):
|
||||
with self.condition:
|
||||
if not self.current(epoch) or self.sensor is None or self.sensor[0] != epoch:
|
||||
return None
|
||||
return self.sensor[1:]
|
||||
|
||||
def perceive(self):
|
||||
# The first sensor packet is admitted only after the worker's complete
|
||||
# model-stack readiness barrier. Do not race startup on a partial stack.
|
||||
@@ -170,13 +185,12 @@ class ContinuousPipeline:
|
||||
self.dropped += max(0, frame-previous[1]-1)
|
||||
previous = packet[:2]
|
||||
started = self.clock()
|
||||
result = self.model.perceive(observation, frame)
|
||||
with self.condition:
|
||||
if not self.current(epoch):
|
||||
continue
|
||||
self.perception = (epoch, result)
|
||||
self.perception_revision += 1
|
||||
self.condition.notify_all()
|
||||
result = self.model.perceive(observation, frame,
|
||||
publish_front=lambda value, epoch=epoch: self.publish_perception(epoch, value),
|
||||
latest_sensor=lambda epoch=epoch: self.latest_sensor(epoch))
|
||||
self.publish_perception(epoch, result)
|
||||
# Archive every processed packet even if pause/reset fenced its
|
||||
# publication. An early front may already have informed control.
|
||||
|
||||
def archive(result=result, observation=observation, frame=frame, started=started):
|
||||
now = self.clock()
|
||||
@@ -191,6 +205,7 @@ class ContinuousPipeline:
|
||||
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,
|
||||
supplement_completed_at=(extra["completed_at"] if extra else None),
|
||||
module_ms=result["module_ms"], semantic_observations=result["semantic_observations"],
|
||||
detection_views=[dict(captured_at=view["observation"]["captured_at"],
|
||||
frame_id=view["samples"]["frame_id"],
|
||||
|
||||
@@ -739,6 +739,8 @@ class ComposedInference:
|
||||
dict(calibration=calibration, boxes=boxes, surface=surface)])
|
||||
for view in detection_views:
|
||||
view_calibration = view["calibration"]
|
||||
if "lens_depths" in view:
|
||||
self.source.lens_depths = view["lens_depths"]
|
||||
_, du, dv, seen = project(points, view_calibration, self.source)
|
||||
ground_pixels = np.zeros(len(points), dtype=bool)
|
||||
ground_pixels[seen] = view["surface"][self.source.indices(du[seen], dv[seen])]
|
||||
@@ -757,6 +759,9 @@ class ComposedInference:
|
||||
detection_evidence.append({"box": [x1, y1, x2, y2],
|
||||
**({"object": objects[box_index]} if objects else {}),
|
||||
"view_yaw_degrees": view_calibration.get("view_yaw_degrees", 0), **association})
|
||||
if hasattr(self.source, "lens_depths"):
|
||||
self.source.lens_depths = inputs.get(
|
||||
"source.camera.lens-depths", self.source.lens_depths)
|
||||
if intent["state"] in {"stuck", "goal-reached", "unstable"}:
|
||||
reason = intent["state"]
|
||||
elif self.goal is None and not (arrival_candidate or body_goal_query or orientation or recovering):
|
||||
|
||||
@@ -29,6 +29,13 @@ def archive_perception(directory, result):
|
||||
}
|
||||
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")
|
||||
if role == "supplement" and view["frame_id"] != result["frame_id"]:
|
||||
# A fresh side capture has its own geometry; the task frame's
|
||||
# .range/.sensors files cannot reconstruct this projection.
|
||||
arrays.update(range_points=observation["points"],
|
||||
lens_depths=np.asarray(observation["lens_depths"]))
|
||||
arrays.update({"range_rays." + key: value
|
||||
for key, value in observation.get("range_rays", {}).items()})
|
||||
metadata = dict(
|
||||
schema_version="missioncore.perception-evidence/v1",
|
||||
frame_id=view["frame_id"], role=role,
|
||||
|
||||
@@ -87,3 +87,18 @@ def test_perception_evidence_rejects_preview_resolution(tmp_path):
|
||||
with pytest.raises(ValueError, match="exact 800x600"):
|
||||
archive_perception(tmp_path, result)
|
||||
assert not list(tmp_path.iterdir())
|
||||
|
||||
|
||||
def test_fresh_supplement_archives_its_own_geometry(tmp_path):
|
||||
front, extra = view(10, 10, 0), view(11, 11, 90)
|
||||
extra["observation"].update(captured_at=124., pose=[2, 2, .37, 0, 0, 0, 1],
|
||||
points=np.array([[2., 3., 4.]]), lens_depths=np.ones((2, 4, 4)),
|
||||
range_rays={"origins": np.array([[2., 2., 1.]])})
|
||||
front["supplement"] = extra
|
||||
records = archive_perception(tmp_path, front)
|
||||
assert records[1]["file"] == "00000011.supplement.perception.npz"
|
||||
with np.load(tmp_path / records[1]["file"], allow_pickle=False) as saved:
|
||||
for key, source in (("range_points", "points"), ("lens_depths", "lens_depths")):
|
||||
np.testing.assert_array_equal(saved[key], extra["observation"][source])
|
||||
np.testing.assert_array_equal(saved["range_rays.origins"], [[2., 2., 1.]])
|
||||
assert json.loads(str(saved["metadata_json"]))["captured_at"] == 124.
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
"""Fresh front/side captures must remain causal across slow neural passes."""
|
||||
import copy
|
||||
import importlib
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def modules(monkeypatch):
|
||||
monkeypatch.syspath_prepend(str(Path(__file__).parents[1] / "simulation/ai-polygon"))
|
||||
return (importlib.import_module("continuous_composition"),
|
||||
importlib.import_module("continuous_pipeline"))
|
||||
|
||||
|
||||
def observation(stamp, x):
|
||||
return dict(captured_at=stamp, pose=[x, 0, 0, 0, 0, 0, 1],
|
||||
simulation_time_ns=int(stamp*1e9), lens_depths=[x], calibration={})
|
||||
|
||||
|
||||
def test_front_is_published_before_supplement_with_distinct_capture_identity(modules, monkeypatch):
|
||||
composition, _ = modules
|
||||
model = object.__new__(composition.ContinuousComposition)
|
||||
model.recovery_view_request = dict(key="recovery-1-2-90", yaw_degrees=90, after_seconds=9.)
|
||||
model.supplement_yaw = None
|
||||
model.last_supplement = -100.
|
||||
model.recovery_detection_view = None
|
||||
old, fresh = observation(10., 1.), observation(10.6, 2.)
|
||||
now = [10.]
|
||||
monkeypatch.setattr(composition.time, "monotonic", lambda: now[0])
|
||||
published = []
|
||||
def infer(obs, frame, yaw, **kwargs):
|
||||
if yaw:
|
||||
assert len(published) == 1
|
||||
assert obs is fresh and frame == 106
|
||||
assert "recovery_view" not in published[0]
|
||||
now[0] += .6
|
||||
return dict(observation=obs, frame_id=frame, samples=dict(frame_id=f"{frame}:{yaw}"),
|
||||
values={}, completed_at=now[0])
|
||||
model.perceive_view = infer
|
||||
def publish(front):
|
||||
published.append(front)
|
||||
return True
|
||||
result = model.perceive(old, 100, publish_front=publish, latest_sensor=lambda: (106, fresh))
|
||||
early = published[0]
|
||||
assert len(early["semantic_observations"]) == len(early["detection_views"]) == 1
|
||||
assert "supplement" not in early and "recovery_view" not in early
|
||||
assert result["observation"] is old
|
||||
assert result["supplement"]["observation"] is fresh
|
||||
assert result["recovery_observation"] is fresh
|
||||
assert result["semantic_observations"] == [early["samples"], dict(frame_id="106:90")]
|
||||
assert [v["observation"]["captured_at"] for v in result["detection_views"]] == [10., 10.6]
|
||||
assert result["recovery_view"] == model.recovery_view_request
|
||||
# Publishing completion must not advance either capture timestamp.
|
||||
assert now[0] == pytest.approx(11.2)
|
||||
assert [old["captured_at"], fresh["captured_at"]] == [10., 10.6]
|
||||
|
||||
|
||||
def test_pause_fences_inflight_front_and_does_not_start_side_inference(modules, tmp_path):
|
||||
composition, pipeline_module = modules
|
||||
pipeline = pipeline_module.ContinuousPipeline(None, tmp_path)
|
||||
pipeline.enable(True)
|
||||
epoch = pipeline.epoch
|
||||
obs = observation(10., 1.)
|
||||
pipeline.submit(None, 1, 10., 10_000_000_000, obs)
|
||||
assert pipeline.latest_sensor(epoch) == (1, obs)
|
||||
model = object.__new__(composition.ContinuousComposition)
|
||||
model.recovery_view_request = dict(key="side", yaw_degrees=90)
|
||||
model.supplement_yaw = None
|
||||
model.last_supplement = -100.
|
||||
model.recovery_detection_view = None
|
||||
calls = []
|
||||
def infer(observation, frame, yaw):
|
||||
calls.append(yaw)
|
||||
pipeline.enable(False)
|
||||
return dict(observation=observation, samples={}, values={})
|
||||
model.perceive_view = infer
|
||||
model.perceive(obs, 1, publish_front=lambda value: pipeline.publish_perception(epoch, value),
|
||||
latest_sensor=lambda: pipeline.latest_sensor(epoch))
|
||||
assert calls == [0] and pipeline.perception is None
|
||||
assert pipeline.latest_sensor(epoch) is None
|
||||
pipeline.enable(True)
|
||||
assert not pipeline.publish_perception(epoch, {})
|
||||
assert pipeline.perception is None
|
||||
|
||||
|
||||
def test_recovery_acknowledges_the_side_capture_pose_and_time(modules):
|
||||
composition, _ = modules
|
||||
model = object.__new__(composition.ContinuousComposition)
|
||||
front, side, live = observation(10., 1.), observation(10.6, 2.), observation(11., 3.)
|
||||
calls = []
|
||||
model.mission = SimpleNamespace(recovery=SimpleNamespace(active=False,
|
||||
observe_view=lambda *args: calls.append(args)), orientation_target=lambda: None)
|
||||
model.source = SimpleNamespace(lens_depths=None)
|
||||
model.static_values = {}
|
||||
model.inputs = {}
|
||||
model.goal = None
|
||||
model.observed_goals = SimpleNamespace(evidence={})
|
||||
model.graph = SimpleNamespace(sha256="graph", nodes=[SimpleNamespace(
|
||||
module=SimpleNamespace(module_id="nav", group="motion"))])
|
||||
model.navigation_evidence = {}
|
||||
model.plan_mission = lambda values: {}
|
||||
submitted = []
|
||||
def navigate(values):
|
||||
submitted.append(copy.copy(values))
|
||||
return {"motion.command": {}, "motion.path": []}
|
||||
model.navigate = navigate
|
||||
def view(obs):
|
||||
return dict(observation=obs, values={"detection.boxes": [], "navigation.surface": []})
|
||||
request = dict(key="side", yaw_degrees=90)
|
||||
perception = dict(observation=front, values={}, rgb=None, semantic_observations=[],
|
||||
detection_views=[view(front), view(side)], recovery_view=request,
|
||||
recovery_observation=side, module_ms={}, frame_id=100)
|
||||
live["points"] = []
|
||||
model.navigate_latest(live, perception, "current")
|
||||
assert calls == [(request, side["pose"], 10.6)]
|
||||
assert submitted[0]["source.pose"] == live["pose"]
|
||||
assert submitted[0]["source.camera.lens-depths"] == front["lens_depths"]
|
||||
assert [v["lens_depths"] for v in submitted[0]["source.detection-views"]] == [[1.], [2.]]
|
||||
Reference in New Issue
Block a user