Module contents
Lesson 22 of 37Core 105 min

Off-policy continuous control: deterministic policy gradient, DDPG and TD3

Derive the deterministic policy gradient, build DDPG and TD3, and examine critic errors and their corrections in continuous-action control.

After this lesson you can

  • State the deterministic policy gradient theorem and explain off-policy learning.
  • Implement DDPG and TD3 with replay, Polyak averaging and exploration noise.
  • Explain actor–critic overestimation and TD3's three corrections.
  • Train TD3 on MuJoCo tasks and measure overestimation.
  • Compare on-policy and off-policy methods in sample efficiency and wall-clock time.

Before you start

Finding an action when they cannot be enumerated

In DQN you can compare values of a finite action set. In a robot with several motors, each action is a continuous vector: maximizing Q(s,a)Q(s,a) requires solving another optimization at each state. A deterministic actor μθ(s)\mu_\theta(s) learns to propose an action directly, and a differentiable critic tells it how to change it. The actor does not necessarily find the global maximum: it follows the slope of its critic.

InteractiveThe slope can lead you astray
  • True value
  • Critic 1
  • Minimum of critics
0.90
2.0
Ascend on
True value0.58
Value used1.68
Slope used2.46
Apply ascent steps from the initial action. Reduce the peak or compare with the hypothetical minimum of two critics. Does true value also rise?

The figure is an explicit model of one state and one action: Qreal(a)=1−(a−0.25)2Q_{\mathrm{real}}(a)=1-(a-0.25)^2. The first critic adds a Gaussian peak of width 0.32 centered at 1.25; the second is Qreal+0.03Q_{\mathrm{real}}+0.03. The point moves 0.08 times the selected slope, clipping action to [−2,2][-2,2]. The minimum removes much of the peak in this example, but can have corners and is not necessarily smooth. At the corner the code chooses the first branch’s derivative. This illustrates estimators, not a TD3 run: TD3 uses the minimum in the critic target and updates the actor with the first critic, not the minimum.

The deterministic gradient

Let μθ:S→Rm\mu_\theta:\mathcal S\to\R^m be a differentiable policy, θ∈Rp\theta\in\R^p, and J(θ)J(\theta) the expected discounted return from the initial distribution, with 0<γ<10<\gamma<1. Use an infinite-horizon process including a zero-reward absorbing state after episodic termination. The unnormalized discounted occupancy measure is ρμ(B)=∑t≥0γtP(St∈B∣μ)\rho^\mu(B)=\sum_{t\ge0}\gamma^t\Pr(S_t\in B\mid\mu), with total mass 1/(1−γ)1/(1-\gamma). Define Dθμ(s)∈Rm×pD_\theta\mu(s)\in\R^{m\times p}. The deterministic policy gradient theorem of Silver and colleagues states, under their regularity and integrability conditions and for interior actions,

∇θJ(θ)=∫ρμ( ⁣ds) Dθμθ(s)⊤ ∇aQμ(s,a)∣a=μθ(s).\nabla_\theta J(\theta)=\int \rho^\mu(\dd s)\,D_\theta\mu_\theta(s)\T\,\nabla_a Q^\mu(s,a)\big|_{a=\mu_\theta(s)}.

A sufficient formulation for the following development takes compact S\mathcal S, actions in Rm\R^m, bounded reward and fixed initial density. Assume reward, transition density and their action derivatives are continuous, as are the policy and its Jacobian in θ\theta; also require integrable bounds permitting differentiation under the integral, a bounded derivative of VμV^\mu, and interchange of the discounted series with expectation. The authors’ precise conditions and proof appear in the supplement. These are theorem assumptions, not automatic properties of every simulator with contacts or ReLU network.

If occupancy is normalized as dμ=(1−γ)ρμd^\mu=(1-\gamma)\rho^\mu, the corresponding expectation has a factor 1/(1−γ)1/(1-\gamma). Do not forget it when comparing gradients of objectives expressed using different conventions. The chain rule explains the dimensions: the transposed Jacobian carries the gradient from mm actions to the actor’s pp parameters.

