A custom MuJoCo environment with domain randomization
Design a custom robotic-arm pushing environment in MJCF from an open model, with sensors, actuators and a Gymnasium class; use potential-based reward shaping and domain randomization, then train with PPO or SAC and evaluate robust success.
After this lesson you can
- Write the MJCF model and environment class with its API checker.
- Design dense and success reward terms and check that the optimum matches the task.
- Add randomization of masses, friction, starting positions and sensor noise.
- Train to a high success rate and measure it with and without randomization.
Before you start
An objective is not a reward
In previous lessons the environment was given. Now decide what constitutes the task: an arm must reach a disk and push it to a goal on the table. The simulator returns positions, velocities and contacts, but none alone says whether the task is complete. Define success observably and testably outside the reward function: measure distance from disk to goal, state a tolerance and check the condition in independent episodes.
A custom MuJoCo environment combines a physical model with an interaction contract. The model describes bodies, masses, joints, contact geometries and actuators. The Gymnasium class declares spaces, resets state, applies an action for a fixed number of physics steps and returns observation, reward, termination, truncation and auxiliary information. Termination belongs to the problem; truncation means the observation horizon expired. The distinction also determines when to bootstrap, as seen in SAC.
The lab uses the free Panda model from MuJoCo Menagerie pinned to a revision. The tip acts on a simulated disk; actuators track joint positions. A small Cartesian command becomes a joint correction using the Jacobian. Damped inverse kinematics, , avoids directly inverting a potentially singular matrix; it does not remove joint limits or guarantee obstacle avoidance.
The policy action has two components between −1 and 1. In this experiment it is interpreted as desired displacement in the table plane; the controller maintains tip height and translates displacement into joint positions. This is a control interface, not a force applied directly to the disk. A control step groups several MuJoCo integrator steps: changing that count changes action duration and requires reviewing reward scale and horizon.
The observation combines tip, disk and goal positions, relative distances, velocities and joint state. The policy must know where the goal and disk are, but position alone does not reveal velocity. In a contact task, geometrically similar observations can evolve differently when velocities differ. If you hide a quantity, state explicitly that the problem may become partially observable and consider observation history or a policy with memory.
The damped correction also has an optimization interpretation: for it seeks a small joint change approximating the requested displacement, balancing and . More damping prevents very large changes near a singularity but can leave more Cartesian error. Joint values are then clipped to their limits, changing executed displacement again. The policy learns from the action actually produced by this chain of controller and simulator, not an ideal Cartesian translation.
Before training, check three layers separately: meshes and joints load, a fixed command moves the tip in the intended direction, and contact can move the disk. If the first fails, the optimizer has no learning problem to solve; if the second or third fails, a flat return curve may result from an ineffective action. Also check that observations stay within the declared space and that reset with a fixed seed is reproducible.
The integration sequence diagnoses more finely than one smoke test. Compare tip position before and after a small command along each axis; then place the disk in its path and record tip-disk separation, disk velocity and contact time. If the tip moves but the disk does not, inspect geometries and collision filters. If both move but goal distance does not decrease, inspect push direction and duration. These tests do not certify policy learning: they establish useful task transitions before spending the training budget.
The 100-action limit is also part of the contract. At 25 physics steps per action, each episode lasts at most 2500 integrator steps; duration in seconds depends on the XML timestep. Doubling substeps without changing the action limit doubles available simulated time and makes each command act longer. Comparing success rates afterward as though only the agent changed would conflate two tasks. Record XML, physics step, control frequency and horizon with each checkpoint.
Dense reward without changing the objective
Reward design separates the base reward expressing the task from the signal guiding exploration. Negative distance seems reasonable, but a policy can obtain good reward by staying near the disk without moving it to the goal. Record success, final distance, contacts and actions separately; total reward does not replace those measurements.
One construction with an explicit guarantee is potential-based shaping. For a discounted MDP, , bounded potential and base reward , add
In an episodic task stopping at , treat the terminal state as absorbing with zero potential. For example, outside the terminal define , with positive constants and distances bounded in the valid region. The base objective remains reaching the goal; distances provide an intermediate signal. The shaping factor must match the agent’s discount.
Proof
The discounted sum of the added term through telescopes:
If , exactly remains, identical for every decision from that state. In an infinite horizon, the final term tends to zero by boundedness and strict discounting. An artificial truncation is not necessarily a task terminal: do not zero its potential or future value merely because the collector cut the trajectory. The original guarantee is studied by Ng, Harada and Russell.
∎Invariance does not mean every approximate training run reaches the same policy. Exploration, gradient scale and value approximation can change substantially. Nor does it protect against an incorrect base specification: if the goal is wrong, preserving its optimum preserves the error. The lab uses distance without explicit clipping; the infinite-horizon proof requires verifying distances are bounded or replacing them with a bounded function. The finite telescoping calculation remains valid for each trajectory if the terminal is treated as stated.
To check the calculation, imagine two transitions with and potentials , , . The shaping terms are and : their discounted sum is , exactly . If the episode is merely cut at , the partial sum is , not ; remaining potential belongs to the state from which to continue or bootstrap. Treating that cut as terminal success or failure changes the problem.
Randomize with a testable hypothesis
Domain randomization samples simulator parameters on reset: mass, friction, initial positions or sensor noise. It does not make every policy generalize: it changes the training distribution. Keep a nonrandomized control with the same algorithm and budget, and hold out physical conditions and seeds for evaluation. Tobin and colleagues applied the idea to visual properties to train an object detector on simulated images and transfer it to real images. That perception result alone does not show that randomizing dynamics improves our pushing policy.
Mass and inertia must change consistently. If density of a fixed-geometry body is uniformly multiplied by , both mass and moments of inertia multiply by . To vary friction inspect the effective contact: MuJoCo combines both geometries’ properties according to priority and mixing rules. With equal priority it takes the component-wise maximum. Changing a parameter that never dominates contact may leave dynamics unchanged even if the recorded number changes.
First test a fixed action under two configurations and compare trajectories. Then train and evaluate frozen policies on a held-out grid. For each point retain individual successes and calculate intervals; multiple evaluations of one policy do not replace independent training runs. If a randomization region makes the task impossible, falling success can reflect task definition rather than algorithm capacity.
An empirical rate needs a denominator. If a policy succeeds 30 times in 30 episodes, the observed rate is 100%, but the approximate two-sided 95% Wilson interval has a lower endpoint around 88.6%. Exceeding 90% in the sample and showing with that interval that probability exceeds 90% are different claims. The interval describes episode variation under the fixed protocol; it excludes variation among policies trained with other seeds and does not cover unsampled physical conditions.
At sample extremes the calculation is simple. For successes in trials, the Wilson lower endpoint is ; for zero successes the upper endpoint is , where for a two-sided 95% interval. With the endpoints are 0.8865 and 0.1135. This approximation uses a binomial model of independent episodes with equal success probability: retain the seed selection procedure and avoid interpreting the interval as coverage for new conditions or other policies.
n = 30
z = 1.959963984540054
wilson_lower = n / (n + z*z) # caso especial: 30 éxitos de 30
print('tasa observada:', 30 / n)
print('límite inferior Wilson bilateral 95 %:', round(wilson_lower, 4))
print('límite superior para 0 éxitos de 30:', round(1 - wilson_lower, 4))Separate interventions to understand them. Fix friction and vary mass, then fix mass and vary friction, and finally evaluate combinations. Improvement under both changes together does not identify which caused it. Also, a condition inside the training range measures interpolation in that distribution; one outside measures extrapolation and must be labeled separately. Using test results to reselect ranges turns that set into validation, so another held-out set is needed for final evaluation.
To compare policies, use the same evaluation seed list and retain both results under each initial condition. Paired differences exploit the common starting distribution, although trajectories diverge with different actions. Also describe individual rates: a small difference can conceal that both agents almost always fail. When training is repeated, the independent unit for algorithm stability is the training seed; episodes of one policy share weights and must not be presented as independent runs.
Observation noise is a different intervention from friction. The former changes policy input while the success criterion checks physical state; the latter changes system evolution even if observation is exact. Evaluate them separately before combining them. The randomized training range here is a simulator hypothesis, not a measurement of a particular robot. Real transfer would require measuring relevant uncertainty and checking conditions the simulator may omit, such as deformation, latency or calibration.
Before training, a programmed controller can serve as a task integration test. In our own check with 30 new diagnostic seeds, the two-phase controller reached the goal 30 times under nominal physics, with mass 0.25× or 2×, and with friction 2×; with friction 0.25× it succeeded zero times. This failure identifies a condition worth inspecting, not proof of physical impossibility. Nor is it a SAC success rate: the learned policy must be evaluated separately with its own checkpoints and held-out seeds.
Lab model and environment
The reference model is downloaded from the pinned revision if absent. ORYON_PANDA_DIR can reuse the robotics module folder. The cell checks the XML hash and records all mesh hashes in a local manifest to identify the files used exactly. Mesh hashes record identity but alone do not prove that a preexisting copy matches the source: compare the manifest against a verified copy of that revision if needed. This task’s XML adds a free disk and a sphere at the tip. To isolate pushing contact, it disables other arm collisions: this simplification means it is neither a safety model nor an obstacle-avoidance evaluation.
import hashlib, json, os, urllib.request, xml.etree.ElementTree as ET
from pathlib import Path
import numpy as np
import gymnasium as gym
import mujoco
PANDA = Path(os.environ.get('ORYON_PANDA_DIR', 'oryon-panda-model')).expanduser()
PANDA.mkdir(parents=True, exist_ok=True)
base = 'https://raw.githubusercontent.com/google-deepmind/mujoco_menagerie/822c2d8f877dd166c5b7d3c9f7e3c3b6589473b7/franka_emika_panda/'
xml = PANDA / 'panda.xml'
if not xml.exists(): urllib.request.urlretrieve(base + 'panda.xml', xml)
if hashlib.sha256(xml.read_bytes()).hexdigest() != '96ad67da03710f17f798c9478fd9e9efdf24a3bf8359f05e456dd9fb158ea273':
raise ValueError('El XML no coincide con la revisión fijada')
tree = ET.parse(xml)
files = [xml]
for mesh in tree.findall('.//asset/mesh'):
filename = mesh.get('file')
if filename:
dest = PANDA / 'assets' / filename
dest.parent.mkdir(parents=True, exist_ok=True)
if not dest.exists(): urllib.request.urlretrieve(base + 'assets/' + filename, dest)
files.append(dest)
files = sorted(set(files))
manifest = {str(p.relative_to(PANDA)): hashlib.sha256(p.read_bytes()).hexdigest() for p in files}
(PANDA / 'atlas-manifest.json').write_text(json.dumps(manifest, indent=2), encoding='utf-8')
print('modelo fijado, archivos identificados:', len(files), '| MuJoCo', mujoco.__version__)npm run lab and open the connection link.The task plane is horizontal. The action has two components in requesting Cartesian tip increments; the controller converts them into bounded joint targets. The observation contains relative positions, disk velocity, joint positions, velocities and commands. Randomized mode adds noise to observed positions, not the physical state determining success. Terminal state requires the disk within 3 cm of the goal; the horizon causes truncation, not termination.
def make_panda_model():
tree = ET.parse(PANDA / 'panda.xml')
tree.find('compiler').set('meshdir', (PANDA / 'assets').resolve().as_posix())
key = tree.find('keyframe')
tree.getroot().remove(key)
world = tree.find('worldbody')
for geom in world.findall('.//geom'):
geom.set('contype', '0'); geom.set('conaffinity', '0')
ET.SubElement(world, 'geom', {'name': 'floor', 'type': 'plane', 'size': '2 2 .1', 'friction': '.01 .005 .0001'})
puck = ET.SubElement(world, 'body', {'name': 'puck', 'pos': '.5 0 .025'})
ET.SubElement(puck, 'freejoint', {'name': 'puck_joint'})
ET.SubElement(puck, 'geom', {'name': 'puck_geom', 'type': 'cylinder', 'size': '.025 .025',
'mass': '.1', 'friction': '1 .005 .0001'})
hand = tree.find(".//body[@name='hand']")
ET.SubElement(hand, 'geom', {'name': 'pusher', 'type': 'sphere', 'pos': '0 0 .12', 'size': '.025', 'mass': '.01'})
ET.SubElement(hand, 'site', {'name': 'push_tip', 'pos': '0 0 .12', 'size': '.01'})
return mujoco.MjModel.from_xml_string(ET.tostring(tree.getroot(), encoding='unicode'))
class PandaPush(gym.Env):
metadata = {'render_modes': []}
def __init__(self, randomize=False, horizon=100):
self.m, self.randomize, self.horizon = make_panda_model(), randomize, horizon
self.d = mujoco.MjData(self.m)
self.tip = mujoco.mj_name2id(self.m, mujoco.mjtObj.mjOBJ_SITE, 'push_tip')
self.puck = mujoco.mj_name2id(self.m, mujoco.mjtObj.mjOBJ_BODY, 'puck')
self.geom = mujoco.mj_name2id(self.m, mujoco.mjtObj.mjOBJ_GEOM, 'puck_geom')
self.mass0 = self.m.body_mass[self.puck].copy()
self.inertia0 = self.m.body_inertia[self.puck].copy()
self.friction0 = self.m.geom_friction[self.geom].copy()
self.action_space = gym.spaces.Box(-1, 1, shape=(2,), dtype=np.float32)
self.observation_space = gym.spaces.Box(-np.inf, np.inf, shape=(33,), dtype=np.float32)
self.goal, self.n = np.array([.65, 0.]), 0
def ik(self, target):
low, high = self.m.jnt_range[:7].T
for _ in range(100):
mujoco.mj_forward(self.m, self.d)
error = target - self.d.site_xpos[self.tip]
if np.linalg.norm(error) < .001: break
jp, jr = np.zeros((3, self.m.nv)), np.zeros((3, self.m.nv))
mujoco.mj_jacSite(self.m, self.d, jp, jr, self.tip)
J = jp[:, :7]
dq = J.T @ np.linalg.solve(J @ J.T + .02**2 * np.eye(3), error)
self.d.qpos[:7] = np.clip(self.d.qpos[:7] + .5 * np.clip(dq, -.1, .1), low, high)
def observe(self):
tip = self.d.site_xpos[self.tip, :2].copy()
puck = self.d.xpos[self.puck, :2].copy()
if self.randomize:
tip += self.np_random.normal(0, .001, 2)
puck += self.np_random.normal(0, .001, 2)
return np.r_[tip, puck, self.goal, puck-tip, self.goal-puck, self.d.qvel[9:11],
self.d.qpos[:7], self.d.qvel[:7], self.d.ctrl[:7]].astype(np.float32)
def reset(self, *, seed=None, options=None):
super().reset(seed=seed)
mujoco.mj_resetData(self.m, self.d)
self.d.qpos[:9] = [0, 0, 0, -1.57079, 0, 1.57079, -.7853, .04, .04]
options = options or {}
mass_scale = options.get('mass_scale', self.np_random.uniform(.5, 1.5) if self.randomize else 1)
friction_scale = options.get('friction_scale', self.np_random.uniform(.5, 1.5) if self.randomize else 1)
self.m.body_mass[self.puck] = self.mass0 * mass_scale
self.m.body_inertia[self.puck] = self.inertia0 * mass_scale
self.m.geom_friction[self.geom] = self.friction0
self.m.geom_friction[self.geom, 0] *= friction_scale
mujoco.mj_setConst(self.m, self.d)
self.d.qpos[9:12] = [.50, self.np_random.uniform(-.04, .04), .025]
self.d.qpos[12:16] = [1, 0, 0, 0]
self.goal = np.array([.65, self.np_random.uniform(-.04, .04)])
self.ik(np.array([.42, self.d.qpos[10], .05]))
self.d.ctrl[:7] = self.d.qpos[:7]; self.d.ctrl[7] = 255
self.n = 0
mujoco.mj_forward(self.m, self.d)
return self.observe(), {}
def step(self, action):
action = np.clip(np.asarray(action), -1, 1)
tip = self.d.site_xpos[self.tip].copy()
target = tip + np.r_[.01 * action, .05 - tip[2]]
jp, jr = np.zeros((3, self.m.nv)), np.zeros((3, self.m.nv))
mujoco.mj_jacSite(self.m, self.d, jp, jr, self.tip)
J = jp[:, :7]
dq = J.T @ np.linalg.solve(J @ J.T + .02**2 * np.eye(3), target - tip)
low, high = self.m.jnt_range[:7].T
self.d.ctrl[:7] = np.clip(self.d.ctrl[:7] + dq, low, high)
old = np.linalg.norm(self.d.xpos[self.puck, :2] - self.goal)
old_reach = np.linalg.norm(self.d.xpos[self.puck, :2] - self.d.site_xpos[self.tip, :2])
for _ in range(25): mujoco.mj_step(self.m, self.d)
self.n += 1
distance = np.linalg.norm(self.d.xpos[self.puck, :2] - self.goal)
reach = np.linalg.norm(self.d.xpos[self.puck, :2] - self.d.site_xpos[self.tip, :2])
success = distance < .03
phi_old = -10 * old - 2 * old_reach
phi_new = 0.0 if success else -10 * distance - 2 * reach
reward = float((1 if success else 0) + .99 * phi_new - phi_old)
return self.observe(), reward, bool(success), self.n >= self.horizon and not success, {'success': bool(success), 'distance': float(distance)}
from gymnasium.utils.env_checker import check_env
env = PandaPush()
check_env(env, skip_render_check=True)
observation, _ = env.reset(seed=0)
print('observación:', observation.shape, '| acción:', env.action_space.shape)
env.close()npm run lab and open the connection link.The ground has tangential friction 0.01 and the disk 1.0 by default. At equal priority MuJoCo uses their maximum, so the disk’s applied range does affect its ground contact. Check this property before training. In this version disk mass and inertia change together; starting position and goal are sampled at each reset, and noise is added only in randomized mode. To evaluate a specific condition, pass options={'mass_scale': ..., 'friction_scale': ...} to reset.
The following trainer uses the same SAC from scratch update: squashed Gaussian actor, two critics and learned temperature. Density corrects the tanh Jacobian; the buffer stores only terminated, so truncation retains bootstrap. Executing the definition does not start a long training run.
import copy, math, random
import torch
from torch import nn
from torch.nn import functional as F
DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
def squashed_log_prob(u, mean, log_std):
z = (u - mean) * torch.exp(-log_std)
normal = -.5 * z * z - log_std - .5 * math.log(2 * math.pi)
jacobian = 2 * (math.log(2) - u - F.softplus(-2 * u))
return (normal - jacobian).sum(-1)
class Actor(nn.Module):
def __init__(self, n_obs, n_action, hidden=256):
super().__init__()
self.body = nn.Sequential(nn.Linear(n_obs, hidden), nn.ReLU(), nn.Linear(hidden, hidden), nn.ReLU())
self.mean, self.log_std = nn.Linear(hidden, n_action), nn.Linear(hidden, n_action)
def sample(self, obs):
h = self.body(obs)
mean = self.mean(h)
log_std = -5 + 3.5 * (torch.tanh(self.log_std(h)) + 1)
u = mean + log_std.exp() * torch.randn_like(mean)
return torch.tanh(u), squashed_log_prob(u, mean, log_std)
def deterministic(self, obs):
return torch.tanh(self.mean(self.body(obs)))
class DoubleQ(nn.Module):
def __init__(self, n_obs, n_action, hidden=256):
super().__init__()
def net():
return nn.Sequential(nn.Linear(n_obs + n_action, hidden), nn.ReLU(),
nn.Linear(hidden, hidden), nn.ReLU(), nn.Linear(hidden, 1))
self.q1, self.q2 = net(), net()
def forward(self, obs, action):
x = torch.cat([obs, action], dim=-1)
return self.q1(x).squeeze(-1), self.q2(x).squeeze(-1)
class Replay:
def __init__(self, capacity, n_obs, n_action, device, seed):
self.n_obs, self.n_action = n_obs, n_action
self.data = torch.zeros((capacity, 2 * n_obs + n_action + 2), device=device)
self.capacity, self.i, self.n = capacity, 0, 0
self.gen = torch.Generator(device=device).manual_seed(seed)
def add(self, obs, action, reward, next_obs, terminated):
row = np.concatenate([obs, action, [reward], next_obs, [float(terminated)]]).astype(np.float32)
self.data[self.i] = torch.from_numpy(row).to(self.data.device)
self.i = (self.i + 1) % self.capacity
self.n = min(self.n + 1, self.capacity)
def sample(self, batch):
idx = torch.randint(0, self.n, (batch,), device=self.data.device, generator=self.gen)
f = self.data[idx]
o, a = self.n_obs, self.n_action
return f[:, :o], f[:, o:o+a], f[:, o+a], f[:, o+a+1:2*o+a+1], f[:, -1]
def update_sac(batch, actor, critic, target, log_alpha, optimizers, gamma=.99, tau=.005):
opt_actor, opt_critic, opt_alpha = optimizers
obs, action, reward, next_obs, terminated = batch
alpha = log_alpha.exp().detach()
with torch.no_grad():
next_action, next_logp = actor.sample(next_obs)
q1, q2 = target(next_obs, next_action)
y = reward + gamma * (1 - terminated) * (torch.minimum(q1, q2) - alpha * next_logp)
q1, q2 = critic(obs, action)
loss_q = F.mse_loss(q1, y) + F.mse_loss(q2, y)
opt_critic.zero_grad(set_to_none=True); loss_q.backward(); opt_critic.step()
for p in critic.parameters(): p.requires_grad_(False)
sampled, logp = actor.sample(obs)
q1, q2 = critic(obs, sampled)
loss_actor = (alpha * logp - torch.minimum(q1, q2)).mean()
opt_actor.zero_grad(set_to_none=True); loss_actor.backward(); opt_actor.step()
for p in critic.parameters(): p.requires_grad_(True)
loss_alpha = -(log_alpha * (logp.detach() - action.shape[-1])).mean()
opt_alpha.zero_grad(set_to_none=True); loss_alpha.backward(); opt_alpha.step()
with torch.no_grad():
for p, q in zip(critic.parameters(), target.parameters()): q.lerp_(p, tau)
def evaluate_success(actor, scale, episodes=30, seed=10000):
env = PandaPush(randomize=False)
successes, distances = [], []
with torch.no_grad():
for i in range(episodes):
obs, _ = env.reset(seed=seed+i, options={'mass_scale': scale, 'friction_scale': scale})
while True:
action = actor.deterministic(torch.as_tensor(obs, device=DEVICE).unsqueeze(0))[0].cpu().numpy()
obs, _, done, truncated, info = env.step(action)
if done or truncated: break
successes.append(int(done)); distances.append(info['distance'])
env.close()
return {'successes': successes, 'distances': distances}
def train_arm(randomize, steps=200000, seed=0, interval=25000, directory=Path('atlas_runs/p09-l07'), resume=True,
warmup=5000, batch_size=256, eval_episodes=30, horizon=100, stop_after=None):
random.seed(seed); np.random.seed(seed); torch.manual_seed(seed)
env = PandaPush(randomize=randomize, horizon=horizon)
obs, _ = env.reset(seed=seed); env.action_space.seed(seed)
n_obs, n_action = len(obs), env.action_space.shape[0]
actor = Actor(n_obs, n_action).to(DEVICE)
critic = DoubleQ(n_obs, n_action).to(DEVICE)
target = copy.deepcopy(critic).requires_grad_(False)
log_alpha = torch.zeros(1, requires_grad=True, device=DEVICE)
opts = (torch.optim.Adam(actor.parameters(), 3e-4), torch.optim.Adam(critic.parameters(), 1e-3),
torch.optim.Adam([log_alpha], 1e-3))
replay = Replay(steps, n_obs, n_action, DEVICE, seed)
directory.mkdir(parents=True, exist_ok=True)
history = []; name = 'aleatorio' if randomize else 'fijo'
state_path = directory / f'{name}-state.pt'
asset_hashes = {str(path.relative_to(PANDA)): hashlib.sha256(path.read_bytes()).hexdigest() for path in files}
contract = {'randomize': randomize, 'steps': steps, 'seed': seed, 'interval': interval,
'warmup': warmup, 'batch_size': batch_size, 'eval_episodes': eval_episodes, 'horizon': horizon,
'asset_hashes': asset_hashes, 'mujoco_version': mujoco.__version__, 'gymnasium_version': gym.__version__}
start = 1
if state_path.exists():
if not resume: raise FileExistsError('La carpeta contiene un estado; usa resume=True')
saved = torch.load(state_path, map_location=DEVICE, weights_only=False)
if saved['contract'] != contract: raise ValueError('El contrato de ejecución cambió')
actor.load_state_dict(saved['actor']); critic.load_state_dict(saved['critic']); target.load_state_dict(saved['target'])
with torch.no_grad(): log_alpha.copy_(saved['log_alpha'])
for opt, old in zip(opts, saved['optimizers']): opt.load_state_dict(old)
replay.data.copy_(saved['replay']); replay.i, replay.n = saved['replay_i'], saved['replay_n']
replay.gen.set_state(saved['replay_rng'].cpu())
random.setstate(saved['python_rng']); np.random.set_state(saved['numpy_rng'])
torch.set_rng_state(saved['torch_rng'].cpu())
if DEVICE.type == 'cuda' and saved['cuda_rng'] is not None:
torch.cuda.set_rng_state_all([x.cpu() for x in saved['cuda_rng']])
env.np_random.bit_generator.state = saved['env_rng']
env.action_space.np_random.bit_generator.state = saved['action_rng']
history, start = saved['history'], saved['step'] + 1
if start <= steps:
if not saved['episode_boundary']: raise ValueError('No se reanuda un episodio incompleto')
obs, _ = env.reset()
print('reanudando desde el paso', start)
next_checkpoint = ((start - 1) // interval + 1) * interval
try:
for step in range(start, steps + 1):
if step <= warmup:
action = env.action_space.sample()
else:
with torch.no_grad():
action = actor.sample(torch.as_tensor(obs, device=DEVICE).unsqueeze(0))[0][0].cpu().numpy()
next_obs, reward, done, truncated, _ = env.step(action)
replay.add(obs, action, reward, next_obs, done)
obs = next_obs
if step > warmup: update_sac(replay.sample(batch_size), actor, critic, target, log_alpha, opts)
boundary = bool(done or truncated)
if (step >= next_checkpoint and boundary) or step == steps:
evaluation = {str(s): evaluate_success(actor, s, episodes=eval_episodes) for s in (.5, 1., 1.5, 2.)}
history.append({'step': step, 'randomize': randomize, 'seed': seed, 'evaluation': evaluation})
torch.save({'actor': actor.state_dict(), 'step': step, 'randomize': randomize, 'seed': seed}, directory / f'{name}.pt')
(directory / f'{name}.json').write_text(json.dumps(history, indent=2), encoding='utf-8')
state = {'contract': contract, 'step': step, 'episode_boundary': boundary, 'history': history,
'actor': actor.state_dict(), 'critic': critic.state_dict(), 'target': target.state_dict(),
'log_alpha': log_alpha.detach(), 'optimizers': [opt.state_dict() for opt in opts],
'replay': replay.data, 'replay_i': replay.i, 'replay_n': replay.n,
'replay_rng': replay.gen.get_state(), 'python_rng': random.getstate(),
'numpy_rng': np.random.get_state(), 'torch_rng': torch.get_rng_state(),
'cuda_rng': torch.cuda.get_rng_state_all() if DEVICE.type == 'cuda' else None,
'env_rng': env.np_random.bit_generator.state,
'action_rng': env.action_space.np_random.bit_generator.state}
temporary = directory / f'{name}-state.tmp'
torch.save(state, temporary); temporary.replace(state_path)
next_checkpoint = (step // interval + 1) * interval
print(name, step, {s: sum(v['successes']) for s, v in evaluation.items()}, flush=True)
if stop_after is not None and step >= stop_after: break
if boundary: obs, _ = env.reset()
finally:
env.close()
return history
# Una actualización pequeña comprueba el camino del búfer al actor y a los críticos.
test_actor = Actor(3, 2, hidden=16)
test_critic = DoubleQ(3, 2, hidden=16)
test_target = copy.deepcopy(test_critic).requires_grad_(False)
test_alpha = torch.zeros(1, requires_grad=True)
test_opts = (torch.optim.Adam(test_actor.parameters(), 3e-4), torch.optim.Adam(test_critic.parameters(), 1e-3),
torch.optim.Adam([test_alpha], 1e-3))
test_buffer = Replay(8, 3, 2, torch.device('cpu'), seed=0)
for i in range(8):
test_buffer.add(np.full(3, i, np.float32), np.zeros(2, np.float32), 0., np.full(3, i+1, np.float32), False)
before = test_actor.mean.weight.detach().clone()
update_sac(test_buffer.sample(4), test_actor, test_critic, test_target, test_alpha, test_opts)
assert torch.isfinite(test_actor.mean.weight).all() and not torch.equal(before, test_actor.mean.weight)
print('búfer y actualización SAC: comprobados')npm run lab and open the connection link.This configuration is a first verifiable campaign, not a guarantee of exceeding 90%. About every 25,000 steps it saves weights, optimizers, buffer and generators at an episode boundary; after interruption, resume=True continues from the last complete state at the next episode. The contract checks XML and mesh hashes and MuJoCo and Gymnasium versions; also save a copy of environment code, since that check does not detect changes in its Python definition. Bit-for-bit equality depends on device and operations used. Evaluation conditions change mass and friction together to detect joint sensitivity; add separate sweeps and more training seeds before attributing an effect to either. Do not select test seeds after seeing results.
# Ejecución larga: 200000 transiciones por modalidad; evalúa 30 episodios por escala.
historial_fijo = train_arm(randomize=False, steps=200000, seed=0)
historial_aleatorio = train_arm(randomize=True, steps=200000, seed=0)npm run lab and open the connection link.In our own campaign with the previous lesson’s SAC classes, both variants completed 200,000 CPU transitions using training seed 0. We froze final actors and evaluated 30 episodes per condition with held-out seeds 20000–20029. The nominal actor achieved 0 successes out of 30 in every condition; the randomized actor achieved:
| Randomized actor condition | Successes | Two-sided 95% Wilson interval |
|---|---|---|
| Nominal physics | 30/30 | 88.6% to 100% |
| Disk mass ×0.25 | 30/30 | 88.6% to 100% |
| Disk mass ×2 | 30/30 | 88.6% to 100% |
| Disk friction ×0.25 | 21/30 | 52.1% to 83.3% |
| Disk friction ×2 | 14/30 | 30.2% to 63.9% |
| Position noise, standard deviation 1 mm | 30/30 | 88.6% to 100% |
Each intervention changes only the indicated parameter. Episodes are paired by initial seed but trajectories can diverge. These figures describe two checkpoints, not SAC variability across training runs or a transfer guarantee. Observed nominal success for the randomized actor exceeds 90%, though the interval does not establish probability above that threshold. Friction sensitivity also prevents describing it as robust to every condition tested. The nominal actor failed even under nominal physics; on ten different diagnostic seeds it moved the disk 0.269 m on average but ended 0.410 m from the goal with no successes. Activity and return are insufficient to check the objective.
Exercises
Step 1 of 2. What happens when the discounted terms are summed?
def randomize_physics(model, rng, low, high):
pass