14.9 Function Approximation in Reinforcement Learning

Apart from the planners of Section 14.6, which worked from known equations of motion, every quantity we have learned so far lived in a table: sixteen rows for the cells of the lake, one row for each prompt of the verifier task. Now picture a cart that balances a pole hinged on top of it. Its state is four real numbers, the cart's position and velocity and the pole's angle and angular velocity, and in a thousand episodes the agent will never see the same four numbers twice. A table over such states would need a new row for every visit, and what it learned at one visit would say nothing about the next. We want a function that gives similar values to similar states, so that what the agent learns while the pole leans left at one speed carries over to the moment it leans left at a slightly different speed.

The problem is as old as the field. Bellman named the growth of tables with the number of state variables the curse of dimensionality (Bellman, 1957), and in 1959 Arthur Samuel's checkers program already scored board positions by a weighted sum of features instead of looking them up (Samuel, 1959). Replacing a table by a parameterized function is called function approximation. With neural networks as the functions, it carried reinforcement learning to backgammon (Tesauro, 1995), to Atari games (mnih2015human, ) and to Go (Silver et al., 2016).

For policy gradients the step is short, because nothing in the derivations of Section 14.7 and Section 14.8 used the table. REINFORCE needs only the score ∇θlog⁡πθ(a∣s)\nabla_\theta \log \pi_\theta(a \mid s), and a network supplies it as readily as a table row. What changes is that one update now moves the estimate at every state. This sharing makes learning on continuous states possible, and it is also a new way for learning to go wrong. We make the step on two small control tasks, a cart with a pole and a pendulum driven by a continuous torque, measure how far one update spreads, and end with what the resulting agent still cannot do.

import gymnasium as gym

14.9.1 Networks in Place of Tables#

The tables of the earlier sections become networks in two places: the policy, and the value estimate that served as a baseline. Before writing either network we look at a table in a form that a network extends.

14.9.1.1 Tables as Linear Networks on One-Hot States#

Policy.tabular of Section 14.5 stores its preferences in a 16×416 \times 4 embedding table θ\theta, and the preferences at state ss are row ss of that table. Row ss equals θ⊤es\theta^\top \mathbf{e}_s, where es\mathbf{e}_s is the one-hot vector of state ss. A table is therefore a linear network whose input features are fixed one-hot vectors. The classic remedy for continuous states has the same form: it cuts the state space into boxes and lets es\mathbf{e}_s be the one-hot vector of the box that contains ss. An early learning controller for the cart and pole below used 162 such boxes, a partition designed by hand (Barto et al., 1983). A network with one hidden layer keeps this form and replaces the fixed features by learned ones: the preferences become W2tanh⁡(W1s+b1)+b2\mathbf{W}_2 \tanh(\mathbf{W}_1 \mathbf{s} + \mathbf{b}_1) + \mathbf{b}_2, where s\mathbf{s} is now the vector of real-valued observations itself.

The two forms differ in what one update does. Take a value estimate V^w\hat{V}_w with parameters ww and one gradient step of size ηV\eta_V on 12(y−V^w(s0))2\frac{1}{2}\big(y - \hat{V}_w(s_0)\big)^2, which moves the estimate at a single state s0s_0 toward a target yy. To first order in ηV\eta_V, the estimate at any state ss changes by

ΔV^(s)=ηV(y−V^(s0)) k(s,s0),k(s,s0)=∇wV^(s)⊤∇wV^(s0).(14.9.1)\Delta \hat{V}(s) = \eta_V \big(y - \hat{V}(s_0)\big)\, k(s, s_0), \qquad k(s, s_0) = \nabla_w \hat{V}(s)^\top \nabla_w \hat{V}(s_0). \tag{14.9.1}

Thus the change at ss is the change requested at s0s_0, scaled by how much the gradients at the two states overlap. For a table, ∇wV^(s)=es\nabla_w \hat{V}(s) = \mathbf{e}_s, so k(s,s0)k(s, s_0) is 11 when s=s0s = s_0 and 00 otherwise: a gradient step at one state leaves every other entry where it was. (Adam, the default optimizer of Policy, can still move an entry whose gradient is zero in the current batch, through its stored momentum, so the statement holds for gradients rather than for every optimizer step.) For a network, kk is a smooth function of the two states, which is the tangent kernel of the network (Jacot et al., 2018). A step at s0s_0 then moves the estimates at similar states along with it. Exercise 7 derives (14.9.1), and Section 14.9.4.1 measures the shape of kk for the network we train.

14.9.1.2 The Policy and Value Networks#

The Policy container of Section 14.5 holds a policy network and its optimizer. In Section 14.8 the learned baseline was a separate NumPy table: after each batch it moved V^(st)\hat{V}(s_t) a step ηV\eta_V toward the reward-to-go G^t\hat{G}_t observed at every visited state. Here the baseline becomes a network too, and it moves into the container. ActorCritic subclasses Policy and adds a value module value with its own Adam optimizer opt_v. V returns the values as a framework array, the form a loss differentiates, and value_np takes and returns NumPy arrays, like the boundary methods of Policy. The name refers to the two parts: the policy is often called the actor and the value estimate the critic. Its tabular constructor builds both as zero-initialized tables, so that a table can stand in for either network, as in the measurement at the end of this section:

class ActorCritic(d2l.Policy):
    """A policy and a value function, each with its own optimizer."""
    def __init__(self, policy, value, lr=1e-2):
        super().__init__(policy, lr)
        self.value = value
        self.opt_v = torch.optim.Adam(value.parameters(), lr=lr)

    def V(self, obs):
        """V(s) for a batch of states, as a tensor."""
        return self.value(obs).squeeze(-1)

    def value_np(self, obs):
        """V(s) for a numpy batch of states, as numpy."""
        with torch.inference_mode():
            return self.V(torch.as_tensor(obs)).numpy()

    @classmethod
    def tabular(cls, num_states, num_actions, lr=0.1, seed=None):
        """Preference and value tables: two zero-initialized embeddings."""
        with d2l.seeded(seed):
            policy, value = (nn.Embedding(num_states, num_actions),
                             nn.Embedding(num_states, 1))
        nn.init.zeros_(policy.weight), nn.init.zeros_(value.weight)
        return cls(policy, value, lr)

