def _run(self): """ Main loop of the actor worker (rollout worker). Process tasks (mainly ROLLOUT_STEP) until we get the termination signal, which usually means end of training. Currently there is no mechanism to restart dead workers if something bad happens during training. We can only retry on the initial reset(). This is definitely something to work on. """ log.info('Initializing vector env runner %d...', self.worker_idx) # workers should ignore Ctrl+C because the termination is handled in the event loop by a special msg signal.signal(signal.SIGINT, signal.SIG_IGN) if self.cfg.actor_worker_gpus: set_gpus_for_process( self.worker_idx, num_gpus_per_process=1, process_type='actor', gpu_mask=self.cfg.actor_worker_gpus, ) torch.multiprocessing.set_sharing_strategy('file_system') timing = Timing() last_report = time.time() with torch.no_grad(): while not self.terminate: try: try: with timing.add_time('waiting'), timing.timeit('wait_actor'): tasks = self.task_queue.get_many(timeout=0.1) except Empty: tasks = [] for task in tasks: task_type, data = task if task_type == TaskType.INIT: self._init() continue if task_type == TaskType.TERMINATE: self._terminate() break # handling actual workload if task_type == TaskType.ROLLOUT_STEP: if 'work' not in timing: timing.waiting = 0 # measure waiting only after real work has started with timing.add_time('work'), timing.timeit('one_step'): self._advance_rollouts(data, timing) elif task_type == TaskType.RESET: with timing.add_time('reset'): self._handle_reset() elif task_type == TaskType.PBT: self._process_pbt_task(data) elif task_type == TaskType.UPDATE_ENV_STEPS: for env in self.env_runners: env.update_env_steps(data) if time.time() - last_report > 5.0 and 'one_step' in timing: timing_stats = dict(wait_actor=timing.wait_actor, step_actor=timing.one_step) memory_mb = memory_consumption_mb() stats = dict(memory_actor=memory_mb) safe_put(self.report_queue, dict(timing=timing_stats, stats=stats), queue_name='report') last_report = time.time() except RuntimeError as exc: log.warning('Error while processing data w: %d, exception: %s', self.worker_idx, exc) log.warning('Terminate process...') self.terminate = True safe_put(self.report_queue, dict(critical_error=self.worker_idx), queue_name='report') except KeyboardInterrupt: self.terminate = True except: log.exception('Unknown exception in rollout worker') self.terminate = True if self.worker_idx <= 1: time.sleep(0.1) log.info( 'Env runner %d, CPU aff. %r, rollouts %d: timing %s', self.worker_idx, psutil.Process().cpu_affinity(), self.num_complete_rollouts, timing, )
def sample(self, proc_idx): # workers should ignore Ctrl+C because the termination is handled in the event loop by a special msg signal.signal(signal.SIGINT, signal.SIG_IGN) if self.cfg.sampler_worker_gpus: set_gpus_for_process( proc_idx, num_gpus_per_process=1, process_type='sampler_proc', available_gpus=self.cfg.sampler_worker_gpus, ) timing = Timing() from threadpoolctl import threadpool_limits with threadpool_limits(limits=1, user_api=None): if self.cfg.set_workers_cpu_affinity: set_process_cpu_affinity(proc_idx, self.cfg.num_workers) initial_cpu_affinity = psutil.Process().cpu_affinity( ) if platform != 'darwin' else None psutil.Process().nice(10) with timing.timeit('env_init'): envs = [] env_key = ['env' for _ in range(self.cfg.num_envs_per_worker)] for env_idx in range(self.cfg.num_envs_per_worker): global_env_id = proc_idx * self.cfg.num_envs_per_worker + env_idx env_config = AttrDict(worker_index=proc_idx, vector_index=env_idx, env_id=global_env_id) env = make_env_func(cfg=self.cfg, env_config=env_config) log.debug( 'CPU affinity after create_env: %r', psutil.Process().cpu_affinity() if platform != 'darwin' else 'MacOS - None') env.seed(global_env_id) envs.append(env) # this is to track the performance for individual DMLab levels if hasattr(env.unwrapped, 'level_name'): env_key[env_idx] = env.unwrapped.level_name episode_length = [0 for _ in envs] episode_lengths = [deque([], maxlen=20) for _ in envs] try: with timing.timeit('first_reset'): for env_idx, env in enumerate(envs): env.reset() log.info('Process %d finished resetting %d/%d envs', proc_idx, env_idx + 1, len(envs)) self.report_queue.put( dict(proc_idx=proc_idx, finished_reset=True)) self.start_event.wait() with timing.timeit('work'): last_report = last_report_frames = total_env_frames = 0 while not self.terminate.value and total_env_frames < self.cfg.sample_env_frames_per_worker: for env_idx, env in enumerate(envs): actions = [ env.action_space.sample() for _ in range(env.num_agents) ] with timing.add_time(f'{env_key[env_idx]}.step'): obs, rewards, dones, infos = env.step(actions) num_frames = sum( [info.get('num_frames', 1) for info in infos]) total_env_frames += num_frames episode_length[env_idx] += num_frames if all(dones): episode_lengths[env_idx].append( episode_length[env_idx]) episode_length[env_idx] = 0 with timing.add_time('report'): now = time.time() if now - last_report > self.report_every_sec: last_report = now frames_since_last_report = total_env_frames - last_report_frames last_report_frames = total_env_frames self.report_queue.put( dict(proc_idx=proc_idx, env_frames=frames_since_last_report)) # Extra check to make sure cpu affinity is preserved throughout the execution. # I observed weird effect when some environments tried to alter affinity of the current process, leading # to decreased performance. # This can be caused by some interactions between deep learning libs, OpenCV, MKL, OpenMP, etc. # At least user should know about it if this is happening. cpu_affinity = psutil.Process().cpu_affinity( ) if platform != 'darwin' else None assert initial_cpu_affinity == cpu_affinity, \ f'Worker CPU affinity was changed from {initial_cpu_affinity} to {cpu_affinity}!' \ f'This can significantly affect performance!' except: log.exception('Unknown exception') log.error('Unknown exception in worker %d, terminating...', proc_idx) self.report_queue.put(dict(proc_idx=proc_idx, crash=True)) time.sleep(proc_idx * 0.01 + 0.01) log.info('Process %d finished sampling. Timing: %s', proc_idx, timing) for env_idx, env in enumerate(envs): if len(episode_lengths[env_idx]) > 0: log.warning('Level %s avg episode len %d', env_key[env_idx], np.mean(episode_lengths[env_idx])) for env in envs: env.close()