To understand the result, write Vμ(s)=Qμ(s,μθ(s))V^\mu(s)=Q^\mu(s,\mu_\theta(s)) and differentiate Bellman. The local term Dθμ⊤∇aQD_\theta\mu\T\nabla_a Q and the term γE[∇θVμ(S′)∣s,μ(s)]\gamma\E[\nabla_\theta V^\mu(S')\mid s,\mu(s)] appear. Recursively expanding the latter accumulates local terms weighted by γt\gamma^t; averaging initial states gives the occupancy above. The argument requires justification for differentiation under the integral and exchanging series and expectation; a differentiable network alone is not enough.

To expose the step, call gθ(s)=Dθμθ(s)⊤∇aQμ(s,a)∣a=μθ(s)g_\theta(s)=D_\theta\mu_\theta(s)\T\nabla_a Q^\mu(s,a)|_{a=\mu_\theta(s)} and let PμP_\mu be the policy transition operator. If VμV^\mu is differentiable and differentiation and expectation can be exchanged, Bellman gives ∇θVμ=gθ+γPμ∇θVμ\nabla_\theta V^\mu=g_\theta+\gamma P_\mu\nabla_\theta V^\mu. If the operator series converges and sum and integral can be exchanged,

∇θVμ=∑t=0∞γtPμtgθ.\nabla_\theta V^\mu=\sum_{t=0}^{\infty}\gamma^t P_\mu^t g_\theta.

Integrating this identity over the initial distribution produces discounted occupancy. This development incorporates how future states change with action through ∇aQμ\nabla_a Q^\mu; it does not assume state distribution is independent of θ\theta. The cited theorem uses specific technical MDP, derivative and integrability conditions. Action bounds require handling projection or parametrization; at a boundary an ordinary derivative does not describe all feasible directions.

The same result arises as the limit of a Gaussian policy whose variance tends to zero, under assumptions permitting limit and expectation to be exchanged. The guided exercise shows where these enter. A deterministic policy need not explore; experience is collected with a noisy behavior policy and reused via replay. This does not automatically make the formula above an exact gradient when ρμ\rho^\mu is replaced with the buffer distribution. Silver and colleagues’ off-policy equation omits a term for dependence of QμQ^\mu and is an approximation. With a fixed critic, the gradient of empirical objective 1N∑iQϕ(si,μθ(si))\frac1N\sum_i Q_\phi(s_i,\mu_\theta(s_i)) is exactly its chain rule, but optimizes that surrogate on sampled states. Insufficient coverage and critic errors can make it a poor direction for true return.

DDPG: actor, critic and slow targets

DDPG, proposed by Lillicrap and colleagues, combines an actor and critic with replay and target networks. The buffer stores (s,a,r,s′,d)(s,a,r,s',d); dd is one only if the next state truly terminates the problem. For a batch, with target parameters denoted by primes,

y=r+γ(1−d)Qϕ′(s′,μθ′(s′)),LQ=ED[(Qϕ(s,a)−y)2],Lμ=−Es∼D[Qϕ(s,μθ(s))].y=r+\gamma(1-d)Q_{\phi'}(s',\mu_{\theta'}(s')),\qquad L_Q=\E_{\mathcal D}[(Q_\phi(s,a)-y)^2],\qquad L_\mu=-\E_{s\sim\mathcal D}[Q_\phi(s,\mu_\theta(s))].

Target yy is computed without gradients. When updating the actor, the critic must remain differentiable with respect to input aa, but its parameters are frozen so the actor optimizer does not update them. Separate optimizers are insufficient if accumulated gradients are accidentally used. Both target networks are initialized by copying active networks, then slowly updated by Polyak averaging ϕ′←(1−τ)ϕ′+τϕ\phi'\leftarrow(1-\tau)\phi'+\tau\phi, and likewise for θ′\theta', with 0<τ≤10<\tau\le1. After kk updates the initial copy has weight (1−τ)k(1-\tau)^k. Half-life in target updates is log⁡(1/2)/log⁡(1−τ)\log(1/2)/\log(1-\tau); if updates happen every two critic steps, its unit is not a transition.

Unrolling the recurrence shows what is averaged. If wiw_i is a component of the active network at update ii, then

wk′=(1−τ)kw0′+τ∑i=1k(1−τ)k−iwi.w'_k=(1-\tau)^k w'_0+\tau\sum_{i=1}^{k}(1-\tau)^{k-i}w_i.

Weights are nonnegative and sum to one. For 0<τ<10<\tau<1, older values receive less weight; with τ=1\tau=1 copying is immediate and the logarithmic half-life formula must be treated separately. Smoothing parameters is not generally equivalent to averaging outputs of a nonlinear network. It also does not correct systematic critic bias: it only changes target dynamics.

In an environment with vector bounds ll and hh, the actor can emit u=tanh⁡(z)∈[−1,1]mu=\tanh(z)\in[-1,1]^m and send a=l+(h−l)(u+1)/2a=l+(h-l)(u+1)/2. Store the action the environment actually received in the buffer. During an initial phase use random actions inside bounds; then add exploration noise to the actor and clip again. Behavior noise is not the noise TD3 adds to the target, nor should it appear in deterministic-policy evaluation.

Independent and correlated noise

DDPG used Ornstein–Uhlenbeck (OU) noise. An exact stationary discretization with step Δt\Delta t writes xt+1=ρxt+σ1−ρ2 ξtx_{t+1}=\rho x_t+\sigma\sqrt{1-\rho^2}\,\xi_t, ξt∼N(0,1)\xi_t\sim\Normal(0,1) and ρ=e−κΔt\rho=e^{-\kappa\Delta t}, with x0∼N(0,σ2)x_0\sim\Normal(0,\sigma^2). Marginal variance is σ2\sigma^2 and one-step autocorrelation is ρ\rho before action clipping. Independent Gaussian noise corresponds here to ρ=0\rho=0.

Scale and persistence matter together. If xtx_t has variance σ2\sigma^2 and is independent of ξt\xi_t, next-step variance is ρ2σ2+(1−ρ2)σ2=σ2\rho^2\sigma^2+(1-\rho^2)\sigma^2=\sigma^2. Also, Cov⁡(xt,xt+k)=σ2ρk\Cov(x_t,x_{t+k})=\sigma^2\rho^k. With inertia, a force retaining its sign can accumulate velocity even when its instantaneous variance equals independent noise. Action clipping changes both distributions and can create mass at the bounds, so the variance equality holds only before clipping.

InteractiveInertia and temporal correlation
  • i.i.d. Gaussian
  • Discretized OU
0.90
0.8
0.00 s
i.i.d. angular range (rad)1.23
Correlated angular range (rad)8.80
Run both pendulums and change noise correlation and standard deviation. Compare trajectories using the same innovation sequence and observe angular range.

The figure integrates a toy model from rest with θ˙=ω\dot\theta=\omega and ω˙=−sin⁡θ−0.15ω+u\dot\omega=-\sin\theta-0.15\omega+u, using semi-implicit Euler with step 0.05 for 10 time units. Each action uu is noise clipped to [−2,2][-2,2]. Both curves share deterministic Gaussian innovations and the same marginal standard deviation before clipping. One trajectory does not prove which explorer is better: change horizon, system or seeds and compare coverage and performance. In their experiments, Fujimoto and colleagues report no improvement from OU over independent noise; this is not a universal law.

Why the actor exploits the critic and what TD3 changes

If the critic has positive error at an action, the actor can move toward that error. Maximization selects high estimates, analogously to maximization bias in double Q-learning, but now the optimizer is a network and actor and critic errors are coupled. Two critics are not magically independent: they share data, targets and policy. Taking their minimum can reduce overestimation, although it also introduces downward bias.

In an idealized case, suppose two critics at a fixed action are Q+ε1Q+\eps_1 and Q+ε2Q+\eps_2, with independent centered Gaussian errors of standard deviation σ\sigma. Since min⁡(x,y)=(x+y−∣x−y∣)/2\min(x,y)=(x+y-|x-y|)/2 and ε1−ε2∼N(0,2σ2)\eps_1-\eps_2\sim\Normal(0,2\sigma^2), the minimum has expectation Q−σ/πQ-\sigma/\sqrt{\pi}. This concretely demonstrates the cost of caution: even individually unbiased critics give a downward-biased minimum. For correlated, biased or action-dependent errors that value does not apply; the minimum is not a guaranteed bound on true value.

TD3 introduces three coordinated changes. First it maintains two critics and uses the minimum of their target networks. Second it perturbs the target action with clipped Gaussian noise and projects to the bounds: this averages targets in a neighborhood and makes narrow peaks harder to exploit, without guaranteeing exact smoothness. Third it updates the actor and target networks only every dd critic updates. Delay gives critics more opportunities to fit before the policy moves, without guaranteeing convergence.

a~′=clip⁡ ⁣(μθ′(s′)+clip⁡(ε,−c,c),l,h),y=r+γ(1−d)min⁡i=1,2Qϕi′(s′,a~′).\tilde a'=\operatorname{clip}\!\left(\mu_{\theta'}(s')+\operatorname{clip}(\eps,-c,c),l,h\right),\quad y=r+\gamma(1-d)\min_{i=1,2}Q_{\phi_i'}(s',\tilde a').

The actor still ascends Qϕ1(s,μθ(s))Q_{\phi_1}(s,\mu_\theta(s)). The two noises have different roles: one collects actions; the other changes only the training target. The original paper uses, in its action units, target standard deviation 0.2, clipping 0.5, delay 2 and τ=0.005\tau=0.005. Its protocol uses a million steps and ten seeds. In table 2 for Hopper-v1, TD3 obtains mean return 3304.75 versus 2407.42 without delay, 2392.59 without smoothing and 1837.32 without the minimum; these are averages over the last ten evaluations and ten trials, not Hopper-v5 results or universal isolated effects. In HalfCheetah-v1, removing the minimum gives 9792.80 versus 9532.99 for TD3: each component’s importance depends on task and metric.

InteractiveCritic and return: a short test
  • Critic at start
  • Observed discounted return
Final Q − return gap−30.81
Episodes per point2
Truncated at last point0
Choose DDPG, TD3 or an ablation. Compare initial Q prediction with observed discounted return, bearing in mind the small episode count.

Data are from a short local run of the next lab on Hopper-v5, CPU with Gymnasium 1.4 and MuJoCo 4.0.1. Each condition uses training seed 0, 1024 transitions, 128 initial random actions, batch 32 and a two-layer network of 64 units. At each point two deterministic-policy episodes are evaluated with seeds 100000 + episodio (where episodio is the episode number) and discount 0.99; lines are means of Q1(s0,μ(s0))Q_1(s_0,\mu(s_0)) and those episodes’ discounted return. None was truncated in this run. The difference is a noisy diagnostic with only two episodes, not a precise bias estimate or statistical method comparison. Original files include each episode; the full lab can be repeated with more seeds and episodes. If an episode ends due to an external limit, observed return is censored while the critic still includes bootstrap, so the difference no longer compares exactly the same horizon.

For a meaningful QQ versus return comparison, evaluate the same policy, initial state and discount. Undiscounted return does not estimate discounted QQ. Repeating episodes from an initial distribution estimates a mean under that distribution but does not measure error uniformly over the buffer. One positive difference can be episode randomness; record each pair, repeat training runs and examine negative differences and truncations too. In a deterministic simulator, initial-state and seed diversity must be designed deliberately.

Engineering and comparison

In MuJoCo, record version, action scale, simulation step and termination conditions. External truncation is not physical termination: retain bootstrap with the actual final observation. Updates per transition and buffer size change how often each sample is reused. Observation or reward normalization also changes the experiment; freeze its statistics in evaluation.

To compare with PPO, fix environments, evaluation seeds, transition counts and tuning budget, following the evaluation methodology. Report curves against transitions and wall-clock time, including device and training cost. PPO consumes a rollout for several epochs then discards it; TD3 reuses replay and usually updates throughout interaction. A sample-efficiency advantage does not mean the same method is faster in seconds or that an observed difference identifies one cause.

Lab: DDPG, TD3 and ablations

The next program implements actor and critics from scratch in PyTorch. The circular buffer resides on the chosen device, including GPU if available. Policy and buffer use normalized actions in [−1,1][-1,1]; affine scaling is applied only when calling the environment. Critics receive the normalized action actually executed. Bootstrap is zeroed for terminated, not truncated; the next observation after truncation is saved before reset.

Full mode trains five seeds per condition and environment, one million transitions each, with 10000 initial random actions. Restrict work using ORYON_TD3_ENV and ORYON_TD3_CASE, which accept the code’s options. ORYON_TD3_DEVICE selects cpu or cuda and ORYON_TD3_OUT the output directory. ORYON_QUICK=1 reduces this to one seed, 1024 transitions and two evaluation episodes per point: it checks the pipeline, not reproduces the benchmark. Install PyTorch, NumPy, Gymnasium 1.4 and MuJoCo; for HalfCheetah-v5 use Gymnasium’s MuJoCo dependency. This program needs no data from other lessons.

Explicit parameters are rate 0.0003, discount 0.99, exploration noise 0.1, target noise 0.2 clipped to 0.5, and Polyak 0.005. TD3 and its ablations use two critics, DDPG one. The actor updates every two critic steps except in DDPG and the no-delay ablation. Each evaluation report retains per-episode Q1Q_1 at the initial state, discounted and undiscounted returns, length and termination signals. Recorded time includes evaluation and depends on shared hardware.

[ ]Train and evaluate DDPG and TD3Local 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', 'HalfCheetah-v5')
cases = ('ddpg', 'td3', 'no_min', 'no_delay', 'no_smoothing')
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', 'HalfCheetah-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, 25_000, 10)
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)
    test_env = 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.

