Function Approximation in Reinforcement Learning

Dive into Deep Learning · §14.9

Function Approximation in Reinforcement Learning
tables as one-hot linear nets · neural tangent kernel · ActorCritic MLPs · truncation bootstrap · Gaussian policies · score vs. pathwise gradients

Why Continuous Control Requires Function Approximation

Motivation & Mental Model

  • Zero state revisits on CartPole-v1: Because \mathbf{s}_t = (x_t, \dot{x}_t, \vartheta_t, \dot{\vartheta}_t)^\top \in \mathbb{R}^4 is continuous, an agent never visits the exact same state vector twice across 1{,}000 episodes.
  • Shared-weight generalization: A lookup table learns nothing at \vartheta + 10^{-4} from an update at \vartheta, whereas a neural network shares weights \theta across the entire state space.

Tables as One-Hot Linear Nets and the Tangent Kernel

How One Update Spreads Across States

\Delta \hat{V}_w(s) \approx \eta_V\big(y - \hat{V}_w(s_0)\big)\,k(s, s_0)

  • Tabular isolation (k(s, s_0) = \mathbf{1}(s = s_0)): One-hot features \nabla_w \hat{V}_w(s) = \mathbf{e}_s leave every unvisited state untouched.
  • Neural coupling (k(s, s_0) = \nabla_w \hat{V}_w(s)^\top \nabla_w \hat{V}_w(s_0)): Positive for nearby states s \approx s_0 (generalization), but nonzero or negative at distant states (interference).

The ActorCritic Container and Tanh MLPs

Replacing Policy and Value Tables with Networks

  • Separate 64-unit tanh MLPs: ActorCritic pairs an actor network (opt_pi) with a critic baseline network (opt_v).
  • Why tanh activations: Smooth activation surfaces outperform ReLU on low-dimensional on-policy control benchmarks (Andrychowicz et al., 2021).
def tanh_mlp(in_dim, hidden, out_dim):
    """A network with one tanh hidden layer."""
    return nn.Sequential(nn.Linear(in_dim, hidden), nn.Tanh(),
                         nn.Linear(hidden, out_dim))

@classmethod
def mlp(cls, obs_dim, num_actions, hidden=64, lr=1e-2, seed=None):
    """The same container with the tables replaced by one-hidden-layer nets."""
    with d2l.seeded(seed):
        policy, value = (tanh_mlp(obs_dim, hidden, num_actions),
                         tanh_mlp(obs_dim, hidden, 1))
    return cls(policy, value, lr)

Multi-Step Value Regression per Batch

Keeping the Critic Baseline Accurate

Unlike the in-place tabular update (\eta_V = 0.1), a value net fits targets y_t \sim 100 via Adam steps of 10^{-2}:

def fit_value(ac, obs, target, num_steps=1):
    """Regress the value head on a fixed target: eq_value_baseline for nets."""
    obs, target = torch.as_tensor(obs), torch.as_tensor(target)
    for _ in range(num_steps):
        loss = ((ac.V(obs) - target) ** 2).mean()
        ac.opt_v.zero_grad()
        loss.backward()
        ac.opt_v.step()
    return loss.item()
  • Why 1 gradient step per batch lags behind: On Pendulum, taking num_steps=1 per batch explains only 40\%–80\% of return variance (1 - \textrm{Var}(y - \hat{V})/\textrm{Var}(y)), leaving massive noise in the policy weights; num_steps=40 raises explained variance to \approx 99\%.

Bootstrapping Time-Limit Truncations

Preventing Artificial Penalties on Long Episodes

y_t = \hat{G}_t + (1 - \textrm{term}_T)\,\gamma^{T - t}\,\hat{V}_w(s_T)

  • Numerical severity on CartPole (\gamma = 0.99): At step t = 490 of a 500-step win (\hat{V} \approx 100), unbootstrapped \hat{G}_{490} \approx 9.6 yields advantage -90.4, punishing balanced play.
def truncation_bootstrap(self, gamma, V):
    """gamma^(T-t) (1 - term_T) V(s_T) for every step t of each episode:
    the discounted value of the future that a time-limit cut did not see.
    V maps a batch of numpy states to numpy values."""
    tail = np.zeros_like(self.rew)
    last = self.ep_ends - 1
    tail[last] = gamma * (1 - self.term[last]) * V(self.next_obs[last])
    return self.backward_scan(tail, gamma)

