Module contents
Lesson 20 of 37Core 120 min

Proximal Policy Optimization: the algorithm and its details

Locate PPO on the map: from TRPO's surrogate to the clipped objective, its case-by-case analysis and the adaptive KL-penalty variant. Implement the full CleanRL-style loop, study implementation details behind much of its performance, and diagnose training using approximate KL, clipped fraction and explained variance. Train locally in MuJoCo and prepare for RLHF and MAPPO.

After this lesson you can

  • Derive the clipped objective and prove it is a pessimistic lower bound on the surrogate.
  • Implement full PPO with vectorized rollouts, GAE, minibatches, policy and value clipping, and KL stopping.
  • Adapt PPO to continuous actions with Gaussian policies and normalization wrappers.
  • Diagnose training failures using PPO metrics.
  • Measure which implementation details matter using an ablation.

Before you start

Reuse a rollout without forgetting its origin

TRPO constrains mean KL and uses Hessian-vector products and line search. PPO proposes objectives optimizable by first-order methods for several epochs on the same data. This simplifies updates but also makes it easy to move too far from the policy that generated the batch.

Keep the collection policy as a fixed reference: its log probabilities, old values and advantages belong to that rollout. Recalculating them after updating the actor makes the ratio stop measuring the intended change.

The clipped minimum, case by case

For datum (st,at)(s_t,a_t) collected with πold\pi_{\mathrm{old}}, define

ρt(θ)=πθ(at∣st)πold(at∣st),ℓt(θ)=min⁡ ⁣(ρtA^t, clip⁡(ρt,1−ϵ,1+ϵ)A^t).\rho_t(\theta)=\frac{\pi_\theta(a_t\mid s_t)} {\pi_{\mathrm{old}}(a_t\mid s_t)},\qquad \ell_t(\theta)= \min\!\left(\rho_t\hat A_t,\, \operatorname{clip}(\rho_t,1-\epsilon,1+\epsilon)\hat A_t\right).

The PPO clipped objective maximizes the mean of ℓt\ell_t. Its minimum is always at most the unclipped term ρtA^t\rho_t\hat A_t for the same data. It is a lower bound on that sample surrogate, not a guaranteed lower bound on true return.

InteractiveThe four clipping cases
ρ=0ρ=2.52.5−2.5

Solid line: min(ρÂ, clip(ρ,1−ε,1+ε)Â). Dashed: ρÂ. For positive advantage, the branch is flat above 1+ε; for negative advantage, below 1−ε. At the join the ordinary derivative is undefined unless Â=0. The minimum is a per-sample lower bound on the unclipped surrogate; it is not a bound on true return and does not by itself constrain KL.

ρ=π new(a|s)/π old(a|s) is assumed finite and nonnegative. This figure calculates the analytic term for one sample, not a PPO run. Source: Schulman et al., PPO.

0.20
1.0
1.00
Clipped objective
1.000
Unclipped surrogate
1.000
Derivative with respect to ρ
1.00
Change advantage sign and interval to see the active branch.

If A^>0\hat A>0, increasing ρ\rho improves the term until 1+ϵ1+\epsilon; above that the minimum selects the constant branch. Below 1−ϵ1-\epsilon the unclipped branch remains active, penalizing reduced probability for an advantageous action. If A^<0\hat A<0 the symmetric case occurs: below 1−ϵ1-\epsilon the clipped branch is constant and above 1+ϵ1+\epsilon the unclipped term continues penalizing increased probability. Within the interval both branches coincide. At switching points the function may not be differentiable; the selected subgradient depends on implementation.

Clipping removes certain incentives of each sample; it does not globally constrain all probabilities. Shared parameters, other samples and multiple epochs can continue moving the policy on a sample already on its plateau. It does not itself limit KL either.

KL penalty and training loop

The adaptive KL penalty variant subtracts mean KL relative to the old policy from the surrogate, multiplied by a coefficient adjusted according to observed distance. This KL is a batch-estimated mean and its adaptation is not equivalent to TRPO’s maximum-KL guarantee.

LKL(θ)=Et[ρt(θ)A^t]−β Es∼dold[DKL(πold(⋅∣s)∥πθ(⋅∣s))].L^{\mathrm{KL}}(\theta)= \mathbb E_t[\rho_t(\theta)\hat A_t] -\beta\,\mathbb E_{s\sim d_{\mathrm{old}}} [D_{\mathrm{KL}}(\pi_{\mathrm{old}}(\cdot\mid s)\Vert\pi_\theta(\cdot\mid s))].

For example, a control rule could double β\beta when observed KL exceeds 1,51,5 times a target and halve it when below 0,50,5 times that target. Thresholds and factors are part of the chosen protocol; adaptation acts on later updates and does not guarantee any individual KL is bounded.

A PPO loop collects vectorized transitions, computes GAE and critic targets, freezes old data and performs several epochs of shuffled minibatches. Then it discards the rollout and collects another under the new policy. At terminations and truncations use both GAE masks: use the actual final observation for bootstrap when appropriate and prevent trace propagation into the reset episode.

InteractiveDrift by epoch
5.364e-71.162e-61.788e-612 epoch

Each point measures the actor at the end of that epoch on the same rollout, with frozen old log probabilities. k3 averages exp(log ρ) − 1 − log ρ over rollout actions; the fraction counts |ρ − 1| > ε. Stopping is checked after each full epoch. KL is a sample estimate, not a guarantee for the whole policy.

Probe; short run; minibatch 16, initial rate 0.000250, ε=0.200. Declared source: Ejecución local de PPO discreto; KL al final de cada época sobre el rollout fijo y evaluación voraz independiente. File validation checks format, not provenance.

Last recorded epoch
2
KL threshold exceeded
not recorded
Configured KL threshold
0.0300
Explore a real reduced run or load your reports to compare KL and clipped fraction during epochs on the same rollout.

For the critic, some implementations compare ordinary squared error with error of a value clipped around the old prediction and minimize the larger. Others do not clip value: they differ, so record the variant. Entropy usually enters as a negative-signed bonus in minimized loss. KL stopping may interrupt remaining epochs when a diagnostic exceeds a threshold; depending on where measured, it can detect excess after an update already happened.

Details that change the experiment

Implementation details affect learning and comparison: advantage normalization, observation or reward scaling and clipping, initialization, Adam numerical tolerance, learning-rate schedule and gradient norm clipping. Batch versus minibatch advantage normalization gives different signals; statistics are unstable in small minibatches and standard deviation can be zero with one sample. Reward normalization changes the problem scale seen by the critic: always log raw return too.

Orthogonal initialization and smaller actor-output gain are concrete choices, not a convergence theorem. An ablation should change one detail at a time, retain comparable budget and seeds, and declare other options. Engstrom and colleagues study how implementation choices affect PPO/TRPO comparisons; Andrychowicz and colleagues investigate over 50 choices in a common framework. Results depend on environments and protocols and do not imply a universal setting.

Specifically, table 2 of Engstrom and colleagues reports Hopper-v2 reward 2513, with 95% bootstrap interval [2391, 2632], for PPO with studied details, versus 2142 [2008, 2279] for PPO-M removing that optimization set. They use 1000 resamples and at least 80 agents per estimate after hyperparameter searches. This is not an isolated single-detail ablation or a Hopper-v5 result. In another protocol, Andrychowicz and colleagues explore 2000 normalization and clipping configurations on Hopper-v1: score percentiles 90, 95 and 99 are 1533, 1662 and 1809. Each configuration uses three seeds and one million steps; score summarizes periodic evaluations, not one seed’s final return.

To reproduce code also consult PPO implementation details and pin its version. Two programs called PPO may differ in masks, normalization, losses, budget, wrappers and evaluation.

Continuous actions

In continuous control a diagonal Gaussian policy can learn a state-dependent mean and log⁡σ\log\sigma per dimension. If a latent is transformed with tanh⁡\tanh and affine scaling, transformed-action log density requires the Jacobian; comparing both policies on the same latent and fixed transform cancels that term in the continuous ratio.

Clipping a Gaussian sample to bounds creates mass at endpoints. Subsequently computing the Gaussian density of the clipped action as if it were the original sample does not represent that distribution. One can instead interpret the latent as the algorithm’s action and clipping as part of dynamics, retaining the original latent’s log probability; declare that choice. In finite precision even tanh⁡\tanh may round to a bound: log such cases and do not attribute the continuous change-of-variable identity exactly to floats.