Compare with Stable-Baselines3

The next cell trains Stable-Baselines3 TD3 with the same seeds, tasks, transitions, main parameters, network size, random phase and evaluation frequency as the previous program. It was tested with Stable-Baselines3 2.9.2. To include library PPO as well, enable ORYON_COMPARE_PPO=1. Evaluation uses a separate environment and the same evaluation seeds per training run.

Matching main hyperparameters does not make implementations identical: initialization, replay storage and optimizer details can differ. Custom replay is on the selected device; SB3 uses its own implementation. Do not attribute a difference in seconds solely to the algorithm. In SB3 the TD3 callback runs when collecting a transition, before the associated update; the custom program evaluates afterward. This cell’s PPO uses rollouts of 64 and four epochs, not the same policy or normalization as the prior lesson’s continuous PPO. Its callback can evaluate during rollout collection, before the next update. In both cases the final file saved after learn can contain an update after the callback’s last evaluation: do not automatically attribute that last return to the file. Both programs’ times include evaluations and may vary with shared load.

[ ]Stable-Baselines3 TD3 and PPOLocal GPU
import json
import os
import time
from pathlib import Path
import gymnasium as gym
import numpy as np
import stable_baselines3 as sb3
import torch
import mujoco
from stable_baselines3.common.callbacks import BaseCallback
from stable_baselines3.common.noise import NormalActionNoise