The Neural REINFORCE Training Loop

Combining Rollouts, Truncation Bootstrap, and Value Regression

train_reinforce collects 8 episodes per update, adds truncation_bootstrap to reward_to_go, standardizes the empirical advantages y_t - \hat{V}_w(s_t), updates the actor once, and fits the critic for 40 steps:

def train_reinforce(seed, make_agent, env_name, gamma=0.99, num_updates=60,
                    batch_episodes=8, value_steps=40):
    """REINFORCE with a learned baseline for the agent `make_agent` builds."""
    rng, env = np.random.default_rng(seed), gym.make(env_name)
    ac = make_agent(seed)
    env.reset(seed=seed)
    for _ in range(num_updates):
        batch = d2l.rollout(env, ac.act, batch_episodes, rng)
        G = (batch.reward_to_go(gamma)
             + batch.truncation_bootstrap(gamma, ac.value_np))   # time limits
        w = d2l.standardize(G - ac.value_np(batch.obs))
        L = d2l.policy_step(ac, batch.obs, batch.act, w)
        fit_value(ac, batch.obs, G, num_steps=value_steps)  # fit V-hat well
        yield float(batch.episode_returns().mean()), L
  • Four practical departures from exact \nabla_\theta J: (1) Dropping \gamma^t weights all steps equally; (2) bootstrapping s_T injects critic bias at cutoffs; (3) batch centering couples samples; and (4) dividing by batch \sigma and N rescales gradients before Adam’s coordinate normalization.

REINFORCE with a Learned Baseline on CartPole

Reaching the 500-Step Ceiling

Training 3 seeds of ActorCritic.mlp(4, 2) on CartPole-v1 with \gamma = 0.99 (effective horizon 100 steps) solves the task within 50 updates (\approx 120{,}000 environment steps):

  • Rapid climb from random play: Untrained MLPs drop the pole after \approx 20 steps; all 3 seeds reach the 500-step ceiling by update 50.
  • Role of truncation bootstrap: Without truncation_bootstrap, late updates frequently dip below 500 as successful trajectories penalize their final steps.

Why the Surrogate Policy Loss Value Is Uninformative

Monitoring RL Training Properly

Deep learning frameworks compute the policy gradient by differentiating the scalar surrogate loss L(\theta) = -\frac{1}{N}\sum_t \tilde{w}_t \log \pi_\theta(a_t \mid s_t) with \tilde{w}_t detached:

L(\theta) = -\frac{1}{N}\sum_{t=1}^N \tilde{w}_t\,\log \pi_\theta(a_t \mid s_t) = -s_{\log\pi}\,\textrm{corr}(\tilde{w}, \log\pi)

  • Gradient matches, scalar value does not: While CartPole return climbs from 20 to 500, L(\theta) hovers near -0.05 because standardized weights \tilde{w}_t have mean 0 and unit variance.
  • Debugging rule: Always monitor episode returns, value explained variance, and policy entropy—never the scalar value of L(\theta).

Continuous Actions: The Gaussian Policy

Parameterizing Real-Valued Torques

For continuous control (Pendulum-v1, torque u \in [-2, 2]), GaussianPolicy models \pi_\theta(a \mid s) = \mathcal{N}(a;\; \mu_\theta(s), \sigma^2) using an MLP mean head \mu_\theta(s) and a learnable log-standard-deviation parameter \log\sigma:

\log \pi_\theta(a \mid s) = -\frac{1}{2}z^2 - \log\sigma - \frac{1}{2}\log(2\pi), \qquad \frac{\partial \log \pi_\theta}{\partial \mu} = \frac{z}{\sigma}, \qquad \frac{\partial \log \pi_\theta}{\partial \log\sigma} = z^2 - 1

where z = (a - \mu_\theta(s))/\sigma.

density: True
score in mu: True | score in log sigma: True
  • How \mu and \sigma adapt: A positive advantage weight \tilde{w}_t > 0 pulls the mean \mu_\theta(s) toward a_t (via z/\sigma), widens \sigma when an outlier |z| > 1 succeeds, and shrinks \sigma when near-mean actions |z| < 1 succeed.