The constructor mlp supplies networks instead of tables, each built by tanh_mlp: a policy network with obs_dim inputs and one preference per action, and a value network of the same shape with one output. Each has one hidden layer of 64 units, a common width for tasks this small, with tanh, the activation that a large study of on-policy methods found to work best for policy networks (Andrychowicz et al., 2021). The softmax of Section 14.7, πθ(a∣s)∝exp⁡(preferencea)\pi_\theta(a \mid s) \propto \exp(\textrm{preference}_a), acts on the network outputs as it did on a table row. The score now includes the hidden layer, and automatic differentiation applies the extra chain rule:

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))

@d2l.add_to_class(ActorCritic)
@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)

14.9.1.3 Value Regression#

For a table, the update of the learned baseline moved one entry toward one observed target. For a network, the counterpart is regression: optimizer steps on the mean squared error between V^(st)\hat{V}(s_t) and the targets of the whole batch. fit_value takes num_steps such steps toward a fixed target vector, on the value network ac.value of the ActorCritic above.

How many steps does the baseline need per batch? The targets are discounted returns of order 100100 in size on both tasks below, while an Adam step moves each parameter by roughly its learning rate, 0.010.01. With one step per batch, the baseline lags behind its targets. On the pendulum task below, the fraction of the targets' variance that the baseline accounts for, 1−Var(G^−V^)/Var(G^)1 - \textrm{Var}(\hat{G} - \hat{V}) / \textrm{Var}(\hat{G}), then climbs only to between 0.40.4 and 0.80.8 by the end of a run on most seeds, and stays lower on some. The rest of the weight G^t−V^(st)\hat{G}_t - \hat{V}(s_t) is noise that a good baseline would remove. Forty steps per batch raise this fraction to about 0.990.99, and forty is what the training loop below uses.

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()

14.9.1.4 Time Limits#

Both tasks of this section stop episodes by a clock: CartPole after 500 steps, Pendulum after 200. Section 14.1 drew the consequence: the sum of rewards of an episode cut by a time limit is not its return, because the process would have gone on. Reward-to-go treats the cut as the end. Consider a CartPole episode that balances the pole until the limit. Near the cut its reward-to-go shrinks toward 11, while the value network sees a balanced pole like any other and predicts about what it predicts at upright states early in an episode. The weights G^t−V^(st)\hat{G}_t - \hat{V}(s_t) of the last steps are then strongly negative, and the update pushes down the very actions that kept the pole up. Take γ=0.99\gamma = 0.99, T=500T = 500 and a value network that predicts 1/(1−γ)=1001/(1-\gamma) = 100, the value of balancing forever. At t=490t = 490 the reward-to-go is G^t=(1−0.9910)/0.01≈9.6\hat{G}_t = (1 - 0.99^{10})/0.01 \approx 9.6, a weight near −90-90. Exercise 1 computes these weights along the whole episode.

The correction adds back the value of the future that the cut hid (Pardo et al., 2018). This treats the limit as a convenience of training, not as part of the task; if the limit were part of the task, the remaining time would belong in the state (Section 14.1). Let an episode have steps t=0,…,T−1t = 0, \ldots, T-1, let sTs_T be the state its last action reached, and let term∈{0,1}\mathrm{term} \in \{0, 1\} record whether that state is terminal. The target of step tt becomes

yt=G^t+(1−term) γT−t V^(sT).(14.9.2)y_t = \hat{G}_t + (1 - \mathrm{term})\, \gamma^{T-t}\, \hat{V}(s_T). \tag{14.9.2}

For an episode that terminated nothing is added. For a truncated one, every step receives the discounted value of the state where recording stopped, as if the episode had continued from there. At t=490t = 490 above the correction adds 0.9910⋅100≈90.40.99^{10} \cdot 100 \approx 90.4, so yt≈100y_t \approx 100 and the weight returns to about 00. The Batch of Section 14.7 already records what this needs: next_obs holds st+1s_{t+1} for every step, and term records termination and never truncation, the rule of Section 14.1. truncation_bootstrap builds a vector that is zero except at the last step of each episode, where it holds γ(1−term)V^(sT)\gamma (1 - \mathrm{term}) \hat{V}(s_T), and runs the backward scan xt+γxt+1+γ2xt+2+⋯x_t + \gamma x_{t+1} + \gamma^2 x_{t+2} + \cdots of Section 14.8 over it, which carries that value back to every earlier step with the factor γT−t\gamma^{T-t}:

@d2l.add_to_class(d2l.Batch)
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)

14.9.2 REINFORCE on CartPole#

With the policy network, the value network and the targets in place, we assemble the training loop and run it on the cart with the pole.

14.9.2.1 The Training Loop#

train_reinforce is REINFORCE with a learned baseline for any policy object: make_agent(seed) builds the agent and env_name names the environment. Each update collects eight episodes with rollout, computes the targets yty_t, takes one policy step with weights computed from yt−V^(st)y_t - \hat{V}(s_t), and then fits V^\hat{V} to the targets with forty regression steps. Apart from the networks, four things differ from the learned-baseline runs of Section 14.8. The optimizer is Adam, the one each Policy owns, instead of plain SGD. The weights pass through d2l.standardize, which subtracts their batch mean and divides by their batch standard deviation. The baseline is fitted by regression instead of entry by entry. Truncated episodes are bootstrapped.

Under Adam, dividing every weight by one positive number barely changes the step, because Adam divides each coordinate by a running estimate of its own scale (exercise 5 makes this precise). Normalization still does two things. Its centering acts as a second baseline, computed from the batch itself. Its division keeps the scale of the weights steady while the returns grow over a run, a drift that Adam's slowly decaying average follows only with a lag.

The update that results is not the gradient of the objective J(θ)J(\theta). With NN steps in the batch and normalized weights w~t\tilde{w}_t, the policy step follows

g^=1N∑tw~t ∇θlog⁡πθ(at∣st),w~=standardize(y−V^(s)).(14.9.3)\hat{g} = \frac{1}{N} \sum_{t} \tilde{w}_t\, \nabla_\theta \log \pi_\theta(a_t \mid s_t), \qquad \tilde{w} = \mathrm{standardize}\big(y - \hat{V}(s)\big). \tag{14.9.3}

