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 requires solving another optimization at each state. A deterministic actor 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.
The figure is an explicit model of one state and one action: . The first critic adds a Gaussian peak of width 0.32 centered at 1.25; the second is . The point moves 0.08 times the selected slope, clipping action to . 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 be a differentiable policy, , and the expected discounted return from the initial distribution, with . Use an infinite-horizon process including a zero-reward absorbing state after episodic termination. The unnormalized discounted occupancy measure is , with total mass . Define . The deterministic policy gradient theorem of Silver and colleagues states, under their regularity and integrability conditions and for interior actions,
A sufficient formulation for the following development takes compact , actions in , bounded reward and fixed initial density. Assume reward, transition density and their action derivatives are continuous, as are the policy and its Jacobian in ; also require integrable bounds permitting differentiation under the integral, a bounded derivative of , 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 , the corresponding expectation has a factor . 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 actions to the actor’s parameters.
To understand the result, write and differentiate Bellman. The local term and the term appear. Recursively expanding the latter accumulates local terms weighted by ; 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 and let be the policy transition operator. If is differentiable and differentiation and expectation can be exchanged, Bellman gives . If the operator series converges and sum and integral can be exchanged,
Integrating this identity over the initial distribution produces discounted occupancy. This development incorporates how future states change with action through ; it does not assume state distribution is independent of . 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 is replaced with the buffer distribution. Silver and colleagues’ off-policy equation omits a term for dependence of and is an approximation. With a fixed critic, the gradient of empirical objective 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 ; is one only if the next state truly terminates the problem. For a batch, with target parameters denoted by primes,
Target is computed without gradients. When updating the actor, the critic must remain differentiable with respect to input , 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 , and likewise for , with . After updates the initial copy has weight . Half-life in target updates is ; if updates happen every two critic steps, its unit is not a transition.
Unrolling the recurrence shows what is averaged. If is a component of the active network at update , then
Weights are nonnegative and sum to one. For , older values receive less weight; with 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 and , the actor can emit and send . 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 writes , and , with . Marginal variance is and one-step autocorrelation is before action clipping. Independent Gaussian noise corresponds here to .
Scale and persistence matter together. If has variance and is independent of , next-step variance is . Also, . 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.
The figure integrates a toy model from rest with and , using semi-implicit Euler with step 0.05 for 10 time units. Each action is noise clipped to . 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 and , with independent centered Gaussian errors of standard deviation . Since and , the minimum has expectation . 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 critic updates. Delay gives critics more opportunities to fit before the policy moves, without guaranteeing convergence.
The actor still ascends . 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 . 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.
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 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 versus return comparison, evaluate the same policy, initial state and discount. Undiscounted return does not estimate discounted . 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 ; 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 at the initial state, discounted and undiscounted returns, length and termination signals. Recorded time includes evaluation and depends on shared hardware.
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)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.
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()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.
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()npm run lab and open the connection link.Exercises
Step 1 of 4. What is the gradient of the policy log with respect to θ?
import torch
def td3_target(next_obs, rewards, terminated, actor_targ, q1_targ, q2_targ, noise_std, noise_clip, gamma):
passimport 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))