Normalizing observations using accumulated statistics can stabilize scale, but evaluation must use the same frozen statistics without learning from evaluation episodes. Reported returns must be in original environment units.

Diagnose without inventing a cause

Diagnosing PPO requires examining several signals together. For old-policy samples with common support, if x=log⁡πθ−log⁡πoldx=\log\pi_\theta-\log\pi_{\mathrm{old}}, the mean of

k3=ex−1−xk_3=e^x-1-x

estimates Es[DKL(πold∥πθ)]\mathbb E_s[D_{\mathrm{KL}}(\pi_{\mathrm{old}}\Vert\pi_\theta)]: Eold[ex]=1\mathbb E_{\mathrm{old}}[e^x]=1 and Eold[−x]\mathbb E_{\mathrm{old}}[-x] is KL in that direction. Each contribution k3k_3 is nonnegative by ex≥1+xe^x\geq1+x. In finite precision cancellation can produce tiny negative values; they do not represent negative divergence. Different support, data not from the old policy or biased state sampling changes the interpretation. CleanRL documents this diagnostic alongside fraction of ratios outside the interval.

The clipped fraction often counts ∣ρ−1∣>ϵ|\rho-1|>\epsilon, but not all such samples are on an active plateau: advantage sign matters too. Critic explained variance can be negative and is undefined for a constant target. High KL, collapsing entropy or a weak critic are clues, not uniquely identified causes. Evaluate raw return across seeds and check masks before explaining a curve.

InteractiveDiagnostics with measured results
0.5001.0001.50064128 transitions

Return averages only episodes recorded in each evaluation (greedy with separate evaluation environments and seeds); a point without episodes is empty. KL k3, clipped fraction and entropy come from the last recorded epoch of each update; explained variance is reported by the file. Seeds are not mixed and a failure is not inferred from one curve.

Probe; short run; minibatch 16, initial rate 0.000250, ε=0.200. Declared source: Ejecución local de PPO discreto; KL al final de cada época sobre el rollout fijo y evaluación voraz independiente. The format is validated, but the file alone does not certify provenance.

Last update
4
Last reading
1.0000
Evaluation episodes
2
Explore a real reduced run or load training reports to study metrics and configurations.

Both panels start with three reports generated by this lesson’s discrete lab in ORYON_QUICK=1 mode. All use one seed and four updates. The first uses at most two epochs with KL stopping; the other two use four epochs without KL stopping and differ only in initial learning rate, 0.00025 versus 0.01. None of the three runs met all probe tolerances with that short budget; curves help inspect these runs, do not prove learning and support no population conclusion. You can replace them by loading one or more own reports with declared configurations.

PPO appears in many systems, including language-policy tuning with rewards and multi-agent applications; action, reward, reference and KL definitions differ. Do not confuse KL relative to the old policy during PPO with an additional penalty relative to a reference model in RLHF.

Labs

This lab implements discrete PPO with PyTorch and Gymnasium 1.4. It separately trains the previous lesson’s five probes, CartPole-v1 and LunarLander-v3; install gymnasium[box2d,classic-control]==1.4.0 and PyTorch for both environments. Full mode uses five seeds. ORYON_QUICK=1 reduces interactions and evaluations to verify the path; it does not claim the agent solves any task. ORYON_PPO_OUT chooses the reports directory. Value-loss clipping and advantage normalization are optional via ORYON_PPO_CLIP_VALUE=0 or 1 and ORYON_PPO_NORM_ADV=0 or 1. ORYON_PPO_EPOCHS, ORYON_PPO_MINIBATCH, ORYON_PPO_LR, ORYON_PPO_EPSILON and ORYON_PPO_TARGET_KL compare real configurations; use off to disable KL stopping and different output directories for each run. ORYON_PPO_BAD_TRUNC=1 enables only a deliberately incorrect diagnostic variant omitting truncation bootstrap; default is 0 and the report unambiguously identifies the failure. To induce truncations, ORYON_PPO_TIME_LIMIT accepts a positive integer step count for both environments in training and evaluation; without it Gymnasium’s registered limit remains. Probes do not use this limit. Each rollout logs counts of terminal and truncation signals, including simultaneous ones.

Old policy, collected logs and values remain frozen during each rollout’s epochs. By default advantages are normalized once per rollout; critic loss targets unnormalized advantage plus old value. KL limit is checked after each epoch on the whole rollout and can stop remaining epochs: clipping does not itself guarantee a maximum KL. KL k1, k3 and clipped-fraction curves refer to the policy at each epoch’s end, not an average of minibatches with different policies. They are estimates with sampled actions; k1 may be negative. Each evaluation uses separate seeds and environments and a greedy policy.

[ ]Discrete PPO with GAE and diagnosticsLocal 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 gymnasium import spaces
from torch import nn
from torch.distributions import Categorical

if not gym.__version__.startswith('1.4.'):
    raise RuntimeError('Esta celda usa el contrato SAME_STEP de Gymnasium 1.4.x')
quick = os.environ.get('ORYON_QUICK', '0') == '1'
value_flag = os.environ.get('ORYON_PPO_CLIP_VALUE', '1')
if value_flag not in ('0','1'): raise ValueError('ORYON_PPO_CLIP_VALUE debe ser 0 o 1')
clip_value = value_flag == '1'
norm_flag = os.environ.get('ORYON_PPO_NORM_ADV','1')
if norm_flag not in ('0','1'): raise ValueError('ORYON_PPO_NORM_ADV debe ser 0 o 1')
norm_adv = norm_flag == '1'
bad_trunc_flag = os.environ.get('ORYON_PPO_BAD_TRUNC','0')
if bad_trunc_flag not in ('0','1'): raise ValueError('ORYON_PPO_BAD_TRUNC debe ser 0 o 1')
bad_trunc = bad_trunc_flag == '1'
raw_time_limit = os.environ.get('ORYON_PPO_TIME_LIMIT')
if raw_time_limit is not None:
    if not raw_time_limit.isascii() or not raw_time_limit.isdecimal() or int(raw_time_limit)<1:
        raise ValueError('ORYON_PPO_TIME_LIMIT debe ser un entero positivo')
    time_limit = int(raw_time_limit)
else:
    time_limit = None
out = Path(os.environ.get('ORYON_PPO_OUT', 'oryon-ppo-discrete'))
out.mkdir(parents=True, exist_ok=True)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
seeds = [0] if quick else [0,1,2,3,4]
n_env, horizon = (2,16) if quick else (8,128)
epochs = int(os.environ.get('ORYON_PPO_EPOCHS', '2' if quick else '4'))
minibatch_size = int(os.environ.get('ORYON_PPO_MINIBATCH', '16' if quick else '256'))
gamma, lam = .99, .95
epsilon = float(os.environ.get('ORYON_PPO_EPSILON', '.2'))
raw_kl = os.environ.get('ORYON_PPO_TARGET_KL', '.03')
target_kl = None if raw_kl == 'off' else float(raw_kl)
lr_initial = float(os.environ.get('ORYON_PPO_LR', '.00025'))
vf_coef, entropy_coef, max_grad_norm = .5, .01, .5
if (epochs<1 or minibatch_size<1 or not math.isfinite(epsilon) or not 0<epsilon<1
    or not math.isfinite(lr_initial) or lr_initial<=0
    or (target_kl is not None and (not math.isfinite(target_kl) or target_kl<=0))):
    raise ValueError('Configuración PPO fuera de rango')
eval_every, eval_episodes = (2,2) if quick else (50,10)