torch.set_num_threads(1)
quick = os.environ.get('ORYON_QUICK', '0') == '1'
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)
tasks = (os.environ['ORYON_TD3_ENV'],) if 'ORYON_TD3_ENV' in os.environ else ('Hopper-v5', 'HalfCheetah-v5')
if any(task not in ('Hopper-v5', 'HalfCheetah-v5') for task in tasks):
    raise ValueError('Entorno desconocido')
seeds = [0] if quick else list(range(5))
steps, warmup, batch_size, every, episodes = (1024, 128, 32, 256, 2) if quick else (1_000_000, 10_000, 256, 25_000, 10)
capacity, width = (2048, 64) if quick else (1_000_000, 256)
methods = ('TD3', 'PPO') if os.environ.get('ORYON_COMPARE_PPO', '0') == '1' else ('TD3',)

class EvaluateCallback(BaseCallback):
    def __init__(self, env_id, seed, started):
        super().__init__()
        self.env_id, self.seed, self.started = env_id, seed, started
        self.history = []
    def _on_step(self):
        if self.num_timesteps % every:
            return True
        env = gym.make(self.env_id)
        rows = []
        try:
            for episode in range(episodes):
                obs, _ = env.reset(seed=100000 + 1000 * self.seed + episode)
                total, discounted, factor, length = 0., 0., 1., 0
                while True:
                    action, _ = self.model.predict(obs, deterministic=True)
                    obs, reward, terminated, truncated, _ = env.step(action)
                    total += float(reward)
                    discounted += factor * float(reward)
                    factor *= .99
                    length += 1
                    if terminated or truncated:
                        break
                rows.append({'return': total, 'discounted_return': discounted, 'length': length,
                             'terminated': bool(terminated), 'truncated': bool(truncated)})
        finally:
            env.close()
        self.history.append({'step': self.num_timesteps, 'elapsed_seconds': time.monotonic() - self.started,
                             'episodes': rows})
        return True

