subproc_vec_env.py 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import numpy as np
  2. from multiprocessing import Process, Pipe
  3. from vec_env import VecEnv, CloudpickleWrapper
  4. def worker(remote, parent_remote, env_fn_wrapper):
  5. parent_remote.close()
  6. env = env_fn_wrapper.x()
  7. while True:
  8. cmd, data = remote.recv()
  9. if cmd == 'step':
  10. ob, reward, done, info = env.step(data)
  11. if done:
  12. ob = env.reset()
  13. remote.send((ob, reward, done, info))
  14. elif cmd == 'reset':
  15. ob = env.reset()
  16. remote.send(ob)
  17. elif cmd == 'reset_task':
  18. ob = env.reset_task()
  19. remote.send(ob)
  20. elif cmd == 'close':
  21. remote.close()
  22. break
  23. elif cmd == 'get_spaces':
  24. remote.send((env.observation_space, env.action_space))
  25. else:
  26. raise NotImplementedError
  27. class SubprocVecEnv(VecEnv):
  28. def __init__(self, env_fns, spaces=None):
  29. """
  30. envs: list of gym environments to run in subprocesses
  31. """
  32. self.waiting = False
  33. self.closed = False
  34. nenvs = len(env_fns)
  35. self.remotes, self.work_remotes = zip(*[Pipe() for _ in range(nenvs)])
  36. self.ps = [Process(target=worker, args=(work_remote, remote, CloudpickleWrapper(env_fn)))
  37. for (work_remote, remote, env_fn) in zip(self.work_remotes, self.remotes, env_fns)]
  38. for p in self.ps:
  39. p.daemon = True # if the main process crashes, we should not cause things to hang
  40. p.start()
  41. for remote in self.work_remotes:
  42. remote.close()
  43. self.remotes[0].send(('get_spaces', None))
  44. observation_space, action_space = self.remotes[0].recv()
  45. VecEnv.__init__(self, len(env_fns), observation_space, action_space)
  46. def step_async(self, actions):
  47. for remote, action in zip(self.remotes, actions):
  48. remote.send(('step', action))
  49. self.waiting = True
  50. def step_wait(self):
  51. results = [remote.recv() for remote in self.remotes]
  52. self.waiting = False
  53. obs, rews, dones, infos = zip(*results)
  54. return np.stack(obs), np.stack(rews), np.stack(dones), infos
  55. def reset(self):
  56. for remote in self.remotes:
  57. remote.send(('reset', None))
  58. return np.stack([remote.recv() for remote in self.remotes])
  59. def reset_task(self):
  60. for remote in self.remotes:
  61. remote.send(('reset_task', None))
  62. return np.stack([remote.recv() for remote in self.remotes])
  63. def close(self):
  64. if self.closed:
  65. return
  66. if self.waiting:
  67. for remote in self.remotes:
  68. remote.recv()
  69. for remote in self.remotes:
  70. remote.send(('close', None))
  71. for p in self.ps:
  72. p.join()
  73. self.closed = True