# Copia del contrato de las cinco sondas integradas en m22-l13.
class Probe(gym.Env):
    metadata = {'render_modes': []}
    def __init__(self, kind):
        if kind not in range(5): raise ValueError('Sonda desconocida')
        self.kind = kind
        self.observation_space = spaces.Discrete(2)
        self.action_space = spaces.Discrete(2)
    def reset(self, *, seed=None, options=None):
        super().reset(seed=seed)
        default = int(self.np_random.integers(2)) if self.kind in (1,4) else 0
        self.state = int(options.get('state',default)) if options else default
        if not self.observation_space.contains(self.state): raise ValueError('Estado inválido')
        return self.state, {}
    def step(self, action):
        if not self.action_space.contains(action): raise ValueError('Acción inválida')
        if self.kind == 0: reward, terminated = 1., True
        elif self.kind == 1: reward, terminated = (1. if self.state else -1.), True
        elif self.kind == 2: reward, terminated = (0.,False) if self.state == 0 else (1.,True)
        elif self.kind == 3: reward, terminated = float(action), True
        else: reward, terminated = float(action == self.state), True
        if self.kind == 2 and not terminated: self.state = 1
        return self.state, reward, terminated, False, {}

def env_for(kind):
    if isinstance(kind,int): return Probe(kind)
    return gym.make(kind) if time_limit is None else gym.make(kind,max_episode_steps=time_limit)

def encode(observation, probe):
    if probe: return np.eye(2,dtype=np.float32)[np.asarray(observation,dtype=int)]
    return np.asarray(observation,dtype=np.float32)

def tensor(x):
    return torch.as_tensor(np.asarray(x),dtype=torch.float32,device=device)

def layer(n_in,n_out,gain):
    module = nn.Linear(n_in,n_out)
    nn.init.orthogonal_(module.weight,gain); nn.init.zeros_(module.bias)
    return module

class ActorCritic(nn.Module):
    def __init__(self, obs_size, actions):
        super().__init__()
        self.body = nn.Sequential(layer(obs_size,64,math.sqrt(2)),nn.Tanh(),
                                  layer(64,64,math.sqrt(2)),nn.Tanh())
        self.actor = layer(64,actions,.01)
        self.critic = layer(64,1,1.)
    def forward(self,x):
        h = self.body(x)
        return self.actor(h),self.critic(h).squeeze(-1)

def gae(reward,value,next_value,terminated,truncated,discount,trace,wrong_truncation=False):
    result = np.empty_like(reward,dtype=np.float64)
    carry = np.zeros(reward.shape[1])
    for t in range(reward.shape[0]-1,-1,-1):
        bootstrap_mask = ~(terminated[t]|truncated[t]) if wrong_truncation else ~terminated[t]
        delta = reward[t]+discount*bootstrap_mask*next_value[t]-value[t]
        carry = delta+discount*trace*(~(terminated[t]|truncated[t]))*carry
        result[t] = carry
    return result

def real_successor(next_obs,terminated,truncated,info):
    done = terminated|truncated
    actual = np.asarray(next_obs).copy()
    if done.any():
        if 'final_obs' not in info or '_final_obs' not in info:
            raise RuntimeError('Falta final_obs de SAME_STEP')
        if not np.array_equal(info['_final_obs'],done):
            raise RuntimeError('Máscara final_obs incompatible')
        for i in np.flatnonzero(done): actual[i] = info['final_obs'][i]
    return actual

# La traza se detiene en el truncamiento; solo terminal anula bootstrap.
reward = np.array([[1.],[2.]])
flags = np.array([[False],[True]])
assert np.allclose(gae(reward,np.zeros_like(reward),np.array([[3.],[9.]]),
                       flags,flags[::-1],.5,1.),[[2.5],[2.]])
assert np.allclose(gae(reward,np.zeros_like(reward),np.array([[3.],[9.]]),
                       flags,flags[::-1],.5,1.,True),[[1.],[2.]])

def evaluate(model,kind,seed):
    env = env_for(kind); episodes = []
    try:
        for i in range(eval_episodes):
            eval_seed = 100000+1000*seed+i
            obs,_ = env.reset(seed=eval_seed); total=0.; length=0
            while True:
                with torch.no_grad():
                    logits,_ = model(tensor(encode(obs,isinstance(kind,int))).unsqueeze(0))
                    action = int(logits.argmax(dim=-1).item())
                obs,reward,term,trunc,_ = env.step(action)
                total += float(reward); length += 1
                if term or trunc:
                    episodes.append({'seed':eval_seed,'return':total,'length':length,
                                     'terminated':bool(term),'truncated':bool(trunc)})
                    break
    finally: env.close()
    return episodes

def probe_check(model,kind,discount):
    # Q de un paso y V de la política actual: las sondas 3/4 dependen de π.
    truth = {0:{0:[1.,1.]},1:{0:[-1.,-1.],1:[1.,1.]},
             2:{0:[discount,discount],1:[1.,1.]},3:{0:[0.,1.]},
             4:{0:[1.,0.],1:[0.,1.]}}
    errors = []; value_errors = []; choices = []; env = Probe(kind)
    try:
        for state,expected in truth[kind].items():
            with torch.no_grad():
                logits,current_value = model(tensor(encode(state,True)).unsqueeze(0))
                probs = torch.softmax(logits,dim=-1)[0].cpu().numpy()
            if kind == 0: true_value = 1.
            elif kind == 1: true_value = 1. if state else -1.
            elif kind == 2: true_value = discount if state == 0 else 1.
            elif kind == 3: true_value = float(probs[1])
            else: true_value = float(probs[state])
            value_errors.append(abs(float(current_value.item())-true_value))
            choices.append({'state':state,'greedy_action':int(logits.argmax(-1).item())})
            for action in range(2):
                env.reset(seed=0,options={'state':state})
                nxt,reward,term,trunc,_ = env.step(action)
                with torch.no_grad():
                    _,next_value = model(tensor(encode(nxt,True)).unsqueeze(0))
                predicted = float(reward) + (0. if term else discount*float(next_value.item()))
                errors.append(abs(predicted-expected[action]))
    finally: env.close()
    optimal_choices = kind not in (3,4) or all(
        c['greedy_action'] == (1 if kind == 3 else c['state']) for c in choices)
    return {'max_abs_q_error':max(errors),'max_abs_value_error':max(value_errors),
            'greedy_choices':choices,
            'passed_tolerance_0_05':max(errors)<=.05 and max(value_errors)<=.05 and optimal_choices}

