Equations · Williams, “Simple statistical gradient-following algorithms for connectionist reinforcement learning” (1992); Sutton et al., policy gradient theorem (2000)
The policy gradient (REINFORCE) formula, explained
The gradient of a policy's expected return, written as something you can estimate from sampled episodes. Each action's log-probability is pushed up in proportion to the return that followed it: actions that led to high returns become more likely.
Term by term
The objective: the expected total (discounted) reward of the policy with parameters . It is maximized, by gradient ascent.
The gradient with respect to the policy's parameters.
An average over trajectories generated by running the policy. In practice, an average over a few sampled episodes. Here is a trajectory, not a temperature.
The direction in parameter space that makes action more likely in state . Taking the gradient of the log is what lets the expectation's gradient be estimated by sampling (the "log-derivative trick").
Logarithm · Pi · Given (conditional bar) · State s and action a
A small worked example
Two actions, softmax policy with logits , so . One episode: action 1 is taken and the return is . For a softmax, . The estimate is ; a step of size gives and .
In code
import torch
def reinforce_loss(log_probs, rewards, gamma=0.99):
# log_probs: (T,) log pi(a_t|s_t) for one episode; rewards: r_1 .. r_T
G, returns = 0.0, []
for r in reversed(rewards):
G = r + gamma * G
returns.insert(0, G)
return -(log_probs * torch.tensor(returns)).sum() # minimize the negativeEvery symbol in it
Other equations
- Scaled dot-product attention
- Softmax
- Cross-entropy loss
- Adam update
- Layer normalization
- RMSNorm
- The ELBO
- KL divergence
- Backpropagation through one layer
- LoRA
- GELU
- Dropout
- Batch normalization
- Rotary position embedding (RoPE)
- Multi-head attention
- PPO clipped objective
- DPO loss
- Bellman equation
- Q-learning update
- InfoNCE contrastive loss
- Diffusion forward process
- DDPM simplified loss
- VAE reparameterization trick
- GAN minimax objective
- AdamW
- Cosine learning-rate schedule
- Perplexity
- Logistic regression
- Normal equation (linear regression)
- Singular value decomposition (SVD)
- Principal component analysis (PCA)