Four things separate g^\hat{g} from ∇θJ\nabla_\theta J. The factor γt\gamma^t is dropped, so the score at a late step counts as much as at an early one; this is the reward-to-go estimator of Section 14.8, which in general is not the gradient of any objective (Nota and Thomas, 2020). The targets yty_t of a truncated episode contain V^(sT)\hat{V}(s_T), so the critic's error at the cut enters the weights as bias. The centering uses the batch's own mean, which depends weakly on the sampled actions. Dividing by NN and by the batch's standard deviation rescales each batch by its own data, after which Adam takes a step of roughly fixed size. No stochastic-approximation theorem applies to this combination directly, so the evidence that the loop works comes from runs, not from a convergence proof.

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

14.9.2.2 CartPole#

CartPole is the classic pole-balancing problem (Barto et al., 1983). Its state is the four numbers of the opening, and its two actions push the cart left or right. Every step with the pole up earns reward 11. The episode terminates when the pole tips too far or the cart leaves the track, and it is truncated after 500 steps, so the best possible return is 500. Compared with the runs on the lake, three settings change: the constructor is ActorCritic.mlp(4, 2) instead of Policy.tabular(16, 4), the environment is 'CartPole-v1', and the discount is 0.990.99, which raises the effective horizon 1/(1−γ)1/(1-\gamma) of Section 14.1 from 20 to 100 steps. d2l.run_seeds (Section 27.9) runs the training generator once per seed and stacks what it yields. We train three seeds for 60 updates:

def cartpole_agent(seed):
    return ActorCritic.mlp(4, 2, seed=seed)

runs = d2l.run_seeds(train_reinforce, 3, make_agent=cartpole_agent,
                     env_name='CartPole-v1')
d2l.plot_curves({'REINFORCE + learned baseline': runs[:, :, 0]},
                xlabel='update', ylabel='mean return of the batch',
                reference=500)

The untrained policy balances the pole for about 20 steps. Every seed's batch mean reaches the 500-step ceiling by about update 50 and mostly stays there, although single batches still dip below it. On this task the time-limit correction barely changed the average return in our runs, because only the successful episodes are truncated, but without it the policy left the ceiling more often late in the run.

14.9.2.3 The Surrogate Loss#

train_reinforce yields a second number at every update, the value L of the surrogate loss that policy_step minimizes (Section 14.7). Deep learning frameworks express updates through scalar losses, so instead of assembling g^\hat{g} explicitly, policy_step minimizes

L(θ)=−1N∑tw~t log⁡πθ(at∣st),(14.9.4)L(\theta) = -\frac{1}{N} \sum_{t} \tilde{w}_t\, \log \pi_\theta(a_t \mid s_t), \tag{14.9.4}

with the weights w~t\tilde{w}_t held fixed. They arrive as a NumPy array and carry no gradient graph. The gradient of LL is −g^-\hat{g}, so a descent step on LL is a step along g^\hat{g}. The value of LL, however, does not estimate how well the policy performs. LL is built to have the right derivative at the current parameters, and nothing more, so a decrease in LL need not mean an increase in return. The CartPole runs recorded both:

d2l.plot_curves({'CartPole': runs[:, :, 1]}, xlabel='update',
                ylabel='policy loss L')

While the return rises from 20 to 500, LL stays small, below 0.10.1 in size, and negative on almost every update after the first. Because the normalized weights have mean zero and unit spread, LL is minus the standard deviation of the log-probabilities in the batch times their correlation with the weights (exercise 4). It is negative when the actions with positive weight already have above-average probability, and its size says nothing about the return. To follow training, watch the return, and quantities that describe the update itself, such as how far the policy moved.

14.9.3 Continuous Actions#

A softmax needs a finite list of actions. Many control problems have a real-valued action instead, a torque or a steering angle. The score-function derivation of Section 14.7 never used the finiteness of the action set; it needs only that log⁡πθ(a∣s)\log \pi_\theta(a \mid s) can be differentiated in θ\theta. So a policy whose density over real actions has that property can be trained by the same loop.

14.9.3.1 The Gaussian Policy#

We return to the pendulum of Section 14.6 (Pendulum-v1). A pendulum hangs from a motorized pivot, and the action is a torque u∈[−2,2]u \in [-2, 2]. We write ϑ\vartheta for the angle of the pendulum from upright, keeping θ\theta for the policy parameters. The planners of Section 14.6 knew the equations of motion and differentiated them. The policy-gradient agent knows nothing of them: it sees only the observation (cos⁡ϑ,sin⁡ϑ,ϑ˙)(\cos\vartheta, \sin\vartheta, \dot{\vartheta}) and, at each step, the reward −(ϑ2+0.1 ϑ˙2+0.001 u2)-(\vartheta^2 + 0.1\,\dot{\vartheta}^2 + 0.001\,u^2) with ϑ\vartheta wrapped to [−π,π][-\pi, \pi], so the cost is lowest when the pendulum stands still at the top. Every episode starts at a random angle and is truncated after 200 steps. An uncontrolled pendulum collects a return near −1200-1200, and a controller that swings it up and balances it collects about −200-200 or better.

We use a Gaussian policy πθ(a∣s)=N(a;μθ(s),σ2)\pi_\theta(a \mid s) = \mathcal{N}\big(a; \mu_\theta(s), \sigma^2\big), whose network produces the mean action. GaussianHead is that network. A trunk computes hidden features, one tanh layer by default; the trunk argument replaces it by any module with hidden outputs. A linear layer maps the features to the mean μθ(s)\mu_\theta(s); with zero_mean=True its weights and bias start at zero, which the Pendulum runs below use. The log standard deviation log⁡σ\log \sigma is one learned vector by default, so σ\sigma is the same at every state. With state_std=True it becomes a second linear layer on the features, clamped to [−5,2][-5, 2], so that σ\sigma depends on the state; exercise 2 uses this option. Because log⁡σ\log \sigma belongs to the policy module, the policy step updates it along with the mean:

class GaussianHead(nn.Module):
    """A Gaussian over actions: a trunk of hidden features, a linear mean,
    and a log standard deviation that is one learned vector or, with
    `state_std=True`, a second linear head clamped to [-5, 2]. The default
    trunk is one tanh layer; any module with `hidden` outputs will do.
    `zero_mean=True` sets the mean layer to zero, so that mu = 0 at first."""
    def __init__(self, obs_dim, act_dim, hidden, state_std=False, trunk=None,
                 zero_mean=False):
        super().__init__()
        self.trunk = trunk if trunk is not None else nn.Sequential(
            nn.Linear(obs_dim, hidden), nn.Tanh())
        self.mean = nn.Linear(hidden, act_dim)
        if zero_mean:
            nn.init.zeros_(self.mean.weight), nn.init.zeros_(self.mean.bias)
        self.state_std = state_std
        self.log_std = (nn.Linear(hidden, act_dim) if state_std
                        else nn.Parameter(torch.zeros(act_dim)))

    def forward(self, obs):
        h = self.trunk(obs)
        if self.state_std:
            return self.mean(h), self.log_std(h).clamp(-5, 2).exp()
        return self.mean(h), self.log_std.exp()

