Module contents
Lesson 23 of 37Advanced 110 min

Maximum entropy RL and Soft Actor-Critic

Derive soft Bellman equations and Boltzmann policies, build SAC with tanh-squashed Gaussian actions and automatic temperature, and interpret control as inference.

After this lesson you can

  • Derive the optimal Boltzmann policy and soft value of the maximum-entropy objective.
  • Prove policy improvement in tabular soft iteration.
  • Implement SAC with twin critics, reparameterization, tanh Jacobian correction and automatic temperature.
  • Interpret maximum-entropy RL as inference in a graphical model.
  • Compare SAC, TD3 and PPO in MuJoCo using statistical evaluation.

Before you start

Choosing without losing diversity

A deterministic policy can find a good action but also stop visiting alternatives before learning about them. Maximum-entropy RL rewards both reward and policy entropy in visited states. This favors diversity but does not guarantee exploration of every useful region or policy robustness.

For finite actions, a stationary policy and discount 0<γ<10<\gamma<1, fix the convention

J(π)=Eπ[∑t=0∞γt(r(St,At)+αH(π(⋅∣St)))],H(π)=−∑aπ(a)log⁡π(a).J(\pi)=\E_\pi\left[\sum_{t=0}^\infty\gamma^t\left(r(S_t,A_t)+\alpha H(\pi(\cdot\mid S_t))\right)\right], \qquad H(\pi)=-\sum_a\pi(a)\log\pi(a).

With α>0\alpha>0 and fixed Q(a)Q(a) values, the Boltzmann distribution follows from an identity. Define Z=∑aeQ(a)/αZ=\sum_a e^{Q(a)/\alpha} and p∗(a)=eQ(a)/α/Zp^*(a)=e^{Q(a)/\alpha}/Z. For any distribution π\pi,

∑aπ(a)Q(a)+αH(π)=αlog⁡Z−αDKL(π∥p∗).\sum_a\pi(a)Q(a)+\alpha H(\pi) =\alpha\log Z-\alpha D_{\mathrm{KL}}(\pi\|p^*).

KL is nonnegative and vanishes only if π=p∗\pi=p^*, so this is the unique solution and its value is αlog⁡Z\alpha\log Z. As α\alpha tends to zero, the value approaches the maximum; probability is shared equally among tied maxima. For large α\alpha the policy tends to uniform, although the discrete value grows with αlog⁡∣A∣\alpha\log |\mathcal A|. Use stable logsumexp: subtract the maximum before exponentiating.

Consider two actions valued 0 and 1. Their probability ratio is π(1)/π(0)=exp⁡(1/α)\pi(1)/\pi(0)=\exp(1/\alpha): at low temperature the second dominates; as α\alpha rises the ratio approaches one. This compares actions in one state with the same QQ. In a real agent, changing temperature also changes collected data and learned values; not every observed difference can be attributed to the instantaneous distribution change.

Entropy regularizes a preference; it does not identify epistemic uncertainty. A very diffuse distribution can assign mass to harmful actions, and a Gaussian unimodal before tanh does not generally represent several separate strategies in a high-dimensional action space. Action entropy also differs from visited-state entropy: a random policy can stay in a small region of the environment. If reward is multiplied by a positive constant, keeping the same tradeoff also requires scaling α\alpha by that constant.

InteractiveTemperature in a multimodal landscape
0.50
Maximum Q on the grid1.881
Relative soft value1.090
Change α and observe density and relative soft value. Compare the two Q peaks.

The figure integrates an explicit function on [−2,2][-2,2] by quadrature: two Gaussian peaks of heights 2 and 1.6 centered at 0.9 and −1, plus −0.15a2-0.15a^2. The policy has density proportional to exp⁡(Q/α)\exp(Q/\alpha) relative to Lebesgue measure. The displayed value uses the uniform reference measure dν=da/4d\nu=da/4: it is αlog⁡∫eQ/αdν\alpha\log\int e^{Q/\alpha}d\nu and represents reward minus αDKL(π∥ν)\alpha D_{\rm KL}(\pi\|\nu). The value with differential entropy relative to Lebesgue measure is larger by αlog⁡4\alpha\log 4. At high temperature relative value tends to the uniform mean of QQ, not the maximum.

Soft Bellman and improvement