for task in tasks:
    for method in methods:
        for seed in seeds:
            env = gym.make(task)
            try:
                if method == 'TD3':
                    action_dim = env.action_space.shape[0]
                    action_noise = NormalActionNoise(mean=np.zeros(action_dim), sigma=np.full(action_dim, .1))
                    model = sb3.TD3('MlpPolicy', env, learning_rate=3e-4, buffer_size=capacity,
                        learning_starts=warmup, batch_size=batch_size, tau=.005, gamma=.99,
                        train_freq=(1, 'step'), gradient_steps=1, action_noise=action_noise,
                        policy_delay=2, target_policy_noise=.2, target_noise_clip=.5,
                        policy_kwargs={'net_arch': [width, width]}, seed=seed, device=device, verbose=0)
                else:
                    model = sb3.PPO('MlpPolicy', env, learning_rate=3e-4, n_steps=64,
                        batch_size=64, n_epochs=4, gamma=.99, gae_lambda=.95,
                        policy_kwargs={'net_arch': [width, width]}, seed=seed, device=device, verbose=0)
                started = time.monotonic()
                callback = EvaluateCallback(task, seed, started)
                model.learn(total_timesteps=steps, callback=callback)
                path = root / ('SB3-' + method + '-' + task + '-seed' + str(seed) + '.json')
                result = {'method': method, 'environment': task, 'seed': seed, 'quick': quick,
                          'steps': model.num_timesteps, 'sb3': sb3.__version__, 'gymnasium': gym.__version__,
                          'numpy': np.__version__, 'torch': torch.__version__, 'mujoco': mujoco.__version__,
                          'device': str(device), 'evaluation_seed': '100000 + 1000 * seed + episode',
                          'history': callback.history}
                path.write_text(json.dumps(result, indent=2, allow_nan=False), encoding='utf-8')
                model.save(path.with_suffix('.zip'))
                print('SB3', method, task, seed, 'pasos', model.num_timesteps,
                      'evaluaciones', len(callback.history), flush=True)
            finally:
                env.close()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The next cell reads reports from custom TD3 and SB3, validates environment, seeds, budget and evaluation points, and plots return against transitions and elapsed time. It includes PPO if enabled. In the time chart each point averages seed times and returns at the same transition count: it does not directly estimate mean return at a common clock time. One seed in quick mode cannot estimate between-run variability. Retain per-seed data and apply the prior lesson’s intervals for full analysis; curves show means, not uncertainty.

