{ "cells": [ { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# For tips on running notebooks in Google Colab, see\n# https://codelin.vip/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\nThis tutorial shows how to use PyTorch to train a Deep Q Learning (DQN)\nagent on the CartPole-v1 task from\n[Gymnasium](https://gymnasium.farama.org).\n\nYou might find it helpful to read the original [Deep Q Learning\n(DQN)](https://arxiv.org/abs/1312.5602) paper\n\n**Task**\n\nThe agent has to decide between two actions - moving the cart left or\nright - so that the pole attached to it stays upright. You can find more\ninformation about the environment and other more challenging\nenvironments at [Gymnasium\\'s\nwebsite](https://gymnasium.farama.org/environments/classic_control/cart_pole/).\n\n![CartPole](https://pytorch.org/tutorials/_static/img/cartpole.gif)\n\nAs the agent observes the current state of the environment and chooses\nan action, the environment *transitions* to a new state, and also\nreturns a reward that indicates the consequences of the action. In this\ntask, rewards are +1 for every incremental timestep and the environment\nterminates if the pole falls over too far or the cart moves more than\n2.4 units away from center. This means better performing scenarios will\nrun for longer duration, accumulating larger return.\n\nThe CartPole task is designed so that the inputs to the agent are 4 real\nvalues representing the environment state (position, velocity, etc.). We\ntake these 4 inputs without any scaling and pass them through a small\nfully-connected network with 2 outputs, one for each action. The network\nis trained to predict the expected value for each action, given the\ninput state. The action with the highest expected value is then chosen.\n\n**Packages**\n\nFirst, let\\'s import needed packages. Firstly, we need\n[gymnasium](https://gymnasium.farama.org/) for the environment,\ninstalled by using [pip]{.title-ref}. This is a fork of the original\nOpenAI Gym project and maintained by the same team since Gym v0.19. If\nyou are running this in Google Colab, run:\n\n``` {.bash}\n%%bash\npip3 install gymnasium[classic_control]\n```\n\nWe\\'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\nimport math\nimport random\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom collections import namedtuple, deque\nfrom itertools import count\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\n\nenv = gym.make(\"CartPole-v1\")\n\n# set up matplotlib\nis_ipython = 'inline' in matplotlib.get_backend()\nif is_ipython:\n from IPython import display\n\nplt.ion()\n\n# if GPU is to be used\ndevice = 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\nWe\\'ll be using experience replay memory for training our DQN. It stores\nthe transitions that the agent observes, allowing us to reuse this data\nlater. By sampling from it randomly, the transitions that build up a\nbatch are decorrelated. It has been shown that this greatly stabilizes\nand improves the DQN training procedure.\n\nFor 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\nclass 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\nis.\n\nDQN algorithm\n=============\n\nOur environment is deterministic, so all equations presented here are\nalso formulated deterministically for the sake of simplicity. In the\nreinforcement learning literature, they would also contain expectations\nover stochastic transitions in the environment.\n\nOur aim will be to train a policy that tries to maximize the discounted,\ncumulative reward\n$R_{t_0} = \\sum_{t=t_0}^{\\infty} \\gamma^{t - t_0} r_t$, where $R_{t_0}$\nis also known as the *return*. The discount, $\\gamma$, should be a\nconstant between $0$ and $1$ that ensures the sum converges. A lower\n$\\gamma$ makes rewards from the uncertain far future less important for\nour agent than the ones in the near future that it can be fairly\nconfident about. It also encourages agents to collect reward closer in\ntime than equivalent rewards that are temporally far away in the future.\n\nThe main idea behind Q-learning is that if we had a function\n$Q^*: State \\times Action \\rightarrow \\mathbb{R}$, that could tell us\nwhat our return would be, if we were to take an action in a given state,\nthen we could easily construct a policy that maximizes our rewards:\n\n$$\\pi^*(s) = \\arg\\!\\max_a \\ Q^*(s, a)$$\n\nHowever, we don\\'t know everything about the world, so we don\\'t have\naccess to $Q^*$. But, since neural networks are universal function\napproximators, we can simply create one and train it to resemble $Q^*$.\n\nFor our training update rule, we\\'ll use a fact that every $Q$ function\nfor some policy obeys the Bellman equation:\n\n$$Q^{\\pi}(s, a) = r + \\gamma Q^{\\pi}(s', \\pi(s'))$$\n\nThe difference between the two sides of the equality is known as the\ntemporal difference error, $\\delta$:\n\n$$\\delta = Q(s, a) - (r + \\gamma \\max_a' Q(s', a))$$\n\nTo minimize this error, we will use the [Huber\nloss](https://en.wikipedia.org/wiki/Huber_loss). The Huber loss acts\nlike the mean squared error when the error is small, but like the mean\nabsolute error when the error is large - this makes it more robust to\noutliers when the estimates of $Q$ are very noisy. We calculate this\nover 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\nQ-network\n---------\n\nOur model will be a feed forward neural network that takes in the\ndifference between the current and previous screen patches. It has two\noutputs, representing $Q(s, \\mathrm{left})$ and $Q(s, \\mathrm{right})$\n(where $s$ is the input to the network). In effect, the network is\ntrying to predict the *expected return* of taking each action given the\ncurrent 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\nHyperparameters and utilities\n-----------------------------\n\nThis cell instantiates our model and its optimizer, and defines some\nutilities:\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\nBATCH_SIZE = 128\nGAMMA = 0.99\nEPS_START = 0.9\nEPS_END = 0.05\nEPS_DECAY = 1000\nTAU = 0.005\nLR = 1e-4\n\n# Get number of actions from gym action space\nn_actions = env.action_space.n\n# Get the number of state observations\nstate, info = env.reset()\nn_observations = len(state)\n\npolicy_net = DQN(n_observations, n_actions).to(device)\ntarget_net = DQN(n_observations, n_actions).to(device)\ntarget_net.load_state_dict(policy_net.state_dict())\n\noptimizer = optim.AdamW(policy_net.parameters(), lr=LR, amsgrad=True)\nmemory = ReplayMemory(10000)\n\n\nsteps_done = 0\n\n\ndef 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\nepisode_durations = []\n\n\ndef 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\nFinally, the code for training our model.\n\nHere, you can find an `optimize_model` function that performs a single\nstep of the optimization. It first samples a batch, concatenates all the\ntensors 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\ndefinition we set $V(s) = 0$ if $s$ is a terminal state. We also use a\ntarget network to compute $V(s_{t+1})$ for added stability. The target\nnetwork is updated at every step with a [soft\nupdate](https://arxiv.org/pdf/1509.02971.pdf) controlled by the\nhyperparameter `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\nthe environment and obtain the initial `state` Tensor. Then, we sample\nan action, execute it, observe the next state and the reward (always 1),\nand optimize our model once. When the episode ends (our model fails), we\nrestart the loop.\n\nBelow, [num\\_episodes]{.title-ref} is set to 600 if a GPU is available,\notherwise 50 episodes are scheduled so training does not take too long.\nHowever, 50 episodes is insufficient for to observe good performance on\nCartPole. You should see the model constantly achieve 500 steps within\n600 training episodes. Training RL agents can be a noisy process, so\nrestarting training can produce better results if convergence is not\nobserved.\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\nelse:\n num_episodes = 50\n\nfor 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 # \u03b8\u2032 \u2190 \u03c4 \u03b8 + (1 \u2212\u03c4 )\u03b8\u2032\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\nprint('Complete')\nplot_durations(show_result=True)\nplt.ioff()\nplt.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\nActions are chosen either randomly or based on a policy, getting the\nnext step sample from the gym environment. We record the results in the\nreplay memory and also run optimization step on every iteration.\nOptimization picks a random batch from the replay memory to do training\nof the new policy. The \\\"older\\\" target\\_net is also used in\noptimization to compute the expected Q values. A soft update of its\nweights 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.12" } }, "nbformat": 4, "nbformat_minor": 0 }