write me a python pytorch script that beats super mario bros 1 (nes), i have a 2080ti…
- User
write me a python pytorch script that beats super mario bros 1 (nes), i have a 2080ti for training and use wsl
- Assistant
write me a python pytorch script that beats super mario bros 1 (nes), i have a 2080ti for training and use wsl
Certainly! I can help you create a Python script using PyTorch to train an AI agent to play Super Mario Bros (NES). We'll use the OpenAI Gym Retro environment, which allows you to interact with classic games for reinforcement learning purposes.
Important Note: To use Gym Retro with Super Mario Bros, you will need to provide your own legally obtained ROM file of the game. Unauthorized distribution of ROM files is illegal.
Here's a step-by-step guide to set up your environment and create the training script.
First, ensure that you have Python 3 installed. Then, install the necessary Python packages:
pip install torch torchvision
pip install gym
pip install gym-retro
Clone the Gym Retro repository and import your Super Mario Bros ROM:
# Clone the Gym Retro repository
git clone https://github.com/openai/retro.git
cd retro
pip install -e .
# Import your ROM (replace the path with the actual path to your ROM file)
python -m retro.import /path/to/your/roms/
Make sure to replace /path/to/your/roms/ with the directory containing your Super Mario Bros NES ROM file.
Below is the Python script for a Deep Q-Network (DQN) agent that plays Super Mario Bros. The script includes the environment setup, neural network definition, and training loop.
import retro
import numpy as np
import cv2
import torch
import torch.nn as nn
import torch.optim as optim
from collections import deque
import random
# Set device to GPU if available
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# Hyperparameters
NUM_EPISODES = 5000
MAX_STEPS = 5000
GAMMA = 0.99
LEARNING_RATE = 0.00025
MEMORY_SIZE = 100000
BATCH_SIZE = 64
START_EPSILON = 1.0
END_EPSILON = 0.01
EPSILON_DECAY = 0.0001
TARGET_UPDATE_FREQ = 1000
# Preprocessing parameters
IMG_HEIGHT = 84
IMG_WIDTH = 84
NUM_STACKED_FRAMES = 4
class DQNetwork(nn.Module):
def __init__(self, action_size):
super(DQNetwork, self).__init__()
self.net = nn.Sequential(
nn.Conv2d(NUM_STACKED_FRAMES, 32, kernel_size=8, stride=4),
nn.ReLU(),
nn.Conv2d(32, 64, kernel_size=4, stride=2),
nn.ReLU(),
nn.Conv2d(64, 64, kernel_size=3, stride=1),
nn.ReLU(),
nn.Flatten(),
nn.Linear(3136, 512), # Adjust input size if necessary
nn.ReLU(),
nn.Linear(512, action_size)
)
def forward(self, x):
return self.net(x)
def preprocess_frame(frame):
# Grayscale and resize the frame
frame = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY)
frame = cv2.resize(frame, (IMG_HEIGHT, IMG_WIDTH), interpolation=cv2.INTER_AREA)
return frame
def stack_frames(stacked_frames, frame, is_new_episode):
frame = preprocess_frame(frame)
if is_new_episode:
stacked_frames = deque([frame for _ in range(NUM_STACKED_FRAMES)], maxlen=NUM_STACKED_FRAMES)
else:
stacked_frames.append(frame)
stacked_state = np.stack(stacked_frames, axis=0)
return stacked_state, stacked_frames
def get_epsilon(steps_done):
epsilon = END_EPSILON + (START_EPSILON - END_EPSILON) * \
np.exp(-EPSILON_DECAY * steps_done)
return epsilon
def main():
env = retro.make(game='SuperMarioBros-Nes')
action_space = env.action_space.n
policy_net = DQNetwork(action_space).to(device)
target_net = DQNetwork(action_space).to(device)
target_net.load_state_dict(policy_net.state_dict())
target_net.eval()
optimizer = optim.Adam(policy_net.parameters(), lr=LEARNING_RATE)
criterion = nn.MSELoss()
replay_memory = deque(maxlen=MEMORY_SIZE)
steps_done = 0
for episode in range(1, NUM_EPISODES + 1):
state = env.reset()
stacked_frames = deque(maxlen=NUM_STACKED_FRAMES)
state, stacked_frames = stack_frames(stacked_frames, state, True)
state = np.array(state, dtype=np.float32) / 255.0
total_reward = 0
done = False
for t in range(MAX_STEPS):
epsilon = get_epsilon(steps_done)
steps_done += 1
if random.random() < epsilon:
action = env.action_space.sample()
else:
with torch.no_grad():
state_tensor = torch.from_numpy(state).unsqueeze(0).to(device)
q_values = policy_net(state_tensor)
action = torch.argmax(q_values).item()
next_state, reward, done, info = env.step(action)
total_reward += reward
next_state, stacked_frames = stack_frames(stacked_frames, next_state, False)
next_state = np.array(next_state, dtype=np.float32) / 255.0
replay_memory.append((state, action, reward, next_state, done))
state = next_state
if len(replay_memory) > BATCH_SIZE:
batch = random.sample(replay_memory, BATCH_SIZE)
states_mb = np.array([m[0] for m in batch], dtype=np.float32)
actions_mb = np.array([m[1] for m in batch])
rewards_mb = np.array([m[2] for m in batch])
next_states_mb = np.array([m[3] for m in batch], dtype=np.float32)
dones_mb = np.array([m[4] for m in batch])
states_t = torch.tensor(states_mb).to(device)
actions_t = torch.tensor(actions_mb).unsqueeze(1).to(device)
rewards_t = torch.tensor(rewards_mb).to(device)
next_states_t = torch.tensor(next_states_mb).to(device)
dones_t = torch.tensor(dones_mb.astype(np.uint8)).to(device)
q_values = policy_net(states_t).gather(1, actions_t).squeeze(1)
next_q_values = target_net(next_states_t).max(1)[0]
expected_q_values = rewards_t + (GAMMA * next_q_values * (1 - dones_t))
loss = criterion(q_values, expected_q_values.detach())
optimizer.zero_grad()
loss.backward()
optimizer.step()
if steps_done % TARGET_UPDATE_FREQ == 0:
target_net.load_state_dict(policy_net.state_dict())
if done:
break
print(f"Episode {episode} - Total Reward: {total_reward}, Epsilon: {epsilon:.4f}")
env.close()
torch.save(policy_net.state_dict(), 'super_mario_dqn.pth')
if __name__ == "__main__":
main()
Save the script in a file, for example, super_mario_dqn.py, and run it using:
python super_mario_dqn.py
Enjoy training your AI agent! Feel free to ask if you have any questions or need further assistance with the code or concepts.
Not yet included in a published release.