This tutorial walks you through the fundamentals of Deep Reinforcement
Learning. At the end, you will implement an AI-powered Mario (using
) that
can play the game by itself.
Although no prior knowledge of RL is necessary for this tutorial, you
can familiarize yourself with these RL
concepts,
and have this handy
cheatsheet
as your companion. The full code is available
here.
importtorchfromtorchimportnnfromtorchvisionimporttransformsasTfromPILimportImageimportnumpyasnpfrompathlibimportPathfromcollectionsimportdequeimportrandom,datetime,os# Gym is an OpenAI toolkit for RLimportgymfromgym.spacesimportBoxfromgym.wrappersimportFrameStack# NES Emulator for OpenAI Gymfromnes_py.wrappersimportJoypadSpace# Super Mario environment for OpenAI Gymimportgym_super_mario_brosfromtensordictimportTensorDictfromtorchrl.dataimportTensorDictReplayBuffer,LazyMemmapStorage
Gym has been unmaintained since 2022 and does not support NumPy 2.0 amongst other critical functionality.
Please upgrade to Gymnasium, the maintained drop-in replacement of Gym, or contact the authors of your software and request that they upgrade.
Users of this version of Gym should be able to simply replace 'import gym' with 'import gymnasium as gym' in the vast majority of cases.
See the migration guide at https://gymnasium.farama.org/introduction/migration_guide/ for additional information.
/usr/local/lib/python3.12/dist-packages/torchrl/__init__.py:48: UserWarning: failed to set start method to spawn, and current start method for mp is fork.
warn(
RL Definitions
Environment The world that an agent interacts with and learns from.
Actiona : How the Agent responds to the Environment. The
set of all possible Actions is called action-space.
States : The current characteristic of the Environment. The
set of all possible States the Environment can be in is called
state-space.
Rewardr : Reward is the key feedback from Environment to
Agent. It is what drives the Agent to learn and to change its future
action. An aggregation of rewards over multiple time steps is called
Return.
Optimal Action-Value functionQ∗(s,a) : Gives the expected
return if you start in state s, take an arbitrary action
a, and then for each future time step take the action that
maximizes returns. Q can be said to stand for the “quality” of
the action in a state. We try to approximate this function.
Environment
Initialize Environment
In Mario, the environment consists of tubes, mushrooms and other
components.
When Mario makes an action, the environment responds with the changed
(next) state, reward and other info.
# Initialize Super Mario environment (in v0.26 change render mode to 'human' to see results on the screen)ifgym.__version__<'0.26':env=gym_super_mario_bros.make("SuperMarioBros-1-1-v0",new_step_api=True)else:env=gym_super_mario_bros.make("SuperMarioBros-1-1-v0",render_mode='rgb',apply_api_compatibility=True)# Limit the action-space to# 0. walk right# 1. jump rightenv=JoypadSpace(env,[["right"],["right","A"]])env.reset()next_state,reward,done,trunc,info=env.step(action=0)print(f"{next_state.shape},\n{reward},\n{done},\n{info}")
/usr/local/lib/python3.12/dist-packages/gym/envs/registration.py:555:UserWarning: WARN:The environment SuperMarioBros-1-1-v0 is out of date.You should consider upgrading to version `v3`.
logger.warn(/usr/local/lib/python3.12/dist-packages/gym/envs/registration.py: WARN environment creator metadata doesnrendermodesvideoframes_per_second'
Preprocess Environment
Environment data is returned to the agent in next_state. As you saw
above, each state is represented by a [3,240,256] size array.
Often that is more information than our agent needs; for instance,
Mario’s actions do not depend on the color of the pipes or the sky!
We use Wrappers to preprocess environment data before sending it to
the agent.
GrayScaleObservation is a common wrapper to transform an RGB image
to grayscale; doing so reduces the size of the state representation
without losing useful information. Now the size of each state:
[1,240,256]
ResizeObservation downsamples each observation into a square image.
New size: [1,84,84]
SkipFrame is a custom wrapper that inherits from and
implements the function. Because consecutive frames don’t
vary much, we can skip n-intermediate frames without losing much
information. The n-th frame aggregates rewards accumulated over each
skipped frame.
Agent
We create a class Mario to represent our agent in the game. Mario
should be able to:
Act according to the optimal action policy based on the current
state (of the environment).
Remember experiences. Experience = (current state, current
action, reward, next state). Mario caches and later recalls his
experiences to update his action policy.
Learn a better action policy over time
classMario:def__init__():passdefact(self,state):"""Given a state, choose an epsilon-greedy action"""passdefcache(self,experience):"""Add the experience to memory"""passdefrecall(self):"""Sample experiences from memory"""passdeflearn(self):"""Update online action value (Q) function with a batch of experiences"""pass
In the following sections, we will populate Mario’s parameters and
define his functions.
Act
For any given state, an agent can choose to do the most optimal action
(exploit) or a random action (explore).
Mario randomly explores with a chance of self.exploration_rate; when
he chooses to exploit, he relies on MarioNet (implemented in
Learn section) to provide the most optimal action.
These two functions serve as Mario’s “memory” process.
cache(): Each time Mario performs an action, he stores the
experience to his memory. His experience includes the current
state, action performed, reward from the action, the next state,
and whether the game is done.
recall(): Mario randomly samples a batch of experiences from his
memory, and uses that to learn the game.
classMario(Mario):# subclassing for continuitydef__init__(self,state_dim
Learn
Mario uses the DDQN algorithm
under the hood. DDQN uses two ConvNets - Qonline and
Qtarget - that independently approximate the optimal
action-value function.
In this example we run the training loop for 40 episodes, but for Mario to truly learn the ways of
his world, we suggest running the loop for at least 40,000 episodes!
use_cuda=torch.cuda.is_available()print(f"Using CUDA: {use_cuda}")print()save_dir=Path("checkpoints")/datetime.datetime.now().strftime("%Y-%m-%dT%H-%M-%S")save_dir.mkdir(parents=True)mario=Mario(state_dim=(4,84,84),action_dim=env.action_space.n,save_dir=save_dir)logger=MetricLogger(save_dir)episodes=40foreinrange(episodes):state=env.reset()# Play the game!whileTrue:# Run agent on the stateaction=mario.act(state)# Agent performs actionnext_state,reward,done,trunc,info=env.step(action)# Remembermario.cache(state,next_state,action,reward,done)# Learnq,loss=mario.learn()# Logginglogger.log_step(reward,loss,q)# Update statestate=next_state# Check if end of gameifdoneorinfo["flag_get"]:breaklogger.log_episode()if(e%20==0)or(e==episodes-1):logger.record(episode=e,epsilon=mario.exploration_rate,step=mario.curr_step)
Using CUDA: True
Episode 0 - Step 471 - Epsilon 0.9998822569175251 - Mean Reward 977.0 - Mean Length 471.0 - Mean Loss 0.0 - Mean Q Value 0.0 - Time Delta 3.359 - Time 2026-11-06T20:34:15
Episode 20 - Step 4077 - Epsilon 0.9989812691314297 - Mean Reward 684.714 - Mean Length 194.143 - Mean Loss 0.0 - Mean Q Value 0.0 - Time Delta 28.198 - Time 2026-11-06T20:34:44
Episode 39 - Step 7554 - Epsilon 0.9981132818582383 - Mean Reward 670.425 - Mean Length 188.85 - Mean Loss 0.0 - Mean Q Value 0.0 - Time Delta 27.617 - Time 2026-11-06T20:35:11
Conclusion
In this tutorial, we saw how we can use PyTorch to train a game-playing AI. You can use the same methods
to train an AI to play any of the games at the OpenAI gym. Hope you enjoyed this tutorial, feel free to reach us at
our github!
Total running time of the script: (1 minutes 0.211 seconds)
/usr/local/lib/python3.12/dist-packages/gym/utils/passive_env_checker.py:233:DeprecationWarning: `np.bool8` is a deprecated alias for `np.bool_`.(DeprecatedNumPy1.24)
FrameStack is a wrapper that allows us to squash consecutive frames
of the environment into a single observation point to feed to our
learning model. This way, we can identify if Mario was landing or
jumping based on the direction of his movement in the previous several
frames.
classSkipFrame(gym.Wrapper):def__init__(self,env,skip):"""Return only every `skip`-th frame"""super().__init__(env)self._skip=skipdefstep(self,action):"""Repeat action, and sum reward"""total_reward=0.0foriinrange(self._skip):# Accumulate reward and repeat the same actionobs,reward,done,trunk,info=self.env.step(action)total_reward+=rewardifdone:breakreturnobs,total_reward,done,trunk,infoclassGrayScaleObservation(gym.ObservationWrapper):def__init__(self,env):super().__init__(env)obs_shape=self.observation_space.shape[:2]self.observation_space=Box(low=0,high=255,shape=obs_shape,dtype=np.uint8)defpermute_orientation(self,observation):# permute [H, W, C] array to [C, H, W] tensorobservation=np.transpose(observation,(2,0,1))observation=torch.tensor(observation.copy(),dtype=torch.float)returnobservationdefobservation(self,observation):observation=self.permute_orientation(observation)transform=T.Grayscale()observation=transform(observation)returnobservationclassResizeObservation(gym.ObservationWrapper):def__init__(self,env,shape):super().__init__(env)ifisinstance(shape,int):self.shape=(shape,shape)else:self.shape=tuple(shape)obs_shape=self.shape+self.observation_space.shape[2:]self.observation_space=Box(low=0,high=255,shape=obs_shape,dtype=np.uint8)defobservation(self,observation):transforms=T.Compose([T.Resize(self.shape,antialias=True),T.Normalize(0,255)])observation=transforms(observation).squeeze(0)returnobservation# Apply Wrappers to environmentenv=SkipFrame(env,skip=4)env=GrayScaleObservation(env)env=ResizeObservation(env,shape=84)ifgym.__version__<'0.26':env=FrameStack(env,num_stack=4,new_step_api=True)else:env=FrameStack(env,num_stack=4)
After applying the above wrappers to the environment, the final wrapped
state consists of 4 gray-scaled consecutive frames stacked together, as
shown above in the image on the left. Each time Mario makes an action,
the environment responds with a state of this structure. The structure
is represented by a 3-D array of size [4,84,84].
In our implementation, we share feature generator features across
Qonline and Qtarget, but maintain separate FC
classifiers for each. θtarget (the parameters of
Qtarget) is frozen to prevent updating by backprop. Instead,
it is periodically synced with θonline (more on this
later).
TD Estimate - the predicted optimal Q∗ for a given state
s
TDe=Qonline∗(s,a)
TD Target - aggregation of current reward and the estimated
Q∗ in the next state s′
a′=argmaxaQonline(s′,a)
TDt=r+γQtarget∗(s′,a′)
Because we don’t know what next action a′ will be, we use the
action a′ maximizes Qonline in the next state
.
Notice we use the
@torch.no_grad()
decorator on td_target() to disable gradient calculations here
(because we don’t need to backpropagate on θtarget).
As Mario samples inputs from his replay buffer, we compute TDt
and TDe and backpropagate this loss down Qonline to
update its parameters θonline (α is the
learning rate lr passed to the optimizer)
θonline←θonline+α∇(TDe−TDt)
θtarget does not update through backpropagation.
Instead, we periodically copy θonline to
θtarget
classMario(Mario):defsave(self):save_path=(self.save_dir/f"mario_net_{int(self.curr_step//self.save_every)}.chkpt")torch.save(dict(model=self.net.state_dict(),exploration_rate=self.exploration_rate),save_path,)print(f"MarioNet saved to {save_path} at step {self.curr_step}")
Putting it all together
classMario(Mario):def__init__(self,state_dim,action_dim,save_dir):super().__init__(state_dim,action_dim,save_dir)self.burnin=1e4# min. experiences before trainingself.learn_every=3# no. of experiences between updates to Q_onlineself.sync_every=1e4# no. of experiences between Q_target & Q_online syncdeflearn(self):ifself.curr_step%self.sync_every==0:self.sync_Q_target()ifself.curr_step%self.save_every==0:self.save()ifself.curr_step<self.burnin:returnNone,Noneifself.curr_step%self.learn_every!=0:returnNone,None# Sample from memorystate,next_state,action,reward,done=self.recall()# Get TD Estimatetd_est=self.td_estimate(state,action)# Get TD Targettd_tgt=self.td_target(reward,next_state,done)# Backpropagate loss through Q_onlineloss=self.update_Q_online(td_est,td_tgt)return(td_est.mean().item(),loss)
=
save_dir
/
"log"
with
open
(
self
.
save_log
,
"w"
)
as
f
:
f
.
write
(
f
"
{
'Episode'
:
>8
}{
'Step'
:
>8
}{
'Epsilon'
:
>10
}{
'MeanReward'
:
>15
}
"
f
"
{
'MeanLength'
:
>15
}{
'MeanLoss'
:
>15
}{
'MeanQValue'
:
>15
}
"
f
"
{
'TimeDelta'
:
>15
}{
'Time'
:
>20
}
\n
"
)
self
.
ep_rewards_plot
=
save_dir
/
"reward_plot.jpg"
self
.
ep_lengths_plot
=
save_dir
/
"length_plot.jpg"
self
.
ep_avg_losses_plot
=
save_dir
/
"loss_plot.jpg"
self
.
ep_avg_qs_plot
=
save_dir
/
"q_plot.jpg"
# History metrics
self
.
ep_rewards
=
[]
self
.
ep_lengths
=
[]
self
.
ep_avg_losses
=
[]
self
.
ep_avg_qs
=
[]
# Moving averages, added for every call to record()