question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

SubprocVecEnv example code does not work

See original GitHub issue

I am opening a new issue because #40 does not match, and is a bit messy (and closed).

Describe the bug Subprocess creation fails. Same env works with DummyVecEnv.

UPDATE: Wrapping the whole code (or at least the SubprocVecEnv construction and subsequent usage) in an if __name__=="__main__": solves the problem. Thus I guess this report should now be seen as a request to update the documentation to better accommodate for Windows users, as this seems to be a Windows thing, ref. where to put freeze_support() in a Python script?

Code example Example code from the documentation:

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()

System Info

  • Windows 10 x64
  • Installed stable-baselines with pip yesterday
  • GPU: Single Nvidia GTX1070
  • Python 3.6.7
  • tensorflow-gpu 1.12.0 (from pip)
  • gym 0.10.9 (from pip)
  • MS_MPI 10.0.12498.5 and MS_MPI SDK (default download from Microsoft as of yesterday)
  • CUDA 9.0 with patches and CuDNN 7.4.1.5

Additional context Console output for num_cpus=1 (same error message, but a shorter read):

Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "C:\Users\elias\AppData\Local\Programs\Python\Python36\lib\multiprocessing\spawn.py", line 105, in spawn_main
    exitcode = _main(fd)
  File "C:\Users\elias\AppData\Local\Programs\Python\Python36\lib\multiprocessing\spawn.py", line 114, in _main
    prepare(preparation_data)
  File "C:\Users\elias\AppData\Local\Programs\Python\Python36\lib\multiprocessing\spawn.py", line 225, in prepare
    _fixup_main_from_path(data['init_main_from_path'])
  File "C:\Users\elias\AppData\Local\Programs\Python\Python36\lib\multiprocessing\spawn.py", line 277, in _fixup_main_from_path
    run_name="__mp_main__")
  File "C:\Users\elias\AppData\Local\Programs\Python\Python36\lib\runpy.py", line 263, in run_path
    pkg_name=pkg_name, script_name=fname)
  File "C:\Users\elias\AppData\Local\Programs\Python\Python36\lib\runpy.py", line 96, in _run_module_code
    mod_name, mod_spec, pkg_name, script_name)
  File "C:\Users\elias\AppData\Local\Programs\Python\Python36\lib\runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "C:\Users\elias\Dropbox (Personal)\PhD\Projects\SMB\stable_baselines_multiproc_example.py", line 28, in <module>
    env = SubprocVecEnv([make_env(env_id, i) for i in range(num_cpu)])
  File "C:\Users\elias\AppData\Local\Programs\Python\Python36\lib\site-packages\stable_baselines\common\vec_env\subproc_vec_env.py", line 59, in __init__
    process.start()
  File "C:\Users\elias\AppData\Local\Programs\Python\Python36\lib\multiprocessing\process.py", line 105, in start
    self._popen = self._Popen(self)
  File "C:\Users\elias\AppData\Local\Programs\Python\Python36\lib\multiprocessing\context.py", line 223, in _Popen
    return _default_context.get_context().Process._Popen(process_obj)
  File "C:\Users\elias\AppData\Local\Programs\Python\Python36\lib\multiprocessing\context.py", line 322, in _Popen
    return Popen(process_obj)
  File "C:\Users\elias\AppData\Local\Programs\Python\Python36\lib\multiprocessing\popen_spawn_win32.py", line 33, in __init__
    prep_data = spawn.get_preparation_data(process_obj._name)
  File "C:\Users\elias\AppData\Local\Programs\Python\Python36\lib\multiprocessing\spawn.py", line 143, in get_preparation_data
    _check_not_importing_main()
  File "C:\Users\elias\AppData\Local\Programs\Python\Python36\lib\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.

Note that the program does not terminate.

Commenting out lines from the bottom of the file reveals that the crucial line is the one where the SubprocVecEnv is constructed (as can also be seen from the stack trace).

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Comments:7

github_iconTop GitHub Comments

1reaction
EliasHaslecommented, May 23, 2020

You can put it around your whole script. Just make sure to indent the encapsulated code.

1reaction
liquidsnakebluecommented, May 23, 2020

Could you update this post with a new example showing the solution? I’m trying to figure this out myself and can’t seem to solve where to put the

if name == ‘main’:

Will keep searching. Thanks in advance, have a great day.

Read more comments on GitHub >

github_iconTop Results From Across the Web

SubprocVecEnv not working with Custom Env (Stable Baselines
Check this sample code: import numpy as np import gym from baselines.common.vec_env.subproc_vec_env import SubprocVecEnv env_name ...
Read more >
Vectorized Environments - Stable Baselines - Read the Docs
When using SubprocVecEnv , users must wrap the code in an if __name__ ... On Linux, the default start method is fork which...
Read more >
Stable Baselines3 Tutorial - Multiprocessing of environments
SubprocVecEnv which run each environment in a separate process; DummyVecEnv which ... if there is only one process, there is no need to...
Read more >
How to use the gym.wrappers function in gym - Snyk
Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues...
Read more >
Understanding OpenAI baseline source code and making it do ...
SubprocVecEnv __init__: a dive into multiprocessing ... (e.g. when len(env_fns) == 12 and in_series == 3, it will run 4 ... For example,...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found