GaussianPolicy subclasses ActorCritic, builds a GaussianHead and a value network with tanh_mlp, like that of mlp, and overrides the three methods that depend on the distribution, log_prob, act and act_greedy. rollout, policy_step, fit_value and train_reinforce use only this interface and need no change:

class GaussianPolicy(ActorCritic):
    """The same interface over a Normal instead of a softmax; nothing that
    consumes the interface changes. `head_args` go to GaussianHead."""
    def __init__(self, obs_dim, act_dim, hidden=64, lr=1e-2, seed=None,
                 **head_args):
        with d2l.seeded(seed):
            policy = GaussianHead(obs_dim, act_dim, hidden, **head_args)
            value = tanh_mlp(obs_dim, hidden, 1)
        super().__init__(policy, value, lr)

    def log_prob(self, obs, act):
        """log pi(a|s): the Normal density, summed over action dimensions."""
        mean, std = self.policy(obs)
        return torch.distributions.Normal(mean, std).log_prob(act).sum(-1)

    def act(self, obs, rng):
        """Sample mu(s) + sigma(s) z, z ~ N(0, I) from the numpy rng."""
        with torch.inference_mode():
            mean, std = self.policy(torch.as_tensor(obs))
        return mean.numpy() + std.numpy() * rng.standard_normal(
            mean.shape, dtype=np.float32)

    def act_greedy(self, obs, rng=None):
        """The mean action mu(s)."""
        with torch.inference_mode():
            return self.policy(torch.as_tensor(obs))[0].numpy()

The environment clips each sampled torque to [−2,2][-2, 2], so act can return the unbounded Gaussian draw; log_prob scores the unclipped sample, and exercise 2 shows why the estimate stays unbiased. The update uses log_prob only through its gradient, the score. With z=(a−μ)/σz = (a - \mu)/\sigma, the score of a Gaussian is

∂log⁡π∂μ=zσ,∂log⁡π∂log⁡σ=z2−1.(14.9.5)\frac{\partial \log \pi}{\partial \mu} = \frac{z}{\sigma}, \qquad \frac{\partial \log \pi}{\partial \log \sigma} = z^2 - 1. \tag{14.9.5}

With a positive weight, a sample above the mean pulls μ\mu up, a sample far from the mean in either direction pulls σ\sigma up, and a sample close to the mean pulls σ\sigma down. We check log_prob against the formula for the Gaussian density, and its gradients against these two formulas, at σ=0.5\sigma = 0.5 and five random states and actions. The mean layer's bias enters μ\mu with derivative 11, so its gradient is the score in μ\mu summed over the five samples:

sigma = 0.5
gp = GaussianPolicy(3, 1, seed=1)
gp.policy.log_std.data.fill_(np.log(sigma))
rng = np.random.default_rng(1)
obs = rng.standard_normal((5, 3)).astype(np.float32)
act = rng.standard_normal((5, 1)).astype(np.float32)
z = (act - np.stack([gp.act_greedy(o) for o in obs])) / sigma
hand = -0.5 * z ** 2 - np.log(sigma) - 0.5 * np.log(2 * np.pi)
print('density:', np.allclose(gp.log_prob_np(obs, act), hand.sum(-1), atol=1e-5))
gp.log_prob(torch.as_tensor(obs), torch.as_tensor(act)).sum().backward()
g_mu, g_ls = gp.policy.mean.bias.grad.numpy(), gp.policy.log_std.grad.numpy()
print('score in mu:', np.allclose(g_mu, (z / sigma).sum(0), atol=1e-4),
      '| score in log sigma:', np.allclose(g_ls, (z ** 2 - 1).sum(0), atol=1e-4))
density: True
score in mu: True | score in log sigma: True

All three checks print True: log_prob is the Gaussian density, and its gradients are the score that the update uses.

14.9.3.2 Pendulum#

The curves report the undiscounted 200-step return, while the update discounts at γ=0.95\gamma = 0.95, an effective horizon of 20 steps. The discount is our choice here, not part of the task. A torque matters for the next few dozen steps far more than for the cost a hundred steps later, and the shorter horizon gives targets with lower variance but some bias with respect to the reported objective; γ=0.9\gamma = 0.9 trained about as well in our runs.

pendulum_agent sets the weights and the bias of the mean layer to zero (zero_mean=True), so that every seed starts at μ=0\mu = 0 with σ=1\sigma = 1, whatever the random draw of the other layers. A mean outside [−2,2][-2, 2] would stall learning. The environment would clip nearly every sample to the same bound, the reward would no longer depend on which sample was drawn, and the score would be multiplied by weights that carry no information about the action. The initialization of our layers keeps the initial mean well inside the bounds, but initializations with larger weights put it outside on some seeds, and those seeds stall. A last policy layer with very small or zero weights is a standard recommendation for on-policy methods (Andrychowicz et al., 2021). The policy must first learn to swing the pendulum up before it can balance it, so we train for 300 updates of eight episodes:

def pendulum_agent(seed):   # every seed starts at mu = 0
    return GaussianPolicy(3, 1, seed=seed, zero_mean=True)

runs_p = d2l.run_seeds(train_reinforce, 3, make_agent=pendulum_agent,
                       env_name='Pendulum-v1', gamma=0.95, num_updates=300)
d2l.plot_curves({'REINFORCE + learned baseline': runs_p[:, :, 0]},
                xlabel='update', ylabel='mean return of the batch',
                reference=-200, smooth=10)

Returns start near −1200-1200. Every run learns to swing the pendulum up and balance it. Its ten-update average crosses −200-200 after roughly 150 to 300 updates, that is, after a few hundred thousand environment steps, and its best stays between about −150-150 and −200-200. Later updates mostly stay near that level, although a run can fall back by several hundred for a few updates. Over the run σ\sigma falls to about half its initial value, the direction that exercise 2 predicts near a good action. Here the time-limit correction matters: every Pendulum episode is truncated, and without the correction only about half of the seeds in our runs reached −200-200 within the same budget.

