Module contents
Lesson 18 of 37Core 110 min

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.

InteractiveThe critic changes the estimated direction

Preparing actor and critic.

Adjust the quality of an explicit critic and compare estimates with the reference gradient.

Advantage and temporal error

Advantage compares an action with mean value of acting under the policy:

Aπ(s,a)=Qπ(s,a)−Vπ(s).A^\pi(s,a)=Q^\pi(s,a)-V^\pi(s).

With exact value, for a transition from the same dynamics and a fixed action, error δt=Rt+1+γVπ(St+1)−Vπ(St)\delta_t=R_{t+1}+\gamma V^\pi(S_{t+1})-V^\pi(S_t) satisfies

E[δt∣St=s,At=a]=E[Rt+1+γVπ(St+1)∣s,a]−Vπ(s)=Aπ(s,a).\mathbb E[\delta_t\mid S_t=s,A_t=a] =\mathbb E[R_{t+1}+\gamma V^\pi(S_{t+1})\mid s,a]-V^\pi(s) =A^\pi(s,a).

At a true terminal, future value is zero. If the critic is approximate, value error can bias that expectation. Multiplying δt\delta_t 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 nn-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 VV fixed throughout the calculation and a sequence without intermediate boundary, define

A^t(k)=∑j=0k−1γjRt+j+1+γkV(St+k)−V(St).\hat A_t^{(k)}= \sum_{j=0}^{k-1}\gamma^jR_{t+j+1} +\gamma^kV(S_{t+k})-V(S_t).

Substituting δt+j=Rt+j+1+γV(St+j+1)−V(St+j)\delta_{t+j}=R_{t+j+1}+\gamma V(S_{t+j+1})-V(S_{t+j}) cancels interior values, leaving A^t(k)=∑j=0k−1γjδt+j\hat A_t^{(k)}=\sum_{j=0}^{k-1}\gamma^j\delta_{t+j}. For a finite window of KK transitions, mix 1- through KK-step advantages with weights (1−λ)λk−1(1-\lambda)\lambda^{k-1} for k<Kk<K and residual weight λK−1\lambda^{K-1} for k=Kk=K. Exchanging sums gives generalized advantage estimation

A^tGAE(γ,λ)=∑j=0K−1(γλ)jδt+j,0≤λ≤1.\hat A_t^{\mathrm{GAE}(\gamma,\lambda)} =\sum_{j=0}^{K-1}(\gamma\lambda)^j\delta_{t+j}, \quad 0\leq\lambda\leq1.

Residual weight is needed for the finite mixture to sum to one and correctly include λ=1\lambda=1. γ\gamma defines how rewards are discounted in the chosen objective; λ\lambda mixes estimator horizons. In practice both are tuned, but they are different parameters.

InteractiveHow far GAE looks ahead

Preparing trajectories and advantages.

Change discount and λ and observe temporal-error propagation in an explicit MDP.

With λ=0\lambda=0 the one-step TD error remains. With λ=1\lambda=1, a complete truly terminated trajectory telescopes to Gt−V(St)G_t-V(S_t): if VV is inexact this need not be an unbiased conditional advantage, though V(St)V(S_t) may remain a valid gradient baseline. In a cut window an approximate final value retains bootstrap error even with λ=1\lambda=1.

Changing λ\lambda 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, VtV_t, reward and value VtnextV_t^{\mathrm{next}} of its actual next observation, before any reset. With termination indicator dtd_t and truncation ctc_t:

δt=rt+γ(1−dt)Vtnext−Vt,A^t=δt+γλ(1−dt)(1−ct)A^t+1.\delta_t=r_t+\gamma(1-d_t)V_t^{\mathrm{next}}-V_t,\qquad \hat A_t=\delta_t+\gamma\lambda(1-d_t)(1-c_t)\hat A_{t+1}.

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.

InteractiveA rollout with internal resets
Environmentt=0t=1t=2t=3t=4t=5t=6t=7
1
2
3
4