Swinging Up Pendulum with Neural REINFORCE

Zero-Mean Initialization and Sample Complexity

Training GaussianPolicy(3, 1, zero_mean=True) on Pendulum-v1 over 300 updates of 8 episodes (480{,}000 total steps) swings up and balances the pendulum across all seeds:

  • Why zero_mean=True matters: Initializing the final mean layer to zero (\mu_0(s) = 0, \sigma_0 = 1) prevents early torques from saturating the [-2, 2] clip bounds where reward feedback vanishes.
  • High on-policy sample cost vs. §14.6 & §15.5: Unlike §14.6’s iLQR planner (which differentiated known physics directly), model-free REINFORCE learns from trig observations (\cos\vartheta, \sin\vartheta, \dot{\vartheta}) and scalar rewards alone—taking 150–300 updates (\sim 300{,}000 steps) to cross §14.6’s -200 balancing bar, whereas off-policy SAC (§15.5) will solve it in 5{,}000–11{,}000 steps.

Score-Function vs. Pathwise Action Gradients

Two Ways to Differentiate Through Continuous Actions

When the return or critic Q(a) is a differentiable function of a continuous action a = \mu + \sigma z with z \sim \mathcal{N}(0, 1), we can compare the score-function gradient against the pathwise gradient (Kingma & Welling, 2014):