def train(kind,seed):
    random.seed(seed); np.random.seed(seed); torch.manual_seed(seed)
    if torch.cuda.is_available(): torch.cuda.manual_seed_all(seed)
    probe = isinstance(kind,int)
    # Las sondas se cotejan con m22-l13, donde γ=0,9.
    discount = .9 if probe else gamma
    total_updates = (4 if quick else 50) if probe else (4 if quick else
                    (1000 if kind == 'CartPole-v1' else 2000))
    envs = gym.vector.SyncVectorEnv([lambda kind=kind:env_for(kind) for _ in range(n_env)],
                                    autoreset_mode=gym.vector.AutoresetMode.SAME_STEP)
    try:
        obs,_ = envs.reset(seed=[1000*seed+i for i in range(n_env)])
        width = 2 if probe else int(np.prod(envs.single_observation_space.shape))
        model = ActorCritic(width,envs.single_action_space.n).to(device)
        optimizer = torch.optim.Adam(model.parameters(),lr=lr_initial,eps=1e-5)
        history = []; running_returns = np.zeros(n_env)
        for update in range(1,total_updates+1):
            optimizer.param_groups[0]['lr'] = lr_initial*(1-(update-1)/total_updates)
            obs_rows=[]; actions=[]; old_logps=[]; values=[]; successors=[]
            rewards=[]; terms=[]; truncs=[]; completed=[]
            for _ in range(horizon):
                x = tensor(encode(obs,probe))
                with torch.no_grad():
                    logits,value = model(x); dist = Categorical(logits=logits)
                    action = dist.sample(); old_logp = dist.log_prob(action)
                next_obs,reward,term,trunc,info = envs.step(action.cpu().numpy())
                actual = real_successor(next_obs,term,trunc,info)
                with torch.no_grad(): _,next_value = model(tensor(encode(actual,probe)))
                obs_rows.append(x); actions.append(action); old_logps.append(old_logp)
                values.append(value.cpu().numpy()); successors.append(next_value.cpu().numpy())
                rewards.append(np.asarray(reward,dtype=float)); terms.append(term.copy()); truncs.append(trunc.copy())
                running_returns += reward
                for i in np.flatnonzero(term|trunc):
                    completed.append(float(running_returns[i])); running_returns[i]=0.
                obs = next_obs
            value_np = np.stack(values)
            raw_adv = gae(np.stack(rewards),value_np,np.stack(successors),
                          np.stack(terms),np.stack(truncs),discount,lam,bad_trunc)
            targets = tensor((raw_adv+value_np).reshape(-1))
            advantage = tensor(raw_adv.reshape(-1))
            # Desviación poblacional y denominador protegido; mismo lote en cada época.
            if norm_adv:
                advantage = (advantage-advantage.mean())/(advantage.std(unbiased=False)+1e-8)
            obs_batch = torch.cat(obs_rows); action_batch = torch.cat(actions)
            old_logp_batch = torch.cat(old_logps); old_value_batch = tensor(value_np.reshape(-1))
            count = n_env*horizon; epoch_rows=[]; stop_reason='epoch_limit'
            for epoch in range(1,epochs+1):
                indices = torch.randperm(count,device=device); batches=0; last_norm=None
                for start in range(0,count,minibatch_size):
                    ix=indices[start:start+minibatch_size]
                    logits,predicted = model(obs_batch[ix])
                    dist = Categorical(logits=logits)
                    ratio = torch.exp(dist.log_prob(action_batch[ix])-old_logp_batch[ix])
                    objective = torch.minimum(ratio*advantage[ix],
                                              ratio.clamp(1-epsilon,1+epsilon)*advantage[ix])
                    policy_loss = -objective.mean()
                    value_error = (predicted-targets[ix]).square()
                    if clip_value:
                        clipped = old_value_batch[ix]+(predicted-old_value_batch[ix]).clamp(-epsilon,epsilon)
                        value_error = torch.maximum(value_error,(clipped-targets[ix]).square())
                    value_loss = .5*value_error.mean()
                    entropy = dist.entropy().mean()
                    loss = policy_loss+vf_coef*value_loss-entropy_coef*entropy
                    if not torch.isfinite(loss): raise FloatingPointError('Pérdida no finita')
                    optimizer.zero_grad(set_to_none=True); loss.backward()
                    last_norm = float(nn.utils.clip_grad_norm_(model.parameters(),max_grad_norm,error_if_nonfinite=True))
                    optimizer.step(); batches += 1
                with torch.no_grad():
                    logits,predicted = model(obs_batch); dist = Categorical(logits=logits)
                    logratio = dist.log_prob(action_batch)-old_logp_batch
                    ratio = logratio.exp()
                    kl_k1 = float((-logratio).mean())
                    kl_k3 = float(((ratio-1)-logratio).mean())
                    clipfrac = float(((ratio-1).abs()>epsilon).float().mean())
                    objective = torch.minimum(ratio*advantage,ratio.clamp(1-epsilon,1+epsilon)*advantage)
                    error = (predicted-targets).square()
                    if clip_value:
                        clipped=old_value_batch+(predicted-old_value_batch).clamp(-epsilon,epsilon)
                        error=torch.maximum(error,(clipped-targets).square())
                    row = {'epoch':epoch,'minibatches':batches,'kl_k1':kl_k1,'kl_k3':kl_k3,
                           'clip_fraction':clipfrac,'loss_policy':float(-objective.mean()),
                           'loss_value':float(.5*error.mean()),'entropy':float(dist.entropy().mean()),
                           'gradient_norm_before_clip_last_minibatch':last_norm}
                if not all(math.isfinite(row[k]) for k in ('kl_k1','kl_k3','clip_fraction','loss_policy','loss_value','entropy')):
                    raise FloatingPointError('Métricas no finitas')
                row['stopped_early'] = target_kl is not None and kl_k3 > target_kl
                epoch_rows.append(row)
                if row['stopped_early']:
                    stop_reason='kl_k3'; break
            with torch.no_grad(): _,predicted_final=model(obs_batch)
            var_target=float(targets.var(unbiased=False))
            var_error=float((targets-predicted_final).var(unbiased=False))
            explained = None if var_target <= 1e-12 else 1-var_error/var_target
            row = {'update':update,'transitions':update*count,
                   'learning_rate':float(optimizer.param_groups[0]['lr']),
                   'terminated_count':int(np.count_nonzero(terms)),
                   'truncated_count':int(np.count_nonzero(truncs)),
                   'both_flags_count':int(np.count_nonzero(np.stack(terms)&np.stack(truncs))),
                   'training_completed_returns':completed,'epochs':epoch_rows,
                   'stop_reason':stop_reason,'explained_variance':explained,'evaluation':[]}
            if update%eval_every==0 or update==total_updates:
                row['evaluation']=evaluate(model,kind,seed)
                print('sonda '+str(kind) if probe else kind,'semilla',seed,'actualización',update,
                      'retorno',np.mean([x['return'] for x in row['evaluation']]),
                      'KL k3',epoch_rows[-1]['kl_k3'],'clip',epoch_rows[-1]['clip_fraction'],flush=True)
            history.append(row)
        label = ('Sonda '+str(kind) if probe else kind) + (' | fallo: sin bootstrap en truncamiento' if bad_trunc else '')
        config_id=f'e{epochs}-m{minibatch_size}-lr{lr_initial}-eps{epsilon}-kl{target_kl}-norm{int(norm_adv)}-v{int(clip_value)}-badtrunc{int(bad_trunc)}-limit{time_limit}'
        return {'id':label.replace(' ','-')+'-seed-'+str(seed)+'-'+config_id,'label':label,
                'environment':'Probe' if probe else kind,'probe_kind':kind if probe else None,
                'seed':seed,'config':{'minibatch_size':minibatch_size,
                      'learning_rate':lr_initial,'clip_epsilon':epsilon,'target_kl':target_kl,
                      'time_limit_override':None if probe else time_limit,
                      'fault_no_bootstrap_on_truncation':bad_trunc},
                'history':history,'probe_check':probe_check(model,kind,discount) if probe else None}
    finally:
        envs.close()

report = {'schema':'oryon-ppo-m22-l20-v1',
          'source':'Ejecución local de PPO discreto; KL al final de cada época sobre el rollout fijo y evaluación voraz independiente',
          'evaluation_policy':'voraz con entornos y semillas de evaluación separados',
          'quick':quick,'device':str(device),'torch':torch.__version__,
          'gymnasium':gym.__version__,'numpy':np.__version__,'seeds':seeds,
          'configuration':{'n_env':n_env,'horizon':horizon,'epochs_max':epochs,
              'minibatch_size':minibatch_size,'gamma_tasks':gamma,'gamma_probes':.9,'lambda':lam,
              'clip_policy':epsilon,'clip_value':clip_value,'target_kl_k3':target_kl,
              'learning_rate_initial':lr_initial,'learning_rate_schedule':'lineal por actualización',
              'adam_eps':1e-5,'value_coef':vf_coef,'entropy_coef':entropy_coef,
              'gradient_clip':max_grad_norm,'advantage_normalization':'rollout, std poblacional' if norm_adv else 'sin normalizar',
              'fault_no_bootstrap_on_truncation':bad_trunc,
              'time_limit_override':time_limit,'time_limit_scope':'CartPole y LunarLander; sondas sin límite adicional',
              'actor_time_weighting':'uniforme por transición','autoreset':'SAME_STEP',
              'evaluation_every':eval_every,'evaluation_episodes':eval_episodes,
              'evaluation_seed':'100000 + 1000 * train_seed + episode'},'runs':[]}
for kind in (0,1,2,3,4,'CartPole-v1','LunarLander-v3'):
    for seed in seeds:
        failure=None
        try: result=train(kind,seed)
        except Exception: 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:\n'+failure)
        report['runs'].append(result)
        (out/'ppo-discrete-report.json').write_text(json.dumps(report,indent=2,allow_nan=False),encoding='utf-8')
print('Informe:',out/'ppo-discrete-report.json')
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Probe validation compares both critic value with the current policy’s analytic value and each critic-derived one-step Q with its analytic solution. In probes 3 and 4 exact value changes with policy: it is not incorrectly compared with optimal value. It also checks the greedy action when a unique optimal choice exists. A reduced test can fail that tolerance: the report retains errors and decisions rather than declaring early success. KL is computed only for actions sampled in the rollout and stopping applies after an epoch; an epoch can exceed the threshold before detection. The algorithm does not guarantee monotonic improvement.

