Skip to content

Update mario_rl_tutorial.py #2381

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

Merged
merged 5 commits into from
Jun 6, 2023
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 14 additions & 9 deletions intermediate_source/mario_rl_tutorial.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
, storage
# -*- coding: utf-8 -*-
"""
Train a Mario-playing RL Agent
Expand Down Expand Up @@ -53,6 +54,8 @@
# Super Mario environment for OpenAI Gym
import gym_super_mario_bros

from tensordict import TensorDict
from torchrl.data import TensorDictReplayBuffer, LazyMemmapStorage

######################################################################
# RL Definitions
Expand Down Expand Up @@ -348,7 +351,7 @@ def act(self, state):
class Mario(Mario): # subclassing for continuity
def __init__(self, state_dim, action_dim, save_dir):
super().__init__(state_dim, action_dim, save_dir)
self.memory = deque(maxlen=100000)
self.memory = TensorDictReplayBuffer(storage=LazyMemmapStorage(100000))
self.batch_size = 32

def cache(self, state, next_state, action, reward, done):
Expand All @@ -373,14 +376,15 @@ def first_if_tuple(x):
reward = torch.tensor([reward], device=self.device)
done = torch.tensor([done], device=self.device)

self.memory.append((state, next_state, action, reward, done,))
# self.memory.append((state, next_state, action, reward, done,))
self.memory.add(TensorDict({"state": state, "next_state": next_state, "action": action, "reward": reward, "done": done}, batch_size=[]))

def recall(self):
"""
Retrieve a batch of experiences from memory
"""
batch = random.sample(self.memory, self.batch_size)
state, next_state, action, reward, done = map(torch.stack, zip(*batch))
batch = self.memory.sample(self.batch_size)
state, next_state, action, reward, done = (batch.get(key) for key in ("state", "next_state", "action", "reward", "done"))
return state, next_state, action.squeeze(), reward.squeeze(), done.squeeze()


Expand Down Expand Up @@ -711,17 +715,18 @@ def record(self, episode, epsilon, step):
f"{datetime.datetime.now().strftime('%Y-%m-%dT%H:%M:%S'):>20}\n"
)

for metric in ["ep_rewards", "ep_lengths", "ep_avg_losses", "ep_avg_qs"]:
plt.plot(getattr(self, f"moving_avg_{metric}"))
plt.savefig(getattr(self, f"{metric}_plot"))
for metric in ["ep_lengths", "ep_avg_losses", "ep_avg_qs", "ep_rewards"]:
plt.clf()
plt.plot(getattr(self, f"moving_avg_{metric}"), label=f"moving_avg_{metric}")
plt.legend()
plt.savefig(getattr(self, f"{metric}_plot"))


######################################################################
# Let’s play!
# """""""""""""""
#
# In this example we run the training loop for 10 episodes, but for Mario to truly learn the ways of
# 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()
Expand All @@ -735,7 +740,7 @@ def record(self, episode, epsilon, step):

logger = MetricLogger(save_dir)

episodes = 10
episodes = 40
for e in range(episodes):

state = env.reset()
Expand Down