Actor-critic and GAE
Add a critic that learns the value function and compute GAE while handling terminations and truncations; measure lambda’s bias-variance tradeoff and assess critic quality by explained variance on Hopper.
After this lesson you can
- Implement backward GAE with termination masks and bootstrap at truncation.
- Train the critic on lambda returns and measure its explained variance.
- Empirically compare lambda values from 0 to 1 in bias, variance and learning.
- Obtain stable learning on Hopper with a basic actor-critic.
Before you start
How much future to look at
REINFORCE waits until a trajectory ends to learn what happened after each action. That return is a direct signal, but can vary greatly even from the same state under the same policy. A critic predicts the future before the episode ends. How much should we trust it? Looking at one transition allows its error to bias the signal; waiting until the end accumulates noise from many rewards and decisions.
Generalized advantage estimation, GAE, combines temporal-difference errors with parameter . This lesson develops the identity, implements recursion without mixing episodes and measures its behavior on Hopper. The previous lesson’s REINFORCE baseline subtracts a value from Monte Carlo return; here the critic also provides values constructing the actor target. That difference changes unbiasedness assumptions.
The evaluation rule remains the same: deterministic test policy, separate environments and multiple training seeds. A single-seed curve or high critic explained variance alone does not demonstrate a useful gait. The harness must save returns, diagnostics and configuration, using the same budget for compared variants.
From full return to one temporal step
Value functions describe expected return under a fixed policy. With discount , the Bellman equation expresses value as expected immediate reward plus discounted subsequent value. If is approximate, observed temporal error on a nonterminal transition is
For a genuine end, the subsequent term is zero. If and we condition on current state and action, expected equals advantage , assuming the same future policy. With an approximate critic equality can fail. One-step TD error uses one reward and one prediction: it samples less future than a complete return but incorporates critic error at the next state.
At the other extreme, Monte Carlo return minus uses rewards observed until genuine termination. Current value subtracted as a baseline independent of the current action does not itself bias the score gradient, even when inaccurate. However the random sum of future rewards can have considerable dispersion. If a segment ends at a collection cutoff or external truncation, observed return omits future: adding uses approximate bootstrap, so the result is no longer a complete Monte Carlo return.
There is no universal law that increasing always reduces bias and increases variance for every network and sample. A useful intuition under controlled conditions is that longer horizons replace predictions with observed rewards. But TD errors from different steps are correlated and the policy changes during training. A measurement must specify the reference value defining bias, policy generating data and resampling unit.
Where critic error enters
Let for a fixed policy and consider a nonterminating transition. Conditioning on and , Bellman’s equation gives
Current-state error is subtracted; next-state error depends on where the action leads. If is exact both vanish. If approximate, the difference depends on the transition and can change the signal distinguishing actions. Terminal states use zero value under the MDP convention, so the formula must be adjusted at that boundary. This explains the TD bias mechanism without assuming every inaccurate critic has large error or a fixed sign.
Distinguish bias of an advantage estimate from policy-gradient bias. In a complete episode with , conditional expectation of is . As an estimate of true advantage it retains shift . In the score gradient that shift depends only on state and cancels in expectation under the preceding lesson’s baseline assumptions. It is incorrect to say the numerical advantage estimate is unbiased for any critic merely because the gradient with that baseline is.
For intermediate , future-state values appear within the sum. Those states depend on the current action, so their error cannot automatically be removed as a current-state baseline. When the episode truncates, even contains approximate final value: the signal can depend on bootstrap error there too. A proof treating all endings as terminal or replacing final value by zero proves a different claim.
GAE as sum and recursion
For only remains, the one-step TD estimator. For , expanding the sum cancels interior values:
where final value is defined as zero if the last transition terminates the task. Only then is the expression the episode’s complete Monte Carlo return minus initial value. With external truncation or rollout cutoff the last term bootstraps; calling it Monte Carlo without qualification hides dependence on the critic.
For and an infinite horizon under conditions making sums converge, GAE is also a geometric average of -step advantages. Weights sum to one. Each -step advantage contains observed rewards and a final bootstrap. A finite trajectory requires treating the last-horizon remainder: simply cutting the infinite series loses its mass. Backward recursion implements the finite sum directly without storing every horizon.
The equivalence follows by grouping coefficients. One-step advantage is ; two-step is ; three-step adds . In the geometric mixture, the coefficient of is , exactly the definition’s weight. Interchanging sums requires convergence or a finite horizon with its remainder; individual finiteness is insufficient.
Recursion runs backward in time: each step accumulates local error plus discounted future advantage. Cost is linear in segment length and can be vectorized across environments with one accumulator per column. In parallel systems each column’s boundary can occur in a different row. A scalar mask shared by the batch would cut continuing episodes or mix reset episodes. The code exercise tests two environments with different boundaries.
The original work by Schulman and colleagues introduces GAE as an exponential family of estimators reducing variance at the cost of possible bias with approximate value. Its study also uses trust-region optimization and specific tasks; it does not turn a choice of into a guarantee for Hopper or this lab’s basic actor-critic. That work also discusses as an approximation to an undiscounted objective; here we explicitly write the discounted objective when used to avoid confusing conventions.
For context, the paper’s experimental three-dimensional bipedal locomotion uses 50000-step batches and results averaged over nine seeds. Its sweep gives best results for that task within and . Actor and value networks for three-dimensional robots have three hidden layers of 100, 50 and 25 tanh units; policy update is TRPO. These are published experiment conditions and results, not a numerical forecast for this lesson’s Hopper. For quadrupeds the paper reports five runs and a more limited comparison; do not read those averages as nine seeds for every task.
The figure separates two questions. The chain compares an estimator with a known reference under an explicit model; in Hopper the curve comes from particular training runs and episodes. The same label does not mean chain bias describes the Hopper policy. A higher learning-curve point can reflect exploration, critic adaptation or seed variation as well as the advantage estimator.
The chain has three steps, one action and . Each reward is 0 or 2 with equal probability, independently of the others; true state values are . With one action, its true advantage at the initial state is zero. The figure’s critic deliberately uses , so , and . Therefore
Each reward has mean one and variance one; independence removes covariances. Here bias vanishes at one and variance rises, but these are properties of the defined model, not a universal law. An exact critic or correlated rewards would produce different curves. The figure calculates these expressions and separately shows the lab’s Hopper curve without interpolating untrained results.
Measuring bias and variance when true value is unknown
In Hopper we do not know exactly. An empirical comparison can freeze policy and critic, save state-action pairs and simulate multiple independent continuations from each pair. Some estimate expected reference return; others compute GAE. The reference is a finite Monte Carlo average, not truth: it has sampling error. If any continuation is externally cut and completed with the critic, the reference also incorporates bootstrap error. Retain the number of cutoffs and convention applied.
Estimating conditional GAE variation needs multiple continuations for the same pair . Calculate variance within each group then summarize variances, stating group weighting. One estimate per pair mixes continuation noise with real state-action differences. It can describe total sample dispersion, but not how the estimator varies when the future of one pair is repeated. Using the same futures for several values pairs differences, avoiding confusion with different futures.
The mean of over pairs can summarize difference from the estimated reference. Accompany it with standard error across pairs and remember errors can cancel: a near-zero mean does not imply low bias at every state. Mean squared error incorporates both GAE error and uncertainty in the finite reference. More reference continuations reduce some noise but do not automatically make estimated value exact. Comparison also depends on the pair-selection distribution and does not directly extrapolate to unsampled states.
Another distinction prevents circular conclusions. Rollout advantage variance mixes variation across states, actions and rewards; it may rise because the policy visits more varied situations even when conditional estimator variance falls. During training policy and critic change, so a var(advantage) curve alone does not establish a bias-variance tradeoff. The analytic chain, conditioned continuations and learning curves are complementary evidence with different scopes.
Two masks, not one
A transition can terminate the MDP, truncate at an external limit or continue. The first lesson’s distinction requires separating two operations:
- TD bootstrap. Use and the actual final observation value of that transition. Pure truncation does not zero the value.
- Sum continuation. Use . Either flag resets the environment; the next episode’s advantage does not belong to the previous one.
If , implementable formulas are
with and . When both flags are true, termination zeroes bootstrap and reset cuts recursion. At a rollout edge that neither terminates nor truncates, use subsequent value in the final , but there is no later advantage in the buffer to add; initialize recursion to zero for that segment.
Imagine two buffers with identical rewards, current values and flags, reset after a truncation. If their actual final-state values differ, truncated-transition TD must differ too. Yet the next episode’s initial observation could be identical in both buffers. A function receiving only that reset observation’s value and one value at rollout end lacks information to distinguish them. This is not a loop-order problem: the interface is missing data.
The distinction affects storage too. Save observation, action, reward and flags with the actual subsequent observation or its value under the frozen critic. If calculating values after collection, retain final states before the wrapper overwrites them. If calculating during collection, record the critic version. In both cases the critic target must use the same boundary convention as actor advantage. An array-shape-only test cannot detect an incorrect final value.
The compact signature gae(rewards, values, dones, truncs, last_value, gamma, lam) suffices only for a rollout without internal resets, or if each truncated transition’s final value is supplied separately. In a multi-episode buffer, values[t+1] may refer to a reset observation. This lesson’s implementation therefore receives per-transition next_values: it preserves the actual subsequent-state value, including intermediate truncation. A single global last_value cannot recover discarded final states.
Gymnasium documents multiple autoreset modes. SAME_STEP can already return the new episode’s observation and provide the final observation in info; in NEXT_STEP reset occurs on the following step. Check version and wrapper before deciding where comes from. The important test is not an abstract key name, but that intermediate truncation uses the final state and does not propagate recursion across reset.
Fit the critic and read its diagnostic
Actor-critic uses the critic to reduce noise and the actor to adjust policy. Freezing the target prevents loss changing through it during fitting: critic gradient must pass through the current prediction, not . Fitting value on the same data before computing advantages can introduce additional dependence; calculate them with a previous copy and state the order. The GAE paper warns about that sequence in its experimental description.
EV compares residual variance with target variance, as in regression metrics. If negative, residual varies more than target. This does not necessarily mean mean squared error is worse than every constant, because variance removes mean bias. A constant shift in all predictions can give EV one despite wrong values. If target is constant, the denominator is zero and the metric undefined. Also report mean error and squared error, ideally on separate data, and state whether the target is lambda return or observed return.
One concrete comparison does follow. On the same set, the constant predictor equal to the mean of has MSE equal to . If EV is negative, and, since MSE is , critic MSE exceeds that mean constant. An arbitrary distant constant can have even greater MSE. Conversely, positive EV does not guarantee better MSE than the mean predictor: a sufficiently large systematic shift increases the second term without changing residual variance.
High EV against lambda returns using the critic itself does not demonstrate accuracy against true . Targets and policy change during training, and better fit does not guarantee actor improvement. The law of total variance helps distinguish state variation and state-conditional noise, but does not turn EV into a causal learning measure.
The following calculation separates three cases. A constant prediction equal to the mean gives EV zero; exaggerating differences can yield negative EV; a constant shift can yield EV one despite positive squared error. The last case shows why another metric should accompany the diagnostic.
import numpy as np
def explained_variance(y, prediction):
y, prediction = np.asarray(y, float), np.asarray(prediction, float)
variance = np.var(y)
return np.nan if variance == 0 else 1 - np.var(y - prediction) / variance
y = np.array([0., 1., 2.])
for prediction in [np.ones(3), np.array([0., 3., 6.]), y + 5]:
print("EV", explained_variance(y, prediction),
"MSE", np.mean((y - prediction)**2))The lambda target is not a fixed supervised dataset label: it is recalculated when the previous critic changes, and the state distribution also changes as the actor learns. EV measured on the same batch after several critic updates may be optimistic for that batch. A pre-fit measurement on a new batch asks how the critic generalizes to those targets, although targets still depend on approximate value. Record when the measurement occurred as well as its value.
EV does not reveal where errors occur. Two critics with the same summary can fail in different states: one at the start, another near a fall. To investigate a collapsing actor, stratify residuals by state region or proximity to termination and compare predictions with observed returns in held-out episodes. This does not require calling one observed return the true expected state value: one noisy continuation is a sample, and multiple continuations from one state require reproducing it and resampling the future.
Value clipping and scale
An optional variant limits prediction changes relative to . Construct and penalize the maximum of unclipped and clipped squared errors. This is an implementation decision, not a necessary GAE property or improvement guarantee. Its threshold is in return units: multiplying all rewards by a constant changes what the same means relatively. Stable Baselines3 offers optional clipping, but its code applies MSE to the clipped prediction, not the maximum of the two losses above. Declare which variant runs.
An excessively high critic learning rate can make loss and predictions oscillate. Resulting advantages can be dominated by value errors even with correct recursion. Before changing , record loss, EV, target and prediction magnitudes; also check ending mask and final observation identity. Reducing step size, normalizing units or increasing data are intervention hypotheses, not a proven explanation of a particular failure.
Lab: GAE and Hopper
First implement recursion for one temporal stream. Each next_values entry corresponds to that transition’s actual subsequent observation before reset. Initialize the last stored advantage to zero: this cuts the sum at the buffer edge without removing bootstrap in the last TD error. This cell uses only NumPy and can run in the browser.
import numpy as np
def gae(rewards, values, next_values, terminated, truncated, gamma, lam):
r = np.asarray(rewards, dtype=float)
v = np.asarray(values, dtype=float)
nv = np.asarray(next_values, dtype=float)
term = np.asarray(terminated, dtype=bool)
trunc = np.asarray(truncated, dtype=bool)
if r.ndim != 1 or any(a.shape != r.shape for a in (v, nv, term, trunc)):
raise ValueError("Se requieren vectores de la misma longitud")
if not (0 <= gamma <= 1 and 0 <= lam <= 1):
raise ValueError("gamma y lambda deben estar entre cero y uno")
delta = r + gamma * np.where(term, 0.0, nv) - v
advantages = np.empty_like(r)
carry = 0.0
for t in range(len(r) - 1, -1, -1):
carry = delta[t] + gamma * lam * (not (term[t] or trunc[t])) * carry
advantages[t] = carry
return advantages, advantages + v
r = [1, 2, 3]
v = [0.4, 0.6, 0.2]
nv = [7, 0.2, 0.8]
term = [False, False, True]
trunc = [True, False, False]
a, target = gae(r, v, nv, term, trunc, 0.99, 0.95)
print("Ventajas:", np.round(a, 6), "objetivos:", np.round(target, 6))
r_changed = [1, 200, 300]
assert np.isclose(gae(r_changed, v, nv, term, trunc, 0.99, 0.95)[0][0], a[0])
assert np.isclose(a[0], 7.53)The first step truncates and its actual subsequent value is 7, even though the next stored state belongs to a new episode. Initial advantage is therefore 7.53 and does not change when the next episode’s rewards change. If both flags were true, termination would cancel and yield 0.6. where selects zero at termination: multiplying zero mask by NaN does not produce zero in floating-point arithmetic. In production prefer not evaluating the critic on nonfinite terminal states and check values needed for continuations and truncations are finite. The test deliberately uses a boundary different from the numeric exercise and does not depend on a learning curve.
A forward-sum reference independently checks recursion: for each , sum with weights and stop at the first end flag or array edge. Test ordinary episodes, intermediate terminations and truncations, unflagged rollout cutoff and both flags together. A test with only complete episodes cannot detect crossing a reset.
def gae_forward(r, v, nv, term, trunc, gamma, lam):
result = np.zeros(len(r))
for start in range(len(r)):
weight = 1.0
for t in range(start, len(r)):
value_after = 0.0 if term[t] else nv[t]
result[start] += weight * (r[t] + gamma * value_after - v[t])
if term[t] or trunc[t]:
break
weight *= gamma * lam
return result
rng = np.random.default_rng(555)
for _ in range(100):
r, v, nv = (rng.normal(size=9) for _ in range(3))
term, trunc = rng.random(9) < 0.15, rng.random(9) < 0.15
lam = rng.uniform()
backward = gae(r, v, nv, term, trunc, .97, lam)[0]
forward = gae_forward(r, v, nv, term, trunc, .97, lam)
np.testing.assert_allclose(backward, forward, rtol=1e-12, atol=1e-12)
print("100 casos forward/backward coinciden")
terminal_nan = gae([1], [.4], [np.nan], [True], [False], .99, .95)[0]
print("Valor posterior terminal NaN:", terminal_nan)
assert np.allclose(terminal_nan, [.6])Reference and recursion share mask definitions but not calculation order. Agreement in these tests does not verify that the environment actually stored the correct subsequent state: check that in the collector and a real reset case. Nor does it show advantage accurately estimates true value. Unit tests and empirical experiment answer different questions.
A reproducible actor-critic
The sweep below uses Hopper-v5 on CPU, eight environments, 128-step rollouts per environment and 200 updates per run. Each combination therefore receives 204800 interaction steps. Compare , and with three training seeds; at the same points evaluate actor mean on three held-out seeds. The log contains every run, not only the best. Critic configuration was selected after a pilot using seed 0 and its evaluations, so those episodes are not a fully blind hyperparameter selection test.
The actor averages rollout steps, normalizes batch advantages and clips gradient norm. This is a practical actor-critic update: it omits the per-episode outer factor of the preceding lesson’s initial-state discounted identity and is not presented as an exactly unbiased estimator of that objective. The critic uses a frozen lambda target. Its output is scaled by 30 and the loss divides residual by 30, a parameterization selected after pilot instability. Code clipping is gradient norm, not value prediction; value clipping was explained above but is not applied here.
The next local cell defines matrix GAE and networks. Each training run uses one seed, CPU and one PyTorch thread. Browser NumPy cell functions and local variables do not share an interpreter, so required elements are redefined here. Observations are clipped to [-10, 10] before entering networks; the latent Gaussian action is saved for log density and clipped only when sent to the environment.
import platform
import gymnasium as gym
import mujoco
import numpy as np
import torch
from torch import nn
from torch.distributions import Normal
torch.set_num_threads(1)
GAMMA, N_ENV, HORIZON, UPDATES = .99, 8, 128, 200
EVAL_SEEDS = [200000, 200001, 200002]
print("Versiones:", platform.python_version(), torch.__version__, gym.__version__, mujoco.__version__, np.__version__)
def gae_matrix(rewards, values, next_values, terminated, truncated, gamma, lam):
r, v, nv = map(np.asarray, (rewards, values, next_values))
term, trunc = np.asarray(terminated, bool), np.asarray(truncated, bool)
if not (r.shape == v.shape == nv.shape == term.shape == trunc.shape):
raise ValueError("formas incompatibles")
delta = r + gamma * np.where(term, 0.0, nv) - v
result = np.zeros_like(delta, dtype=np.float64)
carry = np.zeros_like(delta[0], dtype=np.float64)
for t in range(len(delta) - 1, -1, -1):
carry = delta[t] + gamma * lam * (~(term[t] | trunc[t])) * carry
result[t] = carry
return result
def gae_matrix_forward(r, v, nv, term, trunc, gamma, lam):
out = np.zeros_like(r, dtype=float)
for start in range(len(r)):
for env_id in range(r.shape[1]):
weight = 1.0
for t in range(start, len(r)):
after = 0.0 if term[t, env_id] else nv[t, env_id]
out[start, env_id] += weight * (r[t, env_id] + gamma * after - v[t, env_id])
if term[t, env_id] or trunc[t, env_id]:
break
weight *= gamma * lam
return out
test_rng = np.random.default_rng(555)
for _ in range(100):
r, v, nv = (test_rng.normal(size=(9, 3)) for _ in range(3))
term, trunc = test_rng.random((9, 3)) < .15, test_rng.random((9, 3)) < .15
lam = test_rng.uniform()
np.testing.assert_allclose(gae_matrix(r, v, nv, term, trunc, .97, lam),
gae_matrix_forward(r, v, nv, term, trunc, .97, lam))
r = np.array([[1, 2], [3, 4], [5, 6], [7, 8]], dtype=float)
v = np.array([[.1, .2], [.3, .4], [.5, .6], [.7, .8]])
nv = np.array([[.3, .4], [9., .6], [.7, 8.], [4., 5.]])
term = np.array([[0, 0], [0, 0], [0, 1], [0, 0]], dtype=bool)
trunc = np.array([[0, 0], [1, 0], [0, 0], [0, 0]], dtype=bool)
for lam in (0., .4, .95, 1.):
actual = gae_matrix(r, v, nv, term, trunc, .9, lam)
np.testing.assert_allclose(actual, gae_matrix_forward(r, v, nv, term, trunc, .9, lam))
assert np.isclose(actual[1, 0], 3 + .9 * 9 - .3)
assert np.isclose(actual[2, 1], 6 - .6)
assert np.isclose(actual[3, 0], 7 + .9 * 4 - .7)
terminal_nan = gae_matrix(np.array([[1.]]), np.array([[2.]]), np.array([[np.nan]]),
np.array([[True]]), np.array([[False]]), .99, .95)
assert np.allclose(terminal_nan, [[-1.]])
both = gae_matrix(np.array([[1.]]), np.array([[2.]]), np.array([[999.]]),
np.array([[True]]), np.array([[True]]), .99, .95)
assert np.allclose(both, [[-1.]])
print("GAE matricial: extremos, fronteras, 100 comparaciones y terminal NaN superados")
def explained_variance_local(y, prediction):
variance = np.var(y)
return np.nan if variance == 0 else 1 - np.var(y - prediction) / variance
def obs_tensor(obs):
return torch.as_tensor(np.clip(obs, -10, 10), dtype=torch.float32)
class Agent(nn.Module):
def __init__(self, obs_dim, action_dim):
super().__init__()
self.actor = nn.Sequential(nn.Linear(obs_dim, 64), nn.Tanh(), nn.Linear(64, 64), nn.Tanh(), nn.Linear(64, action_dim))
self.critic = nn.Sequential(nn.Linear(obs_dim, 64), nn.Tanh(), nn.Linear(64, 64), nn.Tanh(), nn.Linear(64, 1))
self.log_std = nn.Parameter(torch.full((action_dim,), -0.5))
for net in (self.actor, self.critic):
for layer in net:
if isinstance(layer, nn.Linear):
nn.init.orthogonal_(layer.weight, gain=np.sqrt(2))
nn.init.zeros_(layer.bias)
nn.init.orthogonal_(self.actor[-1].weight, gain=.01)
nn.init.orthogonal_(self.critic[-1].weight, gain=1.0)
def value(self, obs):
return 30.0 * self.critic(obs).squeeze(-1)
def evaluate(agent, seeds=EVAL_SEEDS):
env = gym.make("Hopper-v5")
results = []
try:
for seed in seeds:
state, _ = env.reset(seed=seed)
score, steps = 0.0, 0
while True:
with torch.no_grad():
action = agent.actor(obs_tensor(state[None, :])).numpy()[0]
state, reward, term, trunc, _ = env.step(np.clip(action, env.action_space.low, env.action_space.high))
score += reward
steps += 1
if term or trunc:
results.append({"seed": seed, "return": float(score), "steps": steps,
"terminated": bool(term), "truncated": bool(trunc)})
break
finally:
env.close()
return resultsnpm run lab and open the connection link.The collector calculates subsequent value before resetting each environment. On termination it does not evaluate the critic on that state; on truncation it does so before reset. It stores flags separately. EV is calculated before fitting the critic to the rollout, against that rollout’s lambda targets: it diagnoses fit to those targets, not direct accuracy against true value. Since targets vary with , comparing EV across variants is not equivalent to comparison against a common label.
def run_hopper(lam, seed):
torch.manual_seed(seed)
rng = np.random.default_rng(seed)
envs = [gym.make("Hopper-v5") for _ in range(N_ENV)]
obs = np.array([env.reset(seed=1000000 + seed * N_ENV + i)[0] for i, env in enumerate(envs)])
agent = Agent(obs.shape[1], envs[0].action_space.shape[0])
actor_opt = torch.optim.Adam(list(agent.actor.parameters()) + [agent.log_std], lr=3e-4)
critic_opt = torch.optim.Adam(agent.critic.parameters(), lr=1e-3)
low, high = envs[0].action_space.low, envs[0].action_space.high
history = []
try:
for update in range(1, UPDATES + 1):
states, actions, rewards, vals, next_vals, terms, truncs = ([] for _ in range(7))
for _ in range(HORIZON):
current = obs.copy()
with torch.no_grad():
tensor = obs_tensor(current)
mu = agent.actor(tensor).numpy()
std = agent.log_std.clamp(-2, 1).exp().numpy()
value = agent.value(tensor).numpy()
latent = mu + std * rng.standard_normal(mu.shape).astype(np.float32)
actual_next, rew, term, trunc = [], [], [], []
for i, env in enumerate(envs):
nxt, reward, ended, cut, _ = env.step(np.clip(latent[i], low, high))
actual_next.append(nxt); rew.append(reward); term.append(ended); trunc.append(cut)
nv = np.zeros(N_ENV, dtype=np.float32)
nonterminal = np.flatnonzero(~np.asarray(term, dtype=bool))
if len(nonterminal):
with torch.no_grad():
nv[nonterminal] = agent.value(obs_tensor(np.asarray(actual_next)[nonterminal])).numpy()
states.append(current); actions.append(latent); rewards.append(rew)
vals.append(value); next_vals.append(nv); terms.append(term); truncs.append(trunc)
obs = np.array(actual_next)
for i, env in enumerate(envs):
if term[i] or trunc[i]:
obs[i], _ = env.reset()
states, actions, rewards, vals, next_vals, terms, truncs = map(np.asarray, (states, actions, rewards, vals, next_vals, terms, truncs))
adv = gae_matrix(rewards, vals, next_vals, terms, truncs, GAMMA, lam)
targets = adv + vals
ev = explained_variance_local(targets, vals)
flat_obs = obs_tensor(states.reshape(-1, states.shape[-1]))
flat_action = torch.tensor(actions.reshape(-1, actions.shape[-1]), dtype=torch.float32)
flat_adv = torch.tensor(adv.reshape(-1), dtype=torch.float32)
flat_adv = (flat_adv - flat_adv.mean()) / (flat_adv.std() + 1e-8)
flat_target = torch.tensor(targets.reshape(-1), dtype=torch.float32)
mu = agent.actor(flat_obs)
dist = Normal(mu, agent.log_std.clamp(-2, 1).exp())
actor_loss = -(dist.log_prob(flat_action).sum(-1) * flat_adv.detach()).mean()
actor_opt.zero_grad(); actor_loss.backward()
nn.utils.clip_grad_norm_(list(agent.actor.parameters()) + [agent.log_std], .5)
actor_opt.step()
for _ in range(4):
value_loss = (((agent.value(flat_obs) - flat_target) / 30.0) ** 2).mean()
critic_opt.zero_grad(); value_loss.backward()
nn.utils.clip_grad_norm_(agent.critic.parameters(), .5)
critic_opt.step()
if update % 20 == 0 or update == 1 or update == UPDATES:
history.append({"steps": update * HORIZON * N_ENV, "update": update, "evaluation": evaluate(agent),
"ev": None if np.isnan(ev) else float(ev),
"target_variance": float(np.var(targets)),
"target_mean": float(np.mean(targets)), "value_loss": float(value_loss.item()),
"advantage_variance": float(np.var(adv))})
finally:
for env in envs:
env.close()
return {"lambda": lam, "seed": seed, "history": history}, agent
runs, agents = [], {}
for seed in range(3):
for lam in (0.0, 0.95, 1.0):
run, agent = run_hopper(lam, seed)
runs.append(run)
agents[(lam, seed)] = agent
means = [round(float(np.mean([e["return"] for e in p["evaluation"]])), 3) for p in run["history"]]
evs = [None if p["ev"] is None else round(p["ev"], 3) for p in run["history"]]
print("lambda", lam, "semilla", seed, "retornos", means, "EV", evs)npm run lab and open the connection link.Printed values are ordered by evaluation point: the first is 1024 steps and the rest multiples of 20480 through 204800. Each return shown averages three evaluation episodes of one policy; training seeds are different units. For complete comparison also retain individual scores, episode flags and configuration. The interactive shows three seed traces and their mean, without inventing points between unrun values.
Because curve seeds were consulted during the pilot motivating critic scale, now hold out three others to evaluate all nine final actors. Declare selection and tests before seeing this table: do not afterward choose the best-looking seed, training point or variant. Each row is one trained policy and each return column a test episode; they are not three extra training runs.
FINAL_SEEDS = [400000, 400001, 400002]
final_test = {}
for run in runs:
key = (run["lambda"], run["seed"])
episodes = evaluate(agents[key], FINAL_SEEDS)
final_test[key] = episodes
print("lambda", key[0], "entrenamiento", key[1],
"retornos", [round(e["return"], 3) for e in episodes],
"terminados/truncados", sum(e["terminated"] for e in episodes),
sum(e["truncated"] for e in episodes))npm run lab and open the connection link.In the reference run, all nine training runs completed the planned 204800 steps. From 102400 steps onward, all 54 recorded pre-fit EV points across nine runs exceeded 0.5; the rounded minimum was 0.695. Earlier values were lower and curves were not monotonic. This concerns EV against the rollout’s own lambda targets, not accuracy against true value.
The table below shows each final policy’s three individual returns on new seeds 400000, 400001 and 400002, in order. Numbers come from the evaluation cell and are rounded to three decimals.
| Training seed | Test returns | |
|---|---|---|
| 0 | 0 | 336.945, 338.548, 335.211 |
| 0 | 1 | 373.161, 372.355, 369.113 |
| 0 | 2 | 339.541, 340.114, 336.723 |
| 0.95 | 0 | 381.284, 390.184, 374.164 |
| 0.95 | 1 | 381.127, 380.011, 382.351 |
| 0.95 | 2 | 437.840, 571.773, 428.655 |
| 1 | 0 | 315.164, 314.401, 313.749 |
| 1 | 1 | 291.303, 290.859, 289.549 |
| 1 | 2 | 405.973, 405.571, 404.946 |
Every curve seed’s final mean return exceeded its first point, but increases and fluctuations differed: the figure retains all nine evaluation trajectories. Three episodes in a row do not replace three training runs. With only three training seeds per configuration, results describe the experiment and do not establish universal superiority of a value. Scale selection after the pilot and different value targets across variants also limit causal interpretation.
Conditioned continuations to compare estimators
Use the final actor for and seed 0, freezing actor and critic. For each of 32 initial states, take a first action and save complete MuJoCo integration state after that transition. From each same state-action pair generate four GAE continuations and 16 independent continuations to approximate reference return. Each uses the same four continuations. To preserve the external horizon also restore the TimeLimit step counter; this depends on the installed API and is not a generic wrapper interface.
The reference is mean discounted return minus the same initial value. If a continuation truncates, complete it with final-state value and count it: it then shares critic dependence and is not complete Monte Carlo. The program returns mean variance within each state-action pair, mean difference from estimated reference and standard error across pairs. It also prints variance mixing all pairs, labeled as such, and truncation count. mse_frente_referencia averages squared difference between the mean of the pair’s four GAE estimates and its estimated reference; it is not single-trajectory MSE. Finite-reference error limits interpretation of each difference.
def compare_conditioned(agent, n_states=32, n_ref=16, n_gae=4, seed=20261028):
agent.eval()
env, clone = gym.make("Hopper-v5"), gym.make("Hopper-v5")
model = env.unwrapped.model
spec = mujoco.mjtState.mjSTATE_INTEGRATION
rng = np.random.default_rng(seed)
def value(obs):
with torch.no_grad():
return agent.value(obs_tensor(obs[None, :])).item()
def action(obs):
with torch.no_grad():
mu = agent.actor(obs_tensor(obs[None, :])).numpy()[0]
sigma = agent.log_std.clamp(-2, 1).exp().numpy()
latent = mu + sigma * rng.standard_normal(mu.shape).astype(np.float32)
return np.clip(latent, env.action_space.low, env.action_space.high)
def rollout(environment, obs):
rewards, values, next_values, terms, truncs = [], [], [], [], []
while True:
v = value(obs)
nxt, reward, term, trunc, _ = environment.step(action(obs))
nv = 0.0 if term else value(nxt)
rewards.append(reward); values.append(v); next_values.append(nv)
terms.append(term); truncs.append(trunc)
obs = nxt
if term or trunc:
return rewards, values, next_values, terms, truncs
rows = []
try:
for i in range(n_states):
obs, _ = env.reset(seed=3000000 + i)
first_value = value(obs)
first_action = action(obs)
next_obs, reward, term, trunc, _ = env.step(first_action)
next_value = 0.0 if term else value(next_obs)
if term or trunc:
raise RuntimeError("El primer paso acabó: revisa el protocolo")
physics = np.empty(mujoco.mj_stateSize(model, spec), dtype=np.float64)
mujoco.mj_getState(model, env.unwrapped.data, physics, spec)
def continuation():
clone.reset(seed=0)
mujoco.mj_setState(clone.unwrapped.model, clone.unwrapped.data, physics, spec)
mujoco.mj_forward(clone.unwrapped.model, clone.unwrapped.data)
clone._elapsed_steps = 1
return rollout(clone, next_obs.copy())
suffixes = [rollout(env, next_obs.copy())] + [continuation() for _ in range(n_gae - 1)]
estimates = {lam: [] for lam in (0.0, .95, 1.0)}
for suffix in suffixes:
inputs = [[reward] + suffix[0], [first_value] + suffix[1], [next_value] + suffix[2],
[term] + suffix[3], [trunc] + suffix[4]]
inputs = [np.asarray(x)[:, None] for x in inputs]
for lam in estimates:
estimates[lam].append(float(gae_matrix(*inputs, GAMMA, lam)[0, 0]))
references, reference_steps, reference_truncations = [], [], 0
for _ in range(n_ref):
cont = continuation()
reference_steps.append(len(cont[0]))
total, factor = float(reward), GAMMA
for r in cont[0]:
total += factor * r
factor *= GAMMA
if cont[4][-1]:
total += factor * cont[2][-1]
reference_truncations += 1
references.append(float(total - first_value))
rows.append({"state_seed": 3000000 + i, "first_action": first_action.tolist(),
"advantages": estimates, "references": references,
"reference_mean": float(np.mean(references)),
"reference_se": float(np.std(references, ddof=1) / np.sqrt(n_ref)),
"gae_steps": [1 + len(s[0]) for s in suffixes],
"gae_truncated": sum(bool(s[4][-1]) for s in suffixes),
"reference_steps": reference_steps, "reference_truncated": reference_truncations})
finally:
env.close(); clone.close()
stats = {}
for lam in (0.0, .95, 1.0):
samples = np.array([row["advantages"][lam] for row in rows])
means = samples.mean(axis=1)
references = np.array([row["reference_mean"] for row in rows])
differences = means - references
stats[lam] = {"var_dentro": float(samples.var(axis=1, ddof=1).mean()),
"var_mezclada": float(samples.var(ddof=1)),
"diferencia_media": float(differences.mean()),
"error_tipico": float(differences.std(ddof=1) / np.sqrt(n_states)),
"mse_frente_referencia": float(np.mean(differences**2))}
steps = sum(1 + sum(n - 1 for n in row["gae_steps"]) + sum(row["reference_steps"]) for row in rows)
return stats, steps, sum(row["gae_truncated"] for row in rows), sum(row["reference_truncated"] for row in rows), rows
conditioned, compare_steps, gae_cuts, reference_cuts, conditioned_records = compare_conditioned(agents[(.95, 0)])
print("Pasos:", compare_steps, "truncamientos GAE/referencia:", gae_cuts, reference_cuts)
for lam, data in conditioned.items():
print("lambda", lam, {key: round(value, 3) for key, value in data.items()})npm run lab and open the connection link.The reference run used 105462 environment steps and had no truncations in GAE or reference continuations. The table rounds the cell values:
| Mean within-pair variance | Mean difference from reference | Standard error across pairs | |
|---|---|---|---|
| 0 | 0.000 | -3.562 | 0.816 |
| 0.95 | 3.575 | -2.163 | 0.781 |
| 1 | 112.274 | 0.781 | 1.039 |
Conditional variance for is zero in this design because state, first action and deterministic initial transition are fixed: one-step error does not use continuations. Increasing incorporates random futures and observed variance rises in this sample. Mean difference from reference approaches zero, but the reference has only 16 continuations and shown standard error is an uncertainty scale, not a guarantee that bias equals the table number. In particular, is compatible with zero difference on that scale; it does not alone prove absence of bias.
This comparison covers initial states and one frozen policy selected after training with . It does not show the same figures hold for falling states, other policies or seeds. A wider comparison would sample additional regions and repeat across actors while retaining the same pair definition and budget. The 105462 extra comparison steps are counted separately from each policy’s training steps.
Episode data remain available in runs, final_test and conditioned_records, including individual reference returns, initial action and four advantages per pair. To retain them after closing the session, write a record with explicit encoding. Configuration and versions should accompany the file; also save code version and actor parameters to repeat evaluation without retraining.
import json
from pathlib import Path
record = {
"environment": "Hopper-v5", "gamma": GAMMA, "num_envs": N_ENV,
"horizon": HORIZON, "updates": UPDATES, "evaluation_seeds": EVAL_SEEDS,
"training_seeds": [0, 1, 2], "lambda_values": [0.0, .95, 1.0],
"value_scale": 30.0, "actor_lr": 3e-4, "critic_lr": 1e-3,
"conditional_rng_seed": 20261028, "conditional_reference_count": 16,
"conditional_gae_count": 4, "final_seeds": FINAL_SEEDS, "python": platform.python_version(),
"torch": torch.__version__, "gymnasium": gym.__version__, "mujoco": mujoco.__version__,
"numpy": np.__version__, "runs": runs,
"final_test": [{"lambda": key[0], "seed": key[1], "episodes": episodes}
for key, episodes in final_test.items()],
"conditional_records": conditioned_records,
}
Path("gae-hopper-results.json").write_text(json.dumps(record, ensure_ascii=False, indent=2), encoding="utf-8")
Exercises
Step 1 of 3. What remains if ?
gae_batch(rewards, values, next_values, terminated, truncated, gamma, lam) for NumPy matrices of shape (T, N), with time in rows and environments in columns. Return advantages of the same shape. Use each transition’s actual subsequent value in the TD error, zero bootstrap only on termination, and stop recursion after termination or truncation. A terminal subsequent value can be NaN: it must not contaminate the result. Initialize future advantage to zero at the rollout edge.import numpy as np
def gae_batch(rewards, values, next_values, terminated, truncated, gamma, lam):
passGAE combines TD errors over different horizons and needs one mask for bootstrapping and another to stop recursion at reset. The critic approximates a target constructed with previous values; its explained variance diagnoses that target and does not prove the actor is good. The effect of on Hopper must be measured under a comparable protocol.