Episode 0, position 0, r=0.0, V(s)=1.00, V(actual final observation)=1.20. Bootstrap mask: 1; trace continuation mask: 1.

Explicit deterministic model with four copies and episodes of 2 to 5 steps. The displayed rewards and values come from the teaching model, not a trained agent. In each cell δ=r+γ(1−terminated)V(actual successor)−V(s). Backward, Âₜ=δₜ+γλ(1−terminated)(1−truncated)Âₜ₊₁; at the end of the visible rollout the future trace is zero, but δ retains the final successor value.

A truncation uses the final observation before reset and cuts the trace between episodes. A terminal does not bootstrap. Pending squares can be selected but do not participate in the calculation. Source: Schulman et al., GAE.

8
0.90
0.80
Cell
environment 1, t=0
δ / GAE advantage
0.080 / −0.064
Follow bootstrap and trace masks across several environments.

For example, with zero reward and current value, γ=0,9\gamma=0,9, 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 1−Var⁡(y−V)/Var⁡(y)1-\operatorname{Var}(y-V)/\operatorname{Var}(y) with stated dataset and target. It can be negative and is undefined if variance of yy 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.

[ ]GAE: recursion and direct sumBrowser
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.

[ ]Bias and variance in an explicit MDPBrowser
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.

[ ]Vectorized A2C and GAE with resetsLocal GPU
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')
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

ProofTD error as advantage
Prove: Prove the conditional TD-error identity when the critic is exact.
0
Work in an MDP with integrable reward, γ∈[0,1), fixed policy π and value Vπ for the same discount. At terminal states take Vπ=0. Condition on Sₜ=s and Aₜ=a.

Step 1 of 3. What is the conditional expectation of Rₜ₊₁+γVπ(Sₜ₊₁)?

ProofFrom k-step returns to GAE
Prove: Derive GAE for a segment of K transitions without intermediate endings.
0
Write δₜ=rₜ+γVₜ₊₁−Vₜ and Aₜ⁽ᵏ⁾=Σₗ₌₀ᵏ⁻¹γˡδₜ₊ₗ, with γ,λ∈[0,1]. The last value bootstraps from the state actually reached.

Step 1 of 3. What telescoping expression does Aₜ⁽ᵏ⁾ have?

NumericA truncated trajectory
For four transitions take γ=0.99, λ=0.95, rewards (0,0,1,0), current values (0.2; 0.25; 0.4; 0.3), and actual next-observation values (0.25; 0.4; 0.3; 0.8). Only the last transition truncates and does not terminate. Calculate the first GAE advantage, retaining final bootstrap and not continuing the trace beyond truncation.
CodeGAE with resets inside the batch
Implement compute_gae(rewards, values, next_values, terminated, truncated, gamma, lam). The first five arguments have shape (T,N), T,N≥1: rewards, values and next_values contain finite reals, and flags are Boolean. next_values[t,n] is the value of the actual next observation for that transition, including final observation before an autoreset. One final value per environment is insufficient: after intermediate truncation the buffer's next observation may belong to another episode. gamma and lam are finite scalars in [0,1]. Compute δ=rewards+gamma(1−terminated)next_values−values and traverse time backward with factor gammalam(1−terminated)*(1−truncated). The trace crosses neither ending nor truncation; a pure cutoff retains bootstrap and both flags true cancels bootstrap. After the last row the trace is zero, but next_values retains bootstrap if appropriate. Return advantages of shape (T,N), do not mutate inputs and reject invalid shapes, flags or parameters with ValueError.
import numpy as np

def compute_gae(rewards, values, next_values, terminated, truncated, gamma, lam):
  pass
Shift+Enter to run
QuizShare or separate
You compare an actor-critic receiving images with one receiving a low-dimensional state vector. What representation decision is best justified?
[ ]Checking the four-step trajectoryBrowser
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])