# Spinning Up by OpenAI

Some note from [OpenAI Spinning Up](https://spinningup.openai.com/%3E)

## Kinds of RL Algorithms

![A Taxonomy of RL Algorithms](https://4133958719-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LigLKy0c06y4iTEtrkI%2F-LpEThBmKrC0qKCQW9S7%2F-LpETiNfRl5rUR2K8LKx%2Frl_algorithms_9_15.svg?generation=1568996518314094\&alt=media)

## Key Algorithms

### Vanilla Policy Gradient

The key idea underlying policy gradient is to push up the possibilities of actions that lead to higher return, and push down the possibilities of actions that lead to lower return, until you arrive at the optimal policy.

#### Quick Facts

* on-policy
* discrete or continuous action spaces

#### Key Equations

Let $$\pi\_\theta$$ denote a policy with parameters $$\theta$$, and $$J(\pi\_\theta)$$ denote the expected finite-horizon undiscounted return of the policy. The gradient of $$J(\pi\_\theta)$$ is

$$
\nabla\_{\theta} J(\pi\_{\theta}) = E\_{\tau \sim \pi\_{\theta}}{ \left\[    \sum\_{t=0}^{T} \nabla\_{\theta} \log \pi\_{\theta}(a\_t|s\_t) A^{\pi\_{\theta}}(s\_t,a\_t)  \right]   },
$$

where $$\tau$$ is a trajectory and $$A^{\pi\_\theta}$$ is the advantage function for the current policy.

The policy gradient algorithm works by updating policy parameters via stochastic gradient ascent on policy performance:

$$
\theta\_{k+1} = \theta\_k + \alpha \nabla\_{\theta} J(\pi\_{\theta\_k})
$$

#### Exploration vs. Exploitation

VPG trains a stochastic policy in an on-policy way. This means that it explores by sampling actions according to the latest version of its stochastic policy. The amount of randomness in action selection depends on both initial conditions and the training procedure. Over the course of training, the policy typically becomes progressively less random, as the update rule encourages it to exploit rewards that it has already found. This may cause the policy to get trapped in local optima.

#### Pseudocode

![VPG Algorithms](https://4133958719-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LigLKy0c06y4iTEtrkI%2F-LpEThBmKrC0qKCQW9S7%2F-LpETiNhV6fe0dkMrnxu%2F47a7bd5139a29bc2d2dc85cef12bba4b07b1e831-1568993898425.svg?generation=1568996518552098\&alt=media)

#### References

* [Policy Gradient Methods for Reinforcement Learning with Function Approximation](https://papers.nips.cc/paper/1713-policy-gradient-methods-for-reinforcement-learning-with-function-approximation.pdf), Sutton et al. 2000
  * timeless classic of RL theory
  * contains references to the earlier work which led to modern policy gradients.
* [Optimizing Expectations: From Deep Reinforcement Learning to Stochastic Computation Graphs](http://joschu.net/docs/thesis.pdf), Schulman 2016(a)
  * chapter 2 contains a lucid introduction to the theory of policy gradient algorithms, including pseudocode.
* [Benchmarking Deep Reinforcement Learning for Continuous Control](https://arxiv.org/abs/1604.06778), Duan et al. 2016
  * recent benchmark paper that shows how vanilla policy gradient in the deep RL setting(eg. with neural network policies and Adam as the optimizer) compares with other deep RL algorithms.
* [High Dimensional Continuous Control Using Generalized Advantage Estimation](https://arxiv.org/abs/1506.02438), Schulman et al. 2016(b)
  * the implementation VPG makes use of Generalized Advantage Estimation for computing the policy gradient.

### Trust Region Policy Optimization

TRPO updates policies by taking the largest step possible to improve performance, while satisfying a special constraint on how close the new and old policies are allowed to be. The constraint is expressed in terms of KL-Divergence, a measure of distance between probability distributions.

This is different from normal policy gradient, which keeps new and old policies close in parameter space. But even seemingly small differences in parameter space can have very large differences in performance -- so a single bad step can collapse the policy performance. This make it dangerous to use large step sizes with vanilla policy gradients, thus hurting its sampling efficiency. TRPO nicely avoids this kind of collapse, and tends to quickly and monotonically improve performance.

#### Quick Facts

* on-policy
* discrete or continuous action spaces

#### Key Equations

Let $$\pi\_\theta$$ denote a policy with parameter $$\theta$$. The theoretical TRPO update is:

$$
\begin{align}
\theta\_{k+1} = \arg \max\_{\theta} ; & {\mathcal L}(\theta\_k, \theta) \ \text{s.t.} ; & \bar{D}\_{KL}(\theta || \theta\_k) \leq \delta
\end{align}
$$

where $$\mathcal{L}(\theta\_k,\theta)$$ is the *surrogate advantage*. a measure of how policy $$\pi\_\theta$$ performs relative to the old policy $$\pi\_{\theta\_k}$$ using data from the old policy:

$$
{\mathcal L}(\theta\_k, \theta) = E\_{s,a \sim \pi\_{\theta\_k}}{\left\[  \frac{\pi\_{\theta}(a|s)}{\pi\_{\theta\_k}(a|s)} A^{\pi\_{\theta\_k}}(s,a)    \right] },
$$

and $$\bar{D}\_{KL}(\theta||\theta\_k)$$ is an average KL-divergence between policies across states visited by the old policy:

$$
\bar{D}*{KL}(\theta || \theta\_k) = E*{s \sim \pi\_{\theta\_k}}{  \left\[   D\_{KL}\left(\pi\_{\theta}(\cdot|s) || \pi\_{\theta\_k} (\cdot|s) \right)\right] }.
$$

Notice that the objective and constraint are both zero when $$\theta=\theta\_k$$. Furthermore, the gradient of the constraint with respect to $$\theta$$ is zero when $$\theta=\theta\_k$$.

The theoretical TRPO update isn't the easiest to work with, so TRPO makes some approximations to get an answer quickly. We Taylor expand the objective and constraint to leading order around $$\theta\_k$$:

$$
\begin{align}
{\mathcal L}(\theta\_k, \theta) &\approx g^T (\theta - \theta\_k) \\
\bar{D}\_{KL}(\theta || \theta\_k) & \approx \frac{1}{2} (\theta - \theta\_k)^T H (\theta - \theta\_k)
\end{align}
$$

resulting in an approximate optimization problem,

$$
\begin{align}
\theta\_{k+1} = \arg \max\_{\theta} ; & g^T (\theta - \theta\_k) \ \text{s.t.} ; & \frac{1}{2} (\theta - \theta\_k)^T H (\theta - \theta\_k) \leq \delta.
\end{align}
$$

Notice that the gradient $$g$$ of the surrogate advantage function with respect to $$\theta$$, evaluate at $$\theta=\theta\_k$$, is exactly equal to the policy gradient, $$\nabla\_\theta J(\pi\_\theta)$$.

This approximate problem can be analytically solved by the methods of Lagrangian duality, yielding the solution:

$$
\theta\_{k+1} = \theta\_k + \sqrt{\frac{2 \delta}{g^T H^{-1} g}} H^{-1} g.
$$

If we were to stop here, and just use this final result, the algorithm would be exactly calculating the *Natural Policy Gradient*. A problem is that, due to the approximation errors introduced by the Taylor expansion, this may not satisfy the KL constraint, or actually improve the surrogate advantage. TRPO adds a modification to this update rule: a backtracking line search,

$$
\theta\_{k+1} = \theta\_k + \alpha^j \sqrt{\frac{2 \delta}{g^T H^{-1} g}} H^{-1} g,
$$

where $$\alpha\in (0,1)$$ is the backtracking coefficient, and $$j$$ is the smallest nonnegative integer such that $$\pi\_{\theta\_{k+1}}$$ satisfies the KL constraint and produces a positive surrogate advantage.

Lastly: computing and storing the matrix inverse, $$H^{-1}$$, is painfully expensive when dealing with neural network policies with thousands or millions of parameters. TRPO sidesteps the issue by using the conjugate gradient algorithm to solve $$Hx=g$$ for $$x=H^{-1}g$$, requiring only a function which can compute the matrix-vector product $$Hx$$ instead of computing and storing the whole matrix $$H$$ directly. This is not too hard to do: we set up a symbolic operation to calculate

$$
Hx = \nabla\_{\theta} \left( \left(\nabla\_{\theta} \bar{D}\_{KL}(\theta || \theta\_k)\right)^T x \right),
$$

which gives s the correct output without computing the whole matrix.

#### Exploration vs. Exploitation

TRPO trains a stochastic policy in an on-policy way. This means that it explores by sampling actions according to the latest version of its stochastic policy. The amount of randomness in action selection depends on both initial conditions and the training procedure. Over the course of training, the policy typically becomes progressively less random, as the update rule encourages it to exploit rewards that it has already found. This may cause the policy to get trapped in local optima.

#### Pseudocode

![TRPO Algorithm](https://4133958719-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LigLKy0c06y4iTEtrkI%2F-LpIqUztC1ytPf50e4R-%2F-LpIqW-pqZEu9e27yqFZ%2Ffece98b123fdbe62167dade95a7c53d836ddc5a1-1569069512095.svg?generation=1569069864901432\&alt=media)

#### References

* [Trust Region Policy Optimization](https://arxiv.org/abs/1502.05477), Schulman et al. 2015
  * original paper describing TRPO
* [High Dimensional Continuous Control Using Generalized Advantage Estimation](https://arxiv.org/abs/1506.02438), Schulman et al. 2016
  * Generalized Advantage Estimation
* [Approximately Optimal Approximate Reinforcement Learning](https://people.eecs.berkeley.edu/~pabbeel/cs287-fa09/readings/KakadeLangford-icml2002.pdf), Kakade and Langford 2002
  * contains theoretical results which motivate and deeply connect to the theoretical foundations of TRPO.

### Proximal Policy Optimization

#### Quick Facts

#### Key Equations

#### Exploration vs. Exploitation

#### Pseudocode

#### References

### Deep Deterministic Policy Gradient

#### Quick Facts

#### Key Equations

#### Exploration vs. Exploitation

#### Pseudocode

#### References

### Twin Delayed DDPG

#### Quick Facts

#### Key Equations

#### Exploration vs. Exploitation

#### Pseudocode

#### References

### Soft Actor-Critic

#### Quick Facts

#### Key Equations

#### Exploration vs. Exploitation

#### Pseudocode

#### References


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://drdh.gitbook.io/rl/resources/spinning-up-by-openai.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
