{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# For tips on running notebooks in Google Colab, see\n",
"# https://pytorch.org/tutorials/beginner/colab\n",
"%matplotlib inline"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Reinforcement Learning (DQN) Tutorial\n",
"=====================================\n",
"\n",
"**Author**: [Adam Paszke](https://github.com/apaszke)\n",
"\n",
": [Mark Towers](https://github.com/pseudo-rnd-thoughts)\n",
"\n",
"This tutorial shows how to use PyTorch to train a Deep Q Learning (DQN)\n",
"agent on the CartPole-v1 task from\n",
"[Gymnasium](https://gymnasium.farama.org).\n",
"\n",
"You might find it helpful to read the original [Deep Q Learning\n",
"(DQN)](https://arxiv.org/abs/1312.5602) paper\n",
"\n",
"**Task**\n",
"\n",
"The agent has to decide between two actions - moving the cart left or\n",
"right - so that the pole attached to it stays upright. You can find more\n",
"information about the environment and other more challenging\n",
"environments at [Gymnasium\\'s\n",
"website](https://gymnasium.farama.org/environments/classic_control/cart_pole/).\n",
"\n",
"![CartPole](https://pytorch.org/tutorials/_static/img/cartpole.gif)\n",
"\n",
"As the agent observes the current state of the environment and chooses\n",
"an action, the environment *transitions* to a new state, and also\n",
"returns a reward that indicates the consequences of the action. In this\n",
"task, rewards are +1 for every incremental timestep and the environment\n",
"terminates if the pole falls over too far or the cart moves more than\n",
"2.4 units away from center. This means better performing scenarios will\n",
"run for longer duration, accumulating larger return.\n",
"\n",
"The CartPole task is designed so that the inputs to the agent are 4 real\n",
"values representing the environment state (position, velocity, etc.). We\n",
"take these 4 inputs without any scaling and pass them through a small\n",
"fully-connected network with 2 outputs, one for each action. The network\n",
"is trained to predict the expected value for each action, given the\n",
"input state. The action with the highest expected value is then chosen.\n",
"\n",
"**Packages**\n",
"\n",
"First, let\\'s import needed packages. Firstly, we need\n",
"[gymnasium](https://gymnasium.farama.org/) for the environment,\n",
"installed by using [pip]{.title-ref}. This is a fork of the original\n",
"OpenAI Gym project and maintained by the same team since Gym v0.19. If\n",
"you are running this in Google Colab, run:\n",
"\n",
"``` {.sourceCode .bash}\n",
"%%bash\n",
"pip3 install gymnasium[classic_control]\n",
"```\n",
"\n",
"We\\'ll also use the following from PyTorch:\n",
"\n",
"- neural networks (`torch.nn`)\n",
"- optimization (`torch.optim`)\n",
"- automatic differentiation (`torch.autograd`)\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import gymnasium as gym\n",
"import math\n",
"import random\n",
"import matplotlib\n",
"import matplotlib.pyplot as plt\n",
"from collections import namedtuple, deque\n",
"from itertools import count\n",
"\n",
"import torch\n",
"import torch.nn as nn\n",
"import torch.optim as optim\n",
"import torch.nn.functional as F\n",
"\n",
"env = gym.make(\"CartPole-v1\")\n",
"\n",
"# set up matplotlib\n",
"is_ipython = 'inline' in matplotlib.get_backend()\n",
"if is_ipython:\n",
" from IPython import display\n",
"\n",
"plt.ion()\n",
"\n",
"# if GPU is to be used\n",
"device = torch.device(\n",
" \"cuda\" if torch.cuda.is_available() else\n",
" \"mps\" if torch.backends.mps.is_available() else\n",
" \"cpu\"\n",
")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Replay Memory\n",
"=============\n",
"\n",
"We\\'ll be using experience replay memory for training our DQN. It stores\n",
"the transitions that the agent observes, allowing us to reuse this data\n",
"later. By sampling from it randomly, the transitions that build up a\n",
"batch are decorrelated. It has been shown that this greatly stabilizes\n",
"and improves the DQN training procedure.\n",
"\n",
"For this, we\\'re going to need two classes:\n",
"\n",
"- `Transition` - a named tuple representing a single transition in our\n",
" environment. It essentially maps (state, action) pairs to their\n",
" (next\\_state, reward) result, with the state being the screen\n",
" difference image as described later on.\n",
"- `ReplayMemory` - a cyclic buffer of bounded size that holds the\n",
" transitions observed recently. It also implements a `.sample()`\n",
" method for selecting a random batch of transitions for training.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"Transition = namedtuple('Transition',\n",
" ('state', 'action', 'next_state', 'reward'))\n",
"\n",
"\n",
"class ReplayMemory(object):\n",
"\n",
" def __init__(self, capacity):\n",
" self.memory = deque([], maxlen=capacity)\n",
"\n",
" def push(self, *args):\n",
" \"\"\"Save a transition\"\"\"\n",
" self.memory.append(Transition(*args))\n",
"\n",
" def sample(self, batch_size):\n",
" return random.sample(self.memory, batch_size)\n",
"\n",
" def __len__(self):\n",
" return len(self.memory)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Now, let\\'s define our model. But first, let\\'s quickly recap what a DQN\n",
"is.\n",
"\n",
"DQN algorithm\n",
"=============\n",
"\n",
"Our environment is deterministic, so all equations presented here are\n",
"also formulated deterministically for the sake of simplicity. In the\n",
"reinforcement learning literature, they would also contain expectations\n",
"over stochastic transitions in the environment.\n",
"\n",
"Our aim will be to train a policy that tries to maximize the discounted,\n",
"cumulative reward\n",
"$R_{t_0} = \\sum_{t=t_0}^{\\infty} \\gamma^{t - t_0} r_t$, where $R_{t_0}$\n",
"is also known as the *return*. The discount, $\\gamma$, should be a\n",
"constant between $0$ and $1$ that ensures the sum converges. A lower\n",
"$\\gamma$ makes rewards from the uncertain far future less important for\n",
"our agent than the ones in the near future that it can be fairly\n",
"confident about. It also encourages agents to collect reward closer in\n",
"time than equivalent rewards that are temporally far away in the future.\n",
"\n",
"The main idea behind Q-learning is that if we had a function\n",
"$Q^*: State \\times Action \\rightarrow \\mathbb{R}$, that could tell us\n",
"what our return would be, if we were to take an action in a given state,\n",
"then we could easily construct a policy that maximizes our rewards:\n",
"\n",
"$$\\pi^*(s) = \\arg\\!\\max_a \\ Q^*(s, a)$$\n",
"\n",
"However, we don\\'t know everything about the world, so we don\\'t have\n",
"access to $Q^*$. But, since neural networks are universal function\n",
"approximators, we can simply create one and train it to resemble $Q^*$.\n",
"\n",
"For our training update rule, we\\'ll use a fact that every $Q$ function\n",
"for some policy obeys the Bellman equation:\n",
"\n",
"$$Q^{\\pi}(s, a) = r + \\gamma Q^{\\pi}(s', \\pi(s'))$$\n",
"\n",
"The difference between the two sides of the equality is known as the\n",
"temporal difference error, $\\delta$:\n",
"\n",
"$$\\delta = Q(s, a) - (r + \\gamma \\max_a' Q(s', a))$$\n",
"\n",
"To minimize this error, we will use the [Huber\n",
"loss](https://en.wikipedia.org/wiki/Huber_loss). The Huber loss acts\n",
"like the mean squared error when the error is small, but like the mean\n",
"absolute error when the error is large - this makes it more robust to\n",
"outliers when the estimates of $Q$ are very noisy. We calculate this\n",
"over a batch of transitions, $B$, sampled from the replay memory:\n",
"\n",
"$$\\mathcal{L} = \\frac{1}{|B|}\\sum_{(s, a, s', r) \\ \\in \\ B} \\mathcal{L}(\\delta)$$\n",
"\n",
"$$\\begin{aligned}\n",
"\\text{where} \\quad \\mathcal{L}(\\delta) = \\begin{cases}\n",
" \\frac{1}{2}{\\delta^2} & \\text{for } |\\delta| \\le 1, \\\\\n",
" |\\delta| - \\frac{1}{2} & \\text{otherwise.}\n",
"\\end{cases}\n",
"\\end{aligned}$$\n",
"\n",
"Q-network\n",
"---------\n",
"\n",
"Our model will be a feed forward neural network that takes in the\n",
"difference between the current and previous screen patches. It has two\n",
"outputs, representing $Q(s, \\mathrm{left})$ and $Q(s, \\mathrm{right})$\n",
"(where $s$ is the input to the network). In effect, the network is\n",
"trying to predict the *expected return* of taking each action given the\n",
"current input.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"class DQN(nn.Module):\n",
"\n",
" def __init__(self, n_observations, n_actions):\n",
" super(DQN, self).__init__()\n",
" self.layer1 = nn.Linear(n_observations, 128)\n",
" self.layer2 = nn.Linear(128, 128)\n",
" self.layer3 = nn.Linear(128, n_actions)\n",
"\n",
" # Called with either one element to determine next action, or a batch\n",
" # during optimization. Returns tensor([[left0exp,right0exp]...]).\n",
" def forward(self, x):\n",
" x = F.relu(self.layer1(x))\n",
" x = F.relu(self.layer2(x))\n",
" return self.layer3(x)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Training\n",
"========\n",
"\n",
"Hyperparameters and utilities\n",
"-----------------------------\n",
"\n",
"This cell instantiates our model and its optimizer, and defines some\n",
"utilities:\n",
"\n",
"- `select_action` - will select an action according to an epsilon\n",
" greedy policy. Simply put, we\\'ll sometimes use our model for\n",
" choosing the action, and sometimes we\\'ll just sample one uniformly.\n",
" The probability of choosing a random action will start at\n",
" `EPS_START` and will decay exponentially towards `EPS_END`.\n",
" `EPS_DECAY` controls the rate of the decay.\n",
"- `plot_durations` - a helper for plotting the duration of episodes,\n",
" along with an average over the last 100 episodes (the measure used\n",
" in the official evaluations). The plot will be underneath the cell\n",
" containing the main training loop, and will update after every\n",
" episode.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# BATCH_SIZE is the number of transitions sampled from the replay buffer\n",
"# GAMMA is the discount factor as mentioned in the previous section\n",
"# EPS_START is the starting value of epsilon\n",
"# EPS_END is the final value of epsilon\n",
"# EPS_DECAY controls the rate of exponential decay of epsilon, higher means a slower decay\n",
"# TAU is the update rate of the target network\n",
"# LR is the learning rate of the ``AdamW`` optimizer\n",
"BATCH_SIZE = 128\n",
"GAMMA = 0.99\n",
"EPS_START = 0.9\n",
"EPS_END = 0.05\n",
"EPS_DECAY = 1000\n",
"TAU = 0.005\n",
"LR = 1e-4\n",
"\n",
"# Get number of actions from gym action space\n",
"n_actions = env.action_space.n\n",
"# Get the number of state observations\n",
"state, info = env.reset()\n",
"n_observations = len(state)\n",
"\n",
"policy_net = DQN(n_observations, n_actions).to(device)\n",
"target_net = DQN(n_observations, n_actions).to(device)\n",
"target_net.load_state_dict(policy_net.state_dict())\n",
"\n",
"optimizer = optim.AdamW(policy_net.parameters(), lr=LR, amsgrad=True)\n",
"memory = ReplayMemory(10000)\n",
"\n",
"\n",
"steps_done = 0\n",
"\n",
"\n",
"def select_action(state):\n",
" global steps_done\n",
" sample = random.random()\n",
" eps_threshold = EPS_END + (EPS_START - EPS_END) * \\\n",
" math.exp(-1. * steps_done / EPS_DECAY)\n",
" steps_done += 1\n",
" if sample > eps_threshold:\n",
" with torch.no_grad():\n",
" # t.max(1) will return the largest column value of each row.\n",
" # second column on max result is index of where max element was\n",
" # found, so we pick action with the larger expected reward.\n",
" return policy_net(state).max(1).indices.view(1, 1)\n",
" else:\n",
" return torch.tensor([[env.action_space.sample()]], device=device, dtype=torch.long)\n",
"\n",
"\n",
"episode_durations = []\n",
"\n",
"\n",
"def plot_durations(show_result=False):\n",
" plt.figure(1)\n",
" durations_t = torch.tensor(episode_durations, dtype=torch.float)\n",
" if show_result:\n",
" plt.title('Result')\n",
" else:\n",
" plt.clf()\n",
" plt.title('Training...')\n",
" plt.xlabel('Episode')\n",
" plt.ylabel('Duration')\n",
" plt.plot(durations_t.numpy())\n",
" # Take 100 episode averages and plot them too\n",
" if len(durations_t) >= 100:\n",
" means = durations_t.unfold(0, 100, 1).mean(1).view(-1)\n",
" means = torch.cat((torch.zeros(99), means))\n",
" plt.plot(means.numpy())\n",
"\n",
" plt.pause(0.001) # pause a bit so that plots are updated\n",
" if is_ipython:\n",
" if not show_result:\n",
" display.display(plt.gcf())\n",
" display.clear_output(wait=True)\n",
" else:\n",
" display.display(plt.gcf())"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Training loop\n",
"=============\n",
"\n",
"Finally, the code for training our model.\n",
"\n",
"Here, you can find an `optimize_model` function that performs a single\n",
"step of the optimization. It first samples a batch, concatenates all the\n",
"tensors into a single one, computes $Q(s_t, a_t)$ and\n",
"$V(s_{t+1}) = \\max_a Q(s_{t+1}, a)$, and combines them into our loss. By\n",
"definition we set $V(s) = 0$ if $s$ is a terminal state. We also use a\n",
"target network to compute $V(s_{t+1})$ for added stability. The target\n",
"network is updated at every step with a [soft\n",
"update](https://arxiv.org/pdf/1509.02971.pdf) controlled by the\n",
"hyperparameter `TAU`, which was previously defined.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"def optimize_model():\n",
" if len(memory) < BATCH_SIZE:\n",
" return\n",
" transitions = memory.sample(BATCH_SIZE)\n",
" # Transpose the batch (see https://stackoverflow.com/a/19343/3343043 for\n",
" # detailed explanation). This converts batch-array of Transitions\n",
" # to Transition of batch-arrays.\n",
" batch = Transition(*zip(*transitions))\n",
"\n",
" # Compute a mask of non-final states and concatenate the batch elements\n",
" # (a final state would've been the one after which simulation ended)\n",
" non_final_mask = torch.tensor(tuple(map(lambda s: s is not None,\n",
" batch.next_state)), device=device, dtype=torch.bool)\n",
" non_final_next_states = torch.cat([s for s in batch.next_state\n",
" if s is not None])\n",
" state_batch = torch.cat(batch.state)\n",
" action_batch = torch.cat(batch.action)\n",
" reward_batch = torch.cat(batch.reward)\n",
"\n",
" # Compute Q(s_t, a) - the model computes Q(s_t), then we select the\n",
" # columns of actions taken. These are the actions which would've been taken\n",
" # for each batch state according to policy_net\n",
" state_action_values = policy_net(state_batch).gather(1, action_batch)\n",
"\n",
" # Compute V(s_{t+1}) for all next states.\n",
" # Expected values of actions for non_final_next_states are computed based\n",
" # on the \"older\" target_net; selecting their best reward with max(1).values\n",
" # This is merged based on the mask, such that we'll have either the expected\n",
" # state value or 0 in case the state was final.\n",
" next_state_values = torch.zeros(BATCH_SIZE, device=device)\n",
" with torch.no_grad():\n",
" next_state_values[non_final_mask] = target_net(non_final_next_states).max(1).values\n",
" # Compute the expected Q values\n",
" expected_state_action_values = (next_state_values * GAMMA) + reward_batch\n",
"\n",
" # Compute Huber loss\n",
" criterion = nn.SmoothL1Loss()\n",
" loss = criterion(state_action_values, expected_state_action_values.unsqueeze(1))\n",
"\n",
" # Optimize the model\n",
" optimizer.zero_grad()\n",
" loss.backward()\n",
" # In-place gradient clipping\n",
" torch.nn.utils.clip_grad_value_(policy_net.parameters(), 100)\n",
" optimizer.step()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Below, you can find the main training loop. At the beginning we reset\n",
"the environment and obtain the initial `state` Tensor. Then, we sample\n",
"an action, execute it, observe the next state and the reward (always 1),\n",
"and optimize our model once. When the episode ends (our model fails), we\n",
"restart the loop.\n",
"\n",
"Below, [num\\_episodes]{.title-ref} is set to 600 if a GPU is available,\n",
"otherwise 50 episodes are scheduled so training does not take too long.\n",
"However, 50 episodes is insufficient for to observe good performance on\n",
"CartPole. You should see the model constantly achieve 500 steps within\n",
"600 training episodes. Training RL agents can be a noisy process, so\n",
"restarting training can produce better results if convergence is not\n",
"observed.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"if torch.cuda.is_available() or torch.backends.mps.is_available():\n",
" num_episodes = 600\n",
"else:\n",
" num_episodes = 50\n",
"\n",
"for i_episode in range(num_episodes):\n",
" # Initialize the environment and get its state\n",
" state, info = env.reset()\n",
" state = torch.tensor(state, dtype=torch.float32, device=device).unsqueeze(0)\n",
" for t in count():\n",
" action = select_action(state)\n",
" observation, reward, terminated, truncated, _ = env.step(action.item())\n",
" reward = torch.tensor([reward], device=device)\n",
" done = terminated or truncated\n",
"\n",
" if terminated:\n",
" next_state = None\n",
" else:\n",
" next_state = torch.tensor(observation, dtype=torch.float32, device=device).unsqueeze(0)\n",
"\n",
" # Store the transition in memory\n",
" memory.push(state, action, next_state, reward)\n",
"\n",
" # Move to the next state\n",
" state = next_state\n",
"\n",
" # Perform one step of the optimization (on the policy network)\n",
" optimize_model()\n",
"\n",
" # Soft update of the target network's weights\n",
" # θ′ ← τ θ + (1 −τ )θ′\n",
" target_net_state_dict = target_net.state_dict()\n",
" policy_net_state_dict = policy_net.state_dict()\n",
" for key in policy_net_state_dict:\n",
" target_net_state_dict[key] = policy_net_state_dict[key]*TAU + target_net_state_dict[key]*(1-TAU)\n",
" target_net.load_state_dict(target_net_state_dict)\n",
"\n",
" if done:\n",
" episode_durations.append(t + 1)\n",
" plot_durations()\n",
" break\n",
"\n",
"print('Complete')\n",
"plot_durations(show_result=True)\n",
"plt.ioff()\n",
"plt.show()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Here is the diagram that illustrates the overall resulting data flow.\n",
"\n",
"![](https://pytorch.org/tutorials/_static/img/reinforcement_learning_diagram.jpg)\n",
"\n",
"Actions are chosen either randomly or based on a policy, getting the\n",
"next step sample from the gym environment. We record the results in the\n",
"replay memory and also run optimization step on every iteration.\n",
"Optimization picks a random batch from the replay memory to do training\n",
"of the new policy. The \\\"older\\\" target\\_net is also used in\n",
"optimization to compute the expected Q values. A soft update of its\n",
"weights are performed at every step.\n"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.15"
}
},
"nbformat": 4,
"nbformat_minor": 0
}