Policy learning in practice: data, evaluation and sim2real
Build traceable robot-demonstration datasets and evaluation protocols, then study sim-to-real transfer, domain randomization, system identification and residual reinforcement learning.
After this lesson you can
- Design and audit a demonstration dataset with episodes, timestamps, compressed video and metadata.
- Design an evaluation protocol with justified episode counts, Wilson intervals and failure categories.
- Implement visual and dynamics domain randomization in MuJoCo and measure robustness.
- Identify physical parameters from trajectories with least squares.
- Fine-tune an imitation policy with residual RL and explain when it is worthwhile.
Before you start
- 24Behavior cloningDiffusion PolicyAction chunkingManipulation environment designManipulator equationsOpen-loop versus closed-loop evaluation
- 05Binomial proportion confidence intervalsPower and power function
- 22PPO clipped objectiveSoft actor-critic
- 13Out-of-distribution generalizationDataset shift taxonomy
- 11Linear regression model and least-squares fitting
From convincing video to repeatable result
A robot pushing a piece successfully once has not shown that a policy works reliably. The result depends on initial positions, friction, camera, latency and success criterion. A behavior-cloning policy may look accurate on operator images and fail in a state the operator never visited. A diffusion policy adds sampling variability, so its seed must also be recorded.
The figure distinguishes two questions. An interval estimates an unknown proportion from a sample; reversal probability requires assumed true rates. The latter also depends on how conditions are paired. If both policies see exactly the same scene, their successes may be correlated and the figure’s independent model no longer describes the comparison.
An episode is more than a video
A robot-demonstration dataset organizes transitions by episode: observation, action, time, episode and step IDs, task, initial condition and outcome. Retain units, reference frame, frequency, action limits, calibration and controller version. Incremental actions cannot be interpreted as absolute positions; delayed camera frames can make an action appear to anticipate movement that already happened.
LeRobotDataset separates tables and compressed video and retains metadata to locate and reconstruct episodes. Record format and library versions with the experiment. Compare timestamps on a common clock and check monotonicity, gaps, missing frames, action limits and camera offsets. If clocks are compensated, estimate and document the offset before enforcing tolerances. A correct mean frequency does not guarantee every sample is synchronized.
Audit the distribution of tasks, operators, objects, poses and recoveries as well as demonstration success rate. Filtering all errors also removes recovery examples: decide according to the objective and retain provenance. Split by episode and, to measure generalization, by object or condition, never by frame. Freeze the split before choosing hyperparameters.
For example, at 10 Hz an observation at time should describe the state available when the action applied in the next interval was selected. If video arrives 120 ms after the position sensor and you simply join by index, a frame can be paired with an action from another step. Save acquisition and reception times and the clock transformation, and document what the policy knew when deciding. A useful audit plots several complete trajectories with image, action and outcome; marginal histograms alone do not reveal systematic offset.
A minimal metadata list includes episode ID, task and instruction, seed or initial condition, date and versions, camera configuration, frequency, action units and conventions, normalization parameters, outcome and stop reason. For human demonstrations, retain consent and usage restrictions. Compressed video saves space but introduces its own frame timeline: container and acquisition timestamps may differ. Check that relationship during conversion, especially with dropped frames or differing camera rates.
Protocol and sample size
A policy evaluation protocol fixes scene distribution, seeds, horizon, success definition, resets, perturbations, model version and episode count before measurement. Separate validation, where the checkpoint is chosen, from test, where the final result is reported. Pairing gives every policy the same initial condition; separately record collision, lost contact, object out of reach, timeout and perception error. Categories need a priority rule if one episode has multiple failures.
For successes in independent trials with common probability, the Wilson interval at the level associated with is obtained by inverting the score test:
To derive it, test a candidate under the binomial hypothesis and retain values satisfying . Rearranging gives a quadratic inequality in whose roots are the endpoints above. Unlike a normal interval centred directly on , Wilson does not collapse to zero width when all episodes succeed or fail. Its coverage is still approximate and independence matters: repeating the same scenario with the same deterministic policy does not create independent conditions.
With 42 successes out of 50, the 95% interval is approximately . It is not a posterior probability that the rate lies in the interval. Coverage is interpreted over repetitions of the procedure under its assumptions. An interval per policy is also not a direct difference test: use discordant pairs for a paired comparison. If counts scenes where only A succeeds and where only B succeeds, under the symmetric null . If they tie in every scene, no discordances are available to compare.
Pairing matters even when marginal rates are known. Suppose A succeeds with probability 0.8 and B with 0.65. If joint success probability is 0.65, discordant pairs have probabilities 0.15 and 0. If joint success is 0.45, those probabilities are 0.35 and 0.20. Individual rates have not changed, but the comparisons contain very different amounts of information about their difference. The independent simulator in the first figure therefore does not replace pairs recorded in a real experiment.
A good results table includes more than a percentage: report , interval, number of training seeds and success definition. When evaluating multiple objects or tasks, state whether each episode is equally weighted or a per-task mean is calculated. Adding episodes from one object reduces uncertainty about that object but does not multiply independent objects. To compare training seeds, repeat fitting and keep results separate; a binomial interval over episodes from one checkpoint does not capture that variation.
Failure taxonomy also needs a rule. For example: first safety if a limit is exceeded, then lost object if it leaves the area, then collision, and finally timeout if the goal is not reached. This priority gives each episode a reproducible primary category while retaining all secondary indicators. A detector labelling “success” for proximity in one frame can count an object crossing the goal without staying there. Decide whether to require dwell time, orientation and absence of collision before viewing results, and validate the detector against an audited sample.
Power depends on the difference that matters, significance level and joint distribution, not just the two marginal rates. The next lab uses an explicit alternative , ; remaining pairs agree. It simulates multiple experiments and applies the two-sided exact binomial test. The result is an example design, not a guarantee for another environment.
import numpy as np
from scipy.stats import binomtest
def wilson(k, n, z=1.959963984540054):
if n < 1 or not 0 <= k <= n: raise ValueError('conteos inválidos')
p=k/n; d=1+z*z/n
c=(p+z*z/(2*n))/d
h=z*np.sqrt(p*(1-p)/n+z*z/(4*n*n))/d
return c-h,c+h
def paired_p(a,b):
a=np.asarray(a,dtype=bool); b=np.asarray(b,dtype=bool)
if a.shape != b.shape: raise ValueError('parejas incompletas')
only_a=int(np.sum(a & ~b)); only_b=int(np.sum(~a & b))
total=only_a+only_b
return 1.0 if total==0 else binomtest(only_a,total,0.5).pvalue
print('Wilson 42/50:',np.round(wilson(42,50),6))
print('Prueba emparejada 12 frente a 3 discordancias:',round(binomtest(12,15,.5).pvalue,6))rng=np.random.default_rng(13)
for n in (20,50,100,200):
rejected=0; trials=500
for _ in range(trials):
pair=rng.choice(4,size=n,p=[.25,.10,.45,.20])
a=(pair==0)|(pair==2); b=(pair==1)|(pair==2)
rejected += paired_p(a,b)<.05
print(n,'episodios: potencia simulada',round(rejected/trials,3))The Monte Carlo standard error of a proportion estimated with 500 replicates reaches approximately in the worst case. Repeat with more replicates if a close decision is needed. Avoid a universal twenty-episode rule: specify minimum relevant effect, expected correlation and desired precision.
What changes between simulator and robot
The sim-to-real gap is the difference between observation and transition distributions, not one number. It can arise from lighting, textures, calibration and occlusion; mass, friction, contact or deformation; or actuator delay and frequency. In distribution-shift terms, image shift need not match dynamics shift. Measure them separately and use a target test not used to tune ranges.
Domain randomization trains over a distribution of simulation parameters. Tobin and colleagues varied rendering for object localization; Peng and colleagues randomized dynamics in a pushing task. These are results from specific tasks and protocols, not a guarantee that every range transfers. Broad randomization can spread capacity across irrelevant situations and reduce nominal performance. Evaluate both nominal and target domains and ablate each axis. Latency must simulate the age of observations and actions, not just change the stated frequency.
The experiment’s visual policy receives the overhead image and pusher position, without privileged block position. In the CPU campaign, nominal training obtained 25/50 successes under nominal appearance and 16/50 under the shifted combination. Another network trained with per-episode randomized colours, light and camera obtained 11/50 and 16/50 respectively. Both policies used the same test seeds and one initialization each. Under the shifted combination two pairs succeed only for nominal and two only for randomized: the two-sided exact test gives . These counts do not establish equivalence: uncertainty remains across episodes and training runs. The figure assigns no invented rates to intermediate combinations or attributes change to one factor without ablations.
The selector also shows seven separate ablations. Each retrains a network with one axis varied and compares it with the nominal network on the same shifted target: table textures, colours, light, camera, mass, friction or two observation-delay steps. Delay is 200 ms at 10 Hz; the initial observation is repeated for the first steps. In the friction test nominal and randomized networks achieved 10/50 and 2/50, while under shifted mass they achieved 21/50 and 33/50. One training seed per network does not determine why these differences occur. Mass, friction and delay do not change the static gallery image; their effects appear only during trajectory execution.
In this scene block mass changes while retaining its original inertia tensor. This ablation therefore does not represent a uniform density change at the same geometry: one parameter varies while another stays fixed. To study families of physical objects, impose consistent relationships among mass, centre of mass and inertia and validate the simulator with measured trajectories. The same applies to friction: contact response also depends on geometry and solver parameters.
System identification fits parameters to measured trajectories. In a one-dimensional model with known force and viscous friction, each sample gives . Stack columns and and solve least squares. Sufficient excitation is needed for those columns to be independent. If acceleration comes from differencing noisy positions, noise also affects the design matrix and ordinary least squares can be biased. Dry contact is not explained by this viscous model; validate on new trajectories and use intervals to define plausible randomization ranges.
To see why excitation matters, suppose every sample satisfies . Force determines only the combination , not each parameter separately. Changing force amplitude and frequency can separate the columns; examine singular values and residual on a held-out trajectory. If sensor errors are large, integrate the model forward and compare positions instead of differentiating a noisy signal twice, or use an identification method representing input and output noise. A randomized range can centre on the estimate and cover its uncertainty, but must also include model errors unexplained by fitted parameters.
import numpy as np
rng=np.random.default_rng(7)
v=rng.uniform(-2,2,300); a=rng.uniform(-3,3,300)
force=2.0*a+0.4*v+rng.normal(0,0.05,len(v))
X=np.column_stack((a,v)); estimate,_,rank,_=np.linalg.lstsq(X,force,rcond=None)
print('masa y fricción:',np.round(estimate,4),'rango:',rank)Real-contact identification requires a richer model. In the next MuJoCo experiment we apply horizontal forces to a free 0.2 kg block on a table. First fit the simplified model at states where . Its residual shows that description does not explain the full trajectory well. Then use simulator-provided contact forces and verify mass with . The ratio measures effective sliding friction, not identification freely available on a robot: there sensors and a calibrated normal estimate are needed. The simulator value is a control in this test, not a physical measurement.
import numpy as np
import mujoco
xml='''<mujoco><option timestep=".002"/><worldbody>
<geom name="table" type="plane" size="1 1 .1" friction=".45 .005 .0001"/>
<body name="block" pos="0 0 .025"><freejoint/><geom name="box" type="box" size=".025 .025 .025" mass=".2" friction=".45 .005 .0001"/></body>
</worldbody></mujoco>'''
model=mujoco.MjModel.from_xml_string(xml);data=mujoco.MjData(model)
block=mujoco.mj_name2id(model,mujoco.mjtObj.mjOBJ_BODY,'block');rows=[]
for step in range(10000):
force=1.4*np.sin(step*.004)+.5*np.sin(step*.017)
data.xfrc_applied[block,0]=force;mujoco.mj_forward(model,data)
rows.append([data.qacc[0],data.qvel[0],force,data.qfrc_constraint[0],data.qfrc_constraint[2]])
mujoco.mj_step(model,data)
rows=np.asarray(rows);moving=rows[np.abs(rows[:,1])>.01]
cut=int(.7*len(moving));train,test=moving[:cut],moving[cut:]
X=np.column_stack([train[:,0],np.sign(train[:,1])]);target=train[:,2]
theta,_,rank,_=np.linalg.lstsq(X,target,rcond=None)
print('muestras móviles y rango:',len(moving),rank)
print('ajuste simplificado masa y coeficiente efectivo:',theta[0],theta[1]/(theta[0]*9.81))
testX=np.column_stack([test[:,0],np.sign(test[:,1])])
print('RMSE de fuerza en segmento reservado:',np.sqrt(np.mean((testX@theta-test[:,2])**2)))
mass=np.linalg.lstsq(train[:,0,None],train[:,2]+train[:,3],rcond=None)[0][0]
supported=test[test[:,4]>.1]
ratio=np.abs(supported[:,3])/supported[:,4]
print('masa con contacto medido:',mass,'muestras con normal > 0.1 N:',len(supported),'mediana |fx|/fz:',np.median(ratio))
print('masa y fricción de la escena:',model.body_mass[block],model.geom_friction[0,0])npm run lab and open the connection link.A residual policy adds a correction to the base policy:
Residual RL fine-tuning retains useful initial behaviour and learns the difference through environment reward and transition. Johannink and colleagues combined conventional control with a learned correction; here the base can be an imitation policy. A residual guarantees neither safety nor improvement: limit magnitude, retain a base evaluation, log saturation and compare against training from scratch at equal interaction budgets. PPO or SAC require defining the action distribution and treating clipping correctly when calculating probabilities; PPO does not turn a later clip into an untruncated Gaussian density.
If the residual has support in and is multiplied by , each coordinate can change by at most before final clipping. Near an actuation limit, however, clipping can cancel part of the correction. The same residual norm can also be harmless in free space and dangerous in contact. Log force, velocity and stopping per episode; use limits and supervision independent of learned reward. In the code, PPO models the latent action and the environment applies clipping as part of its transition; the clipped action density is not evaluated as if Gaussian.
Local lab: from demonstration to residual
In an isolated environment install PyTorch, MuJoCo, Gymnasium and Stable Baselines3. For the data step also use lerobot==0.3.3, datasets==3.6.0 and PyAV. Torch and torchvision versions must be compatible. The cells share state and execute in order. Output folders are created in the working directory; conversion requires a new path to avoid overwriting data.
The scene reproduces the planar pusher from the simulation lesson. It differs from Push-T, its pixel coordinates and the previous lesson’s visual checkpoint. We therefore train an eight-action chunk denoiser from its own demonstrations; it receives privileged state and uses the first action before replanning. A fixed noise vector makes this base policy deterministic during PPO but does not evaluate diffusion diversity. Comparison records 50 new seeds per condition and one training run. The code requests 30000 steps per method and, since PPO collects blocks of 256, completes 30208 steps. The campaign behind the figure ran without interruption and used 30208 interactions per method. A previous run with the same training seed resumed twice and discarded 272 incomplete-block transitions; it obtained the same successes but is not a second independent seed. Results are simulated and do not prove real-world transfer.
The twenty-step schedule is small: clean-action signal remains at the end of the forward process although reverse sampling starts with normal noise. This is a teaching approximation and the denoiser is an MLP, not lesson 12’s visual U-Net. Demonstrations contribute only windows fully contained in an episode. The residual receives the same state and is limited to 0.25 per coordinate before final clipping. Evaluating a practical system requires more training seeds, observations available at deployment and measurement of sampling-seed sensitivity.
"""Experimento de empuje MuJoCo para m24-l13. Ejecución autónoma; no usa Push-T."""
import os, json, time
from pathlib import Path
import numpy as np
import torch
from torch import nn
import gymnasium as gym
from gymnasium import spaces
import mujoco
from stable_baselines3 import PPO
from stable_baselines3.common.callbacks import BaseCallback
torch.set_num_threads(int(os.environ.get('ORYON_THREADS','1')))
print('hilos intraop Torch:',torch.get_num_threads(),flush=True)
torch.manual_seed(13)
rng = np.random.default_rng(13)
device = os.environ.get('ORYON_DEVICE','cuda' if torch.cuda.is_available() else 'cpu')
OUT = Path(os.environ.get('ORYON_L13_OUT', 'oryon-l13-residual'))
OUT.mkdir(parents=True, exist_ok=True)
XML = '''<mujoco model="push"><option timestep="0.002"/><worldbody>
<light pos="0 0 2"/><camera name="top" pos="0 0 .5" xyaxes="1 0 0 0 1 0"/>
<geom name="table" type="plane" size="1 1 .1" friction="1 .005 .0001"/>
<body name="pusher" pos="-.15 0 .025"><joint name="px" type="slide" axis="1 0 0" damping="5"/><joint name="py" type="slide" axis="0 1 0" damping="5"/><geom type="sphere" size=".015" mass="1" rgba=".2 .4 .8 1"/><site name="tip" size=".005"/></body>
<body name="block" pos="0 0 .025"><freejoint name="blockjoint"/><geom name="box" type="box" size=".025 .025 .025" mass=".1" rgba=".8 .3 .2 1"/></body>
</worldbody><actuator><velocity joint="px" kv="100" ctrlrange="-.2 .2"/><velocity joint="py" kv="100" ctrlrange="-.2 .2"/></actuator></mujoco>'''
class Push(gym.Env):
metadata = {'render_modes':['rgb_array'], 'render_fps':10}
def __init__(self, mode='nominal', residual=None, capture=False, xml=XML):
self.model = mujoco.MjModel.from_xml_string(xml); self.data = mujoco.MjData(self.model)
self.tip = mujoco.mj_name2id(self.model,mujoco.mjtObj.mjOBJ_SITE,'tip')
self.block = mujoco.mj_name2id(self.model,mujoco.mjtObj.mjOBJ_BODY,'block')
self.box = mujoco.mj_name2id(self.model,mujoco.mjtObj.mjOBJ_GEOM,'box')
self.table = mujoco.mj_name2id(self.model,mujoco.mjtObj.mjOBJ_GEOM,'table')
self.mode=mode; self.residual=residual; self.capture=capture; self.renderer=None
self.action_space=spaces.Box(-1.,1.,(2,),dtype=np.float32)
self.observation_space=spaces.Box(-np.inf,np.inf,(6,),dtype=np.float32)
self.goal=np.array([.15,0.]); self.steps=0
def state(self):
return np.r_[self.data.qpos[:2]+[-.15,0],self.data.xpos[self.block,:2],self.goal].astype(np.float32)
def image(self):
if self.renderer is None:self.renderer=mujoco.Renderer(self.model,64,64)
self.renderer.update_scene(self.data,camera='top');return self.renderer.render().copy()
def reset(self,*,seed=None,options=None):
super().reset(seed=seed);mujoco.mj_resetData(self.model,self.data);self.steps=0
if self.mode=='random':
mass=self.np_random.uniform(.08,.22);friction=self.np_random.uniform(.4,1.4)
elif self.mode=='target':mass=.20;friction=.45
else:mass=.1;friction=1.
self.model.body_mass[self.block]=mass;self.model.geom_friction[self.box,0]=friction
self.model.geom_friction[self.table,0]=friction
mujoco.mj_setConst(self.model,self.data)
self.data.qpos[3]=self.np_random.uniform(-.015,.015)
mujoco.mj_forward(self.model,self.data)
return self.state(),{}
def step(self,action):
if self.residual is not None:action=np.clip(self.residual(self.state())+0.25*np.asarray(action),-1,1)
action=np.clip(np.asarray(action,dtype=np.float32),-1,1)
self.data.ctrl[:]=.2*action
for _ in range(50):mujoco.mj_step(self.model,self.data)
mujoco.mj_forward(self.model,self.data);self.steps+=1
distance=float(np.linalg.norm(self.data.xpos[self.block,:2]-self.goal))
done=distance<.035;truncated=self.steps>=100 and not done
return self.state(),-distance+float(done),done,truncated,{'success':done,'distance':distance}
def close(self):
if self.renderer is not None:self.renderer.close();self.renderer=None
def expert(s):
tip,block,goal=s[:2],s[2:4],s[4:]; direction=goal-block
direction=direction/max(np.linalg.norm(direction),1e-8);behind=block-.045*direction
target=behind if np.linalg.norm(tip-behind)>.025 and tip[0]<block[0]-.02 else goal
return np.clip(6*(target-tip),-1,1).astype(np.float32)
def collect(num=100):
episodes=[];env=Push()
for seed in range(num):
s,_=env.reset(seed=seed);episode=[]
for t in range(100):
a=expert(s);ns,r,term,trunc,info=env.step(a)
episode.append((s.copy(),a.copy()));s=ns
if term or trunc:break
episodes.append(episode)
env.close();return episodes
class Denoiser(nn.Module):
def __init__(self):
super().__init__();self.net=nn.Sequential(nn.Linear(23,128),nn.SiLU(),nn.Linear(128,128),nn.SiLU(),nn.Linear(128,16))
def forward(self,x,s,t):return self.net(torch.cat([x,s,t[:,None]],-1))
def train_diffusion(episodes, updates=4000):
windows=[(episode[i][0],np.concatenate([item[1] for item in episode[i:i+8]])) for episode in episodes for i in range(len(episode)-7)]
state=np.stack([s for s,a in windows]);action=np.stack([a for s,a in windows])
model=Denoiser().to(device);assert next(model.parameters()).device.type==device
print('dispositivo real difusión:',next(model.parameters()).device,flush=True)
opt=torch.optim.Adam(model.parameters(),lr=3e-4)
beta=torch.linspace(.01,.2,20,device=device);abar=torch.cumprod(1-beta,0)
states=torch.tensor(state,device=device);actions=torch.tensor(action,device=device)
for update in range(updates):
idx=torch.randint(len(states),(128,),device=device);k=torch.randint(20,(128,),device=device);noise=torch.randn_like(actions[idx]);ab=abar[k,None]
x=ab.sqrt()*actions[idx]+(1-ab).sqrt()*noise
loss=(model(x,states[idx],k.float()/19)-noise).square().mean()
opt.zero_grad();loss.backward();opt.step()
model.eval();torch.save(model.state_dict(),OUT/'diffusion_state.pt')
print('diffusion',len(episodes),'episodios',len(state),'pares',updates,'actualizaciones',float(loss.detach()),flush=True)
return model,abar
def diffusion(model,abar,s):
# Fijar el ruido permite observar el mismo estado como política determinista al entrenar PPO.
with torch.no_grad():
infer_device=next(model.parameters()).device
state=torch.tensor(s[None],device=infer_device)
fixed_noise=np.random.default_rng(73).standard_normal((1,16)).astype(np.float32)
x=torch.tensor(fixed_noise,device=infer_device)
indices=[19,15,11,7,3,0]
for j,k in enumerate(indices):
noise=model(x,state,torch.tensor([k/19],device=infer_device));a=abar[k]
clean=(x-(1-a).sqrt()*noise)/a.sqrt();prev=abar[indices[j+1]] if j+1<len(indices) else torch.tensor(1.,device=infer_device)
x=prev.sqrt()*clean+(1-prev).sqrt()*noise
return np.clip(x[0,:2].cpu().numpy(),-1,1)
def evaluate(policy,mode,seeds=None):
if seeds is None: seeds=range(500,500+int(os.environ.get('ORYON_EVAL_EPISODES','50')))
env=Push(mode);results=[]
for seed in seeds:
s,_=env.reset(seed=seed);ok=False
for t in range(100):
s,r,term,trunc,info=env.step(policy(s));ok|=info['success']
if term or trunc:break
results.append({'seed':seed,'success':int(ok),'distance':info['distance'],'steps':t+1})
env.close();return results
class Trace(BaseCallback):
def __init__(self,name):super().__init__();self.name=name;self.records=[];self.episode_success=[];self.norms=[]
def _on_step(self):
self.norms.append(float(np.linalg.norm(np.clip(self.locals['actions'][0],-1,1))))
if self.locals['dones'][0]:self.episode_success.append(int(self.locals['infos'][0]['success']))
if self.num_timesteps % 5000 == 0:
self.records.append({'steps':self.num_timesteps,'training_episodes':len(self.episode_success),
'training_success':sum(self.episode_success)/len(self.episode_success) if self.episode_success else None,
'mean_action_norm':float(np.mean(self.norms))})
self.episode_success=[];self.norms=[]
(OUT/f'{self.name}_trace.json').write_text(json.dumps(self.records,indent=2),encoding='utf-8')
self.model.save(OUT/f'{self.name}_{self.num_timesteps}')
return True
if __name__=='__main__':
episodes=collect(int(os.environ.get('ORYON_DEMOS','100')))
model,abar=train_diffusion(episodes,int(os.environ.get('ORYON_UPDATES','4000')))
model=model.cpu();abar=abar.cpu()
base=lambda s:diffusion(model,abar,s)
results={'base_nominal':evaluate(base,'nominal'),'base_target':evaluate(base,'target')}
print('base',[(k,sum(x['success'] for x in v),len(v)) for k,v in results.items()],flush=True)
(OUT/'base.json').write_text(json.dumps(results,indent=2),encoding='utf-8')
env=Push('random',residual=base)
agent=PPO('MlpPolicy',env,n_steps=256,batch_size=64,n_epochs=5,learning_rate=3e-4,seed=13,device='cpu',verbose=0)
agent.learn(total_timesteps=int(os.environ.get('ORYON_PPO_STEPS','30000')),callback=Trace('residual'));agent.save(OUT/'residual_ppo')
policy=lambda s:np.clip(base(s)+.25*agent.predict(s,deterministic=True)[0],-1,1)
results['residual_nominal']=evaluate(policy,'nominal');results['residual_target']=evaluate(policy,'target')
env.close()
env=Push('random')
scratch=PPO('MlpPolicy',env,n_steps=256,batch_size=64,n_epochs=5,learning_rate=3e-4,seed=13,device='cpu',verbose=0)
scratch.learn(total_timesteps=int(os.environ.get('ORYON_PPO_STEPS','30000')),callback=Trace('scratch'));scratch.save(OUT/'scratch_ppo')
scratch_policy=lambda s:scratch.predict(s,deterministic=True)[0]
results['scratch_nominal']=evaluate(scratch_policy,'nominal');results['scratch_target']=evaluate(scratch_policy,'target')
env.close()
(OUT/'results.json').write_text(json.dumps(results,indent=2),encoding='utf-8')
print('results',[(k,sum(x['success'] for x in v),len(v)) for k,v in results.items()],flush=True)npm run lab and open the connection link.The measured run produced 0/50 successes for both base and residual under both conditions; PPO from scratch achieved 11/50 nominal and 3/50 under physical change. The residual did not improve here. Evaluation seeds are paired between methods, but only one policy was trained per method: repeat with multiple training seeds before generalizing. Nominally there were 11 episodes where scratch succeeded and residual failed; under physical change there were three. The residual trace recorded no successes in six 5000-interaction windows; in the fourth, PPO from scratch completed 9 of 57 training episodes. These exploration and training-condition rates do not replace final evaluation. Figure intervals describe episode-rate uncertainty under that protocol, not variation between training runs. The code above reproduces the uninterrupted protocol, though results can vary across platforms and runs.
"""Registrar la escena m24-l06 como LeRobotDataset 0.3.3 local."""
from pathlib import Path
import os, json
import numpy as np
from lerobot.datasets.lerobot_dataset import LeRobotDataset
root=Path(os.environ.get('ORYON_DATASET','oryon-l13-dataset').strip())
if root.exists(): raise FileExistsError(f'Elige una ruta vacía: {root}')
features={
'observation.state':{'dtype':'float32','shape':(6,), 'names':['tip_x','tip_y','block_x','block_y','goal_x','goal_y']},
'observation.image':{'dtype':'video','shape':(3,64,64),'names':['channels','height','width']},
'action':{'dtype':'float32','shape':(2,),'names':['x_velocity','y_velocity']},
}
dataset=LeRobotDataset.create('oryon/push-block',fps=10,features=features,root=root,robot_type='planar-pusher',use_videos=True,image_writer_threads=2)
env=Push(capture=True); manifest=[]
for episode in range(int(os.environ.get('ORYON_DEMOS','10'))):
s,_=env.reset(seed=episode)
for step in range(100):
image=env.image();action=expert(s);next_s,reward,done,cut,info=env.step(action)
dataset.add_frame({'observation.state':s,'observation.image':image,'action':action},
task='empujar el bloque a la meta',timestamp=step/10)
s=next_s
if done or cut:break
dataset.save_episode();manifest.append({'seed':episode,'steps':step+1,'success':bool(done)})
print('episodio',episode,'pasos',step+1,'éxito',done,flush=True)
env.close();(root/'collection.json').write_text(json.dumps({'fps':10,'model':'m24-l06 PushBlock adaptado','state':'privilegiado: posición de bloque y meta','episodes':manifest},indent=2),encoding='utf-8')
print('Guardado en',root,flush=True)npm run lab and open the connection link."""Adaptación de lectura por PyAV para torchvision 0.26 sin VideoReader."""
import os
import av
import numpy as np
import torch
import lerobot.datasets.lerobot_dataset as module
def decode_pyav(path,timestamps,tolerance_s,backend=None):
frames=[]; times=[]
with av.open(str(path)) as container:
for frame in container.decode(video=0):
frames.append(frame.to_ndarray(format='rgb24'))
times.append(float(frame.pts*frame.time_base))
if not times:raise ValueError('vídeo vacío')
result=[]
for t in timestamps:
i=int(np.argmin(np.abs(np.asarray(times)-t)))
if abs(times[i]-t)>tolerance_s:raise ValueError('fotograma fuera de tolerancia')
result.append(torch.from_numpy(frames[i]).permute(2,0,1).float()/255)
return torch.stack(result)
module.decode_video_frames=decode_pyav
root=os.environ.get('ORYON_DATASET','oryon-l13-dataset')
dataset=module.LeRobotDataset('oryon/push-block',root=root,video_backend='pyav')
for i in (0,len(dataset)-1):
x=dataset[i]
print('frame',i,'timestamp',float(x['timestamp']),'imagen',tuple(x['observation.image'].shape),'acción',x['action'].tolist())
print('episodios',dataset.num_episodes,'frames',len(dataset))npm run lab and open the connection link."""Ablación visual de empuje MuJoCo, comparando datos nominales y aleatorizados."""
import os, json
from pathlib import Path
import numpy as np
import torch
from torch import nn
import mujoco
torch.set_num_threads(int(os.environ.get('ORYON_THREADS','1')));device='cuda' if torch.cuda.is_available() else 'cpu'
OUT=Path('oryon-l13-visual');OUT.mkdir(parents=True,exist_ok=True)
def appearance(env,mode,rng):
camera=mujoco.mj_name2id(env.model,mujoco.mjtObj.mjOBJ_CAMERA,'top')
if mode=='random':
env.model.geom_rgba[env.box,:3]=rng.uniform(.2,.9,3)
env.model.geom_rgba[env.table,:3]=rng.uniform(.25,.75,3)
env.model.light_diffuse[0]=rng.uniform(.35,1.,3)
env.model.cam_pos[camera,:2]=rng.uniform(-.025,.025,2)
elif mode=='target':
env.model.geom_rgba[env.box,:3]=[.25,.65,.35]
env.model.geom_rgba[env.table,:3]=[.45,.45,.55]
env.model.light_diffuse[0]=[.45,.45,.45]
env.model.cam_pos[camera,:2]=[.02,-.02]
mujoco.mj_forward(env.model,env.data)
def collect(mode,n=100):
rng=np.random.default_rng(41);env=Push();ims=[];states=[];actions=[]
for ep in range(n):
s,_=env.reset(seed=ep);appearance(env,mode,rng)
for t in range(100):
im=env.image()[::2,::2].copy();a=expert(s)
ims.append(im);states.append(s[:2].copy());actions.append(a.copy())
s,_,done,cut,_=env.step(a)
if done or cut:break
if (ep+1)%25==0:print(mode,'demostraciones',ep+1,flush=True)
env.close();return np.stack(ims),np.stack(states),np.stack(actions)
class Policy(nn.Module):
def __init__(self):
super().__init__()
self.vision=nn.Sequential(nn.Conv2d(3,16,5,2,2),nn.ReLU(),nn.Conv2d(16,32,3,2,1),nn.ReLU(),nn.Conv2d(32,32,3,2,1),nn.ReLU(),nn.Flatten())
self.head=nn.Sequential(nn.Linear(32*4*4+2,128),nn.ReLU(),nn.Linear(128,2))
def forward(self,im,tip):return self.head(torch.cat((self.vision(im),tip),dim=1))
def train(data,mode):
imgs,tip,action=data;torch.manual_seed(41);rng=np.random.default_rng(41)
model=Policy().to(device);opt=torch.optim.Adam(model.parameters(),lr=3e-4)
for update in range(int(os.environ.get('ORYON_VISUAL_UPDATES','3000'))):
idx=rng.integers(len(imgs),size=64)
im=torch.from_numpy(imgs[idx]).permute(0,3,1,2).float().to(device)/255
x=torch.from_numpy(tip[idx]).to(device);y=torch.from_numpy(action[idx]).to(device)
loss=(model(im,x)-y).square().mean();opt.zero_grad();loss.backward();opt.step()
model.eval();torch.save(model.state_dict(),OUT/f'{mode}.pt')
print(mode,'pérdida',float(loss.detach()),'pares',len(imgs),flush=True);return model
def evaluate(model,mode):
rng=np.random.default_rng(99);env=Push();records=[]
for seed in range(10000,10000+int(os.environ.get('ORYON_EVAL_EPISODES','50'))):
s,_=env.reset(seed=seed);appearance(env,mode,rng)
for t in range(100):
im=torch.from_numpy(env.image()[::2,::2].copy()).permute(2,0,1)[None].float().to(device)/255
tip=torch.tensor(s[:2][None],device=device)
with torch.no_grad():a=model(im,tip)[0].clamp(-1,1).cpu().numpy()
s,_,done,cut,info=env.step(a)
if done or cut:break
records.append({'seed':seed,'success':bool(done),'steps':t+1,'distance':info['distance']})
env.close();return records
if __name__=='__main__':
results={}
for training in ('nominal','random'):
model=train(collect(training,int(os.environ.get('ORYON_DEMOS','100'))),training)
for test in ('nominal','target'):
results[f'{training}_{test}']=evaluate(model,test)
print(training,test,'éxitos',sum(x['success'] for x in results[f'{training}_{test}']),'/',len(results[f'{training}_{test}']),flush=True)
(OUT/'results.json').write_text(json.dumps(results,indent=2),encoding='utf-8')npm run lab and open the connection link."""Ablaciones por eje de apariencia, dinámica y retardo para la política visual."""
import os, json
from pathlib import Path
import numpy as np
import torch
import mujoco
torch.set_num_threads(int(os.environ.get('ORYON_THREADS','1')));device='cuda' if torch.cuda.is_available() else 'cpu'
OUT=Path(os.environ.get('ORYON_AXES_OUT','oryon-l13-axes'));OUT.mkdir(parents=True,exist_ok=True)
AXES=('texture','color','light','camera','mass','friction','latency')
TEXTURE_ASSET='''<asset>
<texture name="check1" type="2d" builtin="checker" rgb1=".25 .25 .25" rgb2=".75 .75 .75" width="64" height="64"/>
<texture name="check2" type="2d" builtin="checker" rgb1=".3 .4 .5" rgb2=".7 .65 .55" width="64" height="64"/>
<material name="mat1" texture="check1" texrepeat="8 8"/>
<material name="mat2" texture="check2" texrepeat="8 8"/>
</asset>'''
def make_env(axis):
return Push(xml=XML.replace('<worldbody>',TEXTURE_ASSET+'<worldbody>')) if axis=='texture' else Push()
def configure(env,axis,random,rng):
camera=mujoco.mj_name2id(env.model,mujoco.mjtObj.mjOBJ_CAMERA,'top')
mass=.1; friction=1.; delay=0
if axis=='texture':
choice=int(rng.integers(0,3)) if random else 2
env.model.geom_matid[env.table]=-1 if choice==0 else mujoco.mj_name2id(env.model,mujoco.mjtObj.mjOBJ_MATERIAL,f'mat{choice}')
elif axis=='color':
env.model.geom_rgba[env.box,:3]=rng.uniform(.2,.9,3) if random else [.25,.65,.35]
env.model.geom_rgba[env.table,:3]=rng.uniform(.25,.75,3) if random else [.45,.45,.55]
elif axis=='light':env.model.light_diffuse[0]=rng.uniform(.35,1.,3) if random else [.45,.45,.45]
elif axis=='camera':env.model.cam_pos[camera,:2]=rng.uniform(-.025,.025,2) if random else [.02,-.02]
elif axis=='mass':mass=rng.uniform(.08,.22) if random else .20
elif axis=='friction':friction=rng.uniform(.4,1.4) if random else .45
elif axis=='latency':delay=int(rng.integers(0,3)) if random else 2
env.model.body_mass[env.block]=mass;env.model.geom_friction[env.box,0]=friction;env.model.geom_friction[env.table,0]=friction
pos=env.data.qpos.copy();mujoco.mj_setConst(env.model,env.data);env.data.qpos[:]=pos;mujoco.mj_forward(env.model,env.data)
return delay
def samples(axis,n):
rng=np.random.default_rng(41);env=make_env(axis);ims=[];tips=[];acts=[]
for ep in range(n):
s,_=env.reset(seed=ep);delay=configure(env,axis,True,rng);s=env.state();history=[]
for t in range(100):
image=env.image()[::2,::2].copy();history.append((image,s[:2].copy()));view=history[max(0,len(history)-1-delay)]
a=expert(s);ims.append(view[0]);tips.append(view[1]);acts.append(a)
s,_,done,cut,_=env.step(a)
if done or cut:break
env.close();return np.stack(ims),np.stack(tips),np.stack(acts)
def train(data,axis):
images,tips,actions=data;torch.manual_seed(41);rng=np.random.default_rng(41);model=Policy().to(device)
opt=torch.optim.Adam(model.parameters(),lr=3e-4)
for update in range(int(os.environ.get('ORYON_VISUAL_UPDATES','3000'))):
ids=rng.integers(len(images),size=64)
im=torch.from_numpy(images[ids]).permute(0,3,1,2).float().to(device)/255
t=torch.from_numpy(tips[ids]).to(device);a=torch.from_numpy(actions[ids]).to(device)
loss=(model(im,t)-a).square().mean();opt.zero_grad();loss.backward();opt.step()
model.eval();torch.save(model.state_dict(),OUT/f'{axis}.pt')
print(axis,'pares',len(images),'loss',float(loss.detach()),flush=True);return model
def evaluate(model,axis):
rng=np.random.default_rng(99);env=make_env(axis);records=[]
for seed in range(10000,10000+int(os.environ.get('ORYON_EVAL_EPISODES','50'))):
s,_=env.reset(seed=seed);delay=configure(env,axis,False,rng);s=env.state();history=[]
for t in range(100):
image=env.image()[::2,::2].copy();history.append((image,s[:2].copy()));view=history[max(0,len(history)-1-delay)]
im=torch.from_numpy(view[0]).permute(2,0,1)[None].float().to(device)/255
tip=torch.tensor(view[1][None],device=device)
with torch.no_grad():a=model(im,tip)[0].clamp(-1,1).cpu().numpy()
s,_,done,cut,info=env.step(a)
if done or cut:break
records.append({'seed':seed,'success':bool(done),'steps':t+1,'distance':info['distance']})
env.close();return records
if __name__=='__main__':
nominal=Policy().to(device);nominal.load_state_dict(torch.load('oryon-l13-visual/nominal.pt',map_location=device,weights_only=True));nominal.eval()
out={}
for axis in os.environ.get('ORYON_AXES',','.join(AXES)).split(','):
model=train(samples(axis,int(os.environ.get('ORYON_DEMOS','100'))),axis)
for name,policy in [('nominal',nominal),('randomized',model)]:
out[f'{axis}_{name}']=evaluate(policy,axis)
print(axis,name,'éxitos',sum(x['success'] for x in out[f'{axis}_{name}']),'/',len(out[f'{axis}_{name}']),flush=True)
(OUT/'results.json').write_text(json.dumps(out,indent=2),encoding='utf-8')npm run lab and open the connection link.Exercises
def identify_params(trajectories):
passdef validate_episode(t, actions, cameras, dt, tolerance):
pass