Train continuous PPO from scratch on Hopper-v5, HalfCheetah-v5 or Walker2d-v5, using Gymnasium 1.4 and MuJoCo. Install gymnasium[mujoco]==1.4.0, mujoco, PyTorch and NumPy. ORYON_PPO_ENV selects the environment; full mode uses five seeds, eight environments and 2,048,000 transitions per seed. ORYON_QUICK=1 limits the test to one seed, two environments, 16 steps and two updates, with external 64-step episode limit. It does not demonstrate learning or reproduce benchmark numbers.

Choose a condition with ORYON_PPO_CASE: default, no_adv_norm, no_orthogonal, no_value_clip, no_lr_anneal or no_obs_norm. One condition runs at a time and its filename includes environment and condition. Retain all five seeds and individual evaluation returns: an analysis cell can compute IQM over per-seed means and paired seed bootstrap if comparing the same seeds. A one-seed QUICK run cannot estimate between-seed uncertainty. Changing more than one condition simultaneously prevents attributing a difference to one component.

Observation normalization uses mean and variance of training states. Both are frozen while collecting and optimizing each rollout and updated after the batch; evaluation freezes them and does not feed statistics. KL k3 and clipped fraction are logged both with normalization frozen during rollout and after updating it, on the same raw states and latent actions. Early stopping checks only the first measurement at each epoch end: it does not control additional normalization change or guarantee KL stays below threshold. Training reward is divided by the deviation of accumulated discounted returns and clipped to [−10,10]; scale is also frozen per rollout and can change between batches. The critic predicts targets in that changing scale without converting its prior predictions: explained variance is interpreted within the batch, and the experiment is not equivalent to a raw-reward critic. Evaluation logs raw return, without normalization or clipping. Each copy resets its reward accumulator after termination or truncation.

The diagonal Gaussian produces a latent and action is transformed with tanh and affine scaling. PPO’s ratio uses the same old latent, so the continuous Jacobian cancels; reported entropy is latent Gaussian entropy, not transformed-action entropy. Sent components exactly equal to bounds after rounding are counted. In SAME_STEP, GAE uses final_obs for truncation bootstrap value and stops its trace at both signals. The actor averages collected transitions without γᵗ, and advantage normalization uses same-batch statistics: practical decisions, not a guarantee of an unbiased initial discounted-return gradient.

For library comparison, ORYON_PPO_SB3=1 additionally runs Stable-Baselines3 if installed. It uses the same environment, transition budget, seeds and main parameters, and separately evaluates raw return with frozen statistics. SB3 has its own policy and update conventions and stepwise-updated VecNormalize: its usual PPO clips Gaussian actions to bounds and normalizes advantages per minibatch, while this implementation uses tanh and per-rollout normalization. With value clipping, SB3 applies mean squared error to the clipped prediction; here half the maximum of clipped and unclipped errors is used, so the same value coefficient does not equalize that loss. This is not a parity test or isolation of one difference. If SB3 is missing, it stops with an explicit message. The report logs version and method; a reduced run checks both branches work but does not compare performance.

[ ]Continuous PPO and ablationsLocal GPU
import gc
import json
import math
import os
import random
import traceback
from pathlib import Path

import gymnasium as gym
import mujoco
import numpy as np
import torch
from torch import nn
from torch.distributions import Normal

if not gym.__version__.startswith('1.4.'):
    raise RuntimeError('Este laboratorio usa el contrato vectorial de Gymnasium 1.4.x')
quick = os.environ.get('ORYON_QUICK', '0') == '1'
env_id = os.environ.get('ORYON_PPO_ENV', 'Hopper-v5')
if env_id not in ('Hopper-v5', 'HalfCheetah-v5', 'Walker2d-v5'):
    raise ValueError('ORYON_PPO_ENV no es uno de los tres entornos')
case = os.environ.get('ORYON_PPO_CASE', 'default')
cases = ('default','no_adv_norm','no_orthogonal','no_value_clip','no_lr_anneal','no_obs_norm')
if case not in cases:
    raise ValueError('ORYON_PPO_CASE desconocido')
run_sb3 = os.environ.get('ORYON_PPO_SB3', '0') == '1'
out = Path(os.environ.get('ORYON_PPO_OUT', 'oryon-ppo'))
out.mkdir(parents=True, exist_ok=True)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
seeds = [0] if quick else [0,1,2,3,4]
n_env, horizon, updates = (2,16,2) if quick else (8,256,1000)
epochs, minibatch = (2,16) if quick else (10,256)
eval_every, eval_episodes = (1,1) if quick else (50,5)
gamma, lam, clip, vf_clip, lr, target_kl = .99, .95, .2, .2, .0003, .03
value_coef, entropy_coef, max_norm = .5, 0., .5

def make_env():
    return gym.make(env_id,max_episode_steps=64) if quick else gym.make(env_id)

class RunningMoments:
    def __init__(self, shape=()):
        self.mean = np.zeros(shape, dtype=np.float64)
        self.var = np.ones(shape, dtype=np.float64)
        self.count = 1e-4

    def update(self, batch):
        batch = np.asarray(batch, dtype=np.float64)
        if batch.shape[0] == 0:
            return
        m, v, n = batch.mean(axis=0), batch.var(axis=0), batch.shape[0]
        delta = m-self.mean
        total = self.count+n
        self.var = (self.var*self.count+v*n+delta**2*self.count*n/total)/total
        self.mean = self.mean+delta*n/total
        self.count = total

def normalized_obs(obs, moments):
    if case == 'no_obs_norm':
        return np.asarray(obs,dtype=np.float32)
    return np.clip((obs-moments.mean)/np.sqrt(moments.var+1e-8),-10.,10.).astype(np.float32)

def tensor(x):
    return torch.as_tensor(np.asarray(x),dtype=torch.float32,device=device)

def network(obs_dim, output_dim, gain):
    layers = [nn.Linear(obs_dim,64),nn.Tanh(),nn.Linear(64,64),nn.Tanh(),nn.Linear(64,output_dim)]
    if case != 'no_orthogonal':
        for layer in layers:
            if isinstance(layer,nn.Linear):
                nn.init.orthogonal_(layer.weight, math.sqrt(2))
                nn.init.zeros_(layer.bias)
        nn.init.orthogonal_(layers[-1].weight,gain)
    return nn.Sequential(*layers)

class Actor(nn.Module):
    def __init__(self, obs_dim, act_dim):
        super().__init__()
        self.net=network(obs_dim,act_dim,.01)
        self.log_std=nn.Parameter(torch.zeros(act_dim))

    def dist(self,x):
        mean=self.net(x)
        return Normal(mean,self.log_std.clamp(-5.,1.).exp().expand_as(mean))

class Critic(nn.Module):
    def __init__(self, obs_dim):
        super().__init__()
        self.net=network(obs_dim,1,1.)

    def forward(self,x):
        return self.net(x).squeeze(-1)

def gae(reward,value,successor_value,term,trunc):
    out=np.zeros_like(reward,dtype=np.float64)
    carry=np.zeros(reward.shape[1],dtype=np.float64)
    for t in range(len(reward)-1,-1,-1):
        delta=reward[t]+gamma*(~term[t])*successor_value[t]-value[t]
        carry=delta+gamma*lam*(~(term[t]|trunc[t]))*carry
        out[t]=carry
    return out

assert np.allclose(gae(np.array([[1.],[2.]]),np.zeros((2,1)),np.array([[3.],[9.]]),
                       np.array([[False],[True]]),np.array([[True],[False]])),[[3.97],[2.]])

def successor(next_obs,term,trunc,info):
    done=term|trunc
    result=np.asarray(next_obs).copy()
    if done.any():
        if 'final_obs' not in info or '_final_obs' not in info:
            raise RuntimeError('Falta final_obs en SAME_STEP')
        if not np.array_equal(info['_final_obs'],done):
            raise RuntimeError('Máscara final_obs incompatible')
        for i in np.flatnonzero(done):
            result[i]=info['final_obs'][i]
    return result