[ ]Sample and wall-clock curvesLocal GPU
import json
import os
from pathlib import Path
import numpy as np
import matplotlib.pyplot as plt

root = Path(os.environ.get('ORYON_TD3_OUT', 'oryon-td3'))
quick = os.environ.get('ORYON_QUICK', '0') == '1'
tasks = (os.environ['ORYON_TD3_ENV'],) if 'ORYON_TD3_ENV' in os.environ else ('Hopper-v5', 'HalfCheetah-v5')
seeds = [0] if quick else list(range(5))
budget, every, episodes = (1024, 256, 2) if quick else (1_000_000, 25_000, 10)
methods = ['TD3 propio', 'TD3 SB3'] + (['PPO SB3'] if os.environ.get('ORYON_COMPARE_PPO', '0') == '1' else [])
for task in tasks:
    data = {}
    versions = set()
    devices = set()
    for method in methods:
        runs = []
        for seed in seeds:
            if method == 'TD3 propio':
                path = root / (task + '-td3-seed' + str(seed) + '.json')
            else:
                name = 'TD3' if method == 'TD3 SB3' else 'PPO'
                path = root / ('SB3-' + name + '-' + task + '-seed' + str(seed) + '.json')
            if not path.exists():
                raise FileNotFoundError('Falta el informe ' + str(path) + '; ejecuta primero las celdas anteriores con TD3 seleccionado')
            report = json.loads(path.read_text(encoding='utf-8'))
            if report['environment'] != task or report['seed'] != seed or report['quick'] != quick or report['steps'] != budget:
                raise ValueError('Protocolo incompatible en ' + str(path))
            if method == 'TD3 propio' and report.get('case') != 'td3':
                raise ValueError('El informe propio no es TD3: ' + str(path))
            if method != 'TD3 propio' and report.get('method') != ('TD3' if method == 'TD3 SB3' else 'PPO'):
                raise ValueError('El método de SB3 no coincide: ' + str(path))
            versions.add((report['gymnasium'], report['mujoco'], report['numpy'], report['torch']))
            devices.add(report['device'])
            history = report['history']
            if [h['step'] for h in history] != list(range(every, budget + 1, every)):
                raise ValueError('Evaluaciones incompletas en ' + str(path))
            if any(len(h['episodes']) != episodes for h in history):
                raise ValueError('Episodios incompletos en ' + str(path))
            runs.append(history)
        data[method] = runs
    if len(versions) != 1:
        raise ValueError('Versiones de librerías distintas')
    if len(devices) != 1:
        raise ValueError('Dispositivos distintos')
    fig, axes = plt.subplots(1, 2, figsize=(10, 3.5))
    for method, runs in data.items():
        x = [h['step'] for h in runs[0]]
        y = np.array([[np.mean([e['return'] for e in h['episodes']]) for h in run] for run in runs])
        seconds = np.array([[h['elapsed_seconds'] for h in run] for run in runs])
        axes[0].plot(x, y.mean(axis=0), label=method)
        axes[1].plot(seconds.mean(axis=0), y.mean(axis=0), label=method)
        print(task, method, 'retornos finales por semilla:', y[:, -1],
              'pasos por segundo con evaluación:', budget / seconds[:, -1])
    axes[0].set_xlabel('transiciones'); axes[1].set_xlabel('segundos con evaluación')
    for ax in axes:
        ax.set_ylabel('retorno no descontado'); ax.legend()
    fig.suptitle(task + (' (prueba corta)' 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 Polyak updates
A target-network component starts at 0. The active-network component successively takes values 1, 2 and 3; update the target after each value with τ=0.005. What is its final value?
NumericDiscrete half-life
With τ=0.005, what is the smallest integer number of target updates after which the initial copy's weight is at most 0.5?
ProofFrom a Gaussian to a deterministic policy
Prove: Under the stated regularity assumptions, the gradient of a fixed-variance Gaussian policy tends to the deterministic gradient as σ tends to zero.
0
Work with actions on the entire real line, πσ(a|s)=N(μθ(s),σ²). Assume each Gaussian policy's action derivative of Q exists and the following limits, integrals and expectations can be exchanged; occupancy and the Q derivative converge to those of μ.

Step 1 of 4. What is the gradient of the policy log with respect to θ?

QuizA slower actor
What is TD3's actor delay intended to do when the critic is very noisy?
CodeTD3 target
Implement td3_target(next_obs, rewards, terminated, actor_targ, q1_targ, q2_targ, noise_std, noise_clip, gamma). Actor actions are normalized to [-1,1]; rewards and terminated have shape (N,1), critics receive observations and actions and return (N,1). Generate noise using torch.randn_like on actor output, multiply by noise_std, clip to [-noise_clip,noise_clip], then clip the action to [-1,1]. Return rewards + gamma(1-terminated)min(q1,q2), without connecting the result to the computation graph. terminated is boolean; external truncation must not be passed as termination.
import torch
def td3_target(next_obs, rewards, terminated, actor_targ, q1_targ, q2_targ, noise_std, noise_clip, gamma):
  pass
Shift+Enter to run
[ ]Check Polyak averagingBrowser
import math
tau = .005
target = 0.
for online in (1., 2., 3.):
    target = (1 - tau) * target + tau * online
half_life = math.log(.5) / math.log(1 - tau)
print('objetivo:', target, 'semivida:', half_life, 'entero:', math.ceil(half_life))
print('sesgo del mínimo con sigma=1:', -1 / math.sqrt(math.pi))

Summary

Key idea
A deterministic actor ascends a critic’s slope. TD3 controls several target-error sources, but neither replay nor two critics guarantee that slope improves true return.