ConsDrive / team_code /detector_objects.py
ZenoNing's picture
Upload ConsDrive v2 source (part 2)
314ecfb verified
Raw History Blame Contribute Delete
8.04 kB
"""Sensor-only object observations for the stage-3 agent: two-frame detector + tracker (stage 2).
Drop-in replacement for team_code/oracle_objects.py. Every frame the front image goes through
models/detector.py together with the FPN features of the frame 0.25 s earlier (the 4 Hz interval
of the training logs, i.e. `frame_gap` frames at 20 Hz); detections are lifted to the world frame
with the agent's own pose estimate (GPS/UKF + compass) and tracked by team_code/tracker.py, whose
rows follow the object-bank convention the stage-3 model was trained on.
"""
from collections import deque
import numpy as np
import torch
from dataloader.detection_data import ego_motion
from dataloader.detection_labels import EGO_DIM, EGO_SPEED, EGO_X, EGO_Y, EGO_YAW
from dataloader.object_bank import FEAT_DIM, raw_to_features
from models.detector import decode, load_detector
from team_code.tracker import Tracker, TrackerConfig, detections_to_world
class DetectorObjectSource:
needs_sensors = True # step() takes the image and the ego pose, unlike the oracle source
def __init__(self, checkpoint, bank_kwargs, device, frame_gap=5, score_threshold=0.3, tracker_kwargs=None,
update_every=1):
"""update_every: run detector + tracker update on every n-th call only and render the tracks in
between; update_every=frame_gap reproduces the 4 Hz schedule of the offline tracker banks."""
self.device = device
self.model = load_detector(checkpoint, device)
self.frame_gap = int(frame_gap)
self.update_every = int(update_every)
if self.frame_gap % self.update_every:
raise ValueError(f"frame_gap {frame_gap} must be a multiple of update_every {update_every}")
self.score_threshold = float(score_threshold)
cfg = dict(max_objects=int(bank_kwargs.get("max_objects", 32)),
max_keep_distance=float(bank_kwargs.get("max_keep_distance", 80.0)),
max_behind_distance=float(bank_kwargs.get("max_behind_distance", 20.0)),
camera_x=float(bank_kwargs.get("camera_x", -1.5)))
cfg.update(tracker_kwargs or {})
self.tracker = Tracker(TrackerConfig(**cfg))
self.max_objects = self.tracker.cfg.max_objects
self.reset()
def reset(self):
self.tracker.reset()
self._steps_back = self.frame_gap // self.update_every
self._history = deque(maxlen=self._steps_back + 1) # (pyramid, ego state) of update frames
self.last_detections = None
self._calls = 0
self._t_update = None
@torch.no_grad()
def step(self, t, rgb, ego_xy, ego_yaw, speed):
"""rgb: [H, W, 3] uint8 RGB front image; ego pose in the CARLA world frame.
Returns (features [N, FEAT_DIM] float32, mask [N] bool, raw rows, ids, count)."""
self._calls += 1
if (self._calls - 1) % self.update_every:
raw, ids, count = self.tracker.render(float(t), np.asarray(ego_xy, dtype=np.float64), float(ego_yaw),
self._t_update)
return self._outputs(raw, ids, count)
self._t_update = float(t)
ego = np.zeros(EGO_DIM, dtype=np.float32)
ego[EGO_X], ego[EGO_Y], ego[EGO_YAW], ego[EGO_SPEED] = ego_xy[0], ego_xy[1], ego_yaw, speed
image = torch.from_numpy(np.ascontiguousarray(rgb)).permute(2, 0, 1)[None].to(self.device)
first_frame = not self._history
if len(self._history) > self._steps_back:
prev_pyramid, prev_ego = self._history[0]
else: # first 0.25 s of a route: the oldest frame available (at worst the current one)
prev_pyramid, prev_ego = self._history[0] if self._history else (None, ego)
motion = torch.from_numpy(ego_motion(prev_ego, ego))[None].to(self.device)
with torch.autocast("cuda", dtype=torch.bfloat16):
if prev_pyramid is None:
out, pyramid = self.model(image, image, motion)
else:
out, pyramid = self.model(image, prev_pyramid=prev_pyramid, ego_motion=motion)
self._history.append((pyramid, ego))
det = {k: v.float().cpu().numpy() for k, v in decode(out, score_threshold=self.score_threshold)[0].items()}
self.last_detections = det
world = detections_to_world(det, np.asarray(ego_xy, dtype=np.float64), float(ego_yaw),
camera_x=self.tracker.cfg.camera_x)
if first_frame and self.update_every > 1:
# the 4 Hz banks have no detections on a route's first frame (no earlier frame for the
# motion branch); the image-against-itself pass would seed every track with zero velocity
world = []
raw, ids, count = self.tracker.step(float(t), world, np.asarray(ego_xy, dtype=np.float64), float(ego_yaw))
return self._outputs(raw, ids, count)
def _outputs(self, raw, ids, count):
mask = np.arange(self.max_objects) < count
feats = raw_to_features(raw) if count else np.zeros((self.max_objects, FEAT_DIM), np.float32)
return feats, mask, raw, ids, count
def is_stream_checkpoint(checkpoint):
"""True for a train_stream_petr.py checkpoint (models/stream_petr.py), False for train_detector.py."""
args = torch.load(checkpoint, map_location="cpu", weights_only=False).get("args", {})
return "num_queries" in args
class StreamObjectSource(DetectorObjectSource):
"""DetectorObjectSource with the streaming detector (models/stream_petr.py): one image per update,
the detector's own query memory carries the objects between updates, then the same tracker."""
def __init__(self, checkpoint, bank_kwargs, device, frame_gap=5, score_threshold=0.3, tracker_kwargs=None,
update_every=5):
from models.stream_petr import StreamDetector, load_stream_petr
self.device = device
self.detector = StreamDetector(load_stream_petr(checkpoint, device), device, score_threshold)
self.model = self.detector.model
self.frame_gap, self.update_every = int(frame_gap), int(update_every)
self.score_threshold = float(score_threshold)
cfg = dict(max_objects=int(bank_kwargs.get("max_objects", 32)),
max_keep_distance=float(bank_kwargs.get("max_keep_distance", 80.0)),
max_behind_distance=float(bank_kwargs.get("max_behind_distance", 20.0)),
camera_x=float(bank_kwargs.get("camera_x", -1.5)))
cfg.update(tracker_kwargs or {})
self.tracker = Tracker(TrackerConfig(**cfg))
self.max_objects = self.tracker.cfg.max_objects
self.reset()
def reset(self):
self.tracker.reset()
self.detector.reset()
self.last_detections = None
self._calls = 0
self._t_update = None
@torch.no_grad()
def step(self, t, rgb, ego_xy, ego_yaw, speed):
self._calls += 1
if (self._calls - 1) % self.update_every:
raw, ids, count = self.tracker.render(float(t), np.asarray(ego_xy, dtype=np.float64), float(ego_yaw),
self._t_update)
return self._outputs(raw, ids, count)
self._t_update = float(t)
det = self.detector.step(rgb, (float(ego_xy[0]), float(ego_xy[1]), float(ego_yaw)), float(t))
self.last_detections = det
world = detections_to_world(det, np.asarray(ego_xy, dtype=np.float64), float(ego_yaw),
camera_x=self.tracker.cfg.camera_x)
raw, ids, count = self.tracker.step(float(t), world, np.asarray(ego_xy, dtype=np.float64), float(ego_yaw))
return self._outputs(raw, ids, count)
def make_object_source(checkpoint, bank_kwargs, device, **kwargs):
"""DetectorObjectSource or StreamObjectSource, chosen by the checkpoint type."""
cls = StreamObjectSource if is_stream_checkpoint(checkpoint) else DetectorObjectSource
return cls(checkpoint, bank_kwargs, device, **kwargs)