Skip to main content
Given that RL can be posed as an MDP, in this section we continue with a policy-based algorithm that learns the policy directly by optimizing the objective function. The algorithm we treat here, called REINFORCE, is important as its the basis of many other algorithms. It took its name from the fact that during training actions that resulted in good outcomes should become more probable—these actions are positively reinforced. Conversely, actions which resulted in bad outcomes should become less probable. If learning is successful, over the course of many iterations, action probabilities produced by the policy, shift to a distribution that results in good performance in the environment we interact with.
Note that currently the ability of RL to generalize between environments is actively researched. We make no claims of generalization in any algorithm we present. For digging further to RL generalization see Robert Kirk’s post and Google Research’s work.
Action probabilities are changed by following the policy gradient, therefore REINFORCE is known as a policy gradient algorithm. The algorithm needs three components:
ComponentDescription
Parametrized policy πθ(as)\pi_\theta (a \mid s)Neural networks are powerful and flexible function approximators, so we can represent a policy using a neural network with learnable parameters θ\theta - this is the policy network πθ\pi_\theta. Each specific set of parameters of the policy network represents a particular policy - this means that for θ1θ2\theta_1 \neq \theta_2 and a state ss, πθ1(as)πθ2(as)\pi_{\theta_1}(a \mid s) \neq \pi_{\theta_2}(a \mid s) and a single policy network architecture is therefore capable of representing many different policies.
The objective to be maximized J(πθ)J(\pi_\theta)1The expected discounted return, just like in MDP.
Policy GradientA method for updating the policy parameters θ\theta. The policy gradient algorithm searches for a local maximum in J(πθ)J(\pi_\theta): maxθJ(πθ)\max_\theta J(\pi_\theta). This is the common gradient ascent algorithm that adjusts the parameters according to θθ+αθJ(πθ)\theta ← \theta + \alpha \nabla_\theta J(\pi_\theta) where α\alpha is the learning rate. Note that we can pose the objective as a loss that we try to minimize by negating it.
Out of the three components, the most complicated one is the policy gradient that can be shown to be given by the differentiable quantity: θJ(πθ)=Eπθ[θlogπθ(as)vπ(s)] \nabla_\theta J(\pi_\theta)= \mathbb{E}_{\pi_\theta} \left[ \nabla_\theta \log \pi_\theta (a|s) v_\pi (s) \right ] We understand that this expression came out of nowhere but the interested reader can find its detailed derivation in the chapter 2 of this reference. For the derivation we use the log-derivative trick.
Log-Derivative TrickWe begin with a function f(x)f(x) and a parametrized distribution p(xθ)p(x\mid\theta). We want to compute the gradient of the expectation Exp(xθ)[f(x)]\mathbb{E}_{x\sim p(x\mid\theta)}[f(x)] and rewrite it in a form suitable for Monte Carlo estimation.

Step-by-step derivation

