From 20c37a803e998f2dabf418c8240b24bbb2928cfc Mon Sep 17 00:00:00 2001 From: Eliasepfl Date: Wed, 5 Aug 2026 15:04:01 -0400 Subject: [PATCH 1/3] Implement step_async and step_wait step_async ran the whole step and cached the result, so the split the sb3 VecEnv API expects did not exist: a caller doing step_async then step_wait paid the receive cost inside step_async. The send loop now lives in step_async, the receive loop in step_wait, and step calls the two in order. Results are unchanged. Actions still reach every environment before the first receive, so the existing overlap between the parallel games is preserved. --- godot_rl/wrappers/stable_baselines_wrapper.py | 72 +++++++--------- tests/test_sb3_step_async.py | 85 +++++++++++++++++++ 2 files changed, 117 insertions(+), 40 deletions(-) create mode 100644 tests/test_sb3_step_async.py diff --git a/godot_rl/wrappers/stable_baselines_wrapper.py b/godot_rl/wrappers/stable_baselines_wrapper.py index 1db812a9..2427b34c 100644 --- a/godot_rl/wrappers/stable_baselines_wrapper.py +++ b/godot_rl/wrappers/stable_baselines_wrapper.py @@ -43,9 +43,6 @@ def __init__( # Check the action space for validity self._check_valid_action_space() - # Initialize the results holder - self.results = None - def _check_valid_action_space(self) -> None: # Check if the action space is a tuple space with multiple spaces action_space = self.envs[0].action_space @@ -55,39 +52,8 @@ def _check_valid_action_space(self) -> None: ), f"sb3 supports a single action space, this env contains multiple spaces {action_space}" def step(self, action: np.ndarray) -> Tuple[Dict[str, np.ndarray], np.ndarray, np.ndarray, List[Dict[str, Any]]]: - # Initialize lists for collecting results - all_obs = [] - all_rewards = [] - all_term = [] - all_trunc = [] - all_info = [] - - # Get the number of environments - num_envs = self.envs[0].num_envs - - # Send actions to each environment - for i in range(self.n_parallel): - self.envs[i].step_send(action[i * num_envs : (i + 1) * num_envs]) - - # Receive results from each environment - for i in range(self.n_parallel): - obs, reward, term, trunc, info = self.envs[i].step_recv() - all_obs.extend(obs) - all_rewards.extend(reward) - all_term.extend(term) - all_trunc.extend(trunc) - all_info.extend(info) - - # Convert list of dictionaries to dictionary of lists - obs = lod_to_dol(all_obs) - - # Return results - return ( - {k: np.array(v) for k, v in obs.items()}, - np.array(all_rewards, dtype=np.float32), - np.array(all_term), - all_info, - ) + self.step_async(action) + return self.step_wait() def reset(self) -> Dict[str, np.ndarray]: # Initialize lists for collecting results @@ -142,14 +108,40 @@ def set_attr(self): raise NotImplementedError() def step_async(self, actions: np.ndarray) -> None: - # Execute the step function asynchronously, not actually implemented in this setting - self.results = self.step(actions) + # Send the actions to every environment, then return without waiting for the results + num_envs = self.envs[0].num_envs + + for i in range(self.n_parallel): + self.envs[i].step_send(actions[i * num_envs : (i + 1) * num_envs]) def step_wait( self, ) -> Tuple[Dict[str, np.ndarray], np.ndarray, np.ndarray, List[Dict[str, Any]]]: - # Wait for the results from the asynchronous step - return self.results + # Collect the results of the actions sent by step_async + all_obs = [] + all_rewards = [] + all_term = [] + all_trunc = [] + all_info = [] + + for i in range(self.n_parallel): + obs, reward, term, trunc, info = self.envs[i].step_recv() + all_obs.extend(obs) + all_rewards.extend(reward) + all_term.extend(term) + all_trunc.extend(trunc) + all_info.extend(info) + + # Convert list of dictionaries to dictionary of lists + obs = lod_to_dol(all_obs) + + # Return results + return ( + {k: np.array(v) for k, v in obs.items()}, + np.array(all_rewards, dtype=np.float32), + np.array(all_term), + all_info, + ) def stable_baselines_training(args, extras, n_steps: int = 200000, **kwargs) -> None: diff --git a/tests/test_sb3_step_async.py b/tests/test_sb3_step_async.py new file mode 100644 index 00000000..b3f66fa7 --- /dev/null +++ b/tests/test_sb3_step_async.py @@ -0,0 +1,85 @@ +import numpy as np + +from godot_rl.wrappers.stable_baselines_wrapper import StableBaselinesGodotEnv + + +class FakeGodotEnv: + """Stand in for GodotEnv that records the order of the send and receive calls.""" + + def __init__(self, index, num_envs, calls): + self.index = index + self.num_envs = num_envs + self.calls = calls + self.sent_actions = None + + def step_send(self, action): + self.calls.append(("send", self.index)) + self.sent_actions = action + + def step_recv(self): + self.calls.append(("recv", self.index)) + obs = [{"obs": np.full(2, float(self.index))} for _ in range(self.num_envs)] + reward = [float(self.index)] * self.num_envs + term = [False] * self.num_envs + trunc = [False] * self.num_envs + info = [{}] * self.num_envs + return obs, reward, term, trunc, info + + +def make_env(n_parallel=3, num_envs=2): + # Bypass __init__ so no Godot game is launched + env = object.__new__(StableBaselinesGodotEnv) + calls = [] + env.envs = [FakeGodotEnv(i, num_envs, calls) for i in range(n_parallel)] + env.n_parallel = n_parallel + return env, calls + + +def test_step_async_only_sends(): + env, calls = make_env() + env.step_async(np.zeros((6, 1))) + assert calls == [("send", 0), ("send", 1), ("send", 2)] + + +def test_step_wait_collects_after_step_async(): + env, calls = make_env() + env.step_async(np.zeros((6, 1))) + env.step_wait() + assert [kind for kind, _ in calls] == ["send"] * 3 + ["recv"] * 3 + + +def test_step_still_sends_everything_before_the_first_receive(): + env, calls = make_env() + env.step(np.zeros((6, 1))) + assert [kind for kind, _ in calls] == ["send"] * 3 + ["recv"] * 3 + + +def test_actions_are_split_across_environments(): + env, _ = make_env(n_parallel=3, num_envs=2) + env.step_async(np.arange(6).reshape(6, 1)) + assert env.envs[0].sent_actions.tolist() == [[0], [1]] + assert env.envs[1].sent_actions.tolist() == [[2], [3]] + assert env.envs[2].sent_actions.tolist() == [[4], [5]] + + +def test_results_keep_the_environment_order(): + env, _ = make_env(n_parallel=3, num_envs=2) + obs, rewards, dones, infos = env.step(np.zeros((6, 1))) + assert rewards.tolist() == [0.0, 0.0, 1.0, 1.0, 2.0, 2.0] + assert obs["obs"].shape == (6, 2) + assert dones.tolist() == [False] * 6 + assert len(infos) == 6 + + +def test_step_and_the_async_pair_agree(): + env_a, _ = make_env() + env_b, _ = make_env() + actions = np.arange(6).reshape(6, 1) + + obs_a, rewards_a, dones_a, _ = env_a.step(actions) + env_b.step_async(actions) + obs_b, rewards_b, dones_b, _ = env_b.step_wait() + + assert np.array_equal(obs_a["obs"], obs_b["obs"]) + assert np.array_equal(rewards_a, rewards_b) + assert np.array_equal(dones_a, dones_b) From a81a7bedf656bb77ddbc79da897b02e78f9cf0a9 Mon Sep 17 00:00:00 2001 From: Eliasepfl Date: Wed, 9 Sep 2026 06:21:01 -0400 Subject: [PATCH 2/3] Keep the step_async tests importable without stable_baselines3 The rllib CI jobs uninstall stable_baselines3 before running the suite, so a module level import of the sb3 wrapper turns into a pytest collection error and takes the whole run down. Import the wrapper inside the helper that builds the env and skip the module when ray is present, as the other sb3 tests already do. --- tests/test_sb3_step_async.py | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/tests/test_sb3_step_async.py b/tests/test_sb3_step_async.py index b3f66fa7..2b1d4883 100644 --- a/tests/test_sb3_step_async.py +++ b/tests/test_sb3_step_async.py @@ -1,6 +1,11 @@ import numpy as np +import pytest -from godot_rl.wrappers.stable_baselines_wrapper import StableBaselinesGodotEnv +from godot_rl.core.utils import can_import + +# The sb3 wrapper imports stable_baselines3, which the rllib CI job uninstalls, so it is +# imported inside the helper below and the whole module is skipped when ray is present. +pytestmark = pytest.mark.skipif(can_import("ray"), reason="rllib and sb3 are not compatable") class FakeGodotEnv: @@ -27,6 +32,8 @@ def step_recv(self): def make_env(n_parallel=3, num_envs=2): + from godot_rl.wrappers.stable_baselines_wrapper import StableBaselinesGodotEnv + # Bypass __init__ so no Godot game is launched env = object.__new__(StableBaselinesGodotEnv) calls = [] From 31e80f85848bf7ec51c30c01ace4043d9389e89e Mon Sep 17 00:00:00 2001 From: Eliasepfl Date: Wed, 9 Sep 2026 07:43:13 -0400 Subject: [PATCH 3/3] Move the single obs projection onto the step_async/step_wait pair SBGSingleObsEnv only overrode step(), which worked because step_async used to be self.results = self.step(actions), a virtual call. Now that step_async and step_wait do the work themselves, sb3 never enters the subclass step(): VecEnv.step calls the pair, VecEnvWrapper forwards step_async and VecMonitor forwards step_wait. examples/sb3_imitation.py wraps SBGSingleObsEnv in VecMonitor and trains an MlpPolicy, so it would receive the dict observation instead of the array behind obs_key, and lose the terminal_observation the imitation path needs. Override step_wait instead, which both the async pair and the inherited step() now go through. The test drives the subclass through a real VecMonitor and fails without this change. --- godot_rl/wrappers/sbg_single_obs_wrapper.py | 6 ++-- tests/test_sb3_step_async.py | 34 +++++++++++++++++++-- 2 files changed, 35 insertions(+), 5 deletions(-) diff --git a/godot_rl/wrappers/sbg_single_obs_wrapper.py b/godot_rl/wrappers/sbg_single_obs_wrapper.py index 2f261c19..1f41fd0a 100644 --- a/godot_rl/wrappers/sbg_single_obs_wrapper.py +++ b/godot_rl/wrappers/sbg_single_obs_wrapper.py @@ -14,8 +14,10 @@ def __init__(self, obs_key="obs", *args, **kwargs) -> None: self.obs_key = obs_key super().__init__(*args, **kwargs) - def step(self, action: np.ndarray) -> Tuple[np.ndarray, np.ndarray, np.ndarray, List[Dict[str, Any]]]: - obs, rewards, term, info = super().step(action) + def step_wait(self) -> Tuple[np.ndarray, np.ndarray, np.ndarray, List[Dict[str, Any]]]: + # The projection lives here rather than in step() because sb3 drives a vec env through + # the step_async/step_wait pair, so a step() override alone would be bypassed. + obs, rewards, term, info = super().step_wait() # Terminal obs info is needed for imitation learning for idx, done in enumerate(term): diff --git a/tests/test_sb3_step_async.py b/tests/test_sb3_step_async.py index 2b1d4883..dbbe1a9d 100644 --- a/tests/test_sb3_step_async.py +++ b/tests/test_sb3_step_async.py @@ -1,3 +1,4 @@ +import gymnasium as gym import numpy as np import pytest @@ -11,11 +12,14 @@ class FakeGodotEnv: """Stand in for GodotEnv that records the order of the send and receive calls.""" - def __init__(self, index, num_envs, calls): + def __init__(self, index, num_envs, calls, terminate=False): self.index = index self.num_envs = num_envs self.calls = calls self.sent_actions = None + self.terminate = terminate + self.observation_space = gym.spaces.Dict({"obs": gym.spaces.Box(-np.inf, np.inf, shape=(2,))}) + self.action_space = gym.spaces.Box(-1.0, 1.0, shape=(1,)) def step_send(self, action): self.calls.append(("send", self.index)) @@ -25,9 +29,9 @@ def step_recv(self): self.calls.append(("recv", self.index)) obs = [{"obs": np.full(2, float(self.index))} for _ in range(self.num_envs)] reward = [float(self.index)] * self.num_envs - term = [False] * self.num_envs + term = [self.terminate] * self.num_envs trunc = [False] * self.num_envs - info = [{}] * self.num_envs + info = [{} for _ in range(self.num_envs)] return obs, reward, term, trunc, info @@ -90,3 +94,27 @@ def test_step_and_the_async_pair_agree(): assert np.array_equal(obs_a["obs"], obs_b["obs"]) assert np.array_equal(rewards_a, rewards_b) assert np.array_equal(dones_a, dones_b) + + +def test_the_single_obs_subclass_is_still_applied_through_the_async_pair(): + # SBGSingleObsEnv only overrode step(), which used to sit on the async path because + # step_async called self.step(). sb3 drives a vec env through step_async/step_wait, so + # the subclass has to sit on that pair or its projection is silently skipped. + from stable_baselines3.common.vec_env.vec_monitor import VecMonitor + + from godot_rl.wrappers.sbg_single_obs_wrapper import SBGSingleObsEnv + + calls = [] + env = object.__new__(SBGSingleObsEnv) + env.obs_key = "obs" + env.envs = [FakeGodotEnv(i, 2, calls, terminate=True) for i in range(2)] + env.n_parallel = 2 + + obs, _, dones, infos = VecMonitor(env).step(np.zeros((4, 1))) + + # The observation must match observation_space, which is the Box behind obs_key + assert isinstance(obs, np.ndarray), f"expected the projected array, got {type(obs)}" + assert obs.shape == (4, 2) + # Terminal obs info is needed for imitation learning + assert all(dones) + assert all("terminal_observation" in info for info in infos)