A few hundred thousand steps is a great deal of experience for a task this small. Each batch of 1,600 steps drives one update and is then discarded, and the weights come from whole returns rather than from a learned estimate of each action's value. Soft actor-critic (Section 15.5) reaches −200-200 on the same task within about 5,000 to 11,000 steps. How a method can learn that much more from each sample is the question that Chapter 15 takes up.

14.9.3.3 Score-Function and Pathwise Gradients#

A continuous action also allows a second way to differentiate an expected reward. Consider a single state, a Gaussian policy a∼N(μ,σ2)a \sim \mathcal{N}(\mu, \sigma^2), and a known differentiable reward Q(a)Q(a). The gradient of E[Q(a)]\mathbb{E}[Q(a)] with respect to μ\mu has two equivalent forms:

∇μ E[Q(a)]=E[Q(a) a−μσ2]=E[Q′(μ+σz)],z∼N(0,1).(14.9.6)\begin{aligned} \nabla_\mu\, \mathbb{E}\big[ Q(a) \big] &= \mathbb{E}\Big[ Q(a)\, \frac{a - \mu}{\sigma^2} \Big] = \mathbb{E}\big[ Q'(\mu + \sigma z) \big], \\ z &\sim \mathcal{N}(0, 1). \end{aligned} \tag{14.9.6}

The first equality is the score-function identity used throughout this chapter. The second substitutes a=μ+σza = \mu + \sigma z, which moves μ\mu from the distribution into QQ, and differentiates through the sample. This is the pathwise or reparameterization gradient (Kingma and Welling, 2014), and Figure 14.9.1 shows where each estimator's gradient flows. With a known QQ both are unbiased. We compare their noise on Q(a)=−(a−1)2Q(a) = -(a - 1)^2 at μ=0\mu = 0 and σ=0.5\sigma = 0.5, where the exact gradient is 22:

def Q(a):                     # a stand-in critic, differentiable in the action
    return -(a - 1.0) ** 2

sigma, N = 0.5, 100000
a = sigma * np.random.default_rng(2).standard_normal(N, dtype=np.float32)
g_score = Q(a) * a / sigma ** 2               # score-function samples, mu = 0
at = torch.as_tensor(a).requires_grad_(True)  # pathwise: grad through a
Q(at).sum().backward()
g_path = at.grad.numpy()                      # per-sample dQ/da (da/dmu = 1)
print(f'score:    mean {g_score.mean():.2f}, variance {g_score.var():.1f}')
print(f'pathwise: mean {g_path.mean():.2f}, variance {g_path.var():.2f}')
print(f'score variance if Q gains a constant +10: '
      f'{((Q(a) + 10) * a / sigma ** 2).var():.0f}; pathwise is unchanged')
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

Both sample means are close to 22. The exact single-sample variances are 21.7521.75 for the score function and 1.01.0 for the pathwise estimator, a ratio of about twenty, and adding the constant 1010 to QQ raises the score-function variance to 281.75281.75, because QQ multiplies the score. The pathwise estimator depends only on Q′Q', so a constant does not change it. Exercise 6 derives these variances; the ratio depends on QQ, on σ\sigma and on the offset. The price of the lower variance is access to QQ as a differentiable function of the action. In practice QQ is a learned critic QwQ_w, and then the error of its action gradient ∂Qw/∂a\partial Q_w / \partial a becomes bias in the policy gradient.

Figure 14.9.1:

Two estimators of the same gradient. (a) The score-function estimator uses the environment only through the returned reward, so the environment need not be differentiable. (b) The pathwise estimator writes the sample as a=μθ(s)+σθza = \mu_\theta(s) + \sigma_\theta z, here with a single learned σθ\sigma_\theta, and differentiates through ∂Qw/∂a\partial Q_w / \partial a and ∂a/∂θ\partial a / \partial \theta. The critic QwQ_w must be differentiable in the action. It can be trained by regression on replayed data, and its error in ∂Qw/∂a\partial Q_w / \partial a becomes bias in the gradient.

The pathwise form is also how continuous control avoids a maximization over actions. A value-based method acts by computing max⁡aQ(s,a)\max_a Q(s, a), a lookup among four actions on the lake but an optimization problem for a∈Rda \in \mathbb{R}^d at every step. The deterministic policy gradient instead trains an actor network to output a high-value action, following ∂Qw/∂a\partial Q_w / \partial a through a learned critic (Silver et al., 2014).

14.9.4 Generalization across States#

The opening asked for a function that gives similar values to similar states. (14.9.1) says that one gradient step spreads across states according to the kernel kk. We now measure that spread for a freshly built value network of the shape that trained CartPole.

14.9.4.1 A Probe of State Coupling#

The probe raises V^\hat{V} at one of 256 random states in [−1,1]4[-1, 1]^4 by one gradient step toward a target one unit above its current estimate, and records the change at all 256 states. It then does the same for a table of sixteen entries. Each probe replaces the Adam optimizer opt_v by plain SGD (d2l.plain_sgd, Section 27.9), so that the one step follows (14.9.1); Adam would rescale every parameter by its own running scale. fit_value minimizes the mean squared error, whose gradient is twice that of the half squared error, so the table's step of 0.250.25 moves its entry by 0.50.5. The cell sorts the other 255 probes by their distance from the nudged state:

net_probe = ActorCritic.mlp(4, 2, seed=0)
tab_probe = ActorCritic.tabular(16, 4, seed=0)
for ac, lr in ((net_probe, 0.02), (tab_probe, 0.25)):  # one plain step
    ac.opt_v = d2l.plain_sgd(ac.value, lr)
S = np.random.default_rng(0).uniform(-1, 1, (256, 4)).astype(np.float32)
before = net_probe.value_np(S)
fit_value(net_probe, S[:1], before[:1] + 1.0)      # raise ONE state
dV = net_probe.value_np(S) - before
order = 1 + np.argsort(np.linalg.norm(S[1:] - S[0], axis=1))  # nearest first
before_t = tab_probe.value_np(np.arange(16))
fit_value(tab_probe, np.arange(1), before_t[:1] + 1.0)
dV_t = tab_probe.value_np(np.arange(16)) - before_t
print(f'network: nudged state {dV[0]:+.2f}; 10 nearest probes '
      f'{dV[order[:10]].mean():+.2f}, 10 farthest {dV[order[-10:]].mean():+.2f}; '
      f'{(dV[1:] < 0).sum()} of 255 moved down')
print(f'table:   nudged entry {dV_t[0]:+.2f}; '
      f'largest move among the other fifteen: {np.abs(dV_t[1:]).max():.6f}')
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

The nudged state rises, and the ten probes nearest to it rise almost as much, by more than 80 percent of its change. The change falls off with distance, and at the farthest probes it is near zero or slightly negative: some probes move the other way. The table moves the nudged entry by +0.50+0.50 and no other entry at all. How far down the farthest probes move, and how many probes move down, depends on the random initialization of the network; the shape does not. Figure 14.9.2 draws the same contrast on a one-dimensional state.

Figure 14.9.2:

What one value update touches. A value estimate over a one-dimensional state is fitted as a sixteen-entry table and as a network with 64 tanh units, and each takes one gradient step toward a target one unit above its estimate at the marked state x0x_0, with the step size ηV\eta_V of each chosen so that x0x_0 moves by +0.50+0.50. (a) The table moves one entry and nothing else. (b) The network moves its whole curve, because every state's estimate shares parameters with x0x_0's. (c) The two changes side by side. To first order the network's change is ηV (y−V^(x0)) k(x,x0)\eta_V\,\big(y - \hat{V}(x_0)\big)\,k(x, x_0) for the target yy, where kk is the inner product of the parameter gradients at xx and x0x_0: a bump around x0x_0 that turns negative beyond x≈0.7x \approx 0.7 and reaches −0.20-0.20 at the far end.

The positive bump is generalization: experience at one state informs the estimates at states like it, which is why a network learns CartPole without a hand-made partition of its state space. The negative far field is interference: fitting one region of the state space changes the estimates in regions the batch does not contain. A CartPole policy that balances well collects batches of nearly upright states, and fitting them moves the estimates at large pole angles that the batch never visits (exercise 7 follows this through). Such changes can make a training curve dip even when every update fits its own batch well.

14.9.4.2 Limits of the Monte Carlo Agent#

The value network of this section is fitted to observed returns, except at a time-limit cut, where the target contains its own estimate V^(sT)\hat{V}(s_T). Away from the cut, fitting it is ordinary regression. Methods that bootstrap at every step, putting the estimate at the next state into every target, lose this property. Their target moves with every update, the update is no longer the gradient of a fixed objective, and with nonlinear approximators or data from another policy the iteration can diverge (Tsitsiklis and Van Roy, 1997).

We can now train a policy network on continuous states and continuous actions with the REINFORCE estimator, a fitted baseline and the time-limit correction. The agent still has three limits. It waits for every episode to end, because its targets are whole returns; Section 15.1 bootstraps to learn sooner. It uses each batch for one step and discards it; Section 15.2 reuses a batch for a few controlled steps, and Section 15.4 replays old transitions. It does not limit how far one update moves the policy, although a large move can spoil both the current return and the data collected next. Chapter 15 takes up all three, and with them the gap between a few hundred thousand steps here and ten thousand for soft actor-critic.

14.9.5 A Map of the Methods#

This chapter and the next present many methods. Two questions locate each of them: what does it learn, and which data may drive its update? Figure 14.9.3 arranges the methods along these two questions.

Figure 14.9.3:

The methods of this chapter and of Chapter 15, arranged by what they learn and which data may drive their updates. Solid boxes hold this chapter's methods; dashed boxes and gray names belong to Chapter 15. Behavior cloning learns from a fixed set of demonstrations, while DAgger learns from the learner's own states relabeled by an expert, which places it in the on-policy column. Value iteration sits in the off-policy column because its update uses the known kernel rather than data from any one policy. The arrow from the on-policy policy box marks the reuse of recent batches, which needs a correction because the policy has changed since they were collected. The learned model in the off-policy column is fitted to the agent's own stored experience, and the agent plans in it (Section 15.6).

Table 14.9.1 lists the algorithms of both chapters with what each estimates, which data it can use, and where it is introduced.

Table 14.9.1. The algorithm map of these two chapters. "Named in" marks methods this book describes but does not implement.
algorithmwhat it estimateswhich data may drive the updatewhere
value iteration, policy iterationV∗V^* exactly, by sweeping the Bellman operator; VπV^\pi by policy evaluationnone: it consumes the kernel PP and reward rrSection 14.2
behavior cloningπ(a∣s)\pi(a \mid s) by cross-entropy on demonstrationsa fixed expert datasetSection 14.5
DAggerthe same fitthe learner's own states, relabeled by an expert on callSection 14.5
LQR, iLQR, receding-horizon MPCexact quadratic cost-to-go Vt(x)=x⊤PtxV_t(\mathbf{x}) = \mathbf{x}^\top\mathbf{P}_t\mathbf{x} and linear feedback ut∗=−Ktxt\mathbf{u}_t^* = -\mathbf{K}_t\mathbf{x}_t via the Riccati recursionnone: it differentiates the known dynamics f(x,u)f(\mathbf{x}, \mathbf{u}) and quadratic costSection 14.6
Q-learning (tabular)Q∗Q^* from sampled backupsany behavior's transitions (off-policy)Section 14.3
SARSAthe behavior's own QQ, exploration includedits own transitions (on-policy)Section 14.3
certainty-equivalent planningQ∗Q^* of the model counted from samplesany behavior's transitions, countedSection 14.3
UCB, Thompson samplingarm means plus their uncertaintyits own pulls (the bandit)Section 14.4
REINFORCE∇θJ\nabla_\theta J by the score functionfresh trajectories from the current policy onlySection 14.7
REINFORCE with baselines, RLOOthe same gradient at lower variancefresh trajectories from the current policySection 14.8
GRPOgroup-normalized advantages, no value networkfresh groups per prompt, each reused for a few clipped stepsweights in Section 14.8; machinery in Section 15.8
REINFORCE with a learned baseline, on networksπθ\pi_\theta and V^\hat{V} as networksfresh trajectories from the current policySection 14.9
actor-critic (A2C)πθ\pi_\theta plus a bootstrapped criticfresh, near-current trajectoriesSection 15.1
PPOπθ\pi_\theta under a clipped probability ratioone batch, reused for a few stepsSection 15.2
KL-regularized policy optimization (the objective behind RLHF)a policy tilted from a reference by rewardrollouts scored by a learned rewardSection 15.3; RLHF at scale is left to the Language Models part, which takes it up in more depth
DQN, Double DQNQQ as a networka replay buffer of stale experienceSection 15.4
RainbowDQN plus its measured componentsa replay buffernamed in Section 15.9
DDPG, TD3a critic, and a deterministic actor trained to maximize ita replay buffer (off-policy)named in Section 15.5
SACtwin soft critics, and a stochastic squashed actor maximizing reward plus entropya replay buffer (off-policy)Section 15.5
model-predictive control in a learned model; search distilled into the policya model of the dynamics and reward fitted by regression, and plans searched in itthe agent's own stored experience, refit into the modelSection 15.6
Dyna, MBPOthe same model, used to imagine extra transitions for an off-policy learnera replay buffer plus model rolloutsnamed in Section 15.6
offline Q-learning with pessimism, CQLQQ penalized where the data is thina fixed logged dataset, no interaction at allSection 15.7
Decision Transformera return-conditioned sequence modela fixed logged datasetnamed in Section 15.7
MuZero, Dreamera learned model of the environment, to plan or imagine inits own interaction, replayed through the modelnamed in Section 15.9
DPOthe regularized optimum directly from preferencesa fixed preference datasetSection 15.8; preference optimization at scale is left to the Language Models part, which takes it up in more depth

14.9.6 Summary#

A table over continuous states would need a row for every visit, so the policy and the value estimate become networks; a table is the special case of a linear network on one-hot states. The policy-gradient derivation needs only the score, so REINFORCE with a learned baseline carries over to networks with three practical additions: the baseline is fitted by enough regression steps to track its targets, the weights are normalized, and episodes cut by a time limit are bootstrapped with the value of their last state. The update this loop runs is the per-step surrogate rather than an unbiased gradient of JJ, and its loss value says nothing about performance. A Gaussian policy extends the loop to a continuous torque, and with it every Pendulum run swings up and balances, after a few hundred thousand steps. One update moves the estimate at every state, raising similar states and lowering distant ones. The agent waits for whole episodes, uses each batch once and does not limit its steps, which is where Chapter 15 begins.

14.9.7 Exercises#

  1. Discounting at the time limit. train_reinforce yields the undiscounted mean return of the episodes in each batch, while its update weights each step by the reward-to-go at γ=0.99\gamma = 0.99. Every CartPole step earns reward 11, and the environment truncates any episode that reaches 500 steps.

    1. Show that the discounted return of an episode of length TT is (1−γT)/(1−γ)(1 - \gamma^T)/(1 - \gamma), and evaluate it for T∈{20,100,200,500}T \in \{20, 100, 200, 500\}. Conclude that the undiscounted return and the discounted return rank episodes identically. By what factor does each grow when an episode lengthens from 200 to 500 steps?
    2. Without the time-limit correction, compute the reward-to-go G^t\hat{G}_t at t∈{0,400,450,490}t \in \{0, 400, 450, 490\} of an episode that reaches the limit. The value network sees only the state, and the states late in a successful episode resemble those early in it. Which sign do the weights of the last steps of a successful episode tend to have, and what does the policy update do to the actions taken at those steps?
    3. train_reinforce adds batch.truncation_bootstrap(gamma, ac.value_np) to these targets. Suppose that V^\hat{V} predicts 1/(1−γ)1/(1 - \gamma) at every state with the pole up. Show that the target yty_t of every step of a truncated episode is then 1/(1−γ)1/(1 - \gamma), whatever its distance from the limit. Why does the target of an episode that ends with the pole falling still shrink toward its end, and why is that correct?
    4. Every Pendulum episode is truncated, while on CartPole only the successful episodes are. Use this to explain why removing the correction slows Pendulum down much more than CartPole.
  2. [code] Gaussian score. GaussianHead parameterizes a one-dimensional action by the mean μ\mu and the log standard deviation ℓ=log⁡σ\ell = \log \sigma, which is log_std. Write z=(a−μ)/σz = (a - \mu)/\sigma for a sampled action aa.

    1. Show that ∂log⁡π/∂μ=z/σ\partial \log \pi / \partial \mu = z / \sigma and ∂log⁡π/∂ℓ=z2−1\partial \log \pi / \partial \ell = z^2 - 1, and that both have mean zero under the policy.
    2. Let QQ be a quadratic function of the action with second derivative Q′′Q''. Show that E[Q(a) (z2−1)]=σ2Q′′\mathbb{E}\big[Q(a)\,(z^2 - 1)\big] = \sigma^2 Q'', using E[z4]=3\mathbb{E}[z^4] = 3. In which direction does the expected policy-gradient step move σ\sigma near a maximum of QQ? What does this imply for the exploration of a policy whose mean approaches the best action?
    3. Pendulum clips each sampled torque to [−2,2][-2, 2], while log_prob scores the unclipped sample. Explain why the score-function estimate remains unbiased for the return of the clipped environment.
    4. Build the agent of pendulum_agent with GaussianPolicy(3, 1, state_std=True), so that σ\sigma depends on the state, and train three seeds with train_reinforce as in the Pendulum run. Every 25 updates, record σ\sigma at the hanging state (cos⁡ϑ,sin⁡ϑ,ϑ˙)=(−1,0,0)(\cos\vartheta, \sin\vartheta, \dot{\vartheta}) = (-1, 0, 0) and at the upright state (1,0,0)(1, 0, 0). Where does σ\sigma shrink first, and how does this agree with part b? Compare the return curve with runs_p.

    Adapted from Richard S. Sutton and Andrew G. Barto, Reinforcement Learning: An Introduction, Exercise 13.4.

  3. [code] Discontinuous rewards. The second equality of (14.9.6) differentiates through QQ. Take μ=0\mu = 0 and σ=0.5\sigma = 0.5, as in the computation of g_score and g_path, and the threshold reward Q(a)=1Q(a) = 1 for a>1a > 1 and Q(a)=0Q(a) = 0 otherwise.

    1. Compute the exact gradient ∇μE[Q(a)]\nabla_\mu \mathbb{E}[Q(a)]. What does the pathwise estimator return for every sample? Which step of the derivation of the second equality fails?
    2. Replace Q in that computation by the smooth step Qk(a)=1/(1+e−k(a−1))Q_k(a) = 1 / \big(1 + e^{-k(a - 1)}\big) for k∈{1,10,100,1000}k \in \{1, 10, 100, 1000\}, and record the mean and the variance of g_score and of g_path. The samples are single precision, so for k≥100k \geq 100 the factor e−k(a−1)e^{-k(a - 1)} overflows at the smallest samples and the derivative of the formula as written is NaN there; implement QkQ_k with a numerically stable sigmoid. Plot both variances against kk. Which estimator has the lower variance at large kk? Explain how the variance of g_path depends on kk through the height and the width of Qk′Q_k', and how the variance of g_score depends on kk through QkQ_k.
    3. Pendulum clips each sampled torque to [−2,2][-2, 2]. What does a pathwise estimate through the clipped torque return at samples outside this interval? Why does the score-function estimate of problem 2c not lose these samples?
  4. Surrogate loss value. policy_step evaluates the surrogate (14.9.4) on the batch that the current policy has just collected. The weights from d2l.standardize have mean 00 and standard deviation 11 over the NN steps of the batch.

    1. Show that L(θ)=−s cL(\theta) = -s\, c, where ss is the standard deviation of log⁡πθ(at∣st)\log \pi_\theta(a_t \mid s_t) over the batch and cc is the correlation coefficient between the weights and these log-probabilities. Conclude that ∣L(θ)∣≤s|L(\theta)| \leq s.
    2. For GaussianPolicy with one action dimension, show that s≈1/2s \approx 1/\sqrt{2} for every mean network and every σ\sigma. What does this imply for the policy loss of the Pendulum runs?
    3. How does ss behave on CartPole as the policy becomes nearly deterministic? What does this imply for the value of LL late in training?
  5. [code] Normalization under Adam. ● Under plain SGD, dividing the weights by their standard deviation changes the effective learning rate (exercise 6 of Section 14.8). train_reinforce updates with Adam instead. Its step for each coordinate is −η m^t/(v^t+ϵ0)-\eta\, \hat{m}_t / (\sqrt{\hat{v}_t} + \epsilon_0), where m^t\hat{m}_t and v^t\hat{v}_t are bias-corrected moving averages of the gradient gtg_t and of gt2g_t^2 with decay rates β1=0.9\beta_1 = 0.9 and β2=0.999\beta_2 = 0.999.

    1. Show that for ϵ0=0\epsilon_0 = 0, multiplying every gradient by the same constant c>0c > 0 leaves every Adam step unchanged.
    2. Show that
v^t=1−β21−β2t∑i=1tβ2t−igi2.\hat{v}_t = \frac{1 - \beta_2}{1 - \beta_2^t} \sum_{i=1}^{t} \beta_2^{t-i} g_i^2.

By what factor do the weights of the oldest and the newest squared gradient differ at t=300t = 300, the length of the Pendulum runs? Suppose that the gradient of a coordinate keeps a fixed sign and drops tenfold in scale halfway through a run of 300 updates. By what factor is the step at the end of the run smaller than the step at the start?

  1. Keep the centering of d2l.standardize in train_reinforce but drop its division, so that the weights are A - A.mean() with A = G - ac.value_np(batch.obs) and the two variants differ only in scale. Log the standard deviation of the weights of every batch, and train three seeds of both variants on CartPole and on Pendulum. How does the scale of the weights evolve on each task? On which task does part b predict that dropping the division changes the return curves more?
  1. Score versus pathwise variance. ● The samples g_score and g_path estimate the two forms of (14.9.6) for Q(a)=−(a−1)2Q(a) = -(a - 1)^2 at μ=0\mu = 0. Use E[z4]=3\mathbb{E}[z^4] = 3 and E[z6]=15\mathbb{E}[z^6] = 15 for z∼N(0,1)z \sim \mathcal{N}(0, 1).

    1. Show that the single-sample variance of the score-function estimate is 15σ2+14+1/σ215\sigma^2 + 14 + 1/\sigma^2 and that of the pathwise estimate is 4σ24\sigma^2. Evaluate both at σ=0.5\sigma = 0.5, and compare them with the printed variances.
    2. Adding a constant cc to QQ is the same as subtracting the baseline b=−cb = -c. With the score a/σ2a/\sigma^2 in the formula for b∗b^* of exercise 2 of Section 14.8, show that b∗=−(1+3σ2)b^* = -(1 + 3\sigma^2) and that the smallest score-function variance is 6σ2+86\sigma^2 + 8. Check the printed variance for c=10c = 10 against your formula.
    3. Let σ→0\sigma \to 0. How do the two variances behave, with and without the optimal baseline? Explain the limit 88 of the score-function variance through the Taylor expansion of QQ around μ\mu. Which of the two estimators remains usable for a deterministic actor?
  2. [code] Tangent kernel. ● The measurement of dV raises V^\hat{V} at one probe state with one plain SGD step of fit_value. Write ww for the parameters of the value network and

k(s,s′)=∇wV^(s)⊤∇wV^(s′)(14.9.7)k(s, s') = \nabla_w \hat{V}(s)^\top \nabla_w \hat{V}(s') \tag{14.9.7}

for its tangent kernel, as in (14.9.1).

  1. Show that one gradient step of size η\eta on 12(y−V^(s0))2\frac{1}{2}\big(y - \hat{V}(s_0)\big)^2 changes the estimate at ss by η (y−V^(s0)) k(s0,s)+O(η2)\eta\, \big(y - \hat{V}(s_0)\big)\, k(s_0, s) + O(\eta^2). fit_value minimizes (y−V^(s0))2\big(y - \hat{V}(s_0)\big)^2 instead; how does the prediction change?
  2. For a freshly constructed net_probe, compute the gradients ∇wV^\nabla_w \hat{V} at the 256 probe states S and the kernel values k(s0,s)k(s_0, s) for s0s_0 = S[0]. Take one plain gradient step with η=10−3\eta = 10^{-3} toward y=V^(s0)+1y = \hat{V}(s_0) + 1, without Adam, and compare the measured change at every probe with the prediction.
  3. Plot k(s0,s)/k(s0,s0)k(s_0, s) / k(s_0, s_0) against the distance ∥s−s0∥\|s - s_0\|. How many probes have a negative kernel value, and how does that count compare with the number of probes that the cell reported moving down?
  4. A CartPole policy that balances well collects batches of mostly near-vertical states. Use the kernel to explain how fitting such a batch changes the value estimate and the policy at large pole angles that the batch never contains. Why can that change make the policy worse at those angles?

Discussions