PPO from scratch with all its details
Implement readable single-file PPO with vectorized environments, clipped updates and implementation details, then compare its measured performance with a local reference under the same budget.
After this lesson you can
- Implement vectorized collection with automatic reset and tensor storage.
- Implement the clipped objective, value loss and entropy bonus.
- Incorporate implementation details and document the reason for each.
- Reproduce locally run CleanRL performance on Hopper and HalfCheetah with one million steps.
Before you start
One sample, many updates
You have just collected a batch with a policy that cannot yet hop. Each transition contains an action and an estimate of how much better it was than average behavior. Can you reuse those data multiple times to improve the policy without treating them as if they came from the new policy? PPO retains the probability with which each action was taken and compares it with the current policy’s probability. Its clipped objective reduces the local incentive for excessive change on one sample but does not itself guarantee a trust region.
This lesson builds the entire chain: collect transitions from several environments, calculate GAE advantages, update actor and critic by minibatch, save normalization statistics and compare with a reference run under the same protocol. The return curve is an empirical result, not proof of correct computation: masks, probabilities and units must also be checked.
The ratio and clipping
Let be the frozen policy generating the batch. For a continuous action with positive density under both policies, the density ratio is
If is positive, increasing that action’s probability increases surrogate . If negative, reducing probability makes the contribution less negative. Either way an extreme ratio can dominate the batch. PPO compares the surrogate with a ratio clipped to and takes the smaller.
With positive advantage, contribution stops growing above ratio ; below that it retains slope . With negative advantage, the plateau appears below . For example, with , and , the unclipped term is , clipped term and minimum .
Inequality follows immediately because the minimum cannot exceed either argument. It bounds the sample surrogate, not the new policy’s true return. Samples share parameters: other actions, critic loss if networks are shared, entropy and optimizer can move the ratio past the plateau. Even with separate networks, other samples’ gradients can change this probability. There is no guarantee all ratios remain in range or strict KL bound.
The ratio changes the action distribution conditional on state. With common support and integrable function ,
The equality follows by substituting the ratio and canceling the old density under the integral. However state still comes from the state distribution generating the old batch. A single-action ratio does not itself correct the new policy’s state distribution. The surrogate is local in this sense too: many epochs can increase mismatch between batch distribution and current policy.
Inside the unclipped region, derivative with respect to ratio is . On plateaus it is zero; at junctions there is a corner and the library’s subgradient convention applies. This treats advantage as constant. Accidentally letting actor gradients pass through the critic or normalized advantages optimizes another function. Explicitly separate target computation from minibatch losses.
TRPO motivates controlling distance between policies, but its practical procedure approximates a divergence constraint. The TRPO paper distinguishes the theoretical procedure and its implementable approximation. PPO proposes reusing data across several optimization epochs of a surrogate: clipping is not equivalent to imposing TRPO’s constraint. KL, clipped fraction and separate performance still need monitoring.
The PPO paper’s continuous-control experiment illustrates why a number needs a protocol. It used seven tasks, three seeds per task and one million steps per run. Table 1 reports a normalized score aggregated across 21 runs: clipping with gives 0.82; no clipping or penalty gives -0.39. Each task was scaled so random policy was zero and the best result one. These are not raw Hopper returns or estimates of our code. For that benchmark table 3 states horizon 2048, Adam rate , 10 epochs, minibatches of 64, and . The text describes a policy with two 64-unit tanh hidden layers, separate policy and value networks and no entropy bonus in that comparison. These conditions do not automatically apply to other paper experiments or every PPO implementation.
What is stored in a rollout
Vectorized collection maintains independent environments for steps. The buffer axes are (tiempo, entorno, ...) (time, environment, …); each transition stores the policy’s observation, latent action, old log probability, previous value, reward and flags. Only after computing GAE are axes flattened into samples. A minibatch should shuffle indices of this batch, not reorder states before temporal recursion.
For continuous actions, one common choice samples diagonal Gaussian , sums component log densities and sends the environment an action clipped to its bounds. If is clipped with clip, the environment receives a different action from the latent one. The policy ratio must evaluate the same stored under old and new distributions. Evaluating Gaussian density at the clipped action as if it were the original sample changes the estimator; effective action distribution has masses at the boundaries. Reported Gaussian entropy is for the latent variable.
Observation normalization introduces additional state. During collection store normalized observations actually fed to the actor. If statistics subsequently change, recomputing them using the new version changes inputs and breaks comparison with old log probability. For final evaluation save and freeze the same statistics with weights. Evaluation reports returns in original units without reward normalization or clipping.
Boundaries require two masks, as in the previous lesson. On genuine termination bootstrap is zero. At an external limit retain value of the actual final observation, but stop GAE recursion before crossing reset. In an autoresetting environment vector, the observation returned for the next step may already belong to a new episode: recover the previous transition’s final observation and normalize it consistently. Do not confuse final state with next episode’s initial state.
Audit the buffer by examining one column: if an environment ends at step , that step’s reward and flag belong to the previous episode, while the next collection observation belongs to the new one. In use . In subsequent recursion use . If the rollout ends without episode termination, subsequent value enters the final TD error and future advantage beyond the buffer initializes to zero. These distinct decisions must be tested separately.
| Record | Shape before flattening | Later use |
|---|---|---|
| Normalized observation | (T, N, obs_dim) | Reconstruct each minibatch’s exact input. |
| Latent action | (T, N, act_dim) | Evaluate the same action under the current policy. |
| Old log probability and value | (T, N) | Frozen ratio denominator and critic target. |
| Reward and flags | (T, N) | Calculate TD errors and stop GAE per environment. |
| Actual subsequent observation value | (T, N) | Bootstrap without using a reset observation. |
Summing component log densities of a diagonal Gaussian yields a scalar joint log density per transition; densities multiply. Averaging instead of summing dimensions changes the exponential ratio and dependence on act_dim. A useful check builds small distributions, compares component sum with torch.distributions.Independent, and verifies ratio one within numerical tolerance before updating using identical inputs and actions. Resolve any failure before interpreting a learning curve.
Before training, test boundaries in a minimal batch. This example uses two hypothetical environments and two steps. The first truncates at step one, the second genuinely terminates; subsequent rewards belong to new episodes. This is not a MuJoCo result, only a mask calculation check.
import numpy as np
rewards = np.array([[1., 2.], [100., 100.]])
values = np.array([[.5, 1.], [0., 0.]])
next_values = np.array([[9., 9.], [0., 0.]])
terminated = np.array([[False, True], [True, True]])
truncated = np.array([[True, False], [False, False]])
gamma, lam = .9, .95
delta = rewards + gamma * np.where(terminated, 0., next_values) - values
adv = np.zeros_like(delta)
carry = np.zeros(2)
for t in range(len(delta) - 1, -1, -1):
carry = delta[t] + gamma * lam * (~(terminated[t] | truncated[t])) * carry
adv[t] = carry
assert np.allclose(adv[0], [8.6, 1.])
old_logp = np.array([-.7, -2.1])
new_logp = old_logp.copy() # misma política, observaciones y acciones
ratio = np.exp(new_logp - old_logp)
assert np.allclose(ratio, 1.)
print("Ventajas antes de los reinicios:", adv[0])
print("Razón antes de actualizar:", ratio)The first value retains bootstrap at truncation and excludes the next episode’s reward. The second zeroes bootstrap on termination. In training code, the ratio test must actually compute both log densities with the actor, not merely copy one vector: here copying illustrates the expected identity.
The update and its details
With advantages and value targets computed from the old actor and critic, an epoch traverses the batch in minibatches. A typical joint loss to minimize is
Some implementations also clip value change and use the maximum of clipped and unclipped losses; others do not. The entropy coefficient can be zero. Record both choices: the PPO name does not specify a unique implementation. Fit value to the batch’s frozen target, not one reconstructed using predictions changing each epoch.
Clipped fraction counts batch samples satisfying . It describes observed ratios, not the exact fraction with zero gradient: positive advantage has a plateau only at the upper boundary, negative only at the lower. Reverse divergence from old to new policy can also be estimated by the mean of , with . A finite batch can yield a negative value even though true KL is nonnegative.
Another estimator uses , nonnegative by . Under old-policy sampling, common support and normalized distributions, , so both estimators have the same expectation: old-to-new KL conditional on batch states. One sample cannot diagnose all training: interpret clipped fraction, KL, entropy, value and returns together across seeds.
Implementation details affect gradient scale and comparability:
- Observations: running mean and variance reduce scale differences but are part of model state. Define initial pseudocount, numerical threshold, clipping and when statistics update.
- Rewards: normalization using discounted-return statistics changes critic-target scale. Clipping normalized rewards also changes the training signal. Do not confuse them with raw evaluation return.
- Advantages: centering and scaling by batch or minibatch changes relative sample weights; centering can even change individual advantage signs. A minibatch of one has no informative deviation and can yield zero or nonfinite signal depending on convention.
- Initialization: orthogonal matrices and selected output gains control initial scales. They do not replace a check of Gaussian deviation and log density.
- Norm clipping: limits the gradient norm received by the optimizer; it does not directly bound KL or guarantee a maximum Adam parameter change.
- Learning-rate annealing: reducing the rate across updates can make final steps more conservative. The schedule must reflect actual budget and be recorded.
The PPO implementation-details guide compares choices in specific implementations. Do not attribute performance differences to a detail without an ablation isolating it. Save configuration, versions, seed, steps, episodes, costs, statistics and weights. A curve without its evaluation protocol cannot distinguish algorithm changes from measurement changes.
Optimizer implementation matters: Adam keeps internal moments not recoverable from actor and critic weights alone. To resume training, also save those moments, step count and normalizers. Identical continuation additionally needs every environment and random-generator state; if interrupted mid-update, it also needs buffer, minibatch order and update position. Even then, bit-for-bit reproducibility depends on deterministic operations and environment. To evaluate a frozen policy, architecture and weights plus observation transformation and deterministic action definition suffice. This distinction prevents confusing an inference checkpoint with full execution state.
Running normalization can update by batches without storing every observation. Let denote size, mean and squared-deviation sum of one set, and define the same for . If both sizes are positive, with and ,
The identity follows by expanding within each group: cross terms vanish because deviations from each group’s own mean sum to zero. Apply the formula componentwise to vector observations. Population variance is for ; an initial pseudocount changes it and must be described. For batches and , the calculation gives , mean , and variance . The coding exercise also checks unequal partitions and multivariate inputs.
An algebraic check
The next cell checks the samplewise bound for both signs and the numerical example. It tests the objective, not Hopper training.
import numpy as np
def ppo_surrogate(ratio, advantage, epsilon):
ratio = np.asarray(ratio)
advantage = np.asarray(advantage)
return np.minimum(ratio * advantage,
np.clip(ratio, 1 - epsilon, 1 + epsilon) * advantage)
r = np.linspace(0, 2, 1001)
for a in (-1.5, 1.5):
assert np.all(ppo_surrogate(r, a, .2) <= r * a + 1e-12)
print("Ejemplo:", ppo_surrogate(.6, -2., .1))
print("Cota verificada para ambos signos en", len(r), "razones")
x = np.arange(1., 6.)
print("Estadísticas de 1 a 5:", len(x), x.mean(), ((x - x.mean())**2).sum(), x.var())Lab: PPO and a reference
The comparison must run custom code and an identified CleanRL version on this machine with the same environments, step count, seeds and evaluation protocol. Keep identities of five training seeds separate from evaluation episodes: five episodes of one actor are not five independent actors. The IQM interval quantifies run variation under the chosen resampling and is necessarily uncertain with five seeds.
This protocol uses one environment per training run so both implementations share batch size and budget, although transitions may differ. The custom implementation also supports multiple environments and is tested with two; with the chosen wrappers each subenvironment has its own observation statistics. A checkpoint retains all of them, but evaluation explicitly uses the frozen environment-zero transformation. A short mechanical test does not show that a policy trained with multiple normalizers behaves identically when evaluated with one; a shared normalizer would be another design requiring implementation and measurement.
The reference is its continuous-action PPO code. That version uses its own wrappers and masks: the comparison records concrete differences instead of claiming equivalence merely because both are called PPO. In particular, if one treats truncation as terminal without bootstrap while the other retains subsequent value, that can affect results and must be interpreted.
The pinned lab reference comes from revision 35896b1fefa9898b904f7e09bcbe6e168e15d2a9, adapted to the installed Gymnasium API, evaluation and saving statistics. It retains the original combined termination/truncation mask. The custom implementation uses two masks, so programs are not identical. Both use Gymnasium 1.4.0 NormalizeReward, whose discounted accumulator in this version does not reset on truncation; this shared behavior is part of the protocol, but no specific effect is attributed without a controlled comparison. Actor, initialization order and seeds were deliberately paired: similar results are not independent reproduction or proof of general variant equivalence.
The first four runs, seed zero for both methods and environments, started before source files were frozen with hashes. Known later changes affected evaluator compatibility and multi-environment generalization; single-instance code was structurally reviewed, but byte-for-byte identity of the loaded file in those runs cannot be certified. Remaining seeds used one frozen version per method, hash-checked before execution. This limits provenance for the first four runs and must accompany interpretation.
To check reproducibility despite that limitation, the four seed-zero runs were repeated with frozen sources and the same million steps. All six checkpoints, five curve evaluations per checkpoint and five held-out final evaluations were compared for each run. The next cell summarizes the comparison report: each checkpoint row contains step, maximum absolute parameter difference, maximum statistic difference, maximum return difference and an equality indicator for steps and flags; the last pair summarizes final evaluation.
cotejo = [["own-Hopper-v5-seed0",[[0,0,0,0,1],[200000,0,0,0,1],[400000,0,0,0,1],[600000,0,0,0,1],[800000,0,0,0,1],[1000000,0,0,0,1]],[0,1]],["own-HalfCheetah-v5-seed0",[[0,0,0,0,1],[200000,0,0,0,1],[400000,0,0,0,1],[600000,0,0,0,1],[800000,0,0,0,1],[1000000,0,0,0,1]],[0,1]],["cleanrl-Hopper-v5-seed0",[[0,0,0,0,1],[200000,0,0,0,1],[400000,0,0,0,1],[600000,0,0,0,1],[800000,0,0,0,1],[1000000,0,0,0,1]],[0,1]],["cleanrl-HalfCheetah-v5-seed0",[[0,0,0,0,1],[200000,0,0,0,1],[400000,0,0,0,1],[600000,0,0,0,1],[800000,0,0,0,1],[1000000,0,0,0,1]],[0,1]]]
for nombre, checkpoints, final in cotejo:
assert len(checkpoints) == 6 and all(row[4] == 1 for row in checkpoints) and final[1] == 1
print(nombre, 'checkpoints', len(checkpoints),
'máx parámetros', max(row[1] for row in checkpoints),
'máx normalizador', max(row[2] for row in checkpoints),
'máx retorno de curva', max(row[3] for row in checkpoints),
'máx retorno final', final[0], 'pasos y banderas iguales', True)
print('Total checkpoints:', sum(len(run[1]) for run in cotejo),
'episodios de curva:', sum(len(run[1]) * 5 for run in cotejo),
'episodios finales:', len(cotejo) * 5)On this machine all four repeats succeeded: parameters and normalizers matched exactly across 24 checkpoints; maximum return difference was zero in 120 curve episodes and 20 test episodes, with matching lengths and flags. Comparing values cannot recover or prove the historical hash not recorded at the original launch. Nor does it guarantee identity on another platform or version.
The next cell defines custom PPO and evaluator in one file. Running it does not start training: components are tested next and the full budget is launched separately. Checkpoints save weights and inference statistics, not full trajectory-resumption state. The teaching version adds a configurable entropy coefficient: zero, as used in the sweep, skips that branch and retains experimental objective operations; a nonzero value activates the latent Gaussian bonus. This option was not evaluated in the table.
# PPO y evaluación en un fichero. Reconstruido del protocolo congelado.
"""Evaluación determinista con el normalizador de entrenamiento congelado."""
from pathlib import Path
import json
import os
import gymnasium as gym
import numpy as np
import torch
EVAL_SEEDS = [400000, 400001, 400002, 400003, 400004]
def observation_stats(env):
while not isinstance(env, gym.wrappers.NormalizeObservation):
env = env.env
return {'mean': env.obs_rms.mean.copy(), 'var': env.obs_rms.var.copy(),
'count': float(env.obs_rms.count), 'epsilon': float(env.epsilon)}
def evaluate(agent, env_id, stats):
env = gym.make(env_id)
results = []
try:
for seed in EVAL_SEEDS:
obs, _ = env.reset(seed=seed)
score, steps = 0., 0
while True:
norm = np.clip((obs - stats['mean']) / np.sqrt(stats['var'] + stats['epsilon']), -10, 10)
with torch.no_grad():
device = next(agent.parameters()).device
action = agent.actor_mean(torch.tensor(norm[None, :], dtype=torch.float32, device=device)).cpu().numpy()[0]
obs, reward, term, trunc, _ = env.step(np.clip(action, env.action_space.low, env.action_space.high))
score += float(reward)
steps += 1
if term or trunc:
break
results.append({'seed': seed, 'return': score, 'steps': steps,
'terminated': bool(term), 'truncated': bool(trunc)})
finally:
env.close()
return results
def save_snapshot(agent, env, env_id, seed, steps, method, history, all_envs=None):
stats = observation_stats(env)
stats_by_env = [observation_stats(x) for x in all_envs] if all_envs is not None else [stats]
folder = Path(os.environ.get('PPO_OUTPUT_DIR', Path(__file__).resolve().parent if '__file__' in globals() else Path.cwd()))
name = f'{method}-{env_id}-seed{seed}'
checkpoint = folder / f'{name}-step{steps}.pt'
torch.save({'state_dict': agent.state_dict(), 'stats': stats, 'stats_by_env': stats_by_env, 'env_id': env_id,
'seed': seed, 'steps': steps, 'method': method}, checkpoint)
episodes = evaluate(agent, env_id, stats)
history.append({'steps': steps, 'evaluation': episodes, 'checkpoint': checkpoint.name})
(folder / f'{name}.json').write_text(json.dumps(history, ensure_ascii=False, indent=2), encoding='utf-8')
print(method, env_id, seed, steps, 'eval', [round(ep['return'], 2) for ep in episodes], flush=True)
"""PPO continuo en CPU, con GAE separado para terminal y truncamiento."""
import argparse
import random
import gymnasium as gym
import numpy as np
import torch
from torch import nn
from torch.distributions import Normal
torch.set_num_threads(1)
def build_env(env_id, gamma, max_episode_steps=None):
env = gym.make(env_id, max_episode_steps=max_episode_steps)
env = gym.wrappers.FlattenObservation(env)
env = gym.wrappers.RecordEpisodeStatistics(env)
env = gym.wrappers.ClipAction(env)
env = gym.wrappers.NormalizeObservation(env)
env = gym.wrappers.TransformObservation(env, lambda obs: np.clip(obs, -10, 10), env.observation_space)
env = gym.wrappers.NormalizeReward(env, gamma=gamma)
return gym.wrappers.TransformReward(env, lambda reward: np.clip(reward, -10, 10))
def layer(n_in, n_out, gain):
result = nn.Linear(n_in, n_out)
nn.init.orthogonal_(result.weight, gain)
nn.init.zeros_(result.bias)
return result
class PPOAgent(nn.Module):
def __init__(self, obs_dim, act_dim):
super().__init__()
# Orden de creación equivalente a la referencia, pero implementación propia.
self.critic = nn.Sequential(layer(obs_dim, 64, np.sqrt(2)), nn.Tanh(),
layer(64, 64, np.sqrt(2)), nn.Tanh(), layer(64, 1, 1.0))
self.actor_mean = nn.Sequential(layer(obs_dim, 64, np.sqrt(2)), nn.Tanh(),
layer(64, 64, np.sqrt(2)), nn.Tanh(), layer(64, act_dim, 0.01))
self.actor_logstd = nn.Parameter(torch.zeros(1, act_dim))
def value(self, state):
return self.critic(state).squeeze(-1)
def policy(self, state):
mean = self.actor_mean(state)
return Normal(mean, self.actor_logstd.exp().expand_as(mean))
def advantages_gae(rewards, values, next_values, terminated, truncated, gamma, lam):
safe_next_values = torch.where(terminated, torch.zeros_like(next_values), next_values)
delta = rewards + gamma * safe_next_values - values
result = torch.empty_like(delta)
tail = torch.zeros_like(delta[0])
for t in reversed(range(len(delta))):
tail = delta[t] + gamma * lam * (~(terminated[t] | truncated[t])).float() * tail
result[t] = tail
return result
def entropy_bonus(distribution):
return distribution.entropy().sum(-1).mean()
def train(env_id, seed, total_steps=1_000_000, num_envs=1, entropy_coef=0.0):
gamma, lam, rollout, epochs, num_minibatches = .99, .95, 2000, 4, 8
batch_size = rollout * num_envs
if num_envs < 1 or total_steps % batch_size:
raise ValueError('El presupuesto debe ser múltiplo del tamaño de rollout')
random.seed(seed); np.random.seed(seed); torch.manual_seed(seed)
envs = gym.vector.SyncVectorEnv([lambda: build_env(env_id, gamma) for _ in range(num_envs)],
autoreset_mode=gym.vector.AutoresetMode.SAME_STEP)
obs, _ = envs.reset(seed=seed)
agent = PPOAgent(obs.shape[-1], envs.single_action_space.shape[0])
optimizer = torch.optim.Adam(agent.parameters(), lr=3e-4, eps=1e-5)
history = []
save_snapshot(agent, envs.envs[0], env_id, seed, 0, 'own', history, all_envs=envs.envs)
n_updates = total_steps // batch_size
for update in range(n_updates):
optimizer.param_groups[0]['lr'] = 3e-4 * (1 - update / n_updates)
states, actions, logps, rewards = [], [], [], []
values, next_values, terms, truncs = [], [], [], []
for _ in range(rollout):
state = torch.tensor(obs, dtype=torch.float32)
with torch.no_grad():
dist = agent.policy(state)
action = dist.sample()
logp = dist.log_prob(action).sum(-1)
value = agent.value(state)
next_obs, reward, terminated, truncated, info = envs.step(action.numpy())
# SAME_STEP devuelve observación reiniciada tras fin. Para truncamientos,
# sustituirla por la observación final anterior al reset.
physical_next = next_obs.copy()
for i in range(len(terminated)):
if truncated[i] and not terminated[i]:
physical_next[i] = info['final_obs'][i]
next_val = torch.zeros_like(value)
alive = np.flatnonzero(~terminated)
if len(alive):
with torch.no_grad():
next_val[alive] = agent.value(torch.tensor(physical_next[alive], dtype=torch.float32))
states.append(state); actions.append(action); logps.append(logp); rewards.append(torch.tensor(reward, dtype=torch.float32))
values.append(value); next_values.append(next_val)
terms.append(torch.tensor(terminated, dtype=torch.bool)); truncs.append(torch.tensor(truncated, dtype=torch.bool))
obs = next_obs
states, actions, logps, rewards, values, next_values, terms, truncs = map(torch.stack,
(states, actions, logps, rewards, values, next_values, terms, truncs))
advantages = advantages_gae(rewards, values, next_values, terms, truncs, gamma, lam)
returns = advantages + values
states = states.reshape(batch_size, -1); actions = actions.reshape(batch_size, -1)
logps = logps.reshape(batch_size); advantages = advantages.reshape(batch_size)
returns = returns.reshape(batch_size); old_values = values.reshape(batch_size)
indices = np.arange(batch_size)
for _ in range(epochs):
np.random.shuffle(indices)
for start in range(0, batch_size, batch_size // num_minibatches):
ix = indices[start:start + batch_size // num_minibatches]
dist = agent.policy(states[ix])
new_logp = dist.log_prob(actions[ix]).sum(-1)
ratio = (new_logp - logps[ix]).exp()
adv = advantages[ix]
adv = (adv - adv.mean()) / (adv.std() + 1e-8)
policy_loss = torch.maximum(-adv * ratio, -adv * ratio.clamp(.8, 1.2)).mean()
new_value = agent.value(states[ix])
clipped_value = old_values[ix] + (new_value - old_values[ix]).clamp(-.2, .2)
value_loss = .5 * torch.maximum((new_value - returns[ix]).square(),
(clipped_value - returns[ix]).square()).mean()
loss = policy_loss + .5 * value_loss
if entropy_coef != 0.0:
loss = loss - entropy_coef * entropy_bonus(dist)
optimizer.zero_grad(); loss.backward()
nn.utils.clip_grad_norm_(agent.parameters(), .5)
optimizer.step()
steps = (update + 1) * batch_size
if steps // 200000 > (steps - batch_size) // 200000 or steps == total_steps:
save_snapshot(agent, envs.envs[0], env_id, seed, steps, 'own', history, all_envs=envs.envs)
if (update + 1) % 25 == 0:
print('own', env_id, 'seed', seed, 'steps', steps, flush=True)
envs.close()
return agent, historynpm run lab and open the connection link.The following test compares summed log densities with an independent multivariate distribution, forces real truncations in two environments and verifies advantage using final-observation value. It also checks that terminal subsequent NaN does not propagate. This tests mechanics, not performance.
from torch.distributions import Independent
agent = PPOAgent(11, 3)
x = torch.zeros((2, 11))
dist = agent.policy(x)
action = dist.sample()
old_logp = dist.log_prob(action).sum(-1)
assert torch.allclose(old_logp, Independent(dist, 1).log_prob(action))
assert torch.allclose((agent.policy(x).log_prob(action).sum(-1) - old_logp).exp(), torch.ones(2))
assert torch.allclose(entropy_bonus(dist), Independent(dist, 1).entropy().mean())
entropy_gradient = torch.autograd.grad(-.03 * entropy_bonus(dist), agent.actor_logstd)[0]
assert torch.allclose(entropy_gradient, torch.full_like(entropy_gradient, -.03))
envs = gym.vector.SyncVectorEnv([lambda: build_env('Hopper-v5', .99, max_episode_steps=1) for _ in range(2)],
autoreset_mode=gym.vector.AutoresetMode.SAME_STEP)
try:
obs, _ = envs.reset(seed=500)
reset_obs, reward, term, trunc, info = envs.step(np.zeros((2, 3), dtype=np.float32))
assert trunc.all() and not term.any()
final_obs = np.stack(info['final_obs'])
assert not np.allclose(final_obs, reset_obs)
value_fn = lambda a: np.sum(np.asarray(a, dtype=float) ** 2, axis=-1)
final_value, reset_value = value_fn(final_obs), value_fn(reset_obs)
assert not np.allclose(final_value, reset_value)
out = advantages_gae(torch.tensor(reward[None, :], dtype=torch.float32), torch.zeros((1, 2)),
torch.tensor(final_value[None, :], dtype=torch.float32),
torch.tensor(term[None, :]), torch.tensor(trunc[None, :]), .99, .95)
np.testing.assert_allclose(out.numpy()[0], reward + .99 * final_value, rtol=1e-5)
assert not np.allclose(out.numpy()[0], reward + .99 * reset_value)
finally:
envs.close()
terminal = advantages_gae(torch.tensor([[1.]]), torch.tensor([[.4]]), torch.tensor([[float('nan')]]),
torch.tensor([[True]]), torch.tensor([[False]]), .99, .95)
assert torch.allclose(terminal, torch.tensor([[.6]]))
print('Log-densidad, entropía y razón inicial: OK')
print('Dos entornos: truncamiento, V(final_obs) y terminal NaN: OK')
versiones_registradas = {
'python': '3.13.1', 'gymnasium': '1.4.0', 'mujoco': '3.17.0', 'numpy': '2.5.2',
'torch': '2.11.0+cu128', 'scipy': '1.18.1', 'tyro': '1.0.16', 'tensorboard': '2.21.0',
'imageio': '2.38.1', 'imageio-ffmpeg': '0.6.0',
}
print('Versiones registradas del experimento y del renderizador:', versiones_registradas)npm run lab and open the connection link.To reproduce full custom training, explicitly run the next cell after defining functions. Each combination generates checkpoints and evaluation episodes; it costs the full budget and therefore does not launch automatically when opening the lesson. Save files with configuration and versions before launching the next method.
for environment in ('Hopper-v5', 'HalfCheetah-v5'):
for seed in range(5):
agent, history = train(environment, seed, total_steps=1_000_000, num_envs=1)
To inspect visual evolution without confusing it with whole-algorithm performance, the next cell replays measured returns of five episodes per checkpoint of custom PPO with training seed zero. These are records of one policy at six times using evaluation seeds 400000–400004. Video shows only the first episode at each point; the graph shows the five-episode mean. No run is interpolated and learning is not assumed monotone.
registros = [[0,[132.1351794551943,130.14359995366755,90.91385392869108,89.55088005607874,93.70631790225677]],[200000,[434.7257226662194,437.96906642924034,436.6878116485615,435.95708784814843,436.39610068611944]],[400000,[1685.3247923742585,1947.757622513761,948.3760696906483,979.5932667305302,981.260441529371]],[600000,[2945.0399198150894,2014.3688919124784,1976.269081291635,2004.3421421271273,2052.0284232108443]],[800000,[1351.9801924320952,1249.123015338494,1590.5822983067808,1406.6783469305312,1139.2465176885519]],[1000000,[1730.2216129613184,1589.7754488180672,1526.6889762882229,1667.6801280483526,1471.7649329456167]]]
for pasos, retornos in registros:
media = sum(retornos) / len(retornos)
print('pasos', pasos, 'retornos', [round(x, 3) for x in retornos], 'media', round(media, 3))To regenerate a video after training Hopper seed zero, save the next cell as render_video.py beside ppo_l04.py, checkpoints and the own-Hopper-v5-seed0.json history produced by training. You need imageio 2.38.1 and imageio-ffmpeg 0.6.0, dependencies detailed below and a working MuJoCo OpenGL context. The program replays the full episode, follows the torso with the camera, changes colors only to distinguish segments and checks return and length against history. It writes video and metadata beside the script; the video does not alter physics.
"""Vídeo completo de un checkpoint PPO propio con normalizador congelado."""
import json
import sys
from pathlib import Path
import gymnasium as gym
import imageio.v2 as imageio
import mujoco
import numpy as np
import torch
from ppo_l04 import PPOAgent
ROOT = Path(__file__).resolve().parent
step = int(sys.argv[1])
checkpoint = torch.load(ROOT / f'own-Hopper-v5-seed0-step{step}.pt', map_location='cpu', weights_only=False)
stats = checkpoint['stats']
env = gym.make('Hopper-v5', render_mode='rgb_array', width=400, height=300)
env.unwrapped.mujoco_renderer.default_cam_config['azimuth'] = 90.0
env.unwrapped.mujoco_renderer.default_cam_config['distance'] = 2.4
env.unwrapped.mujoco_renderer.default_cam_config['type'] = mujoco.mjtCamera.mjCAMERA_TRACKING
env.unwrapped.mujoco_renderer.default_cam_config['trackbodyid'] = mujoco.mj_name2id(
env.unwrapped.model, mujoco.mjtObj.mjOBJ_BODY, 'torso')
# El visor fuerza cámara libre cuando camera_id=-1; None conserva tracking.
env.unwrapped.mujoco_renderer.camera_id = None
colors = {'torso': [.92,.42,.14,1], 'thigh': [.14,.58,.78,1], 'leg': [.92,.68,.20,1], 'foot': [.17,.42,.74,1]}
model = env.unwrapped.model
for j in range(model.ngeom):
body = mujoco.mj_id2name(model, mujoco.mjtObj.mjOBJ_BODY, int(model.geom_bodyid[j]))
if body in colors:
model.geom_matid[j] = -1
model.geom_rgba[j] = colors[body]
agent = PPOAgent(env.observation_space.shape[0], env.action_space.shape[0])
agent.load_state_dict(checkpoint['state_dict'])
agent.eval()
obs, _ = env.reset(seed=400000)
fps = int(env.metadata['render_fps'])
filename = f'hopper-step{step}.mp4'
writer = imageio.get_writer(ROOT / filename, fps=fps, codec='libx264', pixelformat='yuv420p',
macro_block_size=2, ffmpeg_params=['-threads', '1'])
score, length = 0., 0
try:
writer.append_data(env.render())
while True:
norm = np.clip((obs - stats['mean']) / np.sqrt(stats['var'] + stats['epsilon']), -10, 10)
with torch.no_grad():
action = agent.actor_mean(torch.tensor(norm[None, :], dtype=torch.float32)).numpy()[0]
obs, reward, terminated, truncated, _ = env.step(np.clip(action, env.action_space.low, env.action_space.high))
score += float(reward)
length += 1
writer.append_data(env.render())
if terminated or truncated:
break
finally:
writer.close()
env.close()
history = json.loads((ROOT / 'own-Hopper-v5-seed0.json').read_text(encoding='utf-8'))
reference = next(x for x in history if x['steps'] == step)['evaluation'][0]
assert reference['seed'] == 400000 and reference['steps'] == length
assert np.isclose(reference['return'], score, rtol=1e-6, atol=1e-6)
metadata = {'video': filename, 'checkpoint': f'own-Hopper-v5-seed0-step{step}.pt',
'training_steps': step, 'training_seed': 0, 'evaluation_seed': 400000,
'return': score, 'steps': length, 'frames': length + 1, 'fps': fps,
'terminated': bool(terminated), 'truncated': bool(truncated),
'camera': 'seguimiento del torso, azimuth 90 grados, distancia 2.4',
'visualization': 'Colores de segmentos cambiados solo para distinguir cuerpos.'}
(ROOT / f'hopper-step{step}.json').write_text(json.dumps(metadata, ensure_ascii=False, indent=2), encoding='utf-8')
print(json.dumps(metadata, ensure_ascii=False), flush=True)
For example, python render_video.py 600000 replays the 600000-step checkpoint episode. The six figure videos use steps 0, 200000, 400000, 600000, 800000 and 1000000. Seeds and weights are training records, not synthetic animation. After retraining, the program compares video against the new run’s history; platform differences and seed-zero provenance limitation prevent guaranteeing bit-for-bit reproduction of published videos. If using PPO_OUTPUT_DIR, place history and checkpoints beside the renderer or adjust its path.
To reproduce the reference, first copy the custom PPO definition cell to ppo_l04.py and save this generator as generate_cleanrl.py in the same folder. Download the official CleanRL file, check the pinned revision hash and apply adapter changes. CleanRL has an MIT license; retain its repository license notice with the generated file. This generator does not train and requires access to the official source.
The reference run used Python 3.13.1, Gymnasium 1.4.0, MuJoCo 3.17.0, NumPy 2.5.2, PyTorch 2.11.0 built for CUDA 12.8, tyro 1.0.16 and TensorBoard 2.21.0, with CPU training and one PyTorch thread per process. Install these in the local environment before running; the specific PyTorch build and results can vary by platform. Analysis also uses SciPy 1.18.1.
"""Reconstruye el adaptador CleanRL usado en p09-l04 desde la revisión fijada."""
import argparse
import hashlib
from pathlib import Path
from urllib.request import urlopen
COMMIT = "35896b1fefa9898b904f7e09bcbe6e168e15d2a9"
URL = f"https://raw.githubusercontent.com/vwxyzjn/cleanrl/{COMMIT}/cleanrl/ppo_continuous_action.py"
UPSTREAM_SHA256 = "326dd8678bf9cc51abec833eb551ef2409a3804d604b689e1f0a084eca41f655"
ADAPTER_SHA256 = "327a9428f8846a35beb33e637ac337a365b4af57f0cc63b0a93f15bdd6339303"
def replace_once(text, old, new):
if text.count(old) != 1:
raise ValueError(f"El patrón no aparece exactamente una vez: {old[:80]!r}")
return text.replace(old, new, 1)
def make_adapter(source):
text = replace_once(source, "import time\n", "import time\nimport json\n")
text = replace_once(text, "from torch.utils.tensorboard import SummaryWriter\n",
"from torch.utils.tensorboard import SummaryWriter\n"
"from ppo_l04 import save_snapshot\n\ntorch.set_num_threads(1)\n")
text = replace_once(text,
"env = gym.wrappers.TransformObservation(env, lambda obs: np.clip(obs, -10, 10))",
"env = gym.wrappers.TransformObservation(env, lambda obs: np.clip(obs, -10, 10), env.observation_space)")
text = replace_once(text,
"[make_env(args.env_id, i, args.capture_video, run_name, args.gamma) for i in range(args.num_envs)]\n )",
"[make_env(args.env_id, i, args.capture_video, run_name, args.gamma) for i in range(args.num_envs)],\n"
" autoreset_mode=gym.vector.AutoresetMode.SAME_STEP,\n )")
text = replace_once(text, " next_done = torch.zeros(args.num_envs).to(device)\n",
" next_done = torch.zeros(args.num_envs).to(device)\n"
" if args.num_envs != 1:\n"
" raise ValueError('La evaluación congelada de este adaptador requiere un entorno de entrenamiento')\n"
" history = []\n"
" save_snapshot(agent, envs.envs[0], args.env_id, args.seed, global_step, 'cleanrl', history)\n")
start_marker = ' if "final_info" in infos:\n'
end_marker = " # bootstrap value if not done\n"
if text.count(start_marker) != 1 or text.count(end_marker) != 1:
raise ValueError("Marcadores de registro final ambiguos")
begin = text.index(start_marker)
end = text.index(end_marker, begin)
text = text[:begin] + " # Gymnasium 1.x devuelve final_info como diccionario vectorizado.\n\n" + text[end:]
begin = text.index("\n if args.save_model:\n")
end = text.index("\n envs.close()", begin)
text = (text[:begin] +
" crossed_checkpoint = global_step // 200000 > (global_step - args.batch_size) // 200000\n"
" if crossed_checkpoint or iteration == args.num_iterations:\n"
" save_snapshot(agent, envs.envs[0], args.env_id, args.seed, global_step, 'cleanrl', history)\n"
+ text[end:])
return text
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--output", type=Path, default=Path("cleanrl_l04.py"))
args = parser.parse_args()
with urlopen(URL, timeout=30) as response:
raw = response.read()
actual = hashlib.sha256(raw).hexdigest()
if actual != UPSTREAM_SHA256:
raise ValueError(f"Hash de CleanRL inesperado: {actual}")
output = make_adapter(raw.decode("utf-8")).encode("utf-8")
adapter_hash = hashlib.sha256(output).hexdigest()
if adapter_hash != ADAPTER_SHA256:
raise ValueError(f"Hash del adaptador inesperado: {adapter_hash}")
args.output.write_bytes(output)
print("CleanRL verificado:", actual)
print("Adaptador:", args.output, adapter_hash)
if __name__ == "__main__":
main()
Then run the generator and use the explicit arguments below: original program defaults differ from this protocol. Repeat for seeds 0–4 and Hopper-v5 and HalfCheetah-v5. The adapter saves checkpoints using the custom file’s evaluator. The parser still accepts --save-model and --upload-model, but their execution blocks were removed and those flags do nothing in this adapter; lesson checkpoints are created by save_snapshot.
python generate_cleanrl.py
python cleanrl_l04.py --env-id Hopper-v5 --seed 0 --total-timesteps 1000000 --num-envs 1 --num-steps 2000 --num-minibatches 8 --update-epochs 4 --no-cuda
Comparison on held-out seeds
All twenty policies completed one million steps each: five training seeds per method in each environment. For final comparison each policy was evaluated on seeds 500000–500004, distinct from graph checkpoint seeds. Its five raw-return mean is one performance observation per training run. The following cells retain all 25 episodes of each combination; rows correspond to training seeds 0–4 and columns to evaluation seeds 500000–500004.
import numpy as np
resultados = {}
resultados[('Hopper-v5', 'own')] = np.array([[1602.8588314128738,1599.7497943157855,1613.4859697118968,1479.9753056551474,1497.8022649709294],[674.7356872705316,682.7627630435335,688.1990123732334,671.8572009319909,665.4112037479347],[1744.7990343534902,1734.9069815620696,2732.551824310963,1620.1125843498123,2618.2443489810103],[3530.5430190318248,3532.4517903375922,3550.4537133241665,3506.886594815777,3550.530421847306],[3154.3172310636246,1471.9267344294872,3177.574026154819,1690.0137366689248,1821.9359758587418]], dtype=float)
for semilla, episodios in enumerate(resultados[('Hopper-v5', 'own')]):
print('entrenamiento', semilla, 'episodios', [round(float(x), 3) for x in episodios],
'media', round(float(episodios.mean()), 3))npm run lab and open the connection link.resultados[('Hopper-v5', 'cleanrl')] = np.array([[1272.470326067051,1273.0060512734249,1300.80167946139,1286.4220839768261,1276.7347063877176],[1239.7085491771713,862.6121892668606,984.7173034996246,1525.5191386004333,1125.492247476051],[1783.7445804249116,2714.874158963134,3241.5450335159735,3276.5417761442513,1785.4256558313896],[3126.3356964101886,2338.950253856231,2050.3895002857007,2247.3763176426755,1909.9893246715005],[1193.4926054837856,1273.7203515795352,1251.1938962177878,1220.7583403083338,1267.8350632164986]], dtype=float)
for semilla, episodios in enumerate(resultados[('Hopper-v5', 'cleanrl')]):
print('entrenamiento', semilla, 'episodios', [round(float(x), 3) for x in episodios],
'media', round(float(episodios.mean()), 3))npm run lab and open the connection link.resultados[('HalfCheetah-v5', 'own')] = np.array([[1503.200284235881,1432.5693286249657,1393.8047484720082,1462.4616713239607,1369.8079873654879],[1263.0609985423594,1239.9594218657057,1344.5531046081219,1328.4384850022352,1280.8377747722395],[2048.3015813149113,2181.841017016607,2266.021019985681,2208.987198038175,2085.4315781815894],[1281.1403749019503,1289.6528167296947,1279.4814776547837,1283.0426929022808,1175.2678312950743],[1281.1666146230514,1224.9355921711572,1277.013417557229,1292.9574440860138,1274.825220817565]], dtype=float)
for semilla, episodios in enumerate(resultados[('HalfCheetah-v5', 'own')]):
print('entrenamiento', semilla, 'episodios', [round(float(x), 3) for x in episodios],
'media', round(float(episodios.mean()), 3))npm run lab and open the connection link.resultados[('HalfCheetah-v5', 'cleanrl')] = np.array([[1109.9841117599167,1198.2175456003747,1207.8473839132232,1229.7972721334286,1233.5611100303638],[1145.5114783791855,1134.084013524222,1086.4356259766664,1209.201932964235,1183.4186714951734],[3116.844627698843,3341.7452875337335,3223.295931436779,3255.5902805060273,3091.4815453804945],[3068.301149547452,3041.006882813768,2656.9513414232824,2949.0109130352535,818.8869468174772],[1197.7100010902998,1194.7651078595209,1206.186370997997,1130.978018617397,1169.4296724786586]], dtype=float)
for semilla, episodios in enumerate(resultados[('HalfCheetah-v5', 'cleanrl')]):
print('entrenamiento', semilla, 'episodios', [round(float(x), 3) for x in episodios],
'media', round(float(episodios.mean()), 3))npm run lab and open the connection link.For each environment calculate IQM of five per-training means with the first lesson’s discrete trim_mean convention: requested 25% trimming rounds down to one observation, actually removing 20% from each end and averaging the middle three. The percentile interval uses 10000 bootstrap replicates and seed 20261028. For the method difference, resample paired seeds jointly and compute the IQM difference in each replicate, which is generally not the IQM of per-seed differences.
from scipy.stats import trim_mean
def resumen_emparejado(propio, referencia, n_boot=10000, seed=20261028):
x, y = propio.mean(axis=1), referencia.mean(axis=1)
rng = np.random.default_rng(seed)
indices = rng.integers(5, size=(n_boot, 5))
bx = trim_mean(x[indices], .25, axis=1)
by = trim_mean(y[indices], .25, axis=1)
def salida(valor, replicas):
return round(float(valor), 3), np.round(np.percentile(replicas, [2.5, 97.5]), 3).tolist()
return (salida(trim_mean(x, .25), bx), salida(trim_mean(y, .25), by),
salida(trim_mean(x, .25) - trim_mean(y, .25), bx - by))
for entorno in ('Hopper-v5', 'HalfCheetah-v5'):
propio, referencia, diferencia = resumen_emparejado(resultados[(entorno, 'own')],
resultados[(entorno, 'cleanrl')])
print(entorno, 'propio', propio, 'CleanRL', referencia, 'diferencia', diferencia)npm run lab and open the connection link.The local run produced the table below; figures come from prior cells and are rounded to three decimals.
| Environment | Custom IQM and 95% interval | CleanRL IQM and 95% interval | Paired difference and 95% interval |
|---|---|---|---|
| Hopper-v5 | 1970.684 [970.654, 3110.500] | 1619.298 [1178.873, 2485.154] | 351.385 [-395.506, 1081.024] |
| HalfCheetah-v5 | 1331.306 [1264.538, 1916.201] | 1627.509 [1161.092, 2972.805] | -296.203 [-1188.230, 204.205] |
Individual intervals overlap in both environments and paired intervals include zero. With five training runs, evidence is compatible with substantial differences in either direction: overlap neither proves equivalence nor identifies a discrepancy’s cause. Episodes share protocol-fixed evaluation seeds; resampling units are trained policies and each policy’s five episodes remain fixed. These intervals therefore do not separately include uncertainty from sampling other episodes. Keep the two environments separate because return scales differ, and retain extreme scores even when IQM trims them.
The experiment meets the requested budget and comparison under this local configuration, but is not an independent reproduction of the reference: architecture, initialization and seeds were paired, and programs differ in truncation treatment. Seed zero also has the provenance limitation above. Truncation frequency was not recorded during the first four runs, so an observed difference cannot be attributed to the mask. More seeds, another task suite and controlled ablation could investigate robustness and each detail’s effect.
Exercises
Step 1 of 3. What does the definition of imply for ?
combine(n_a, mean_a, m2_a, n_b, mean_b, m2_b). Each M2 is the componentwise sum of squared deviations from its mean. Return (n, mean, m2) when merging batches; an empty batch must return a copy of the other. Means and M2 can be NumPy vectors. Do not add pseudocounts.import numpy as np
def combine(n_a, mean_a, m2_a, n_b, mean_b, m2_b):
passPPO reuses a batch with frozen old probabilities and an objective asymmetrically penalizing ratio changes per sample. Collection, masks, data scale and normalization state are part of the effective algorithm; performance comparison requires independent runs and evaluation under the same budget.