θExp(xθ)[f(x)]  =  θf(x)p(xθ)dx\nabla_\theta \mathbb{E}_{x\sim p(x\mid\theta)}[f(x)] \;=\; \nabla_\theta \int f(x)\,p(x\mid\theta)\,dxExplanation: This uses the definition of an expectation under a density: E[f(x)]=f(x)p(x)dx.\mathbb{E}[f(x)] = \int f(x)p(x)\,dx.
=θ ⁣(f(x)p(xθ))dx= \int \nabla_\theta\!\left( f(x)\,p(x\mid\theta) \right)\,dxExplanation: Under mild regularity conditions, differentiation and integration commute (Leibniz rule), allowing us to move θ\nabla_\theta inside the integral.
=(f(x)θp(xθ)  +  p(xθ)θf(x))dx= \int \big( f(x)\,\nabla_\theta p(x\mid\theta) \;+\; p(x\mid\theta)\,\nabla_\theta f(x) \big)\,dxExplanation: This applies the product rule to θ(fp)\nabla_\theta(f p).
=f(x)θp(xθ)dx= \int f(x)\,\nabla_\theta p(x\mid\theta)\,dxExplanation: We assume f(x)f(x) does not depend on θ\theta, so θf(x)=0\nabla_\theta f(x)=0 and the second term vanishes. This is the standard situation in policy-gradient and score-function estimators.
=f(x)p(xθ)  θp(xθ)p(xθ)dx= \int f(x)\,p(x\mid\theta)\; \frac{\nabla_\theta p(x\mid\theta)}{p(x\mid\theta)}\,dxExplanation: Multiply and divide by p(xθ)p(x\mid\theta); this is valid whenever p(xθ)>0p(x\mid\theta)>0 on the support of interest.
=f(x)p(xθ)  θlogp(xθ)dx= \int f(x)\,p(x\mid\theta)\; \nabla_\theta \log p(x\mid\theta)\,dxExplanation: We use the log-derivative identity:θlogp(xθ)=θp(xθ)p(xθ).\nabla_\theta \log p(x\mid\theta) = \frac{\nabla_\theta p(x\mid\theta)}{p(x\mid\theta)}.
=Exp(xθ)[f(x)θlogp(xθ)]= \mathbb{E}_{x\sim p(x\mid\theta)} \left[\, f(x)\,\nabla_\theta \log p(x\mid\theta)\,\right]Explanation: We rewrite the integral back into expectation form.
This transformation is crucial because it converts the problem of differentiating through an expectation into an expectation of a tractable quantity, enabling Monte Carlo estimation even when f(x)f(x) is a black-box function without a closed-form gradient. We can approximate the value at state ss with the return over many sample trajectories τ\tau that are sampled from the policy network. θJ(πθ)=Eτπθ[Gtθlogπθ(as)] \nabla_\theta J(\pi_\theta)= \mathbb{E}_{\tau \sim \pi_\theta} \left[ G_t \nabla_\theta \log \pi_\theta (a|s) \right ] where GtG_t is the return - a quantity we have seen earlier albeit now the return is limited by the length of each trajectory just like in MC method, Gt(τ)=k=0T1γkRt+1+kG_t(\tau) = \sum_{k=0}^{T-1}\gamma^k R_{t+1+k} The γ\gamma is usually a hyper-parameter that we need to optimize usually iterating over many values in [0.01,…,0.99] and selecting the one with the best results. We also have an expectation in the gradient expression that we need to address. The expectation Eτπθ\mathbb E_{\tau \sim \pi_\theta} we need to take is approximated with a summation over each trajectory aka a Monte-Carlo approximation. Effectively, we are generating the right hand side as in line 8 in the code below, by sampling a trajectory (line 4) and estimating its return (line 7) in a completely model-free fashion i.e. without assuming any knowledge of the transition and reward functions. This is implemented next:
Algorithm: Monte Carlo Policy Gradient (REINFORCE)
LineStatement
1Initialize learning rate α\alpha
2Initialize policy parameters θ\theta of policy network πθ\pi_\theta
3for episode =0= 0 to MAX_EPISODE do
4\quad Sample trajectory τ=(s0,a0,r0,,sT,aT,rT)\tau = (s_0, a_0, r_0, \ldots, s_T, a_T, r_T) using πθ\pi_\theta
5\quad θJ(πθ)0\nabla_\theta J(\pi_\theta) \leftarrow 0
6\quad for t=0t = 0 to T1T-1 do
7\quad\quad Compute return Gt(τ)G_t(\tau)
8\quad\quad θJ(πθ)θJ(πθ)+Gt(τ)θlogπθ(atst)\nabla_\theta J(\pi_\theta) \leftarrow \nabla_\theta J(\pi_\theta) + G_t(\tau) \cdot \nabla_\theta \log \pi_\theta(a_t \mid s_t)
9\quad end for
10\quad θθ+αθJ(πθ)\theta \leftarrow \theta + \alpha \cdot \nabla_\theta J(\pi_\theta)
11end for
It is important that a trajectory is discarded after each parameter update—it cannot be reused. This is because REINFORCE is an on-policy algorithm just like the MC it “learns on the job”. This is evidently seen in line 10 where the parameter update equation uses the policy gradient that itself (line 8) directly depends on action probabilities πθ(atst)\pi_\theta(a_t | s_t) generated by the current policy πθ\pi_\theta only and not some other policy πθ\pi_{\theta'}. Correspondingly, the return Gt(τ)G_t(\tau) where τπθ\tau \sim \pi_\theta must also be generated from πθ\pi_\theta, otherwise the action probabilities will be adjusted based on returns that the policy wouldn’t have generated.

Policy Network

One of the key ingredients that REINFORCE introduces is the policy network that is approximated with a NN eg. a fully connected neural network (e.g. two RELU-layers). 1: Given a policy network net, a Categorical (multinomial) distribution class, and a state 2: Compute the output pdparams = net(state) 3: Construct an instance of an action probability distribution  pd = Categorical(logits=pdparams) 4: Use pd to sample an action, action = pd.sample() 5: Use pd and action to compute the action log probability, log_prob = pd.log_prob(action) Other discrete distributions can be used and many actual libraries parametrize continuous distributions such as Gaussians.

Applying the REINFORCE algorithm

It is now instructive to see an stand-alone example in python for the so called CartPole-v0 2 cartpole
 1  from torch.distributions import Categorical
 2  import gym
 3  import numpy as np
 4  import torch
 5  import torch.nn as nn
 6  import torch.optim as optim
 7
 8  gamma = 0.99
 9
10  class Pi(nn.Module):
11      def __init__(self, in_dim, out_dim):
12          super(Pi, self).__init__()
13          layers = [
14              nn.Linear(in_dim, 64),
15              nn.ReLU(),
16              nn.Linear(64, out_dim),
17          ]
18          self.model = nn.Sequential(*layers)
19          self.onpolicy_reset()
20          self.train() # set training mode
21
22      def onpolicy_reset(self):
23          self.log_probs = []
24          self.rewards = []
25
26      def forward(self, x):
27          pdparam = self.model(x)
28          return pdparam
29
30      def act(self, state):
31          x = torch.from_numpy(state.astype(np.float32)) # to tensor
32          pdparam = self.forward(x) # forward pass
33          pd = Categorical(logits=pdparam) # probability distribution
34          action = pd.sample() # pi(a|s) in action via pd
35          log_prob = pd.log_prob(action) # log_prob of pi(a|s)
36          self.log_probs.append(log_prob) # store for training
37          return action.item()
38
39  def train(pi, optimizer):
40      # Inner gradient-ascent loop of REINFORCE algorithm
41      T = len(pi.rewards)
42      rets = np.empty(T, dtype=np.float32) # the returns
43      future_ret = 0.0
44      # compute the returns efficiently
45      for t in reversed(range(T)):
46          future_ret = pi.rewards[t] + gamma * future_ret
47          rets[t] = future_ret
48      rets = torch.tensor(rets)
49      log_probs = torch.stack(pi.log_probs)
50      loss = - log_probs * rets # gradient term; Negative for maximizing
51      loss = torch.sum(loss)
52      optimizer.zero_grad()
53      loss.backward() # backpropagate, compute gradients
54      optimizer.step() # gradient-ascent, update the weights
55      return loss
56
57  def main():
58      env = gym.make('CartPole-v0')
59      in_dim = env.observation_space.shape[0] # 4
60      out_dim = env.action_space.n # 2
61      pi = Pi(in_dim, out_dim) # policy pi_theta for REINFORCE
62      optimizer = optim.Adam(pi.parameters(), lr=0.01)
63      for epi in range(300):
64          state = env.reset()
65          for t in range(200): # cartpole max timestep is 200
66              action = pi.act(state)
67              state, reward, done, _ = env.step(action)
68              pi.rewards.append(reward)
69              env.render()
70              if done:
71                  break
72          loss = train(pi, optimizer) # train per episode
73          total_reward = sum(pi.rewards)
74          solved = total_reward > 195.0
75          pi.onpolicy_reset() # onpolicy: clear memory after training
76          print(f'Episode {epi}, loss: {loss}, \
77          total_reward: {total_reward}, solved: {solved}')
78
79  if __name__ == '__main__':
80      main()
The REINFORCE algorithm presented here can generally be applied to continuous and discreet problems but it has been shown to possess high variance and sample-inefficiency. Several improvements have been proposed and the interested reader can refer to section 2.5.1 of the suggested book.
Connect these docs to Claude, VSCode, and more via MCP for real-time answers.

Footnotes

  1. Notation wise, since we need to have a bit more flexibility in RL problems, we will use the symbol J(πθ)J(\pi_\theta) as the objective function.
  2. Please note that SLM-Lab, is the library that accompanies this book. You will learn a lot by reviewing the implementations under the agents/algorithms directory to get a feel of how RL problems are abstracted.