\nabla_\mu\,\mathbb{E}_{a \sim \mathcal{N}(\mu, \sigma^2)}\big[Q(a)\big] = \underbrace{\mathbb{E}\Big[Q(a)\,\frac{a - \mu}{\sigma^2}\Big]}_{\text{score-function estimator}} = \underbrace{\mathbb{E}_{z \sim \mathcal{N}(0, 1)}\big[Q'(\mu + \sigma z)\big]}_{\text{pathwise (reparameterization) estimator}}

score:    mean 1.98, variance 21.5
pathwise: mean 2.00, variance 1.00
score variance if Q gains a constant +10: 281; pathwise is unchanged
  • 20× lower variance and shift invariance: On Q(a) = -(a-1)^2 at \mu = 0, \sigma = 0.5, the pathwise estimator has variance 1.00 vs. 21.5 for the score function (exact: 21.75), and is completely invariant to adding +10 to Q(a) (which bloats score-function variance to 281).

Information Flow: Score Function vs. Pathwise Critic

Trade-Off Between Black-Box Rewards and Critic Bias

Comparing the computational graphs shows why on-policy REINFORCE uses the score function while off-policy continuous actor-critics (DDPG, TD3, SAC) use pathwise gradients:

  • Score function (a): Treats the environment as a non-differentiable black box returning scalar numbers R, so it works for discrete actions and unknown dynamics without bias from a critic’s slope.
  • Pathwise gradient (b): Differentiates \partial Q_w / \partial a \cdot \partial a / \partial \theta through a learned neural critic Q_w(s, a), trading massive variance reduction for sensitivity to errors in \partial Q_w / \partial a.

Measuring State Coupling via the Tangent Kernel

Generalization and Interference in a Value MLP

Applying a single plain-SGD step to raise \hat{V}_w(s_0) at one state s_0 \in [-1, 1]^4 by +0.50 measures how the 64-unit tanh MLP moves 255 other random states sorted by Euclidean distance \|s - s_0\|:

network: nudged state +0.49; 10 nearest probes +0.43, 10 farthest -0.06; 15 of 255 moved down
table:   nudged entry +0.50; largest move among the other fifteen: 0.000000
  • Local generalization vs. far-field drift: The 10 nearest states in \mathbb{R}^4 rise by +0.43 to +0.49 (nearly 90\% of s_0’s +0.49 to +0.55 move), whereas the 10 farthest states drift slightly negative (-0.01 to -0.06, with 6–15 of 255 states moving down), while the lookup table moves +0.50 at s_0 and 0.000000 everywhere else.

Visualizing Table Isolation vs. Network Coupling

The Double-Edged Sword of Function Approximation

Plotting a 1D slice of the value function before and after a single +0.50 update at x_0 illustrates why neural RL is both powerful and fragile:

  • Generalization (the positive bump around x_0): Experience at x_0 immediately informs nearby states without visiting them.
  • Interference and the deadly triad: Fitting batches of upright CartPole states alters \hat{V}_w(s) at large tilt angles; when combined with bootstrapping and off-policy data (the deadly triad of Tsitsiklis & Van Roy, 1997), global parameter coupling can cause value iteration to diverge.

Synthesis: Roadmap of Chapter 14 and Chapter 15

What Each Method Learns and Which Data It Consumes

Every algorithm across Chapters 14 and 15 is positioned by two axes: what object it parameterizes (values, policy, or dynamics model) and which data distribution drives its update:

  • Solid boxes (Chapter 14): Exact DP on P, tabular TD (Q-learning/SARSA), bandits (UCB/Thompson), imitation (BC/DAgger), optimal control (LQR/iLQR/MPC), and on-policy Monte Carlo policy gradients (REINFORCE/RLOO/GRPO).
  • Dashed boxes (Chapter 15): Bootstrapped actor-critics (A2C), clipped batch reuse (PPO), replay-buffer value nets (DQN, SAC), learned dynamics models, and pessimistic offline RL.

Concept Check: Function Approximation in RL

Check Your Understanding

Test your understanding of time-limit bootstrapping, Gaussian scores, and pathwise gradients:

  1. Truncation bootstrap: At step t = 490 of a 500-step CartPole episode (\gamma = 0.99) where \hat{V}_w(s) \approx 100 for all upright states, what is the unbootstrapped reward-to-go \hat{G}_{490}, and what is the bootstrapped target y_{490}?
  2. Gaussian exploration decay: Under the Gaussian score \partial_{\log\sigma} \log \pi_\theta(a \mid s) = z^2 - 1, why does \sigma automatically shrink as the mean network \mu_\theta(s) converges toward the optimal action a^*(s)?
  3. Score vs. pathwise on discontinuous rewards: If a verifier pays a step-function reward Q(a) = \mathbf{1}(a > 1), what gradient does the pathwise estimator \mathbb{E}[Q'(\mu + \sigma z)] return, and why does the score-function estimator still work?

Answers:

  1. Without bootstrapping, \hat{G}_{490} = \sum_{k=0}^9 0.99^k = (1 - 0.99^{10})/0.01 \approx 9.56, giving a false negative advantage 9.56 - 100 = -90.44. Adding \gamma^{10}\hat{V}_w(s_{500}) = 0.99^{10}(100) \approx 90.44 restores y_{490} \approx 100.0 and zero advantage.
  2. Once \mu_\theta(s) \approx a^*(s), samples close to the mean (|z| < 1, where z^2 - 1 < 0) achieve the highest return and receive positive advantage weights \tilde{w}_t > 0, while far samples (|z| > 1) receive negative weights—both pushing \log\sigma downward.
  3. Because Q'(a) = 0 everywhere except the jump at a = 1, the pathwise estimator returns 0 for every sample and fails completely; the score-function estimator differentiates \log \pi_\theta(a) instead of Q(a) and remains unbiased for discontinuous rewards.

Summary: From Tabular RL to Function Approximation

Key Takeaways

Component Mathematical Form Purpose & Systems Behavior
Tangent kernel k(s, s_0) = \nabla_w \hat{V}_w(s)^\top \nabla_w \hat{V}_w(s_0) Governs how a step at s_0 generalizes to nearby s and interferes far away
Truncation bootstrap y_t = \hat{G}_t + (1 - \textrm{term}_T)\gamma^{T-t}\hat{V}_w(s_T) Restores unrecorded future value when an episode hits a clock limit
Surrogate loss L(\theta) = -\frac{1}{N}\sum_t \tilde{w}_t \log \pi_\theta(a_t \mid s_t) Generates -\hat{g} via autograd; its scalar value -s_{\log\pi}\textrm{corr} does not track return
Gaussian policy \pi_\theta(a \mid s) = \mathcal{N}(a;\; \mu_\theta(s), \sigma^2) Scores continuous actions via \partial_\mu \log\pi = z/\sigma and \partial_{\log\sigma}\log\pi = z^2 - 1
Pathwise gradient \nabla_\mu \mathbb{E}[Q(a)] = \mathbb{E}_{z \sim \mathcal{N}(0, 1)}[Q'(\mu + \sigma z)] 20\times lower variance than score function, but requires a differentiable critic Q_w