In a finite MDP with bounded reward and fixed α\alpha, define Qπ(s,a)=E[r+γVπ(S′)∣s,a]Q^\pi(s,a)=\E[r+\gamma V^\pi(S')\mid s,a] and

Vπ(s)=∑aπ(a∣s)(Qπ(s,a)−αlog⁡π(a∣s)).V^\pi(s)=\sum_a\pi(a\mid s)\left(Q^\pi(s,a)-\alpha\log\pi(a\mid s)\right).

The optimal soft Bellman equation replaces the maximum with αlog⁡∑aeQ(s,a)/α\alpha\log\sum_a e^{Q(s,a)/\alpha}. Its operator is a sup-norm contraction by factor γ\gamma: logsumexp changes by at most ∥Q−Q′∥∞\|Q-Q'\|_\infty, since each component changes by at most that amount. Thus its fixed point is unique. The next action’s entropy term stays inside V(S′)V(S'), and current reward is not discounted twice. Some references use a different convention shifting the entropy term; translate it before comparing equations.

Soft iteration evaluates a policy and then chooses, in each state, the distribution minimizing DKL(πnueva∥exp⁡(Qπvieja/α)/Z)D_{\rm KL}(\pi_{\rm nueva}\|\exp(Q^{\pi_{\rm vieja}}/\alpha)/Z). In the tabular case with all distributions available, the identity above implies

Ea∼πnueva[Qπvieja(s,a)−αlog⁡πnueva(a∣s)]≥Vπvieja(s).\E_{a\sim\pi_{\rm nueva}}[Q^{\pi_{\rm vieja}}(s,a)-\alpha\log\pi_{\rm nueva}(a\mid s)] \ge V^{\pi_{\rm vieja}}(s).

Apply the definition of QπviejaQ^{\pi_{\rm vieja}} once, then this inequality at the next state. Repeat: rewards and entropies of the new policy replace the old ones, while the remainder is multiplied by γn\gamma^n. Boundedness makes the remainder vanish, yielding Qπnueva≥QπviejaQ^{\pi_{\rm nueva}}\ge Q^{\pi_{\rm vieja}} for every state–action pair. This is the improvement argument in the original SAC paper. Approximate networks, replay and a restricted Gaussian family do not automatically inherit that guarantee.

To follow the inequality, define TπQ(s,a)=E[r+γ∑bπ(b∣S′)(Q(S′,b)−αlog⁡π(b∣S′))]T^\pi Q(s,a)=\E[r+\gamma\sum_b\pi(b\mid S')(Q(S',b)-\alpha\log\pi(b\mid S'))]. Local improvement says TπnuevaQπvieja≥TπviejaQπvieja=QπviejaT^{\pi_{\rm nueva}}Q^{\pi_{\rm vieja}}\ge T^{\pi_{\rm vieja}}Q^{\pi_{\rm vieja}}=Q^{\pi_{\rm vieja}}. The evaluation operator is monotone, so iteration preserves the inequality; it is also a contraction by factor γ\gamma and converges to QπnuevaQ^{\pi_{\rm nueva}}. This second form makes both ordering and limit explicit. Equality is possible, for example, if the old policy is already the Boltzmann distribution in every state.

Soft Q-learning uses the optimal soft operator: evaluate reward plus the next state’s logsumexp value. A tabular implementation with model access can iterate it directly; with sampled data, a stochastic update additionally needs coverage and learning-rate assumptions. In continuous actions the exponential integral usually lacks closed form, so SAC learns a parametrized policy instead of calculating exact normalization in each state.

Bounded actions and densities

A tanh-squashed Gaussian permits actions in (−1,1)d(-1,1)^d. For each state, produce mean μθ(s)\mu_\theta(s) and positive standard deviation σθ(s)\sigma_\theta(s), sample ϵ∼N(0,I)\epsilon\sim\Normal(0,I), set u=μ+σ⊙ϵu=\mu+\sigma\odot\epsilon and a=tanh⁡ua=\tanh u. Reparameterization lets us differentiate the action loss with respect to parameters while treating ϵ\epsilon as external noise.

By change of variables, with u=atanh⁡(a)u=\operatorname{atanh}(a),

log⁡π(a∣s)=∑i[log⁡N(ui;μi,σi)−log⁡(1−tanh⁡2ui)].\log\pi(a\mid s)=\sum_i\left[\log\Normal(u_i;\mu_i,\sigma_i)-\log(1-\tanh^2u_i)\right].

To prevent rounding making tanh⁡(u)\tanh(u) exactly 1 inside a logarithm, use log⁡(1−tanh⁡2u)=2(log⁡2−u−softplus⁡(−2u))\log(1-\tanh^2u)=2(\log2-u-\operatorname{softplus}(-2u)). If actions are then scaled to physical units b=l+(h−l)(a+1)/2b=l+(h-l)(a+1)/2, physical-unit log density additionally subtracts ∑ilog⁡((hi−li)/2)\sum_i\log((h_i-l_i)/2). The lab sets target entropy in normalized coordinates, so does not include that constant in the loss.

Understand the sign using a small region: around a large latent value, tanh compresses an interval of uu into a narrower action interval. The same mass occupies less length and action density therefore increases. Hence divide by the Jacobian determinant’s absolute value and subtract its logarithm. Densities can exceed one without contradiction: the area under the curve must sum to one. When components are independent before transformation, their log densities and corrections add; with full covariance the corresponding joint density is needed.

InteractiveDensity needs the Jacobian
  • With Jacobian
  • Without Jacobian
1.0
0.8
0.90
Corrected visible mass1.000
Uncorrected visible mass0.465
Log-density correction1.661
Move mean, scale and query action. Compare the correct curve with the one omitting the Jacobian.

The figure calculates a one-dimensional Gaussian density and the transformation above. Its displayed integral approximates the window [−0.999,0.999][-0.999,0.999]: it can lose tail mass and quadrature becomes inaccurate near the endpoints. The corrected density’s exact integral over (−1,1)(-1,1) is one. The uncorrected curve is not a normalized action density.

Numerical clipping deserves attention: mathematically tanh never reaches its endpoints for finite uu, but floating point may round it there. Subsequently computing atanh⁡(a)\operatorname{atanh}(a) or log⁡(1−a2)\log(1-a^2) can produce infinities even when the latent was finite. Retain uu and calculate the stable term from it. Deterministic evaluation commonly uses tanh⁡(μ)\tanh(\mu), which is not necessarily the expectation of tanh⁡(u)\tanh(u). Thus evaluation without noise answers a different question from entropy measured in training.

SAC and its temperature

Soft Actor-Critic combines replay, two critics and a stochastic policy. In a transition batch (s,a,r,s′,d)(s,a,r,s',d), dd identifies true termination and a′∼πθ(⋅∣s′)a'\sim\pi_\theta(\cdot\mid s'). With slow target critics,

y=r+γ(1−d)[min⁡iQϕˉi(s′,a′)−αlog⁡πθ(a′∣s′)],LQ=∑iE[(Qϕi(s,a)−y)2].y=r+\gamma(1-d)\left[\min_i Q_{\bar\phi_i}(s',a')-\alpha\log\pi_\theta(a'\mid s')\right],\qquad L_Q=\sum_i\E[(Q_{\phi_i}(s,a)-y)^2].

Compute yy without gradients and minimize E[αlog⁡πθ(a∣s)−min⁡iQϕi(s,a)]\E[\alpha\log\pi_\theta(a\mid s)-\min_iQ_{\phi_i}(s,a)] for the actor over buffer states and reparameterized actions. Critic parameters are not updated in that step, but the derivative of QQ with respect to action must stay active. Target critics move by Polyak averaging. External truncation retains bootstrap from the final observation: it is not a terminal state.

The new target action is drawn from the current policy, with values estimated by target critics; this SAC version needs no target actor. The critic minimum tries to limit overestimation but is not a guaranteed bound on true value. In the actor step αlog⁡π\alpha\log\pi pushes toward diversity and −Q-Q toward valued actions. If the critic invents a peak, the actor can exploit it as in TD3. Nor is the buffer an independent sample from the current policy: it mixes earlier experiences and coverage conditions the update.

For finite-bounded environments, code stores in replay the normalized action that generated the transition and scales only when interacting. It does not store noise added by another behavior policy as if it were a different action. If the environment terminates, next value is multiplied by zero; if only an external time limit is reached, the observation returned before reset is the target’s next state. Recording both signals separately helps find bootstrap errors.

Automatic temperature tuning treats desired entropy Hˉ\bar H as a constraint, using α>0\alpha>0 as dual multiplier. A practical loss for η=log⁡α\eta=\log\alpha is below, where the subscript “detenido” means stop the gradient:

Lη=−E[η(log⁡π(a∣s)+Hˉ)detenido].L_\eta=-\E\left[\eta\left(\log\pi(a\mid s)+\bar H\right)_{\rm detenido}\right].

Its mean gradient is H−HˉH-\bar H: if measured entropy falls below target, descent increases η\eta and hence α\alpha. A common target is Hˉ=−d\bar H=-d, a heuristic for normalized actions, not an optimality theorem. Differential entropy can be negative and changes with units. In a buffer it is estimated over states and action samples: it need not represent the stationary distribution or guarantee constraint satisfaction. Haarnoja and colleagues develop this formulation and practical approximations.

For example, if estimated entropy is −4 and target −3, expected η\eta gradient is negative and a descent step raises temperature. If the estimate is −2, it lowers it. This describes the sign with a fixed policy and state distribution; updating actor and critic changes those quantities and oscillations can arise. Optimizing α\alpha directly or parametrizing it exponentially changes gradient scale. The log⁡α\log\alpha loss above is a practical variant with the same equilibrium sign; Adam can produce similarly sized steps despite different target deviations. In [−1,1]d[-1,1]^d, differential entropy is at most dlog⁡2d\log 2: a larger target would be infeasible even for a uniform policy, and a restricted family may attain less.

InteractiveTemperature, entropy and return
  • Estimated entropy
  • Target
Final α0.795
Final estimated entropy1.930
Final mean return56.60
Choose one of two target entropies and compare measured traces.

These are two separate local Hopper-v5 runs paired by seed 0, with 1024 transitions, 256 initial random actions and short 64-step limit. Entropy is estimated using 64 buffer states and one action sample per state; return is the mean of two deterministic evaluation episodes. Temperature is fixed for the first 256 transitions, then tuned. With target −3, measured entropies exceed it and α falls. With target +3 the reverse occurs and α rises. The second constraint is deliberately infeasible: Hopper has three normalized actions, with maximum entropy 3log⁡2≈2.0793\log2\approx2.079. One seed and a short budget cannot establish which target is better. To reproduce the second trace use factor −1 in the lab.

Control as inference

In control as inference, introduce binary optimality variables OtO_t and a likelihood proportional to exp⁡(r(st,at)/α)\exp(r(s_t,a_t)/\alpha), after shifting and bounding reward as needed to define a valid probability. For a finite horizon, alongside the action prior and transitions, condition on Ot=1O_t=1 for every step. KL divergence between a policy-induced trajectory distribution and that model produces an ELBO: expected reward minus KL regularization relative to the prior. A discrete uniform prior recovers entropy up to a constant. A random horizon with continuation probability γ\gamma relates this construction to discounting. The parallel to a language policy regularized relative to a reference model is the same mathematical structure, not an equivalence of environments or observability.

With stochastic dynamics, the exact posterior conditioned on optimality also favors lucky transitions: it may change the successor distribution relative to actual dynamics. For a realizable control problem, the variational family retains environment transitions and optimizes policy; the objective is a bound, not necessarily the exact posterior. Levine explains the distinction.

For a small discrete action set, SAC can sum policy probabilities and critics exactly in the actor loss, without sampling actions or using tanh. With a huge set enumeration ceases to be cheap; a restricted policy and approximate critic also do not guarantee tabular improvement.

Lab: tabular iteration

This two-state, two-action MDP uses explicit rewards and transitions. Compare optimal values of reward and reward plus entropy: they are not the same quantity. The printed policy in the standard case applies Boltzmann to its Q only to facilitate comparison; it is not the standard deterministic optimal policy.

[ ]PythonBrowser
import numpy as np

P = np.array([[[.8,.2],[.1,.9]], [[.3,.7],[.6,.4]]])
R = np.array([[1.,0.],[0.,.5]])
gamma, alpha = .9, .5

def solve(soft):
    v = np.zeros(2)
    for _ in range(10000):
        q = R + gamma * (P @ v)
        if soft:
            m = q.max(axis=1)
            new = m + alpha * np.log(np.exp((q-m[:,None])/alpha).sum(axis=1))
        else:
            new = q.max(axis=1)
        if np.max(np.abs(new-v)) < 1e-11:
            break
        v = new
    q = R + gamma * (P @ new)
    p = np.exp((q-q.max(axis=1,keepdims=True))/alpha)
    p /= p.sum(axis=1,keepdims=True)
    return new, p

for soft in (False, True):
    value, policy = solve(soft)
    print('suave' if soft else 'estándar', 'valor', value, 'Boltzmann de Q', policy)

Lab: SAC from scratch

Install NumPy, PyTorch and Gymnasium with MuJoCo. The program uses a two-layer network of 256 units, circular replay, two critics, one update per post-warmup transition and one normalized action per component. Evaluation uses the squashed Gaussian mean without noise. Full mode uses five seeds, one million transitions and five episodes per evaluation every 20000 steps; select Hopper-v5, Walker2d-v5 or Ant-v5 with ORYON_SAC_ENV. ORYON_SAC_OUT selects the directory and ORYON_SAC_TARGET_FACTOR multiplies the target-entropy heuristic. ORYON_QUICK=1 checks the pipeline with one seed, 1024 steps and shortened episodes; it does not reproduce a benchmark. Times include evaluation and depend on hardware and shared load. Full results require running the program and are not claimed here.

[ ]SAC with automatic temperatureLocal GPU
import json, math, os, random, time
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
from torch.nn import functional as F

quick = os.getenv('ORYON_QUICK', '0') == '1'
env_id = os.getenv('ORYON_SAC_ENV', 'Hopper-v5')
if env_id not in ('Hopper-v5', 'Walker2d-v5', 'Ant-v5'):
    raise ValueError('Entorno desconocido')
target_factor = float(os.getenv('ORYON_SAC_TARGET_FACTOR', '1'))
if not math.isfinite(target_factor):
    raise ValueError('El factor de entropía debe ser finito')
out = Path(os.getenv('ORYON_SAC_OUT', 'oryon-sac'))
out.mkdir(parents=True, exist_ok=True)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
torch.set_num_threads(1)
steps = 1024 if quick else 1_000_000
warmup = 256 if quick else 10_000
interval = 256 if quick else 20_000
episodes = 2 if quick else 5
seeds = [0] if quick else list(range(5))
batch_size = 64 if quick else 256
capacity = 10000 if quick else 1_000_000
gamma, tau = .99, .005

def network(inputs, outputs):
    return nn.Sequential(nn.Linear(inputs,256),nn.ReLU(),nn.Linear(256,256),nn.ReLU(),nn.Linear(256,outputs))

class Actor(nn.Module):
    def __init__(self, obs, act):
        super().__init__()
        self.net = network(obs, 2*act)
    def sample(self, state):
        mu, log_std = self.net(state).chunk(2, dim=-1)
        dist = Normal(mu, log_std.clamp(-5,2).exp())
        u = dist.rsample(); action = torch.tanh(u)
        correction = 2*(math.log(2)-u-F.softplus(-2*u))
        logp = (dist.log_prob(u)-correction).sum(-1,keepdim=True)
        return action, logp
    def deterministic(self, state):
        mu, _ = self.net(state).chunk(2, dim=-1)
        return torch.tanh(mu)

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

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)
    rng = np.random.default_rng(seed)
    env = make_env(); evaluation = make_env()
    try:
        obs, _ = env.reset(seed=seed); env.action_space.seed(seed)
        low, high = env.action_space.low, env.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')
        od, ad = obs.size, low.size
        actor = Actor(od,ad).to(device)
        q1, q2, t1, t2 = [network(od+ad,1).to(device) for _ in range(4)]
        t1.load_state_dict(q1.state_dict()); t2.load_state_dict(q2.state_dict())
        ao = torch.optim.Adam(actor.parameters(),lr=3e-4)
        qo = torch.optim.Adam(list(q1.parameters())+list(q2.parameters()),lr=3e-4)
        log_alpha = torch.tensor(0., device=device, requires_grad=True)
        alpha_opt = torch.optim.Adam([log_alpha], lr=3e-4)
        target_entropy = -target_factor*ad
        states = np.empty((capacity,od),np.float32); actions = np.empty((capacity,ad),np.float32)
        rewards = np.empty((capacity,1),np.float32); nexts = np.empty_like(states); terms = np.empty_like(rewards)
        history=[]; start=time.perf_counter()
        def tensor(x): return torch.as_tensor(x,dtype=torch.float32,device=device)
        def physical(a): return (low+(a+1)*(high-low)/2).astype(env.action_space.dtype)
        def evaluate():
            results=[]
            for i in range(episodes):
                state,_=evaluation.reset(seed=100000+1000*seed+i); total=0.
                while True:
                    with torch.no_grad(): a=actor.deterministic(tensor(state).unsqueeze(0))[0].cpu().numpy()
                    state,r,term,trunc,_=evaluation.step(physical(a)); total+=float(r)
                    if term or trunc: break
                results.append(total)
            return results
        for step in range(1, steps+1):
            if step <= warmup:
                action = rng.uniform(-1,1,ad).astype(np.float32)
            else:
                with torch.no_grad(): action=actor.sample(tensor(obs).unsqueeze(0))[0][0].cpu().numpy()
            nxt,reward,term,trunc,_=env.step(physical(action))
            ix=(step-1)%capacity
            states[ix]=obs; actions[ix]=action; rewards[ix]=reward; nexts[ix]=nxt; terms[ix]=float(term)
            obs=nxt
            if term or trunc: obs,_=env.reset()
            if step > warmup:
                ix=rng.integers(0,min(step,capacity),size=batch_size)
                s,a,r,ns,d=map(tensor,(states[ix],actions[ix],rewards[ix],nexts[ix],terms[ix]))
                alpha=log_alpha.exp().detach()
                with torch.no_grad():
                    na,nlogp=actor.sample(ns)
                    x=torch.cat((ns,na),-1)
                    target=r+gamma*(1-d)*(torch.minimum(t1(x),t2(x))-alpha*nlogp)
                x=torch.cat((s,a),-1)
                qloss=F.mse_loss(q1(x),target)+F.mse_loss(q2(x),target)
                qo.zero_grad(); qloss.backward(); qo.step()
                for p in list(q1.parameters())+list(q2.parameters()): p.requires_grad_(False)
                pa,logp=actor.sample(s); x=torch.cat((s,pa),-1)
                aloss=(alpha*logp-torch.minimum(q1(x),q2(x))).mean()
                ao.zero_grad(); aloss.backward(); ao.step()
                for p in list(q1.parameters())+list(q2.parameters()): p.requires_grad_(True)
                alpha_loss=-(log_alpha*(logp.detach()+target_entropy)).mean()
                alpha_opt.zero_grad(); alpha_loss.backward(); alpha_opt.step()
                with torch.no_grad():
                    for target_net,online in ((t1,q1),(t2,q2)):
                        for tp,p in zip(target_net.parameters(),online.parameters()): tp.lerp_(p,tau)
                if not torch.isfinite(qloss+aloss+alpha_loss): raise FloatingPointError('Pérdida no finita')
            if step%interval==0:
                ix=rng.integers(0,min(step,capacity),size=batch_size)
                with torch.no_grad(): entropy=float(-actor.sample(tensor(states[ix]))[1].mean())
                returns=evaluate()
                history.append({'step':step,'seconds':time.perf_counter()-start,'alpha':float(log_alpha.exp().detach()),
                                'entropy':entropy,'target_entropy':target_entropy,'returns':returns,
                                'mean_return':float(np.mean(returns))})
                print(env_id,seed,history[-1],flush=True)
        return {'environment':env_id,'seed':seed,'quick':quick,'device':str(device),'steps':steps,
                'gymnasium':gym.__version__,'mujoco':mujoco.__version__,'torch':torch.__version__,'numpy':np.__version__,
                'target_factor':target_factor,'history':history}
    finally:
        env.close(); evaluation.close()

for seed in seeds:
    result=train(seed)
    (out / f'{env_id}-seed{seed}-target{target_factor:g}.json').write_text(json.dumps(result,indent=2),encoding='utf-8')
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Lab: compare custom methods

The next two cells adapt prior lesson programs to the same three environments and one-million-transition budget. Save all reports to a common folder using ORYON_SAC_OUT, ORYON_TD3_OUT and ORYON_PPO_OUT. Run each method for Hopper-v5, Walker2d-v5 and Ant-v5 with the environment variables specified in each program; select ORYON_TD3_CASE=td3 in TD3 and ORYON_PPO_CASE=default in PPO. Each method records five seeds and five evaluation episodes per point with identical evaluation seeds. TD3 supports other conditions, but they are not part of this comparison. PPO supports an optional library branch not used here.

These implementations differ in architecture, normalization and data reuse. PPO uses observation and reward normalization, eight environments and minibatches over rollouts; TD3 and SAC use replay, unnormalized rewards and one environment. Equal transitions and evaluations alone do not isolate a difference’s cause. Time includes evaluation and is comparable only under similar hardware and load. Quick mode shortens episodes to 64 steps for all three, uses one seed and does not support statistical inference.

Before launching long cells, define a common results folder and select a task for each program. In PowerShell, for example, set $env:ORYON_SAC_ENV='Hopper-v5' and $env:ORYON_SAC_OUT='C:\experimentos\sac'; use that same path in ORYON_TD3_OUT, ORYON_PPO_OUT and ORYON_COMPARE_DIR. Change task identifiers in the four corresponding variables to repeat comparison in each environment. Unix-like systems use equivalent variables, for example ORYON_QUICK=1. The folder must be writable and outside results you wish to keep, because repeating a condition with the same seed overwrites its report.

When comparing by samples, one point has the same number of real transitions per method but not the same number of gradient updates. Random warmup also counts as environment interaction. When comparing time, the clock includes evaluation and learning; it does not measure only action inference. Run methods separately on a machine without other intensive jobs if wall time is a study objective. Do not interpret these sample data as a fixed property of the algorithm on every architecture or accelerator.

[ ]Custom TD3 for comparisonLocal GPU
import copy
import json
import os
import random
import time
from pathlib import Path

import gymnasium as gym
import mujoco
import numpy as np
import torch
from torch import nn

torch.set_num_threads(1)
quick = os.environ.get('ORYON_QUICK', '0') == '1'
device = torch.device(os.environ.get('ORYON_TD3_DEVICE', 'cuda' if torch.cuda.is_available() else 'cpu'))
root = Path(os.environ.get('ORYON_TD3_OUT', 'oryon-td3'))
root.mkdir(parents=True, exist_ok=True)
env_names = ('Hopper-v5',)
cases = ('td3',)
env_names = (os.environ['ORYON_TD3_ENV'],) if 'ORYON_TD3_ENV' in os.environ else env_names
cases = (os.environ['ORYON_TD3_CASE'],) if 'ORYON_TD3_CASE' in os.environ else cases
if any(x not in ('Hopper-v5', 'Walker2d-v5', 'Ant-v5') for x in env_names):
    raise ValueError('Entorno desconocido')
if any(x not in ('ddpg', 'td3', 'no_min', 'no_delay', 'no_smoothing') for x in cases):
    raise ValueError('Condición desconocida')
seeds = [0] if quick else list(range(5))
steps, warmup, batch_size, evaluate_every, evaluation_episodes = (1024, 128, 32, 256, 2) if quick else (1_000_000, 10_000, 256, 20_000, 5)
capacity, width = (2048, 64) if quick else (1_000_000, 256)
gamma, tau, target_std, target_clip, exploration_std = .99, .005, .2, .5, .1

class Actor(nn.Module):
    def __init__(self, obs_dim, act_dim):
        super().__init__()
        self.net = nn.Sequential(nn.Linear(obs_dim, width), nn.ReLU(), nn.Linear(width, width), nn.ReLU(), nn.Linear(width, act_dim), nn.Tanh())
    def forward(self, x):
        return self.net(x)

class Critic(nn.Module):
    def __init__(self, obs_dim, act_dim):
        super().__init__()
        self.net = nn.Sequential(nn.Linear(obs_dim + act_dim, width), nn.ReLU(), nn.Linear(width, width), nn.ReLU(), nn.Linear(width, 1))
    def forward(self, obs, act):
        return self.net(torch.cat((obs, act), dim=-1))

class Replay:
    def __init__(self, obs_dim, act_dim):
        self.obs = torch.empty((capacity, obs_dim), device=device)
        self.action = torch.empty((capacity, act_dim), device=device)
        self.next_obs = torch.empty((capacity, obs_dim), device=device)
        self.reward = torch.empty((capacity, 1), device=device)
        self.terminated = torch.empty((capacity, 1), device=device)
        self.pos = 0
        self.size = 0
    def add(self, obs, action, reward, next_obs, terminated):
        self.obs[self.pos] = torch.as_tensor(obs, dtype=torch.float32, device=device)
        self.action[self.pos] = torch.as_tensor(action, dtype=torch.float32, device=device)
        self.next_obs[self.pos] = torch.as_tensor(next_obs, dtype=torch.float32, device=device)
        self.reward[self.pos] = reward
        self.terminated[self.pos] = float(terminated)
        self.pos = (self.pos + 1) % capacity
        self.size = min(capacity, self.size + 1)
    def sample(self):
        ix = torch.randint(self.size, (batch_size,), device=device)
        return self.obs[ix], self.action[ix], self.reward[ix], self.next_obs[ix], self.terminated[ix]

def polyak(online, target):
    with torch.no_grad():
        for p, q in zip(online.parameters(), target.parameters()):
            q.mul_(1 - tau).add_(p, alpha=tau)

def run_one(env_id, case, seed):
    random.seed(seed)
    np.random.seed(seed)
    torch.manual_seed(seed)
    if device.type == 'cuda':
        torch.cuda.manual_seed_all(seed)
    rng = np.random.default_rng(seed)
    env = gym.make(env_id, max_episode_steps=64) if quick else gym.make(env_id)
    test_env = gym.make(env_id, max_episode_steps=64) if quick else gym.make(env_id)
    low, high = env.action_space.low, env.action_space.high
    center, scale = (high + low) / 2, (high - low) / 2
    if not np.all(np.isfinite(low)) or np.any(scale <= 0):
        raise ValueError('Las cotas de acción deben ser finitas y distintas')
    obs_dim, act_dim = env.observation_space.shape[0], env.action_space.shape[0]
    actor = Actor(obs_dim, act_dim).to(device)
    actor_target = copy.deepcopy(actor)
    q1, q2 = Critic(obs_dim, act_dim).to(device), Critic(obs_dim, act_dim).to(device)
    q1_target, q2_target = copy.deepcopy(q1), copy.deepcopy(q2)
    actor_opt = torch.optim.Adam(actor.parameters(), lr=3e-4)
    critic_opt = torch.optim.Adam(list(q1.parameters()) + ([] if case == 'ddpg' else list(q2.parameters())), lr=3e-4)
    replay = Replay(obs_dim, act_dim)

    def action(obs):
        with torch.no_grad():
            return actor(torch.as_tensor(obs, dtype=torch.float32, device=device).unsqueeze(0))[0].cpu().numpy()

    def evaluate():
        episodes = []
        for ep in range(evaluation_episodes):
            obs, _ = test_env.reset(seed=100000 + 1000 * seed + ep)
            with torch.no_grad():
                state = torch.as_tensor(obs, dtype=torch.float32, device=device).unsqueeze(0)
                pred = float(q1(state, actor(state)).item())
            total, discounted, factor, length = 0., 0., 1., 0
            while True:
                unit_action = action(obs)
                obs, reward, terminated, truncated, _ = test_env.step(center + scale * unit_action)
                total += float(reward)
                discounted += factor * float(reward)
                factor *= gamma
                length += 1
                if terminated or truncated:
                    break
            episodes.append({'q_start': pred, 'return': total, 'discounted_return': discounted,
                             'length': length, 'terminated': bool(terminated), 'truncated': bool(truncated)})
        return episodes

    report = {'environment': env_id, 'case': case, 'seed': seed, 'quick': quick,
              'steps': steps, 'warmup': warmup, 'batch_size': batch_size, 'capacity': capacity,
              'width': width, 'gamma': gamma, 'tau': tau, 'target_noise_std': target_std,
              'target_noise_clip': target_clip, 'exploration_std': exploration_std,
              'learning_rate': 3e-4, 'actor_update_delay': 1 if case in ('ddpg', 'no_delay') else 2,
              'device': str(device), 'gymnasium': gym.__version__, 'mujoco': mujoco.__version__,
              'torch': torch.__version__, 'numpy': np.__version__, 'history': []}
    path = root / (env_id + '-' + case + '-seed' + str(seed) + '.json')
    started = time.monotonic()
    try:
        obs, _ = env.reset(seed=seed)
        env.action_space.seed(seed)
        for step in range(1, steps + 1):
            unit_action = rng.uniform(-1, 1, size=act_dim) if step <= warmup else np.clip(action(obs) + rng.normal(0, exploration_std, size=act_dim), -1, 1)
            next_obs, reward, terminated, truncated, _ = env.step(center + scale * unit_action)
            replay.add(obs, unit_action, reward, next_obs, terminated)
            obs = env.reset()[0] if terminated or truncated else next_obs
            if step > warmup and replay.size >= batch_size:
                s, a, r, ns, done = replay.sample()
                with torch.no_grad():
                    next_a = actor_target(ns)
                    if case not in ('ddpg', 'no_smoothing'):
                        noise = (torch.randn_like(next_a) * target_std).clamp(-target_clip, target_clip)
                        next_a = (next_a + noise).clamp(-1, 1)
                    q_target = q1_target(ns, next_a)
                    if case not in ('ddpg', 'no_min'):
                        q_target = torch.minimum(q_target, q2_target(ns, next_a))
                    y = r + gamma * (1 - done) * q_target
                loss = (q1(s, a) - y).square().mean()
                if case != 'ddpg':
                    loss = loss + (q2(s, a) - y).square().mean()
                if not torch.isfinite(loss):
                    raise FloatingPointError('Pérdida de crítico no finita')
                critic_opt.zero_grad(set_to_none=True)
                loss.backward()
                critic_opt.step()
                delay = 1 if case in ('ddpg', 'no_delay') else 2
                if (step - warmup) % delay == 0:
                    for p in q1.parameters():
                        p.requires_grad_(False)
                    actor_loss = -q1(s, actor(s)).mean()
                    if not torch.isfinite(actor_loss):
                        raise FloatingPointError('Pérdida de actor no finita')
                    actor_opt.zero_grad(set_to_none=True)
                    actor_loss.backward()
                    actor_opt.step()
                    for p in q1.parameters():
                        p.requires_grad_(True)
                    polyak(actor, actor_target)
                    polyak(q1, q1_target)
                    if case != 'ddpg':
                        polyak(q2, q2_target)
            if step % evaluate_every == 0 or step == steps:
                episode_data = evaluate()
                elapsed = time.monotonic() - started
                report['history'].append({'step': step, 'elapsed_seconds': elapsed, 'episodes': episode_data})
                path.write_text(json.dumps(report, indent=2, allow_nan=False), encoding='utf-8')
                print(env_id, case, seed, step, 'Q inicial', np.mean([e['q_start'] for e in episode_data]),
                      'retorno descontado observado', np.mean([e['discounted_return'] for e in episode_data]), flush=True)
        torch.save({'actor': actor.state_dict(), 'q1': q1.state_dict(), 'q2': q2.state_dict()}, path.with_suffix('.pt'))
    finally:
        env.close()
        test_env.close()

for env_id in env_names:
    for case in cases:
        for seed in seeds:
            run_one(env_id, case, seed)
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.
[ ]Custom PPO for comparisonLocal GPU
import gc
import json
import math
import time
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', 'Walker2d-v5', 'Ant-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,32) if quick else (8,250,500)
epochs, minibatch = (2,16) if quick else (10,250)
eval_every, eval_episodes = (8,2) if quick else (10,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=[]
        started=time.monotonic()
        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)
                row['elapsed_seconds']=time.monotonic()-started
                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 install rliable in a compatible environment, for example Python 3.11 with NumPy, PyTorch, Gymnasium 1.4, MuJoCo, Matplotlib, pandas<3 and rliable. The cell verifies files, seeds, budget, points, episode counts, device and NumPy, PyTorch, Gymnasium and MuJoCo versions. Shared load and other dependencies can vary even when these match.

First average evaluation episodes for each seed. The curve shows interquartile mean (IQM) of those averages, per task and point, without mixing task scales. In full mode rliable also computes a 95% percentile bootstrap interval for final IQM using 2000 resamples. With five seeds the interval is indicative and can be unstable. The time chart uses mean time per point and does not interpolate returns to a common wall-clock instant; it is a descriptive comparison, not a synchronized interval. ORYON_COMPARE_DIR and ORYON_COMPARE_ENV select folder and task.

The resampling unit is the training run, not each evaluated episode. Two episodes of one policy share learned weights and are not two independent runs. The interval describes uncertainty in the statistic under the resampling procedure, not a guarantee that the best observed policy remains best in another MuJoCo version. Also inspect per-seed values printed with the chart: IQM can hide a rare failure. Individual curves help distinguish a stable method from one with extreme returns, even if central summaries agree.

[ ]Compare with rliableLocal GPU
import json, os
from pathlib import Path
import numpy as np
import matplotlib.pyplot as plt
from rliable import library, metrics

root = Path(os.getenv('ORYON_COMPARE_DIR', 'oryon-sac'))
quick = os.getenv('ORYON_QUICK', '0') == '1'
task = os.getenv('ORYON_COMPARE_ENV', 'Hopper-v5')
if task not in ('Hopper-v5','Walker2d-v5','Ant-v5'):
    raise ValueError('Entorno desconocido')
seeds = [0] if quick else list(range(5))
steps = 1024 if quick else 1_000_000
interval = 256 if quick else 20_000
episodes = 2 if quick else 5
expected = list(range(interval,steps+1,interval))

def read(path):
    if not path.exists(): raise FileNotFoundError('Falta ejecutar el entrenamiento: '+str(path))
    return json.loads(path.read_text(encoding='utf-8'))

def check(report, seed):
    if report['environment'] != task or report['quick'] != quick:
        raise ValueError('Entorno o modo incompatible')
    if 'seed' in report and report['seed'] != seed:
        raise ValueError('Semilla incompatible')

data = {'SAC': [], 'TD3': [], 'PPO': []}
versions, devices = set(), set()
ppo = read(root / ('ppo-'+task+'-default.json'))
check(ppo,0)
if ppo['case'] != 'default' or ppo['seeds'] != seeds:
    raise ValueError('Configuración PPO incompatible')
for seed in seeds:
    sac = read(root / (task+'-seed'+str(seed)+'-target1.json'))
    td3 = read(root / (task+'-td3-seed'+str(seed)+'.json'))
    check(sac,seed); check(td3,seed)
    for report in (sac,td3,ppo):
        versions.add(tuple(report[k] for k in ('gymnasium','mujoco','numpy','torch')))
        devices.add(report['device'])
    if sac['steps'] != steps or sac['target_factor'] != 1 or td3['steps'] != steps or td3['case'] != 'td3':
        raise ValueError('Presupuesto o condición incompatible')
    run = next((x for x in ppo['runs'] if x['seed']==seed and x['method']=='PPO desde cero'),None)
    if run is None: raise ValueError('Falta ejecución PPO desde cero')
    ppo_rows = [x for x in run['history'] if 'evaluation' in x]
    sources = {
        'SAC': [(x['step'],x['seconds'],x['returns']) for x in sac['history']],
        'TD3': [(x['step'],x['elapsed_seconds'],[e['return'] for e in x['episodes']]) for x in td3['history']],
        'PPO': [(x['transitions'],x['elapsed_seconds'],[e['return_raw'] for e in x['evaluation']]) for x in ppo_rows]
    }
    for method, rows in sources.items():
        if [x[0] for x in rows] != expected or any(len(x[2]) != episodes for x in rows):
            raise ValueError('Evaluaciones incompletas en '+method)
        if not all(np.isfinite(x[1]) and np.isfinite(x[2]).all() for x in rows):
            raise ValueError('Resultado no finito')
        data[method].append(rows)

if len(versions) != 1 or len(devices) != 1:
    raise ValueError('Versiones o dispositivos incompatibles')
fig, axes = plt.subplots(1,2,figsize=(10,4))
for method, runs in data.items():
    scores=np.array([[np.mean(row[2]) for row in run] for run in runs])
    times=np.array([[row[1] for row in run] for run in runs])
    curve=np.array([metrics.aggregate_iqm(scores[:,i,None]) for i in range(len(expected))])
    axes[0].plot(expected,curve,label=method)
    axes[1].plot(times.mean(axis=0),curve,label=method)
    print(method, 'retornos finales por semilla:', scores[:,-1], 'segundos por semilla:',times[:,-1])
    if not quick:
        np.random.seed(123)
        estimates, intervals = library.get_interval_estimates(
            {method:scores[:,-1,None]},metrics.aggregate_iqm,reps=2000)
        print('IQM final e intervalo bootstrap 95 %:',estimates[method],intervals[method])
    else:
        print('Prueba corta: sin intervalo entre semillas.')
axes[0].set_xlabel('transiciones')
axes[1].set_xlabel('segundos medios, incluyendo evaluación')
for ax in axes:
    ax.set_ylabel('IQM de retornos por semilla'); ax.legend()
fig.suptitle(task+(' (flujo corto)' if quick else ''))
fig.tight_layout()
plt.show()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

NumericThree actions
For Q = (1, 2, 3) and α = 0.5, calculate α log Σ exp(Q/α).
QuizDual signal
Estimated entropy is below target. Which direction does α take in an ideal dual descent step?
ProofDerive the Boltzmann policy
Prove: For a finite action set and positive α, prove that the Boltzmann policy maximizes expected reward plus α times entropy.
0
Let Z be the sum of exp(Q(a)/α) and p*(a)=exp(Q(a)/α)/Z.

Step 1 of 3. What is log p*(a)?

ProofTabular improvement
Prove: Prove that exact per-state improvement does not decrease soft Q.
0
Assume a finite MDP, bounded rewards, discount below one and exact evaluation of the old policy.

Step 1 of 3. What does exact KL minimization in a state ensure?

CodeSample and log density
Implement sample_and_logprob(mu, log_std): both tensors have shape (N,d). Use Normal.rsample, tanh and the stable correction 2(log(2) − u − softplus(−2u)). Return actions (N,d) and log densities summed across components (N,1).
import torch
def sample_and_logprob(mu, log_std):
  pass
Shift+Enter to run
Key idea
SAC learns a stochastic policy using soft critics and adjusts entropy weight; practical success depends on approximations and careful evaluation.