def evaluate(actor,obs_moments,seed,low,high):
    env=make_env()
    result=[]
    try:
        for i in range(eval_episodes):
            eval_seed=100000+1000*seed+i
            obs,_=env.reset(seed=eval_seed)
            total,length=0.,0
            while True:
                with torch.no_grad():
                    z=actor.dist(tensor(normalized_obs(obs,obs_moments)).unsqueeze(0)).mean[0].cpu().numpy()
                action=(low+(np.tanh(z)+1.)*(high-low)/2.).astype(env.action_space.dtype)
                obs,r,term,trunc,_=env.step(action)
                total+=float(r); length+=1
                if term or trunc:
                    result.append({'seed':eval_seed,'return_raw':total,'length':length,
                                   'terminated':bool(term),'truncated':bool(trunc)})
                    break
    finally:
        env.close()
    return result

def train(seed):
    random.seed(seed); np.random.seed(seed); torch.manual_seed(seed)
    if torch.cuda.is_available(): torch.cuda.manual_seed_all(seed)
    shuffle=np.random.default_rng(seed+50000)
    envs=gym.vector.SyncVectorEnv([make_env 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)])
        low,high=envs.single_action_space.low,envs.single_action_space.high
        if not np.isfinite(low).all() or not np.isfinite(high).all() or np.any(high<=low):
            raise ValueError('Límites de acción inválidos')
        obs_moments=RunningMoments(obs.shape[1:]); reward_moments=RunningMoments()
        discounted=np.zeros(n_env); episode_return=np.zeros(n_env)
        actor=Actor(obs.shape[1],low.size).to(device); critic=Critic(obs.shape[1]).to(device)
        optimizer=torch.optim.Adam(list(actor.parameters())+list(critic.parameters()),lr=lr,eps=1e-5)
        history=[]
        for update in range(1,updates+1):
            learning_rate=lr if case=='no_lr_anneal' else lr*(1-(update-1)/updates)
            for group in optimizer.param_groups: group['lr']=learning_rate
            scale=float(np.sqrt(reward_moments.var+1e-8))
            observations,latents,old_logps,values,next_values=[],[],[],[],[]
            rewards,terms,truncs,raw_states,return_samples=[],[],[],[],[]
            completed,saturated,components=[],0,0
            for _ in range(horizon):
                raw_states.append(obs.copy())
                state=tensor(normalized_obs(obs,obs_moments))
                with torch.no_grad():
                    dist=actor.dist(state); z=dist.sample(); value=critic(state)
                    action=(low+(torch.tanh(z).cpu().numpy()+1.)*(high-low)/2.).astype(envs.single_action_space.dtype)
                    next_obs,reward,term,trunc,info=envs.step(action)
                    real_next=successor(next_obs,term,trunc,info)
                    next_value=critic(tensor(normalized_obs(real_next,obs_moments)))
                    observations.append(state); latents.append(z); old_logps.append(dist.log_prob(z).sum(-1))
                    values.append(value.cpu().numpy()); next_values.append(next_value.cpu().numpy())
                rewards.append(np.clip(reward/scale,-10.,10.)); terms.append(term.copy()); truncs.append(trunc.copy())
                discounted=gamma*discounted+reward
                return_samples.append(discounted.copy())
                episode_return+=reward
                done=term|trunc
                for i in np.flatnonzero(done):
                    completed.append(float(episode_return[i])); episode_return[i]=0.; discounted[i]=0.
                saturated+=int(np.count_nonzero((action==low)|(action==high))); components+=action.size
                obs=next_obs
            old_values=np.stack(values)
            advantages=gae(np.stack(rewards),old_values,np.stack(next_values),np.stack(terms),np.stack(truncs))
            targets=advantages+old_values
            if case!='no_adv_norm':
                advantages=(advantages-advantages.mean())/(advantages.std()+1e-8)
            states=torch.cat(observations); z=torch.cat(latents); old_logp=torch.cat(old_logps)
            old_v=tensor(old_values.reshape(-1)); adv=tensor(advantages.reshape(-1)); target=tensor(targets.reshape(-1))
            samples=states.shape[0]; used_epochs=0; last_norm=0.
            for epoch in range(epochs):
                for indices in np.array_split(shuffle.permutation(samples),math.ceil(samples/minibatch)):
                    ix=torch.as_tensor(indices,dtype=torch.long,device=device)
                    dist=actor.dist(states[ix]); new_logp=dist.log_prob(z[ix]).sum(-1)
                    ratio=torch.exp(new_logp-old_logp[ix])
                    policy_loss=-torch.minimum(ratio*adv[ix],ratio.clamp(1-clip,1+clip)*adv[ix]).mean()
                    value=critic(states[ix]); err=(value-target[ix]).square()
                    if case!='no_value_clip':
                        clipped=old_v[ix]+(value-old_v[ix]).clamp(-vf_clip,vf_clip)
                        err=torch.maximum(err,(clipped-target[ix]).square())
                    value_loss=.5*err.mean(); entropy=dist.entropy().sum(-1).mean()
                    loss=policy_loss+value_coef*value_loss-entropy_coef*entropy
                    if not torch.isfinite(loss): raise FloatingPointError('Pérdida no finita')
                    optimizer.zero_grad(set_to_none=True); loss.backward()
                    last_norm=float(nn.utils.clip_grad_norm_(list(actor.parameters())+list(critic.parameters()),max_norm,error_if_nonfinite=True))
                    optimizer.step()
                used_epochs+=1
                with torch.no_grad():
                    zratio=actor.dist(states).log_prob(z).sum(-1)-old_logp
                    approx_kl=float((torch.expm1(zratio)-zratio).mean())
                if not math.isfinite(approx_kl): raise FloatingPointError('KL no finita')
                if approx_kl>target_kl: break
            with torch.no_grad():
                dist=actor.dist(states); logratio=dist.log_prob(z).sum(-1)-old_logp
                ratio=logratio.exp(); predicted=critic(states).cpu().numpy()
                entropy=float(dist.entropy().sum(-1).mean())
                clipfrac=float(((ratio-1).abs()>clip).float().mean())
                approx_kl=float((torch.expm1(logratio)-logratio).mean())
            variance=float(np.var(targets))
            explained=None if variance<=1e-12 else float(1-np.var(targets.reshape(-1)-predicted)/variance)
            obs_moments.update(np.concatenate(raw_states,axis=0))
            reward_moments.update(np.concatenate(return_samples))
            with torch.no_grad():
                renormalized=tensor(normalized_obs(np.concatenate(raw_states,axis=0),obs_moments))
                changed_logratio=actor.dist(renormalized).log_prob(z).sum(-1)-old_logp
                changed_ratio=changed_logratio.exp()
                kl_after_obs_update=float((torch.expm1(changed_logratio)-changed_logratio).mean())
                clipfrac_after_obs_update=float(((changed_ratio-1).abs()>clip).float().mean())
            if not math.isfinite(kl_after_obs_update) or not math.isfinite(clipfrac_after_obs_update):
                raise FloatingPointError('Diagnóstico tras actualizar normalización no finito')
            row={'update':update,'transitions':update*samples,'epochs_used':used_epochs,
                 'learning_rate':learning_rate,'completed_train_returns_raw':completed,
                 'reward_scale_used':scale,'latent_entropy':entropy,'approx_kl_k3':approx_kl,
                 'clipfrac':clipfrac,'explained_variance':explained,'last_gradient_norm_before_clip':last_norm,
                 'approx_kl_k3_after_obs_update':kl_after_obs_update,
                 'clipfrac_after_obs_update':clipfrac_after_obs_update,
                 'saturated_action_components':saturated,'action_components':components}
            if update%eval_every==0 or update==updates:
                row['evaluation']=evaluate(actor,obs_moments,seed,low,high)
                print(env_id,case,'semilla',seed,'paso',update,'retorno bruto',
                      np.mean([e['return_raw'] for e in row['evaluation']]),'KL k3',approx_kl,flush=True)
            history.append(row)
        return {'method':'PPO desde cero','case':case,'seed':seed,'history':history}
    finally:
        envs.close()

