Actor-critic, advantages and generalized advantage estimation
Join the two families: a TD-trained critic gives the actor advantage estimates with lower variance than returns. Derive GAE as a λ-return of TD errors with distinct roles for γ and λ, build A2C with vectorized environments, and handle implementation details: truncation bootstrapping, mid-rollout resets, entropy and shared heads.
After this lesson you can
- Define the advantage function and prove TD error is an unbiased estimator with the exact critic.
- Derive GAE and explain the bias–variance tradeoff controlled by λ.
- Implement A2C with vectorized environments, GAE, and policy, value and entropy losses.
- Correctly handle termination, truncation and autoreset within a rollout.
- Diagnose an actor-critic with explained variance, entropy and gradient norm.
Before you start
A signal before the episode ends
REINFORCE assigns credit using returns observed to the end. In long episodes this delays updates and can produce highly variable signals. A critic offers another possibility: estimate future value and construct a one-step signal. In exchange, if its estimate is wrong, bootstrap can bias the update.
The actor represents the policy; the critic approximates a value function for that policy. Sharing a network does not suffice for an exact computed gradient: critic quality, data and the optimized objective matter.
Preparing actor and critic.
Advantage and temporal error
Advantage compares an action with mean value of acting under the policy:
With exact value, for a transition from the same dynamics and a fixed action, error satisfies
At a true terminal, future value is zero. If the critic is approximate, value error can bias that expectation. Multiplying by the policy score yields a signal for the actor; its expectation matches the desired gradient only under appropriate sampling, occupancy and discount conditions.
A one-step actor-critic fits value using TD and moves policy using estimated advantage, stopping gradients through that advantage in actor loss. An -step version accumulates more rewards before bootstrapping. An exact tabular critic is not the only useful theoretical case: compatible approximation uses features tied to the policy score and specific projection conditions. This does not mean any value network sharing a trunk with the actor preserves the exact gradient. See Konda and Tsitsiklis and Sutton and colleagues.
From multistep advantages to GAE
For critic fixed throughout the calculation and a sequence without intermediate boundary, define
Substituting cancels interior values, leaving . For a finite window of transitions, mix 1- through -step advantages with weights for and residual weight for . Exchanging sums gives generalized advantage estimation
Residual weight is needed for the finite mixture to sum to one and correctly include . defines how rewards are discounted in the chosen objective; mixes estimator horizons. In practice both are tuned, but they are different parameters.
Preparing trajectories and advantages.
With the one-step TD error remains. With , a complete truly terminated trajectory telescopes to : if is inexact this need not be an unbiased conditional advantage, though may remain a valid gradient baseline. In a cut window an approximate final value retains bootstrap error even with .
Changing often trades bias against variance, but no law guarantees one strictly decreases and the other increases in every MDP. Schulman and colleagues analyze GAE and distinguish bias introduced by discounting an originally undiscounted objective. If the objective is discounted return from the start, temporal weighting or occupancy from the previous lesson must still be respected.
Two different masks
In a vectorized rollout store, for every transition, , reward and value of its actual next observation, before any reset. With termination indicator and truncation :
The first mask decides whether bootstrap exists under problem semantics; the second prevents propagating residuals across reset. If both flags are true, termination cancels bootstrap. The end of a merely cut rollout also retains bootstrap from the last state and adds no unobserved residuals. If the time limit is part of the task’s true horizon, model it as such; not every truncation signal automatically implies a relevant continuation.
For example, with zero reward and current value, , truncation, final value 3 and reset value 7, the correct residual is 2.7. Using reset state gives 6.3. One value for the whole buffer end cannot recover final values of earlier truncations: store or compute them when collecting each transition.
In vectorized Gymnasium, SAME_STEP may return the reset observation and save the final one in info['final_obs'] with its mask. In NEXT_STEP the next step may only reset that environment; the entry is not a normal action transition. In DISABLED save the final observation and explicitly perform a partial reset. Check version, mode and wrappers: official documentation describes contracts.
A2C, losses and diagnostics
A2C collects a synchronous batch of transitions in several environments, computes advantages and updates actor and critic. A3C uses asynchronous workers. OpenAI Baselines describes A2C as a synchronous alternative and reports cost advantages in its GPU tests; that does not show every A2C beats every A3C. The original A3C work studies asynchronous CPU workers under its own protocol.
A common loss combines policy term, value error and an entropy bonus. When minimizing, the bonus has negative sign: subtracting entropy favors more dispersed distributions. A large coefficient may prevent policy concentration; a small one does not guarantee adequate exploration. With a shared trunk, actor gradients do not pass through advantage, but value and entropy losses can also update shared features. Their scales and coefficients affect the tradeoff.
For diagnosis, log evaluation return, entropy, gradient norm before and after clipping and critic explained variance with stated dataset and target. It can be negative and is undefined if variance of is zero. Low entropy alone does not prove the policy is good; high explained variance on the batch does not guarantee generalization. If normalizing advantages by batch, document the axis, handle zero deviation and remember same-batch statistics introduce dependence between samples.
Labs
This lab separates two operations: bootstrap uses the actual next-state value except at termination, while the trace stops at both termination and truncation. The first check uses a batch with internal endings and compares recursion with a direct sum; it does not assume the observation after autoreset has the final observation’s value.
import numpy as np
def gae(rewards, values, next_values, terminated, truncated, gamma, lam):
rewards = np.asarray(rewards, dtype=float)
values = np.asarray(values, dtype=float)
next_values = np.asarray(next_values, dtype=float)
terminated = np.asarray(terminated, dtype=bool)
truncated = np.asarray(truncated, dtype=bool)
if rewards.ndim != 2 or any(x.shape != rewards.shape for x in
(values, next_values, terminated, truncated)):
raise ValueError('Se esperan matrices (tiempo, entornos) de la misma forma')
advantages = np.empty_like(rewards)
carry = np.zeros(rewards.shape[1])
for t in range(rewards.shape[0]-1, -1, -1):
delta = rewards[t] + gamma*(~terminated[t])*next_values[t] - values[t]
carry = delta + gamma*lam*(~terminated[t])*(~truncated[t])*carry
advantages[t] = carry
return advantages
def direct_gae(rewards, values, next_values, terminated, truncated, gamma, lam):
out = np.zeros_like(rewards, dtype=float)
T, N = rewards.shape
for t in range(T):
for env in range(N):
weight = 1.
for k in range(t, T):
delta = rewards[k,env] - values[k,env]
if not terminated[k,env]: delta += gamma*next_values[k,env]
out[t,env] += weight*delta
if terminated[k,env] or truncated[k,env]: break
weight *= gamma*lam
return out
r = np.array([[0., 1.], [10., 2.], [1., 3.]])
v = np.zeros_like(r)
nv = np.array([[3., 2.], [7., 8.], [9., 4.]])
term = np.array([[False,False], [False,True], [True,False]])
trunc = np.array([[True,False], [False,True], [False,False]])
result = gae(r,v,nv,term,trunc,.9,1.)
reference = direct_gae(r,v,nv,term,trunc,.9,1.)
assert np.allclose(result,reference,rtol=0,atol=1e-12)
assert np.allclose(result,[[2.7,4.6],[17.2,2.],[1.,6.6]])
for gamma in (0.,.9,1.):
for lam in (0.,.4,1.):
assert np.allclose(gae(r,v,nv,term,trunc,gamma,lam),
direct_gae(r,v,nv,term,trunc,gamma,lam),rtol=0,atol=1e-12)
print('Ventajas:', result)
print('Máxima diferencia con suma directa:',np.max(np.abs(result-reference)))Now fix an explicit two-state two-action MDP. Transition is P[s,a,siguiente], reward R[s,a], and policy fixed. Compute exact Vπ by solving Bellman and Aπ=Qπ−Vπ, with γ=0.9. From the same initial state and action generate independent trajectories then follow π for six steps. This MDP has no endings: the six-step cutoff is a collection limit and bootstraps from the reached state.
Compare exact critic with one built by adding a fixed value error. For each λ compute sample bias and variance of error relative to exact advantage of that initial pair. The same episodes are reused for each condition. A finite sample has uncertainty and values depend on the MDP and critic: they do not guarantee a universal bias or variance ordering. With λ=1 and approximate critic, finite cutoff still uses approximate bootstrap.
import numpy as np
def gae(rewards, values, next_values, terminated, truncated, gamma, lam):
advantages = np.empty_like(rewards, dtype=float)
carry = np.zeros(rewards.shape[1])
for t in range(rewards.shape[0]-1, -1, -1):
delta = rewards[t] + gamma*(~terminated[t])*next_values[t] - values[t]
carry = delta + gamma*lam*(~terminated[t])*(~truncated[t])*carry
advantages[t] = carry
return advantages
gamma = .9
P = np.array([[[.8,.2],[.3,.7]], [[.6,.4],[.1,.9]]])
R = np.array([[.2,1.],[-.2,.5]])
pi = np.array([[.65,.35],[.4,.6]])
assert np.all(P >= 0) and np.allclose(P.sum(axis=2),1.)
assert np.all(pi >= 0) and np.allclose(pi.sum(axis=1),1.)
Ppi = np.einsum('sa,san->sn',pi,P)
rpi = np.sum(pi*R,axis=1)
v_exact = np.linalg.solve(np.eye(2)-gamma*Ppi,rpi)
q_exact = R + gamma*np.einsum('san,n->sa',P,v_exact)
advantage = q_exact-v_exact[:,None]
assert np.allclose(np.sum(pi*advantage,axis=1),0.,atol=1e-12)
seed = 1826; count = 10000; horizon = 6
rng = np.random.default_rng(seed)
states = np.empty((horizon,count),dtype=np.int8)
next_states = np.empty_like(states)
rewards = np.empty((horizon,count),dtype=float)
state = np.zeros(count,dtype=np.int8)
for t in range(horizon):
# La primera acción se fija en 1; las siguientes se muestrean de π.
action = np.ones(count,dtype=np.int8) if t == 0 else (rng.random(count) >= pi[state,0]).astype(np.int8)
following = (rng.random(count) >= P[state,action,0]).astype(np.int8)
states[t] = state; next_states[t] = following
rewards[t] = R[state,action]
state = following
truth = float(advantage[0,1])
term = np.zeros_like(states,dtype=bool)
trunc = np.zeros_like(states,dtype=bool)
trunc[-1] = True
print('Semilla:',seed,'trayectorias:',count,'longitud:',horizon)
print('V exacto:',np.round(v_exact,6),'ventaja verdadera A(0,1):',round(truth,6))
for name, critic in [('exacto',v_exact),('aproximado',v_exact+np.array([.6,-.4]))]:
for lam in (0.,.5,.9,1.):
estimates = gae(rewards,critic[states],critic[next_states],term,trunc,gamma,lam)[0]
errors = estimates-truth
print(name,'λ=',lam,'sesgo=',round(float(errors.mean()),6),
'varianza del error=',round(float(errors.var(ddof=1)),6),
'error estándar del sesgo=',round(float(errors.std(ddof=1)/np.sqrt(count)),6))This lab implements synchronous A2C with shared trunk and two heads on CartPole-v1 and LunarLander-v3. Install PyTorch and gymnasium[box2d,classic-control]==1.4.0; LunarLander needs Gymnasium’s Box2D dependencies. Five full-mode seeds have independent networks, environments and evaluations. Default budget is 1,024,000 transitions per seed on CartPole and 2,048,000 on LunarLander. They are not assumed solved: compare individual evaluation returns, not a single training run.
The vector uses Gymnasium 1.4 SAME_STEP: at an ending it retrieves the pre-reset observation from final_obs and checks _final_obs. TD error cancels bootstrap only on terminated; GAE recursion stops on termination or truncation. If both signals are true, termination takes precedence for bootstrap. The next-state value at rollout end is computed before network update. The critic learns targets detached from the graph; advantage is not normalized. Actor loss averages collected steps without weighting by γ to the time since start: this is practical A2C, not claimed as the exact gradient of discounted return from the initial state. Critic loss and entropy bonus also affect the shared trunk.
ORYON_QUICK=1 uses two environments, 16 steps and four updates per task with seed 0. It checks flow, not quality. The JSON report logs untransformed returns and terminated and truncated episodes, entropy, explained variance against the batch’s GAE target, and global gradient norms before and after clipping, plus versions, configuration and seeds. The second norm uses actually clipped gradients. If target variance is zero or at most 10⁻¹², explained variance is stored as null. Evaluation uses separate environments and greedy policy; evaluation seeds repeat across checkpoints for comparison, so they are not independent samples per checkpoint. This cell has not yet been run and no measured numbers are available to publish.
import gc
import json
import math
import os
import random
import traceback
from pathlib import Path
import gymnasium as gym
import numpy as np
import torch
from torch import nn
from torch.distributions import Categorical
if not gym.__version__.startswith('1.4.'):
raise RuntimeError('Este laboratorio requiere Gymnasium 1.4.x por su contrato de autoreset')
quick = os.environ.get('ORYON_QUICK', '0') == '1'
out = Path(os.environ.get('ORYON_A2C_OUT', 'oryon-a2c'))
out.mkdir(parents=True, exist_ok=True)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
gamma, lam = .99, .95
n_env = 2 if quick else 8
horizon = 16 if quick else 128
seeds = [0] if quick else [0, 1, 2, 3, 4]
updates_by_env = {'CartPole-v1': 4 if quick else 1000,
'LunarLander-v3': 4 if quick else 2000}
learning_rate, value_coef, entropy_coef, max_grad_norm = .0003, .5, .01, .5
evaluation_episodes = 3 if quick else 10
eval_every = 2 if quick else 100
def gae(rewards, values, successor_values, terminated, truncated, discount, trace):
# Matrices [tiempo, entorno]; successor_values es V de la transición real.
shapes = [np.shape(x) for x in (rewards, values, successor_values, terminated, truncated)]
if len(set(shapes)) != 1 or len(shapes[0]) != 2:
raise ValueError('Las cinco matrices deben tener forma [tiempo, entorno] idéntica')
terminated = np.asarray(terminated, dtype=bool)
truncated = np.asarray(truncated, dtype=bool)
advantage = np.zeros(shapes[0], dtype=np.float64)
running = np.zeros(shapes[0][1], dtype=np.float64)
for t in range(shapes[0][0] - 1, -1, -1):
delta = rewards[t] + discount * (1 - terminated[t].astype(int)) * successor_values[t] - values[t]
running = delta + discount * trace * (~(terminated[t] | truncated[t])) * running
advantage[t] = running
return advantage
def transition_successors(next_observation, terminated, truncated, info):
# SAME_STEP entrega el reset en next_observation; el final vive en info.
done = np.asarray(terminated) | np.asarray(truncated)
successor = np.asarray(next_observation).copy()
if done.any():
if 'final_obs' not in info or '_final_obs' not in info:
raise RuntimeError('Falta la observación final SAME_STEP de Gymnasium 1.4')
mask = np.asarray(info['_final_obs'], dtype=bool)
if not np.array_equal(mask, done):
raise RuntimeError('La máscara de observaciones finales no coincide con done')
for i in np.flatnonzero(done):
successor[i] = info['final_obs'][i]
return successor
# Dos entornos, un truncamiento, una terminación y un final doble.
r = np.array([[1., 1.], [2., 2.], [3., 3.]])
v = np.zeros_like(r)
nv = np.full_like(r, 10.)
term = np.array([[False, False], [False, True], [False, True]])
trunc = np.array([[False, False], [True, False], [False, True]])
adv = gae(r, v, nv, term, trunc, .5, 1.)
assert np.allclose(adv, [[9.5, 7.], [7., 2.], [8., 3.]])
fake_next = np.array([[90.], [91.], [92.]])
fake_info = {'final_obs': np.array([np.array([5.]), None, np.array([7.])], dtype=object),
'_final_obs': np.array([True, False, True])}
assert np.array_equal(transition_successors(fake_next, [True, False, False],
[False, False, True], fake_info).ravel(), [5., 91., 7.])
class ActorCritic(nn.Module):
def __init__(self, obs_size, n_actions):
super().__init__()
self.body = nn.Sequential(nn.Linear(obs_size, 128), nn.Tanh(),
nn.Linear(128, 128), nn.Tanh())
self.actor = nn.Linear(128, n_actions)
self.critic = nn.Linear(128, 1)
def forward(self, x):
h = self.body(x)
return self.actor(h), self.critic(h).squeeze(-1)
def tensor(x):
return torch.as_tensor(np.asarray(x), dtype=torch.float32, device=device)
def evaluate(model, env_id, train_seed):
env = gym.make(env_id)
episodes = []
try:
for i in range(evaluation_episodes):
eval_seed = 100000 + train_seed * 1000 + i
obs, _ = env.reset(seed=eval_seed)
total, steps = 0., 0
while True:
with torch.no_grad():
logits, _ = model(tensor(obs).unsqueeze(0))
action = int(logits.argmax(dim=-1).item())
obs, reward, terminated, truncated, _ = env.step(action)
total += float(reward)
steps += 1
if terminated or truncated:
episodes.append({'seed': eval_seed, 'return': total, 'steps': steps,
'terminated': bool(terminated), 'truncated': bool(truncated)})
break
finally:
env.close()
return episodes
def train(env_id, seed):
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
if torch.cuda.is_available():
torch.cuda.manual_seed_all(seed)
envs = gym.vector.SyncVectorEnv(
[lambda env_id=env_id: gym.make(env_id) for _ in range(n_env)],
autoreset_mode=gym.vector.AutoresetMode.SAME_STEP)
try:
obs, _ = envs.reset(seed=[seed * 1000 + i for i in range(n_env)])
model = ActorCritic(envs.single_observation_space.shape[0], envs.single_action_space.n).to(device)
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
running_returns = np.zeros(n_env, dtype=np.float64)
history = []
for update in range(1, updates_by_env[env_id] + 1):
rewards, values, next_values, terms, truncs = [], [], [], [], []
log_probs, entropies, value_graphs = [], [], []
completed_returns, terminal_count, truncation_count = [], 0, 0
for _ in range(horizon):
logits, value = model(tensor(obs))
distribution = Categorical(logits=logits)
action = distribution.sample()
next_obs, reward, terminated, truncated, info = envs.step(action.cpu().numpy())
successor = transition_successors(next_obs, terminated, truncated, info)
with torch.no_grad():
_, next_value = model(tensor(successor))
rewards.append(np.asarray(reward, dtype=np.float64))
values.append(value.detach().cpu().numpy())
next_values.append(next_value.cpu().numpy())
terms.append(np.asarray(terminated, dtype=bool))
truncs.append(np.asarray(truncated, dtype=bool))
log_probs.append(distribution.log_prob(action))
entropies.append(distribution.entropy())
value_graphs.append(value)
running_returns += reward
done = terminated | truncated
for i in np.flatnonzero(done):
completed_returns.append(float(running_returns[i]))
running_returns[i] = 0.
terminal_count += int(np.count_nonzero(terminated))
truncation_count += int(np.count_nonzero(truncated))
obs = next_obs
values_np = np.stack(values)
advantages = gae(np.stack(rewards), values_np, np.stack(next_values),
np.stack(terms), np.stack(truncs), gamma, lam)
targets = values_np + advantages
advantage_tensor, target_tensor = tensor(advantages), tensor(targets)
predicted = torch.stack(value_graphs)
actor_loss = -(torch.stack(log_probs) * advantage_tensor).mean()
critic_loss = .5 * (predicted - target_tensor).square().mean()
entropy = torch.stack(entropies).mean()
loss = actor_loss + value_coef * critic_loss - entropy_coef * entropy
if not torch.isfinite(loss):
raise FloatingPointError('Pérdida no finita')
optimizer.zero_grad(set_to_none=True)
loss.backward()
norm = float(nn.utils.clip_grad_norm_(model.parameters(), max_grad_norm, error_if_nonfinite=True))
norm_after_clip = float(torch.sqrt(sum(
p.grad.detach().square().sum() for p in model.parameters() if p.grad is not None)))
optimizer.step()
target_variance = float(np.var(targets))
explained = None if target_variance <= 1e-12 else float(1 - np.var(targets-values_np)/target_variance)
row = {'update': update, 'transitions': update * n_env * horizon,
'training_completed_returns': completed_returns,
'training_terminations': terminal_count, 'training_truncations': truncation_count,
'actor_loss': float(actor_loss.detach()), 'critic_loss': float(critic_loss.detach()),
'entropy': float(entropy.detach()), 'explained_variance': explained,
'gradient_norm_before_clip': norm, 'gradient_norm_after_clip': norm_after_clip}
if update % eval_every == 0 or update == updates_by_env[env_id]:
row['evaluation'] = evaluate(model, env_id, seed)
print(env_id, 'semilla', seed, 'actualización', update,
'retorno evaluado', np.mean([e['return'] for e in row['evaluation']]),
'entropía', row['entropy'], 'varianza explicada', explained, flush=True)
history.append(row)
return {'environment': env_id, 'seed': seed, 'history': history}
finally:
envs.close()
report = {'quick': quick, 'gymnasium': gym.__version__, 'numpy': np.__version__,
'torch': torch.__version__, 'device': str(device), 'seeds': seeds,
'configuration': {'gamma': gamma, 'lambda': lam, 'n_env': n_env, 'horizon': horizon,
'updates_by_env': updates_by_env, 'learning_rate': learning_rate,
'value_coefficient': value_coef, 'critic_half_squared_error': True,
'entropy_coefficient': entropy_coef, 'gradient_clip': max_grad_norm,
'autoreset': 'SAME_STEP', 'advantage_normalization': False,
'actor_time_weighting': 'uniforme por transición',
'evaluation_episodes': evaluation_episodes, 'evaluation_every_updates': eval_every,
'evaluation_seed': '100000 + 1000 * train_seed + episode'}, 'runs': []}
for env_id in updates_by_env:
for seed in seeds:
failure = None
try:
result = train(env_id, seed)
except Exception:
# Conserva el diagnóstico como texto sin retener el traceback y sus tensores.
failure = traceback.format_exc()
finally:
gc.collect()
if torch.cuda.is_available():
torch.cuda.empty_cache()
if failure is not None:
raise RuntimeError('Falló el entrenamiento; diagnóstico original:\n' + failure)
report['runs'].append(result)
(out / 'a2c-report.json').write_text(json.dumps(report, indent=2, allow_nan=False), encoding='utf-8')
print('Informe:', out / 'a2c-report.json')npm run lab and open the connection link.Exercises
Step 1 of 3. What is the conditional expectation of Rₜ₊₁+γVπ(Sₜ₊₁)?
Step 1 of 3. What telescoping expression does Aₜ⁽ᵏ⁾ have?
import numpy as np
def compute_gae(rewards, values, next_values, terminated, truncated, gamma, lam):
pass
import numpy as np
r=np.array([0.,0.,1.,0.]); v=np.array([.2,.25,.4,.3]); nxt=np.array([.25,.4,.3,.8])
delta=r+.99*nxt-v
adv=np.zeros(4); carry=0.
for t in range(3,-1,-1):
carry=delta[t]+.99*.95*carry
adv[t]=carry
print('Residuos:',delta)
print('Ventajas:',adv)
print('Ejemplo de truncamiento: final / reinicio:',.9*3.,.9*7.)
assert np.allclose(adv,[1.3875453759715,1.424822303,1.359726,.492])