"""Bench2Drive PIM agent; explicit state is owned by each route's agent.""" import json import os from pathlib import Path import torch from team_code.agent_drivevla import DriveVLABench2DriveAgent from models.pim_driving import PIMDrivingModel def get_entry_point(): return 'PIMBench2DriveAgent' class PIMBench2DriveAgent(DriveVLABench2DriveAgent): def setup(self, path_to_conf_file, route_index=None): super().setup(path_to_conf_file, route_index) if not isinstance(self.model, PIMDrivingModel): raise TypeError('agent_pim requires PIMDrivingModel') if self.cfg.data_module.hist_len != 1 or self.cfg.data_module.encoder != 'fastvlm': raise ValueError('PIM evaluation requires FastVLM and hist_len=1') self._memory = None self._image_id = None self._image_time = None self._previous_sim_time = None self._ablation = os.environ.get('PIM_ABLATION', 'none') if self._ablation not in ('none', 'clear', 'disable_read'): raise ValueError('PIM_ABLATION must be none, clear or disable_read') self.model.pim_read_enabled = self._ablation != 'disable_read' self._pim_log = None logdir = os.environ.get('PIM_LOG_DIR') if logdir: Path(logdir).mkdir(parents=True, exist_ok=True) self._pim_log = open(Path(logdir) / f'route_{route_index}_{os.getpid()}.jsonl', 'w') @torch.no_grad() def run_step(self, input_data, timestamp, sensors=None): now = float(timestamp) if self._previous_sim_time is not None and now < self._previous_sim_time: self._memory = None self._image_id = self._image_time = None self._previous_sim_time = now self._sim_time = now return super().run_step(input_data, timestamp, sensors) def _predict_trajectory(self, driving_input, return_context=False): # Repeated camera packets must not refresh the last observation time. if self._current_image_id != self._image_id: self._image_time = self._sim_time self._image_id = self._current_image_id if self._ablation == 'clear': self._memory = None device = driving_input.camera_images.device result = self.model.forward_step( driving_input, torch.tensor([self._image_time], device=device), torch.tensor([self._current_ego_pose], device=device), self._memory) self._memory = result.state.detach() if result.state is not None else None if self._pim_log: record = {'time': self._sim_time, 'image_time': self._image_time, 'ablation': self._ablation, 'diagnostics': {k: v.detach().cpu().tolist() for k, v in result.diagnostics.items()}} self._pim_log.write(json.dumps(record) + '\n') self._pim_log.flush() if return_context: return result.speed_wps, result.route, result.scene_tokens, result.scene_mask return result.speed_wps, result.route def _allow_creep(self): # Legacy stuck recovery unconditionally overrides a predicted stop. # Disable it for all PIM runs, including ablations, for a fair comparison. return False def destroy(self): self._memory = None if getattr(self, '_pim_log', None): self._pim_log.close() self._pim_log = None super().destroy()