class NoopResetEnv(gym.Wrapper):
def init(self, env, noop_max=30):
"""Sample initial states by taking random number of no-ops on reset.
No-op is assumed to be action 0.
"""
gym.Wrapper.init(self, env)
self.noop_max = noop_max
self.override_num_noops = None
self.noop_action = 0
assert env.unwrapped.get_action_meanings()[0] == 'NOOP'
def reset(self, **kwargs):
""" Do no-op action for a number of steps in [1, noop_max]."""
self.env.reset(**kwargs)
if self.override_num_noops is not None:
noops = self.override_num_noops
else:
noops = self.unwrapped.np_random.integers(1, self.noop_max + 1)
#noops = self.unwrapped.np_random.randint(1, self.noop_max + 1) #pylint: disable=E1101
assert noops > 0
obs, info = None, None
for _ in range(noops):
obs, _, terminated, truncated, info = self.env.step(self.noop_action)
done = terminated or truncated
if done:
obs, info = self.env.reset(**kwargs)
return obs, info
def step(self, ac):
return self.env.step(ac)
class FireResetEnv(gym.Wrapper):
def init(self, env):
"""Take action on reset for environments that are fixed until firing."""
gym.Wrapper.init(self, env)
assert env.unwrapped.get_action_meanings()[1] == 'FIRE'
assert len(env.unwrapped.get_action_meanings()) >= 3
def reset(self, **kwargs):
self.env.reset(**kwargs)
obs, _, terminated, truncated, info = self.env.step(1)
done = terminated or truncated
if done:
self.env.reset(**kwargs)
obs, _, terminated, truncated, info = self.env.step(2)
done = terminated or truncated
if done:
self.env.reset(**kwargs)
return obs, info
def step(self, ac):
return self.env.step(ac)
class EpisodicLifeEnv(gym.Wrapper):
def init(self, env):
"""Make end-of-life == end-of-episode, but only reset on true game over.
Done by DeepMind for the DQN and co. since it helps value estimation.
"""
gym.Wrapper.init(self, env)
self.lives = 0
self.was_real_done = True
def step(self, action):
obs, reward, terminated, truncated, info = self.env.step(action)
done = terminated or truncated
self.was_real_done = done
# check current lives, make loss of life terminal,
# then update lives to handle bonus lives
lives = self.env.unwrapped.ale.lives()
if lives < self.lives and lives > 0:
# for Qbert sometimes we stay in lives == 0 condition for a few frames
# so it's important to keep lives > 0, so that we only reset once
# the environment advertises done.
done = True
self.lives = lives
return obs, reward, terminated, truncated, info
def reset(self, **kwargs):
"""Reset only when lives are exhausted.
This way all states are still reachable even though lives are episodic,
and the learner need not know about any of this behind-the-scenes.
"""
if self.was_real_done:
obs, info = self.env.reset(**kwargs)
else:
# no-op step to advance from terminal/lost life state
obs, _, _, _, info = self.env.step(0)
self.lives = self.env.unwrapped.ale.lives()
return obs, info
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
class MaxAndSkipEnv(gym.Wrapper):
def init(self, env, skip=4):
"""Return only every skip-th frame"""
gym.Wrapper.init(self, env)
# most recent raw observations (for max pooling across time steps)
self._obs_buffer = np.zeros((2,)+env.observation_space.shape, dtype=np.uint8)
self._skip = skip
def step(self, action):
"""Repeat action, sum reward, and max over last observations."""
total_reward = 0.0
done = None
for i in range(self._skip):
obs, reward, terminated, truncated, info = self.env.step(action)
done = terminated or truncated
if i == self._skip - 2: self._obs_buffer[0] = obs
if i == self._skip - 1: self._obs_buffer[1] = obs
total_reward += reward
if done:
break
# Note that the observation on the done=True frame
# doesn't matter
max_frame = self._obs_buffer.max(axis=0)
return max_frame, total_reward, terminated, truncated, info
def reset(self, **kwargs):
return self.env.reset(**kwargs)
class ClipRewardEnv(gym.RewardWrapper):
def init(self, env):
gym.RewardWrapper.init(self, env)
def reward(self, reward):
"""Bin reward to {+1, 0, -1} by its sign."""
return np.sign(reward)
class WarpFrame(gym.ObservationWrapper):
def init(self, env, width=84, height=84, grayscale=True, dict_space_key=None):
"""
Warp frames to 84x84 as done in the Nature paper and later work.
If the environment uses dictionary observations, `dict_space_key` can be specified which indicates which
observation should be warped.
"""
super().__init__(env)
self._width = width
self._height = height
self._grayscale = grayscale
self._key = dict_space_key
if self._grayscale:
num_colors = 1
else:
num_colors = 3
new_space = gym.spaces.Box(
low=0,
high=255,
shape=(self._height, self._width, num_colors),
dtype=np.uint8,
)
if self._key is None:
original_space = self.observation_space
self.observation_space = new_space
else:
original_space = self.observation_space.spaces[self._key]
self.observation_space.spaces[self._key] = new_space
assert original_space.dtype == np.uint8 and len(original_space.shape) == 3
def observation(self, obs):
if self._key is None:
frame = obs
else:
frame = obs[self._key]
if self._grayscale:
frame = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY)
frame = cv2.resize(
frame, (self._width, self._height), interpolation=cv2.INTER_AREA
)
if self._grayscale:
frame = np.expand_dims(frame, -1)
if self._key is None:
obs = frame
else:
obs = obs.copy()
obs[self._key] = frame
return obs
class FrameStack(gym.Wrapper):
def init(self, env, k):
"""Stack k last frames.
Returns lazy array, which is much more memory efficient.
See Also
--------
baselines.common.atari_wrappers.LazyFrames
"""
gym.Wrapper.__init__(self, env)
self.k = k
self.frames = deque([], maxlen=k)
shp = env.observation_space.shape
self.observation_space = spaces.Box(low=0, high=255, shape=(shp[:-1] + (shp[-1] * k,)), dtype=env.observation_space.dtype)
def reset(self):
ob, info = self.env.reset()
for _ in range(self.k):
self.frames.append(ob)
return self._get_ob(), info
def step(self, action):
ob, reward, terminated, truncated, info = self.env.step(action)
done = terminated or truncated
self.frames.append(ob)
return self._get_ob(), reward, terminated, truncated, info
def _get_ob(self):
assert len(self.frames) == self.k
return LazyFrames(list(self.frames))
def observation(self, observation):
# careful! This undoes the memory optimization, use
# with smaller replay buffers only.
return np.array(observation).astype(np.float32) / 255.0
class LazyFrames(object):
def init(self, frames):
"""This object ensures that common frames between the observations are only stored once.
It exists purely to optimize memory usage which can be huge for DQN's 1M frames replay
buffers.
This object should only be converted to numpy array before being passed to the model.
You'd not believe how complex the previous solution was."""
self._frames = frames
self._out = None
def _force(self):
if self._out is None:
self._out = np.concatenate(self._frames, axis=-1)
self._frames = None
return self._out
def __array__(self, dtype=None):
out = self._force()
if dtype is not None:
out = out.astype(dtype)
return out
def __len__(self):
return len(self._force())
def __getitem__(self, i):
return self._force()[i]
def count(self):
frames = self._force()
return frames.shape[frames.ndim - 1]
def frame(self, i):
return self._force()[..., i]
def make_atari(env_id, max_episode_steps=None, render=None):
env = gym.make(env_id, render_mode=render)
assert 'NoFrameskip' in env.spec.id
env = NoopResetEnv(env, noop_max=30)
env = MaxAndSkipEnv(env, skip=4)
if max_episode_steps is not None:
env = TimeLimit(env, max_episode_steps=max_episode_steps)
return env
def wrap_deepmind(env, episode_life=True, clip_rewards=True, frame_stack=False, scale=False):
"""Configure environment for DeepMind-style Atari.
"""
if episode_life:
env = EpisodicLifeEnv(env)
if 'FIRE' in env.unwrapped.get_action_meanings():
env = FireResetEnv(env)
env = WarpFrame(env)
if scale:
env = ScaledFloatFrame(env)
if clip_rewards:
env = ClipRewardEnv(env)
if frame_stack:
env = FrameStack(env, 4)
return env
num_episodes = 10000 # Number of episodes to run
max_steps = 500000 # Maximum steps per episode
N = 20
total_steps = 0
epsilon = 0
print(f"Training for {num_episodes} episodes.\nMax steps for episode: {max_steps}.\nGLHF.")
episode_rewards = []
start_training_time = time.time()
for episode in range(num_episodes):
episode_training_time = time.time()
observation, info = env.reset() # Reset the environment at the start of each episode
observation = np.transpose(observation, [2, 0, 1])
total_reward = 0
for step in range(max_steps):
action, prob, val = agent.choose_action(observation)
observation_, reward, truncated, terminated, info = env.step(action)
observation_ = np.transpose(observation_, [2, 0, 1])
done = terminated or truncated
agent.remember(observation, action, prob, val, reward, done)
#epsilon = agent.learn()
if total_steps % N == 0:
agent.learn()
total_reward += reward
total_steps += 1
if done:
break
observation = observation_
episode_rewards.append(total_reward)
print(
f"Episode {episode + 1} terminated after {time.time() - episode_training_time} seconds and {step + 1}/{total_steps} steps.\nEpsilon value: {epsilon}. Total reward: {total_reward}.\nAverage score on last 50 episodes: {np.mean(episode_rewards[-50:])}.")
if (episode+1) % 500 == 0:
agent.save_models()
env.close()
Given my code above, can you help me employ 8 vectorial environments?
To employ 8 vectorized environments in your code, you need to adjust several parts of your implementation to handle batched observations, actions, and other data. Here's how you can modify your code accordingly:
1. Create Vectorized Environments
Firstly, you need to create a vectorized environment that runs multiple instances of your environment in parallel. You can use gym.vector.SyncVectorEnv or gym.vector.AsyncVectorEnv for this purpose. Here's how you can do it:
import gym
from gym.vector import SyncVectorEnv
num_envs = 8
def create_env(seed):
def _init():
env = make_atari("PongNoFrameskip-v4", 100000, render=None)
env = wrap_deepmind(env, True, True, True, True)
env.seed(seed)
return env
return _init
envs = SyncVectorEnv([create_env(i) for i in range(num_envs)])
This code creates 8 synchronized environments. Each environment is initialized with a different seed to ensure diverse experiences.
2. Adjust the Agent to Handle Batched Observations
Modify your Agent class's choose_action method to handle batch inputs and outputs:
class Agent:
# ... existing code ...
def choose_action(self, observations):
# observations shape: [num_envs, channels, height, width]
states = T.tensor(observations, dtype=T.float).to(self.actor.device)
dist = self.actor(states)
values = self.critic(states)
actions = dist.sample()
probs = dist.log_prob(actions)
# No need to squeeze or convert to items; keep tensors as-is
# actions shape: [num_envs]
# probs shape: [num_envs]
# values shape: [num_envs]
return actions.cpu().numpy(), probs.cpu().detach().numpy(), values.cpu().detach().numpy()
Here, observations is a NumPy array of shape [num_envs, channels, height, width]. The method returns NumPy arrays for actions, probs, and values.
3. Adjust the Memory to Store Batched Data
Modify your PPOMemory class to store batched data:
Here, states, actions, probs, vals, rewards, and dones are arrays or lists containing data for all environments.
4. Adjust the Main Training Loop
Modify your main training loop to handle batched data:
num_episodes = 10000
max_steps = 500000
N = 20
total_steps = 0
print(f"Training for {num_episodes} episodes.\nMax steps per episode: {max_steps}.\nGLHF.")
episode_rewards = []
start_training_time = time.time()
for episode in range(num_episodes):
episode_training_time = time.time()
observations = envs.reset()
# Transpose observations if necessary
observations = np.transpose(observations, [0, 3, 1, 2]) # [num_envs, channels, height, width]
total_rewards = np.zeros(num_envs)
done_flags = np.zeros(num_envs, dtype=bool)
for step in range(max_steps):
actions, probs, vals = agent.choose_action(observations)
observations_, rewards, dones, infos = envs.step(actions)
observations_ = np.transpose(observations_, [0, 3, 1, 2])
agent.remember(observations, actions, probs, vals, rewards, dones)
if total_steps % N == 0:
agent.learn()
total_rewards += rewards
total_steps += 1
# Update the observations for environments that are not done
observations = observations_
done_flags = np.logical_or(done_flags, dones)
if np.all(done_flags):
break
episode_rewards.append(np.mean(total_rewards))
print(
f"Episode {episode + 1} terminated after {time.time() - episode_training_time:.2f} seconds."
f" Total reward: {np.mean(total_rewards)}."
f" Average score over last 50 episodes: {np.mean(episode_rewards[-50:]):.2f}."
)
if (episode + 1) % 500 == 0:
agent.save_models()
In this loop:
observations is an array of shape [num_envs, channels, height, width].
actions is an array of shape [num_envs].
rewards, dones are arrays of shape [num_envs].
We track total_rewards and done_flags for all environments.
5. Ensure the Network Accepts Batched Inputs
Your ActorConvNetwork and CriticConvNetwork should already accept batched inputs, as PyTorch modules handle batch dimensions by default.
6. Adjust the Learning Method to Handle Batches
Ensure that your agent.learn() method handles batched data properly. Since PPOMemory.generate_batches() returns arrays now, ensure your learning loop in agent.learn() iterates over the correct dimensions.
7. Transpose Observations Correctly
Depending on how your WarpFrame and FrameStack wrappers work, you may need to adjust the axes when transposing observations. Verify the shape of observations after reset and step to ensure consistency.
Full Adjusted Agent Class
Here's the adjusted Agent class with the modifications:
class Agent:
def __init__(self, n_actions, input_dims, gamma=0.99, alpha=0.0003, gae_lambda=0.95,
policy_clip=0.2, batch_size=64, n_epochs=10):
# ... existing initialization code ...
def remember(self, states, actions, probs, vals, rewards, dones):
self.memory.store_memory(states, actions, probs, vals, rewards, dones)
def choose_action(self, observations):
states = T.tensor(observations, dtype=T.float).to(self.actor.device)
dist = self.actor(states)
values = self.critic(states)
actions = dist.sample()
probs = dist.log_prob(actions)
# No need to squeeze; keep tensors as-is
actions = actions.cpu().numpy()
probs = probs.cpu().detach().numpy()
values = values.squeeze(1).cpu().detach().numpy()
return actions, probs, values
def learn(self):
# ... existing learning code ...
# Ensure all tensors and arrays are handled in batch
Notes on Learning Method
In your learn method, make sure you handle all computations in batches:
When computing advantages, iterate over the batch dimension.
When computing losses, make sure tensor dimensions align correctly.
Final Remarks
By making these adjustments, you can effectively employ 8 vectorized environments in your training loop. This will allow you to collect experiences from multiple environments in parallel, increasing the efficiency of your training process.
Remember to test your code thoroughly to ensure that all dimensions and data types are handled correctly.