-
Notifications
You must be signed in to change notification settings - Fork 2k
Add PAL to approximate Prioritized Experience Replay #2199
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
bilelsgh
wants to merge
8
commits into
DLR-RM:master
Choose a base branch
from
bilelsgh:pal
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+84
−6
Conversation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Doctring imrovement
Author
|
Here is the code used for testing import gymnasium as gym
from gymnasium import spaces
from loguru import logger
from stable_baselines3 import DQN
from stable_baselines3.common.buffers import PALReplayBuffer
from stable_baselines3.common.env_util import make_atari_env
from stable_baselines3.common.evaluation import evaluate_policy
from stable_baselines3.common.torch_layers import BaseFeaturesExtractor
from stable_baselines3.common.vec_env import VecFrameStack
import torch.nn as nn
import torch as th
import ale_py
class CustomCNN(BaseFeaturesExtractor):
"""
:param observation_space: (gym.Space)
:param features_dim: (int) Number of features extracted.
This corresponds to the number of unit for the last layer.
"""
def __init__(self, observation_space: spaces.Box, features_dim: int = 256):
super().__init__(observation_space, features_dim)
n_input_channels = observation_space.shape[0]
self.cnn = nn.Sequential(
nn.Conv2d(n_input_channels, 32, kernel_size=8, stride=4, padding=0),
nn.ReLU(),
nn.Conv2d(32, 32, kernel_size=4, stride=2, padding=0),
nn.ReLU(),
nn.Conv2d(32, 64, kernel_size=2, stride=1, padding=0),
nn.ReLU(),
nn.Flatten(),
)
# Compute shape by doing one forward pass
with th.no_grad():
n_flatten = self.cnn(
th.as_tensor(observation_space.sample()[None]).float()
).shape[1]
self.linear = nn.Sequential(nn.Linear(n_flatten, features_dim), nn.ReLU())
def forward(self, observations: th.Tensor) -> th.Tensor:
return self.linear(self.cnn(observations))
def drl():
env_names = ['LunarLander-v3']
for env_name in env_names :
for buffer in [None, PALReplayBuffer]:
logger.info(f"Training on {env_name} with buffer: {buffer}")
log_name = f"{env_name}_classic" if not buffer else f"{env_name}_PAL"
env = gym.make(env_name)
model = DQN("MlpPolicy",
env,
replay_buffer_class=buffer,
tensorboard_log="./board",
verbose=0,
device="mps")
model.learn(total_timesteps=300000, log_interval=4, tb_log_name=log_name)
def drl_atari():
gym.register_envs(ale_py)
atari_games = [
'ALE/Breakout-v5',
'ALE/SpaceInvaders-v5',
'ALE/Riverraid-v5'
]
policy_kwargs = dict(
features_extractor_class=CustomCNN,
features_extractor_kwargs=dict(features_dim=512),
)
for game in atari_games:
for buffer in [None]: #PALReplayBuffer]:
log_name = f"{game.split('/')[-1]}_classic" if not buffer else f"{game.split('/')[-1]}_PAL"
logger.info(f"Training on {game} with buffer: {buffer}")
env = make_atari_env(game, n_envs=1, seed=42)
env = VecFrameStack(env, n_stack=4) # Stack de 4 frames
model = DQN(
"CnnPolicy", # CNN pour images
env,
replay_buffer_class=buffer,
learning_starts=10000,
batch_size=32,
exploration_fraction=0.1,
exploration_final_eps=0.05,
tensorboard_log="./atari_board",
verbose=0,
device="mps",
policy_kwargs=policy_kwargs,
)
model.learn(total_timesteps=300000, log_interval=4, tb_log_name=log_name)
if __name__ == '__main__':
#drl()
drl_atari() |
16 tasks
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Feature overview
Implementation of Prioritized Approximation Loss (PAL), an computationally efficient approximation of the Prioritized Experience Replay (PER).
A NeurIPS 2020 paper shows that using PER is equivalent to adapting the loss function while using uniform experience replay.
This means we can avoid managing a sorted buffer and the associated complexity, while still converging to the same gradient.
PAL is a very good alternative while waiting for an effective implementation of the Prioritized Experience Replay while being computationally efficient.
Description
I've added a new loss function, which adapts the Huber Loss by incorporating priority as described in the referenced paper. The buffer itself performs uniform sampling (ReplayBuffer). Additionally, I implemented a PALReplayBuffer (and let the PrioritizedReplayBuffer for the Rainbow implementation (👋 @araffin) #622) to initialize the PAL parameters (following the paper) and to properly handle the case where the PAL is applied within the training method.
Test
The PAL was evaluated on 3 environments including 2 ATARI games that were also evaluated on the PAL paper. The results are displayed in the comments. The architecture of the NN and the DRL parameters are the same as in the PAL paper.
n_input_channelsn_flatten)n_flattenfeatures_dimAtari games
For both Breakout and SpaceInvaders, the reward converges faster to higher value.

Classic env
PAL leads to a better reward on Lunar Lander

It's important to remember that PER (and then PAL) doesn't necessarily lead to better reward every time but depends on the context and the environment where the agent evolves.
Motivation and Context
In accordance with @AlexPasqua PR Prioritized experience replay #1622 (and the corresponding issue Prioritized Experience Replay for DQN #1242)
Types of changes
Checklist
make format(required)make check-codestyleandmake lint(required)make pytestandmake typeboth pass. (required)make doc(required)Note: You can run most of the checks using
make commit-checks.Note: we are using a maximum length of 127 characters per line