def train_sb3(seed):
    try:
        import stable_baselines3 as sb3
        from stable_baselines3.common.vec_env import DummyVecEnv, VecNormalize
    except ImportError as exc:
        raise RuntimeError('ORYON_PPO_SB3=1 requiere instalar stable-baselines3 compatible') from exc
    # Los cambios de caso también se aplican si SB3 expone el parámetro equivalente.
    vec=VecNormalize(DummyVecEnv([make_env for _ in range(n_env)]),
                     norm_obs=(case!='no_obs_norm'),norm_reward=True,gamma=gamma)
    try:
        vec.seed(seed*1000)
        schedule=lr if case=='no_lr_anneal' else lambda remaining: lr*remaining
        model=sb3.PPO('MlpPolicy',vec,seed=seed,device=str(device),learning_rate=schedule,
                      n_steps=horizon,batch_size=minibatch,n_epochs=epochs,gamma=gamma,
                      gae_lambda=lam,clip_range=clip,clip_range_vf=None if case=='no_value_clip' else vf_clip,
                      normalize_advantage=(case!='no_adv_norm'),ent_coef=entropy_coef,vf_coef=value_coef,
                      max_grad_norm=max_norm,target_kl=target_kl,
                      policy_kwargs={'ortho_init':case!='no_orthogonal'},verbose=0)
        model.learn(total_timesteps=updates*n_env*horizon)
        vec.training=False
        env=make_env(); episodes=[]
        try:
            for i in range(eval_episodes):
                eval_seed=100000+1000*seed+i; obs,_=env.reset(seed=eval_seed); total=0.; length=0
                while True:
                    norm=vec.normalize_obs(np.asarray(obs)[None,:])[0]
                    action,_=model.predict(norm,deterministic=True)
                    obs,reward,term,trunc,_=env.step(action)
                    total+=float(reward); length+=1
                    if term or trunc:
                        episodes.append({'seed':eval_seed,'return_raw':total,'length':length,
                                         'terminated':bool(term),'truncated':bool(trunc)})
                        break
        finally:
            env.close()
        return {'method':'Stable-Baselines3 PPO','version':sb3.__version__,'case':case,'seed':seed,
                'transitions':int(model.num_timesteps),'evaluation':episodes}
    finally:
        vec.close()

report={'quick':quick,'environment':env_id,'case':case,'gymnasium':gym.__version__,
        'mujoco':mujoco.__version__,'torch':torch.__version__,'numpy':np.__version__,'device':str(device),
        'seeds':seeds,'configuration':{'n_env':n_env,'horizon':horizon,'updates':updates,
            'epochs':epochs,'minibatch':minibatch,'gamma':gamma,'lambda':lam,'clip':clip,
            'value_clip':None if case=='no_value_clip' else vf_clip,'target_kl':target_kl,
            'learning_rate_initial':lr,'lr_annealing':case!='no_lr_anneal',
            'advantage_normalization':case!='no_adv_norm','observation_normalization':case!='no_obs_norm',
            'orthogonal_initialization':case!='no_orthogonal','reward_normalization':True,
            'reward_clip':10.,'entropy_coef':entropy_coef,'value_coef':value_coef,
            'autoreset':'SAME_STEP','evaluation_episodes':eval_episodes,
            'quick_time_limit':64 if quick else None,
            'evaluation_seed':'100000 + 1000 * train_seed + episode'},'runs':[]}
for seed in seeds:
    for method in (('scratch','sb3') if run_sb3 else ('scratch',)):
        failure=None
        try:
            result=train(seed) if method=='scratch' else train_sb3(seed)
        except Exception:
            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 laboratorio:\n'+failure)
        report['runs'].append(result)
        filename='ppo-'+env_id+'-'+case+'.json'
        (out/filename).write_text(json.dumps(report,indent=2,allow_nan=False),encoding='utf-8')
print('Informe:',out/('ppo-'+env_id+'-'+case+'.json'))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

For analysis first run the continuous lab once per environment and condition, keeping its six reports per environment in one folder. ORYON_PPO_ABLATION_DIR indicates that folder, or ORYON_PPO_OUT if unset. The cell neither trains agents nor invents results: it checks configuration, training and evaluation seeds, budget and versions. If reports are missing or QUICK is used, it reports absence and does not calculate between-seed intervals.

The experimental unit is a training seed. For each seed first average final raw evaluation returns; compute interquartile mean (IQM) of those averages across seeds, weighting edges when seed count is not divisible by four. The 95% intervals are percentiles of 5,000 seed resamples with replacement. Each comparison jointly resamples the same condition and control seeds. We show both difference between their IQMs and IQM of paired differences: different statistics. Returns from different environments are neither pooled nor normalized together. With only five seeds, intervals are indicative and can be unstable; they do not alone prove causation.

[ ]IQM and paired bootstrap for PPO ablationsLocal GPU
import hashlib
import json
import os
from pathlib import Path

import numpy as np

root = Path(os.environ.get('ORYON_PPO_ABLATION_DIR',os.environ.get('ORYON_PPO_OUT','oryon-ppo')))
out = Path(os.environ.get('ORYON_PPO_ABLATION_OUT',str(root)))
out.mkdir(parents=True,exist_ok=True)
envs = ('Hopper-v5','HalfCheetah-v5','Walker2d-v5')
cases = ('default','no_adv_norm','no_orthogonal','no_value_clip','no_lr_anneal','no_obs_norm')
modified = {'default':None,'no_adv_norm':'advantage_normalization',
            'no_orthogonal':'orthogonal_initialization','no_value_clip':'value_clip',
            'no_lr_anneal':'lr_annealing','no_obs_norm':'observation_normalization'}

def iqm(values):
    values = np.sort(np.asarray(values,dtype=float))
    if values.ndim != 1 or not len(values) or not np.isfinite(values).all():
        raise ValueError('IQM necesita una muestra unidimensional finita no vacía')
    n = len(values); lower = .25*n; upper = .75*n
    weights = np.maximum(0.,np.minimum(np.arange(1,n+1),upper)-np.maximum(np.arange(n),lower))
    return float(weights@values/(upper-lower))

def read_report(path,environment,case):
    raw = path.read_bytes()
    report = json.loads(raw)
    if report.get('environment') != environment or report.get('case') != case:
        raise ValueError('Entorno o condición no coinciden con el nombre: '+str(path))
    if not isinstance(report.get('configuration'),dict) or not isinstance(report.get('runs'),list):
        raise ValueError('Informe sin configuración o ejecuciones: '+str(path))
    return report,hashlib.sha256(raw).hexdigest()

def scratch_samples(report):
    config=report['configuration']
    expected_steps=config['updates']*config['n_env']*config['horizon']
    result={}
    for run in report['runs']:
        if run.get('method') != 'PPO desde cero': continue
        if run.get('case') != report['case'] or run['seed'] in result:
            raise ValueError('Condición o semilla duplicada en el informe')
        history=run.get('history',[])
        if not history or history[-1].get('update') != config['updates'] or history[-1].get('transitions') != expected_steps:
            raise ValueError('El entrenamiento no alcanzó el presupuesto declarado')
        episodes=history[-1].get('evaluation',[])
        if len(episodes) != config['evaluation_episodes'] or not episodes:
            raise ValueError('Falta la evaluación final completa')
        keys=[episode['seed'] for episode in episodes]
        expected=[100000+1000*run['seed']+i for i in range(config['evaluation_episodes'])]
        if keys != expected: raise ValueError('Las semillas de evaluación no coinciden con el protocolo')
        if any(not (episode['terminated'] or episode['truncated']) for episode in episodes):
            raise ValueError('Una evaluación no terminó ni se truncó')
        returns=np.asarray([episode['return_raw'] for episode in episodes],dtype=float)
        if not np.isfinite(returns).all(): raise ValueError('Retorno no finito')
        result[run['seed']]={'mean_return':float(returns.mean()),'evaluation_seeds':keys}
    declared=report.get('seeds',[])
    if len(declared)!=len(set(declared)) or set(result)!=set(declared):
        raise ValueError('Las semillas del informe no coinciden con las ejecuciones propias')
    return result

def verify_protocol(reports):
    base=reports['default']; config0=base['configuration']
    for case,report in reports.items():
        if report['quick'] != base['quick']:
            raise ValueError('No mezcles QUICK y entrenamiento completo')
        for name in ('gymnasium','mujoco','torch','numpy','device'):
            if report.get(name)!=base.get(name): raise ValueError('Versiones o dispositivo diferentes: '+name)
        config=report['configuration']; field=modified[case]
        if set(config)!=set(config0): raise ValueError('Claves de configuración diferentes')
        for key in config:
            if key != field and config[key] != config0[key]:
                raise ValueError('Cambió otro parámetro en '+case+': '+key)
        if field is not None and config[field] == config0[field]:
            raise ValueError('La condición no modificó '+field)

