hill-a / stable-baselines

A fork of OpenAI Baselines, implementations of reinforcement learning algorithms
http://stable-baselines.readthedocs.io/
MIT License
4.15k stars 723 forks source link

SubprocVecEnv problem #483

Closed maystroh closed 5 years ago

maystroh commented 5 years ago

When I try to use run a training with multiprocessed environments using the following code

Code example

import gym
import numpy as np

from stable_baselines.common.policies import MlpPolicy
from stable_baselines.common.vec_env import SubprocVecEnv
from stable_baselines.common import set_global_seeds
from stable_baselines import ACKTR

def make_env(env_id, rank, seed=0):
    """
    Utility function for multiprocessed env.

    :param env_id: (str) the environment ID
    :param num_env: (int) the number of environments you wish to have in subprocesses
    :param seed: (int) the inital seed for RNG
    :param rank: (int) index of the subprocess
    """
    def _init():
        env = gym.make(env_id)
        env.seed(seed + rank)
        return env
    set_global_seeds(seed)
    return _init

env_id = "CartPole-v1"
num_cpu = 4  # Number of processes to use
# Create the vectorized environment
env = SubprocVecEnv([make_env(env_id, i) for i in range(num_cpu)])

model = ACKTR(MlpPolicy, env, verbose=1)
model.learn(total_timesteps=25000)

obs = env.reset()
for _ in range(1000):
    action, _states = model.predict(obs)
    obs, rewards, dones, info = env.step(action)
    env.render()

It crashes with the following error:

File "/opt/conda/lib/python3.6/multiprocessing/forkserver.py", line 196, in main
    _serve_one(s, listener, alive_r, old_handlers)
  File "/opt/conda/lib/python3.6/multiprocessing/forkserver.py", line 231, in _serve_one
    code = spawn._main(child_r)
  File "/opt/conda/lib/python3.6/multiprocessing/spawn.py", line 114, in _main
    prepare(preparation_data)
  File "/opt/conda/lib/python3.6/multiprocessing/spawn.py", line 225, in prepare
    _fixup_main_from_path(data['init_main_from_path'])
  File "/opt/conda/lib/python3.6/multiprocessing/spawn.py", line 277, in _fixup_main_from_path
    run_name="__mp_main__")
  File "/opt/conda/lib/python3.6/runpy.py", line 263, in run_path
    pkg_name=pkg_name, script_name=fname)
  File "/opt/conda/lib/python3.6/runpy.py", line 96, in _run_module_code
    mod_name, mod_spec, pkg_name, script_name)
  File "/opt/conda/lib/python3.6/runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "/home/hassan/ClusterGPU/data_GPU/hassan/SurgerySimulator/Local_RL_Cataract/ml-agents-gym/trainings/unity-gym/cataract_mono_tests/test_xvbf.py", line 28, in <module>
    env = SubprocVecEnv([make_env(env_id, i) for i in range(num_cpu)])
  File "/data_GPU/hassan/SurgerySimulator/Local_RL_Cataract/ml-agents-gym/stable_baselines/common/vec_env/subproc_vec_env.py", line 90, in __init__
    process.start()
  File "/opt/conda/lib/python3.6/multiprocessing/process.py", line 105, in start
    self._popen = self._Popen(self)
  File "/opt/conda/lib/python3.6/multiprocessing/context.py", line 291, in _Popen
    return Popen(process_obj)
  File "/opt/conda/lib/python3.6/multiprocessing/popen_forkserver.py", line 35, in __init__
    super().__init__(process_obj)
  File "/opt/conda/lib/python3.6/multiprocessing/popen_fork.py", line 19, in __init__
    self._launch(process_obj)
  File "/opt/conda/lib/python3.6/multiprocessing/popen_forkserver.py", line 42, in _launch
    prep_data = spawn.get_preparation_data(process_obj._name)
  File "/opt/conda/lib/python3.6/multiprocessing/spawn.py", line 143, in get_preparation_data
    _check_not_importing_main()
  File "/opt/conda/lib/python3.6/multiprocessing/spawn.py", line 136, in _check_not_importing_main
    is not going to be frozen to produce an executable.''')
RuntimeError: 
        An attempt has been made to start a new process before the
        current process has finished its bootstrapping phase.

        This probably means that you are not using fork to start your
        child processes and you have forgotten to use the proper idiom
        in the main module:

            if __name__ == '__main__':
                freeze_support()
                ...

        The "freeze_support()" line can be omitted if the program
        is not going to be frozen to produce an executable.
Traceback (most recent call last):
  File "test_xvbf.py", line 28, in <module>
    env = SubprocVecEnv([make_env(env_id, i) for i in range(num_cpu)])
  File "/data_GPU/hassan/SurgerySimulator/Local_RL_Cataract/ml-agents-gym/stable_baselines/common/vec_env/subproc_vec_env.py", line 95, in __init__
    observation_space, action_space = self.remotes[0].recv()
  File "/opt/conda/lib/python3.6/multiprocessing/connection.py", line 250, in recv
    buf = self._recv_bytes()
  File "/opt/conda/lib/python3.6/multiprocessing/connection.py", line 407, in _recv_bytes
    buf = self._recv(4)
  File "/opt/conda/lib/python3.6/multiprocessing/connection.py", line 379, in _recv
    chunk = read(handle, remaining)
ConnectionResetError: [Errno 104] Connection reset by peer

System Info Describe the characteristic of your environment:

Miffyli commented 5 years ago

As the error message suggests, try putting your code into functions and have the if __name__ == '__main__' start the code, i.e.

import gym
import numpy as np

from stable_baselines.common.policies import MlpPolicy
from stable_baselines.common.vec_env import SubprocVecEnv
from stable_baselines.common import set_global_seeds
from stable_baselines import ACKTR

def make_env(env_id, rank, seed=0):
    """
    Utility function for multiprocessed env.

    :param env_id: (str) the environment ID
    :param num_env: (int) the number of environments you wish to have in subprocesses
    :param seed: (int) the inital seed for RNG
    :param rank: (int) index of the subprocess
    """
    def _init():
        env = gym.make(env_id)
        env.seed(seed + rank)
        return env
    set_global_seeds(seed)
    return _init

def main():
    env_id = "CartPole-v1"
    num_cpu = 4  # Number of processes to use
    # Create the vectorized environment
    env = SubprocVecEnv([make_env(env_id, i) for i in range(num_cpu)])

    model = ACKTR(MlpPolicy, env, verbose=1)
    model.learn(total_timesteps=25000)

    obs = env.reset()
    for _ in range(1000):
        action, _states = model.predict(obs)
        obs, rewards, dones, info = env.step(action)
        env.render()

if __name__ == '__main__':
    main()

This should not be a problem on *nixes which use forking for multiprocessing by default, but for you it seems to be starting new processes for some reason.

maystroh commented 5 years ago

Thanks, it was my bad.

araffin commented 5 years ago

Your problem was already explained in the documentation...

windowshopr commented 1 year ago

I'm getting this error as well when trying to run a SubprocVecEnv in a Colab notebook, WITH the training block encased in the if __name__ == '__main__': clause. It could be an issue with my environment too, but I think the environment is fine. It could also be an issue with Colab/multiprocessing, not sure yet. Here are the relevant sections of code:

!apt-get install ffmpeg freeglut3-dev xvfb  # For visualization
import sys
import os

sys.path.insert(0, '/usr/local/lib/python3.9/dist-packages/')

if not os.path.isdir('/usr/local/lib/python3.9/dist-packages/stable_baselines3'):
    !pip3.9 install pyglet==1.4
    !pip3.9 install git+https://github.com/JY251/stable-baselines3.git

import random
import numpy as np
import time
import gym
import stable_baselines3

class CustomEnvironmentClass(gym.Env):
    def __init__(self, )
    # ....rest of environment code here

# TRAINING BLOCK
def main():

    model_name = "_A2C"

    # Create environment
    def make_env():
        def _init():
            return CustomEnvironmentClass()
        return _init

    # Define total training timesteps and an evaluation frequency for early stopping
    total_training_timesteps = int(2e5)
    eval_freqs = 500

    # Create vectorized, concurrent environments
    num_envs = 3
    envs = stable_baselines3.common.vec_env.SubprocVecEnv([make_env() for _ in range(num_envs)])

    # Instantiate the agent
    model = stable_baselines3.A2C("MultiInputPolicy", 
                                envs, 
                                verbose=2,
                                n_steps=5,
                                device='cpu',
                                )

    # Define an early stopping callback for training
    stop_train_callback = stable_baselines3.common.callbacks.StopTrainingOnNoModelImprovement(max_no_improvement_evals=3, 
                                                                                            min_evals=5, 
                                                                                            verbose=1)
    eval_env = CustomEnvironmentClass()
    eval_callback = stable_baselines3.common.callbacks.EvalCallback(eval_env, 
                                                                    eval_freq=eval_freqs, 
                                                                    callback_after_eval=stop_train_callback, 
                                                                    verbose=1)

    # Train the agent and display a progress bar
    model.learn(total_timesteps=total_training_timesteps,
                callback=eval_callback,
                progress_bar=False) # Progress bar as True causes errors on Restart Run All in Colab notebooks

# START THE TRAINING
if __name__ == '__main__':
    main()
ConnectionResetError                      Traceback (most recent call last)
[<ipython-input-7-c7bc734e5e35>](https://localhost:8080/#) in <cell line: 1>()
      1 if __name__ == '__main__':
----> 2     main()

4 frames
[<ipython-input-6-34d42928dab5>](https://localhost:8080/#) in main()
     19 
     20     num_envs = 3
---> 21     envs = stable_baselines3.common.vec_env.SubprocVecEnv([make_env() for _ in range(num_envs)])
     22 
     23     # Instantiate the agent

[/usr/local/lib/python3.9/dist-packages/stable_baselines3/common/vec_env/subproc_vec_env.py](https://localhost:8080/#) in __init__(self, env_fns, start_method)
    110 
    111         self.remotes[0].send(("get_spaces", None))
--> 112         observation_space, action_space = self.remotes[0].recv()
    113         VecEnv.__init__(self, len(env_fns), observation_space, action_space)
    114 

[/usr/lib/python3.9/multiprocessing/connection.py](https://localhost:8080/#) in recv(self)
    248         self._check_closed()
    249         self._check_readable()
--> 250         buf = self._recv_bytes()
    251         return _ForkingPickler.loads(buf.getbuffer())
    252 

[/usr/lib/python3.9/multiprocessing/connection.py](https://localhost:8080/#) in _recv_bytes(self, maxsize)
    412 
    413     def _recv_bytes(self, maxsize=None):
--> 414         buf = self._recv(4)
    415         size, = struct.unpack("!i", buf.getvalue())
    416         if size == -1:

[/usr/lib/python3.9/multiprocessing/connection.py](https://localhost:8080/#) in _recv(self, size, read)
    377         remaining = size
    378         while remaining > 0:
--> 379             chunk = read(handle, remaining)
    380             n = len(chunk)
    381             if n == 0:

ConnectionResetError: [Errno 104] Connection reset by peer