def bootstrap_paired(base,variant,seed,draws=5000):
    base=np.asarray(base,dtype=float); variant=np.asarray(variant,dtype=float)
    if base.shape!=variant.shape or base.ndim!=1 or len(base)<5:
        raise ValueError('Se necesitan al menos cinco semillas emparejadas')
    rng=np.random.default_rng(seed)
    indices=rng.integers(0,len(base),size=(draws,len(base)))
    marginal=[]; paired=[]
    for ix in indices:
        marginal.append(iqm(variant[ix])-iqm(base[ix]))
        paired.append(iqm(variant[ix]-base[ix]))
    return {'difference_of_iqms':iqm(variant)-iqm(base),
            'difference_of_iqms_ci95':np.quantile(marginal,[.025,.975]).tolist(),
            'iqm_of_paired_differences':iqm(variant-base),
            'iqm_of_paired_differences_ci95':np.quantile(paired,[.025,.975]).tolist()}

def bootstrap_iqm(values,seed,draws=5000):
    values=np.asarray(values,dtype=float)
    if values.ndim!=1 or len(values)<5 or not np.isfinite(values).all():
        raise ValueError('Se necesitan al menos cinco semillas finitas')
    rng=np.random.default_rng(seed)
    indices=rng.integers(0,len(values),size=(draws,len(values)))
    return np.quantile([iqm(values[ix]) for ix in indices],[.025,.975]).tolist()

assert iqm([0,1,2,3,4]) == 2.
assert np.isclose(iqm([0,0,0,0,100]),0.)
summary={'bootstrap_seed':2220,'bootstrap_draws':5000,'minimum_training_seeds':5,
         'unit':'semilla de entrenamiento; media de retornos brutos finales de evaluación',
         'interval':'percentil 2,5 % y 97,5 % con remuestreo emparejado',
         'environments':{}}
for environment in envs:
    paths={case:root/('ppo-'+environment+'-'+case+'.json') for case in cases}
    missing=[case for case,path in paths.items() if not path.is_file()]
    if missing:
        summary['environments'][environment]={'status':'faltan informes','missing_cases':missing}
        print(environment,'sin análisis: faltan',', '.join(missing))
        continue
    loaded={case:read_report(path,environment,case) for case,path in paths.items()}
    reports={case:item[0] for case,item in loaded.items()}
    verify_protocol(reports)
    if reports['default']['quick']:
        summary['environments'][environment]={'status':'QUICK: sin inferencia entre semillas',
            'source_sha256':{case:item[1] for case,item in loaded.items()}}
        print(environment,'QUICK: no se calcula bootstrap entre semillas')
        continue
    samples={case:scratch_samples(report) for case,report in reports.items()}
    seeds=sorted(samples['default'])
    if len(seeds)<5: raise ValueError('Se necesitan al menos cinco semillas completas')
    for case in cases:
        if sorted(samples[case]) != seeds: raise ValueError('Semillas no emparejadas: '+case)
        for seed in seeds:
            if samples[case][seed]['evaluation_seeds'] != samples['default'][seed]['evaluation_seeds']:
                raise ValueError('Evaluaciones no emparejadas: '+case)
    base=np.array([samples['default'][seed]['mean_return'] for seed in seeds])
    results={}
    for case in cases:
        vector=np.array([samples[case][seed]['mean_return'] for seed in seeds])
        item={'iqm':iqm(vector),'iqm_ci95':bootstrap_iqm(vector,2220),
              'per_seed_mean_return':dict(zip(map(str,seeds),vector.tolist()))}
        if case!='default': item.update(bootstrap_paired(base,vector,2220))
        results[case]=item
        print(environment,case,'IQM de retornos medios:',round(item['iqm'],4),'IC95:',item['iqm_ci95'])
        if case!='default':
            print('  diferencia de IQM e IC95:',item['difference_of_iqms'],item['difference_of_iqms_ci95'])
            print('  IQM de diferencias emparejadas e IC95:',item['iqm_of_paired_differences'],item['iqm_of_paired_differences_ci95'])
    summary['environments'][environment]={'status':'analizado','training_seeds':seeds,
        'source_sha256':{case:item[1] for case,item in loaded.items()},'results':results}
(out/'ppo-ablation-analysis.json').write_text(json.dumps(summary,indent=2,allow_nan=False),encoding='utf-8')
print('Análisis:',out/'ppo-ablation-analysis.json')
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The comparison checks metadata published by each report, but cannot alone certify exactly the same code version was used or that two seeds produce identical trajectories. Observation normalization affects trajectories and is not an intervention isolated from the rest of learning dynamics. Inspect curves and per-seed returns before interpreting an aggregate.

Exercises

ProofThe four clipping cases
Prove: Prove each clipped-surrogate summand lower-bounds the unclipped surrogate.
0
Let ρ>0, A real and ε∈[0,1). Define c=clip(ρ,1−ε,1+ε) and l=min(ρA,cA). Analyze A>0 and A<0 separately; A=0 is immediate.

Step 1 of 4. If A>0 and ρ≤1+ε, what is l?

NumericLoss and gradient of a sample
For ε=0.2 take three samples with ratios ρ=(1.3; 0.7; 1.1) and advantages A=(2; −1; 0.5). Loss is negative mean of min(ρA, clip(ρ,0.8,1.2)A). For the third sample, what is its loss derivative with respect to its own log-ratio z₃=log ρ₃, with A fixed?
NumericMean batch loss
For ε=0.2, ratios ρ=(0.9; 1.4; 0.6) and advantages A=(1; 0.5; −2), calculate minus the mean of the three PPO clipped terms.
[ ]Check clipping calculationsBrowser
import numpy as np
ratio=np.array([1.3,.7,1.1]); advantage=np.array([2.,-1.,.5])
terms=np.minimum(ratio*advantage,np.clip(ratio,.8,1.2)*advantage)
print('Términos:',terms,'pérdida:',-terms.mean(),'derivada tercera:',-ratio[2]*advantage[2]/3)
ratio=np.array([.9,1.4,.6]); advantage=np.array([1.,.5,-2.])
print('Segunda pérdida:',-np.minimum(ratio*advantage,np.clip(ratio,.8,1.2)*advantage).mean())
CodePPO losses and diagnostics
Implement ppo_loss(new_logp, old_logp, adv, values, old_values, returns, clip, vf_clip, ent) using NumPy. The seven sample arguments are finite real vectors of equal length N≥1; do not modify them. clip is finite real in [0,1), vf_clip finite nonnegative real. Let z=new_logp−old_logp, ρ=exp(z), c=clip(ρ,1−clip,1+clip), v_c=old_values+clip(values−old_values,−vf_clip,vf_clip). Return a dict with policy_loss=−mean(min(ρ·adv,c·adv)), value_loss=0.5·mean(max((values−returns)²,(v_c−returns)²)), entropy=mean(ent), approx_kl=mean(expm1(z)−z) and clipfrac=mean(|ρ−1|>clip). If the ratio or any result is nonfinite, or inputs violate the contract, raise ValueError. Diagnostic k3 estimates KL(old||new) in expectation with old-policy samples and common support; it is not a pointwise guarantee. clipfrac counts out-of-range ratios, although not all are on an active plateau.
import numpy as np

def ppo_loss(new_logp, old_logp, adv, values, old_values, returns, clip, vf_clip, ent):
  pass
Shift+Enter to run
QuizFour diagnostic panels
These are four explicit hypothetical logs, not measured results. Each pair gives initial → final. A: mean KL 0.002→0.15 and clipfrac 0.02→0.70 after a tenfold learning-rate increase. B: critic explained variance −0.1→−0.2 and value loss 4.0→4.3. C: categorical entropy 1.0→0.01 and most likely action 0.5→0.998. D: a targeted TimeLimit test gives target 1.0, but the correct value with r=1, γ=0.9 and V(final)=3 is 3.7. What diagnosis corresponds to A, B, C and D?
QuizSeveral epochs on the same batch
Why can many epochs on one batch increase KL despite PPO clipping?