Simulation, teleoperation and demonstrations
Prepare the tasks: push a T-shaped object to a target pose, the custom arm task from project 9, and simulated bimanual MuJoCo tasks available in LeRobot. Write a scripted expert with simulator-state access, implement keyboard, mouse, or gamepad teleoperation, and store episodes in LeRobot format.
After this lesson you can
- Install simulation environments and verify execution and rendering on the local machine.
- Write a scripted expert for each task and measure its success rate.
- Implement teleoperation and collect quality human demonstrations.
- Save episodes with observations, images, actions, and normalization statistics and replay them.
Before you start
Data decide before the model does
In imitation learning the robot receives examples rather than a reward. Behavior cloning, which you will train in the next lesson, is supervised learning on pairs, and a policy trained this way cannot be better than what those pairs contain. If the saved action was not executed, if the image was taken after the decision, or if normalization statistics saw evaluation episodes, the model learns something else or evaluation leaks information, and no architecture fixes that.
The ACT paper (Zhao et al., 2023) illustrates this with a number. With the same algorithm and 50 successful demonstrations per task in two simulated bimanual tasks, the policy transfers the cube between hands in 86% of attempts when learning from a scripted expert and 50% when learning from people teleoperating with ALOHA leader arms; for insertion, 32% versus 20% (table I, three seeds and 50 evaluations each). The people were not poorer operators: their demonstrations are more varied, with more ways of doing the same thing, making them harder to imitate. This thread runs through the whole project and starts here, with how data are produced and stored.
This lesson builds the half of the project nobody publishes: tasks, experts, teleoperation, and format. At the end you will have a lab that generates full-size datasets of at least 100 demonstrations per task in LeRobot format, with normalization statistics calculated only on training and a replay check that recreates every recorded state from the initial state and actions.
Start with the human T-pushing examples and replay a couple of episodes; then switch to scripted ones and enable trajectory overlay. Humans contact the T at different places, pause to look, and correct. The scripted expert is a deterministic function of state: with the same initial pose it would do exactly the same thing, and its way of pushing (approach a contour point, advance a few centimeters, withdraw) repeats across episodes. On the ALOHA tab the difference is even clearer: all 50 scripted episodes close the right gripper at the same instant, while humans spread their grasps across almost three seconds. Also inspect the last T-pushing readout: final coverage of human demonstrations is around 85%, below the environment’s 0.95 success threshold. We will return to that figure because it says something important about how success is defined.
Three tasks and their contracts
An environment is a contract: what is observed and commanded, in what units, at what frequency, and when the task is finished (review environment design if needed). We will work with three increasingly difficult tasks, all in MuJoCo.
T pushing. A circular pusher of radius 15 mm moves a T-shaped block on a mm table to a fixed pose, . This is the Push-T task from Diffusion Policy (Chi et al., 2023) and gym-pusht, which implements it in two-dimensional Pymunk physics. Action is the pusher’s absolute target position in table pixels (1 px = 1 mm); a PD controller with and moves it there, the policy decides at 10 Hz, and the episode ends at 300 steps. The quality measure is coverage: the fraction of target area occupied by the T. In gym-pusht reward is and success is . Our MuJoCo version reproduces geometry, target, units, controller, and frequencies, but table friction is modeled by damping and dry friction in the T’s planar joints rather than Pymunk’s engine: episodes are not interchangeable with the official environment and rates are not directly comparable.
The project 9 arm. Project 9 designs an arm that reaches and pushes an object as a custom MuJoCo environment. To avoid making this lab depend on another lesson, we write a compact version with the same kind of contract: three hinge joints with position actuators, a tip pushing a free disk, and a target. Action consists of the three joints’ target angles, limited to 0.15 rad change per control step; the policy decides at 20 Hz and success requires the disk to remain within 2 cm of the target for three consecutive steps. If you already have your project 9 environment, this lesson’s recorder asks it for only a small interface (five methods and feature descriptions) and you can substitute the class. If that environment uses domain randomization, the physical parameters drawn for each episode form part of its initial state: save them with the episode, or replay and comparisons between policies will no longer be possible.
Bimanual ALOHA. Two six-joint ViperX arms with grippers, the ACT platform. The action has 14 components: per arm, six target joint positions in radians and one normalized gripper opening in . The policy decides at 50 Hz and each episode lasts 400 steps, eight seconds. There are two tasks: transfer a red cube from right hand to left and insert a peg into a socket held by the other hand. Reward is staged from 0 to 4 (touch, lift, transfer or insert), and success means reaching 4. We use the official MJCF models from gym-aloha, which the lab downloads from PyPI and verifies by hash, and write the environment directly against the MuJoCo API.
| T pushing | Arm | ALOHA | |
|---|---|---|---|
| Action | target in px | 3 target angles (rad) | 12 angles + 2 grippers |
| Proprioceptive state | pusher position | angles and velocities | 14 joint positions |
| Dataset camera | overhead | overhead | overhead |
| Frequency, horizon | 10 Hz, 300 steps | 20 Hz, 300 steps | 50 Hz, 400 steps |
| Success | coverage | disk within cm, 3 steps | reward 4 |
All three contracts share a conceptual interface (observe, act, check success), not an interchangeable vector. Two numbers might be pixels, meters, or radians; a gripper component of 0.5 could be normalized opening, finger separation, or force. Each recorded dataset will therefore state its contract: names, shapes, types, frequency, and units.
Observations, actions, and when each occurs
The definition seems obvious until recording with hardware or an interface. The camera has its own clock and frequency; the control loop has another. If the recorder pairs each action with “the latest available image” using miscalibrated timestamps, the pair can contain an image taken after the decision that already reflects the action’s effect. The policy then learns a relationship that does not exist during deployment. The next interactive isolates this effect with the simplest possible system.
The interactive opens with camera timestamps 100 ms early: each action receives an image taken, on average, 80 ms after deciding. Regression finds a gain 1.9 times the expert’s, and the learned policy overshoots the setpoint on every jump. Note the last two readouts: that policy follows the setpoint even slightly better than the expert, but differs from its trajectory by 1.4 cm root mean square. Imitation aims to reproduce the demonstrator rather than find the best setpoint policy, and here it learns another controller; with a more aggressive expert the same offset would make it unstable. Press “Aligned” and gain returns to 0.94: the paired image is always 20 ms old because at 30 Hz exactly three frames fit in each control period and the phase between clocks does not change. Try “Delayed image” and the policy becomes sluggish, at 0.58. With the camera at 5 Hz, image age changes step by step with clock phase and gain falls to 0.60. The slider stops at 110 ms advance: beyond that, the few pairs whose image already shows the response to the next setpoint jump, with huge observed errors of opposite sign, dominate regression and gain no longer follows a trend. When offset is an integer number of control steps and pairs lie within one segment, the effect has a closed form.
Proof
With and constant , . If , iterating times gives . If , iterating times from gives and, since , again . Thus for every pair in the segment, and has zero residual at , its unique minimizer if some . In closed loop, the learned policy gives , which tends to zero if and only if , that is , and does so without changing sign if and only if .
∎With the interactive’s values, and . One step of advance () gives : pole , damped oscillation. Two steps of advance give and the learned policy diverges, even though the expert was perfectly stable and training loss zero. One step of delay gives : stable, but error falls 24% per step rather than 60%. In the interactive, offsets are not integer steps (the camera takes frames between decisions) and setpoint jumps break the relationship for a few pairs; its gains therefore lie between the theorem’s integer values: with 80 ms advance, between and .
The practical lesson is twofold. First, in simulation alignment is free if the definition’s order is respected: observe, decide, act. Second, with real clocks, save each sensor’s and controller’s original timestamps rather than reconstructing them from a nominal frequency. Our recorder saves two monotonic timestamps per step, one before observing and another upon receiving the action; their difference bounds rendering, device reading, and waiting time.
Absolute positions, deltas, or velocities
The second decision is action representation. Three common choices:
- Absolute position: is the controller target in a fixed frame, as in Push-T or ALOHA joints. It is robust to accumulated errors because each command says where to go, not how far to move, and if one command is lost the next corrects it.
- Position delta: , displacement relative to current end-effector position. It is translation invariant if observation is also relative, but errors integrate: a small systematic bias in each delta becomes drift.
- Velocity: the command is a velocity integrated by the controller; it is the natural output of a keyboard or gamepad, but the policy inherits the problem of integrating noise.
Diffusion Policy found that its method works better with position control than velocity control, contrary to common earlier methods, and attributes this to position being less sensitive to accumulated error when predicting action sequences. Whether a representation generalizes to new initial positions has no universal answer: it depends on whether observation and action live in the same frame. A policy seeing relative positions (object relative to effector, goal relative to object) and emitting deltas in that frame can learn a local rule (“push toward the target”) that transfers well; if it sees absolute positions, whatever it emits, an initial state outside the training range requires input extrapolation. What is universal is that representation is chosen before recording, written in the contract, and never mixed within one dataset.
In all three environments we save the applied action: in T pushing, the target after clipping to the table; in the arm, angles after limiting per-step change and joint stops. A device’s requested action can differ if saturated, and the policy must learn what the environment received.
The scripted expert
An expert need not be elegant; it must be reliable and inexpensive, and it must be measured. This lab’s three illustrate three styles.
- T pushing: plan with the simulator. For each candidate point on the T contour, the expert copies simulator state, simulates a short push in three directions and four lengths, and keeps the one that most reduces mean distance between T vertices and target vertices. It then moves to that point around the block (A* search on an 8 mm grid) and executes the push. It is a brute-force receding-horizon controller: it knows no physics but can query it.
- Arm: geometric rules and inverse kinematics. If the tip is behind the disk and aligned with the target, it advances; otherwise it orbits the disk until behind it. The tip’s Cartesian target is converted to angles with damped least squares, the damped least-squares method of differential inverse kinematics.
- ALOHA: effector waypoints. This is ACT’s expert: a list of poses for each gripper at fixed instants (approach the cube, lower, close, carry it to the meeting point, open), linearly interpolated. Poses are imposed on mocap bodies welded to grippers in a copy of the environment; resulting joints are recorded as commands and replayed in the joint environment, which measures success.
An expert’s success rate is a proportion estimated from few episodes and reported with its interval.
Unlike the Wald interval, , Wilson’s does not collapse to a point when : with 20 successes out of 20 its lower bound is 0.839, not 1. The next lesson dedicates a whole section to evaluating policies by rollout; here we use it to avoid boasting about an expert that succeeded three times out of three.
Lab, part one: tasks and experts
The lab is local: it needs MuJoCo with rendering, pygame for teleoperation, and a connection to download ALOHA models and published human demonstrations. It has two modes controlled by environment variable P13_L01_MODO before opening the kernel. The default corto mode records 3 demonstrations per task in approximately one minute and checks the whole pipeline. completo records 100 per task: the dataset used in the rest of the project. This page’s results are from the short mode. The first cell also installs a memory watchdog: a thread that measures its own process’s resident memory every half second and stops it if it exceeds 3.5 GB, less costly than restarting a machine hung by an oversized collection.
import hashlib, io, json, os, shutil, threading, time
from pathlib import Path
import numpy as np
import mujoco
import psutil
def vigilar_memoria(limite_gb=3.5, periodo_s=0.5):
"""Detiene el proceso si su memoria residente supera el límite."""
proceso = psutil.Process(os.getpid())
def bucle():
while True:
if proceso.memory_info().rss > limite_gb * 2**30:
print(f"memoria por encima de {limite_gb} GB: se detiene el laboratorio", flush=True)
os._exit(3)
time.sleep(periodo_s)
threading.Thread(target=bucle, daemon=True).start()
vigilar_memoria()
MODO = os.environ.get("P13_L01_MODO", "corto")
if MODO not in ("corto", "completo"):
raise ValueError("P13_L01_MODO debe ser 'corto' o 'completo'")
N_DEMOS = 100 if MODO == "completo" else 3
BASE = Path(os.environ.get("ATLAS_LAB_DIR", Path.home() / "atlas-lab")).expanduser() / "p13-l01"
LAB = BASE / MODO
LAB.mkdir(parents=True, exist_ok=True)
def huella(texto):
return hashlib.sha256(texto.encode("utf-8")).hexdigest()
print("MuJoCo", mujoco.__version__, "| modo", MODO, "| demostraciones por tarea:", N_DEMOS)
print("directorio del laboratorio:", LAB)npm run lab and open the connection link.T-pushing simulation works internally in meters, with the table in ; datasets are stored in millimeters, matching gym-pusht pixels. The T is the union of two rectangles (bar mm and stem ), and coverage is calculated with a 2 mm point grid inside the T: the fraction of those points falling inside the target T. The overhead camera is vertically inverted so that, as in gym-pusht, image row 0 corresponds to .
import heapq, itertools
PUSHT_XML = """
<mujoco model="empuje_t">
<compiler angle="radian"/>
<option timestep="0.005" gravity="0 0 -9.81" integrator="implicitfast"/>
<visual><global offwidth="256" offheight="256"/><quality shadowsize="0"/></visual>
<default>
<geom contype="1" conaffinity="1" friction="0.6 0.005 0.0001" solref="0.004 1"/>
</default>
<worldbody>
<light pos="0.256 0.256 1.5" dir="0 0 -1" directional="true" diffuse="0.8 0.8 0.8"/>
<geom name="mesa" type="plane" pos="0.256 0.256 0" size="0.256 0.256 0.01"
rgba="0.93 0.93 0.93 1" contype="0" conaffinity="0"/>
<camera name="arriba" pos="0.256 0.256 0.9" xyaxes="1 0 0 0 1 0" fovy="31.76"/>
<body name="meta" pos="0.256 0.256 0.0005" euler="0 0 0.7853981634">
<geom type="box" pos="0 0.015 0" size="0.06 0.015 0.0005" rgba="0.35 0.75 0.45 1" contype="0" conaffinity="0"/>
<geom type="box" pos="0 0.075 0" size="0.015 0.045 0.0005" rgba="0.35 0.75 0.45 1" contype="0" conaffinity="0"/>
</body>
<body name="t" pos="0 0 0.0125">
<joint name="t_x" type="slide" axis="1 0 0" damping="0.5" frictionloss="0.25"/>
<joint name="t_y" type="slide" axis="0 1 0" damping="0.5" frictionloss="0.25"/>
<joint name="t_rot" type="hinge" axis="0 0 1" damping="0.002" frictionloss="0.006"/>
<geom name="barra" type="box" pos="0 0.015 0" size="0.06 0.015 0.0125" mass="0.06" rgba="0.45 0.55 0.75 1"/>
<geom name="pie" type="box" pos="0 0.075 0" size="0.015 0.045 0.0125" mass="0.045" rgba="0.45 0.55 0.75 1"/>
</body>
<body name="agente" pos="0 0 0.0125">
<joint name="a_x" type="slide" axis="1 0 0"/>
<joint name="a_y" type="slide" axis="0 1 0"/>
<geom name="empujador" type="cylinder" size="0.015 0.0125" mass="1" rgba="0.25 0.35 0.9 1"/>
</body>
</worldbody>
<actuator>
<position name="obj_x" joint="a_x" kp="100" kv="20"/>
<position name="obj_y" joint="a_y" kp="100" kv="20"/>
</actuator>
</mujoco>
"""
META_T = np.array([0.256, 0.256, np.pi / 4])
RADIO_AGENTE = 0.015
CAJAS = np.array([[0.0, 0.015, 0.06, 0.015], [0.0, 0.075, 0.015, 0.045]]) # centro y semiejes
VERTICES = np.array([[-0.06, 0], [0.06, 0], [0.06, 0.03], [-0.06, 0.03], # mismo orden que
[-0.015, 0.03], [0.015, 0.03], [0.015, 0.12], [-0.015, 0.12]]) # lerobot/pusht_keypoints
CONTORNO = np.array([[-0.06, 0], [0.06, 0], [0.06, 0.03], [0.015, 0.03], [0.015, 0.12],
[-0.015, 0.12], [-0.015, 0.03], [-0.06, 0.03]])
def rot(th):
c, s = np.cos(th), np.sin(th)
return np.array([[c, -s], [s, c]])
def dentro_t(local, margen=0.0):
"""Puntos (n, 2) en el marco de la T: ¿caen dentro, con un margen?"""
ok = np.zeros(len(local), bool)
for cx, cy, hx, hy in CAJAS:
ok |= (np.abs(local[:, 0] - cx) <= hx + margen) & (np.abs(local[:, 1] - cy) <= hy + margen)
return ok
def _rejilla(h=0.002):
pts = []
for cx, cy, hx, hy in CAJAS:
X, Y = np.meshgrid(np.arange(cx - hx + h / 2, cx + hx, h), np.arange(cy - hy + h / 2, cy + hy, h))
pts.append(np.c_[X.ravel(), Y.ravel()])
return np.vstack(pts)
REJILLA = _rejilla()
def cobertura(pose, meta=META_T):
mundo = REJILLA @ rot(pose[2]).T + pose[:2]
return float(dentro_t((mundo - meta[:2]) @ rot(meta[2])).mean())
def error_vertices(pose, meta=META_T):
a = VERTICES @ rot(pose[2]).T + pose[:2]
b = VERTICES @ rot(meta[2]).T + meta[:2]
return float(np.linalg.norm(a - b, axis=1).mean())
class EmpujeT:
hz, subpasos, umbral = 10, 20, 0.95
ESTADO = mujoco.mjtState.mjSTATE_INTEGRATION
def __init__(self, lado=96):
self.model = mujoco.MjModel.from_xml_string(PUSHT_XML)
self.data = mujoco.MjData(self.model)
self.lado, self.renderer = lado, None
def reiniciar(self, semilla):
rng = np.random.default_rng(semilla)
mujoco.mj_resetData(self.model, self.data)
while True: # T en cualquier orientación, lejos de la meta; empujador fuera de la T
bloque = np.r_[rng.uniform(0.10, 0.40, 2), rng.uniform(-np.pi, np.pi)]
agente = rng.uniform(0.05, 0.45, 2)
local = ((agente - bloque[:2]) @ rot(bloque[2]))[None]
if not dentro_t(local, margen=RADIO_AGENTE + 0.01)[0] and cobertura(bloque) < 0.5:
break
self.data.qpos[:] = [*bloque, *agente]
self.data.ctrl[:] = agente
mujoco.mj_forward(self.model, self.data)
def pose(self):
return self.data.qpos[:3].copy()
def agente(self):
return self.data.qpos[3:5].copy()
def vertices(self):
p = self.pose()
return (VERTICES @ rot(p[2]).T + p[:2]).ravel()
def paso(self, objetivo):
aplicado = np.clip(np.asarray(objetivo, float), 0.0, 0.512)
self.data.ctrl[:] = aplicado
mujoco.mj_step(self.model, self.data, nstep=self.subpasos)
return aplicado
def imagen(self):
if self.renderer is None:
self.renderer = mujoco.Renderer(self.model, self.lado, self.lado)
self.renderer.update_scene(self.data, camera="arriba")
return np.flipud(self.renderer.render()).copy() # fila 0 = y = 0, como gym-pusht
def estado(self):
s = np.empty(mujoco.mj_stateSize(self.model, self.ESTADO))
mujoco.mj_getState(self.model, self.data, s, self.ESTADO)
return s
def fijar_estado(self, s):
mujoco.mj_setState(self.model, self.data, np.asarray(s, float), self.ESTADO)
mujoco.mj_forward(self.model, self.data)
env = EmpujeT()
env.reiniciar(0)
print("cobertura de la meta consigo misma:", cobertura(META_T))
print("pose inicial (semilla 0):", np.round(env.pose(), 3), "cobertura", round(cobertura(env.pose()), 3))
print("imagen", env.imagen().shape, "| estado de integración:", env.estado().size, "números")npm run lab and open the connection link.The expert tests pushes in a second MjData of the same model, restored to current state with mj_setState: the main simulation is untouched during planning. If no push improves distance, it moves a little at random with its own generator, seeded by the episode seed, so the expert remains a deterministic function of that seed.
def _candidatos(paso=0.012):
"""Puntos del contorno de la T y su normal exterior, sin rincones cóncavos."""
out = []
for i in range(len(CONTORNO)):
a, b = CONTORNO[i], CONTORNO[(i + 1) % len(CONTORNO)]
e = b - a
L = np.linalg.norm(e)
normal = np.array([e[1], -e[0]]) / L
k = max(1, int(L / paso))
for s in (np.arange(k) + 0.5) / k:
p = a + s * e
if not dentro_t((p + normal * (RADIO_AGENTE + 0.006))[None], margen=RADIO_AGENTE)[0]:
out.append((p, normal))
return out
CANDIDATOS = _candidatos()
class ExpertoEmpujeT:
"""Prueba empujes cortos en una copia del simulador y ejecuta el que más acerca la T a la meta."""
def __init__(self, env, semilla=0, longitudes=(0.003, 0.008, 0.02, 0.05), angulos=(0.0, -0.4, 0.4), velocidad=0.02):
self.env, self.copia = env, mujoco.MjData(env.model)
self.longitudes, self.angulos, self.velocidad = longitudes, angulos, velocidad
self.plan, self.rng = [], np.random.default_rng(semilla)
def _simular(self, estado, inicio, objetivos):
d = self.copia
mujoco.mj_setState(self.env.model, d, estado, self.env.ESTADO)
d.qpos[3:5], d.qvel[3:5] = inicio, 0
for o in objetivos:
d.ctrl[:] = o
mujoco.mj_step(self.env.model, d, nstep=self.env.subpasos)
return d.qpos[:3].copy()
@staticmethod
def _empuje(p0, direccion, longitud):
n = max(2, int(np.ceil((longitud + 0.01) / 0.01)))
fin = p0 + direccion * (longitud + 0.01)
return [p0 + direccion * (longitud + 0.01) * (i + 1) / n for i in range(n)] + [fin] * 2
def _elegir(self):
pose, estado = self.env.pose(), self.env.estado()
R = rot(pose[2])
mejor, coste_mejor = None, error_vertices(pose)
for p, n in CANDIDATOS:
n_mundo = R @ n
inicio = R @ p + pose[:2] + n_mundo * (RADIO_AGENTE + 0.006)
if np.any(inicio < 0.02) or np.any(inicio > 0.492):
continue
for ang, L in itertools.product(self.angulos, self.longitudes):
objetivos = self._empuje(inicio, rot(ang) @ (-n_mundo), L)
coste = error_vertices(self._simular(estado, inicio, objetivos))
if coste < coste_mejor - 1e-4:
mejor, coste_mejor = (inicio, objetivos), coste
return mejor
def _camino(self, a, b):
"""Camino libre de colisión con la T: segmento directo o A* en una rejilla de 8 mm."""
pose, margen = self.env.pose(), RADIO_AGENTE + 0.004
libre = lambda pts: ~dentro_t((pts - pose[:2]) @ rot(pose[2]), margen=margen)
tramo_libre = lambda p, q: bool(libre(np.linspace(p, q, max(2, int(np.linalg.norm(q - p) / 0.003)))).all())
if tramo_libre(a, b):
return [b]
h = 0.008
n = int(0.512 / h) + 1
X, Y = np.meshgrid(np.arange(n) * h, np.arange(n) * h, indexing="ij")
ocupado = ~libre(np.c_[X.ravel(), Y.ravel()]).reshape(n, n)
s = tuple(np.clip(np.round(a / h).astype(int), 0, n - 1))
g = tuple(np.clip(np.round(b / h).astype(int), 0, n - 1))
ocupado[s] = ocupado[g] = False
dist, previo, cola = {s: 0.0}, {}, [(0.0, s)]
while cola:
_, u = heapq.heappop(cola)
if u == g:
break
for dx in (-1, 0, 1):
for dy in (-1, 0, 1):
v = (u[0] + dx, u[1] + dy)
if (dx or dy) and 0 <= v[0] < n and 0 <= v[1] < n and not ocupado[v]:
nd = dist[u] + np.hypot(dx, dy)
if nd < dist.get(v, 1e9):
dist[v], previo[v] = nd, u
heapq.heappush(cola, (nd + np.hypot(v[0] - g[0], v[1] - g[1]), v))
if g not in previo:
return [b]
celdas = [g]
while celdas[-1] != s:
celdas.append(previo[celdas[-1]])
puntos = [np.array(c) * h for c in celdas[::-1]][1:-1] + [b]
out, actual, i = [], a, 0 # atajos por línea de visión
while i < len(puntos):
j = len(puntos) - 1
while j > i and not tramo_libre(actual, puntos[j]):
j -= 1
out.append(puntos[j])
actual, i = puntos[j], j + 1
return out
def __call__(self):
if not self.plan:
eleccion, agente = self._elegir(), self.env.agente()
if eleccion is None:
self.plan = [np.clip(agente + self.rng.normal(0, 0.02, 2), 0.03, 0.48)]
else:
inicio, empuje = eleccion
ruta, actual = [], agente
for w in self._camino(agente, inicio):
k = max(1, int(np.ceil(np.linalg.norm(w - actual) / self.velocidad)))
ruta += [actual + (w - actual) * (i + 1) / k for i in range(k)]
actual = w
self.plan = ruta + [inicio] + list(empuje)
return self.plan.pop(0)
env = EmpujeT()
env.reiniciar(0)
experto = ExpertoEmpujeT(env, semilla=0)
t0 = time.perf_counter()
for t in range(300):
env.paso(experto())
if cobertura(env.pose()) >= env.umbral:
break
print(f"semilla 0: {t + 1} pasos, cobertura {cobertura(env.pose()):.3f}, {time.perf_counter() - t0:.1f} s")npm run lab and open the connection link.The arm is simpler to control because the disk is round: any contour point opposite the target can push it. The expert chooses a Cartesian target for the tip and converts it to angles with a few iterations of damped least squares, , on a data copy. When the line from disk to target passes near the base, the arm would have to fold onto itself; the expert first pushes to a subgoal along a more distant arc.
BRAZO_XML = """
<mujoco model="brazo_empuje">
<compiler angle="radian"/>
<option timestep="0.002" integrator="implicitfast"/>
<visual><global offwidth="256" offheight="256"/><quality shadowsize="0"/></visual>
<default>
<joint damping="0.4" armature="0.005"/>
<geom contype="0" conaffinity="0" rgba="0.55 0.58 0.65 1"/>
</default>
<worldbody>
<light pos="0 0.25 1.5" dir="0 0 -1" directional="true" diffuse="0.8 0.8 0.8"/>
<geom name="mesa" type="plane" pos="0 0.22 0" size="0.5 0.32 0.01" rgba="0.93 0.93 0.93 1"
contype="1" conaffinity="1" friction="0.4 0.005 0.0001"/>
<camera name="arriba" pos="0 0.22 1.15" xyaxes="1 0 0 0 1 0" fovy="45"/>
<body name="meta" pos="0 0.3 0.0005" mocap="true">
<geom type="cylinder" size="0.03 0.0005" rgba="0.35 0.75 0.45 1"/>
</body>
<geom name="base" type="cylinder" pos="0 0 0.02" size="0.035 0.02"/>
<body name="l1" pos="0 0 0.045">
<joint name="hombro" type="hinge" axis="0 0 1" range="-0.2 3.34" limited="true"/>
<geom type="capsule" fromto="0 0 0 0.2 0 0" size="0.014"/>
<body name="l2" pos="0.2 0 0">
<joint name="codo" type="hinge" axis="0 0 1" range="-2.6 2.6" limited="true"/>
<geom type="capsule" fromto="0 0 0 0.17 0 0" size="0.012"/>
<body name="l3" pos="0.17 0 0">
<joint name="muneca" type="hinge" axis="0 0 1" range="-2.0 2.0" limited="true"/>
<geom type="capsule" fromto="0 0 0 0.07 0 0" size="0.01"/>
<body name="dedo" pos="0.07 0 -0.02">
<geom name="dedo" type="cylinder" size="0.012 0.012" contype="2" conaffinity="2"
rgba="0.25 0.35 0.9 1" friction="0.3 0.005 0.0001"/>
<site name="punta" size="0.004"/>
</body>
</body>
</body>
</body>
<body name="disco" pos="0 0.3 0.02">
<freejoint name="disco"/>
<geom name="disco" type="cylinder" size="0.03 0.02" mass="0.15" contype="3" conaffinity="3"
rgba="0.85 0.45 0.3 1" friction="0.4 0.005 0.0001"/>
</body>
</worldbody>
<actuator>
<position joint="hombro" kp="40" kv="4"/>
<position joint="codo" kp="25" kv="2.5"/>
<position joint="muneca" kp="10" kv="1"/>
</actuator>
</mujoco>
"""
RADIO_DISCO, RADIO_PUNTA = 0.03, 0.012
class BrazoEmpuje:
hz, subpasos, tolerancia, max_dq = 20, 25, 0.02, 0.15
ESTADO = mujoco.mjtState.mjSTATE_INTEGRATION
def __init__(self, lado=96):
self.model = mujoco.MjModel.from_xml_string(BRAZO_XML)
self.data = mujoco.MjData(self.model)
self.sitio = self.model.site("punta").id
self.lo, self.hi = self.model.jnt_range[:3].T
self.lado, self.renderer = lado, None
def reiniciar(self, semilla):
rng = np.random.default_rng(semilla)
polar = lambda: (lambda r, a: np.array([r * np.cos(a), r * np.sin(a)]))(rng.uniform(0.2, 0.36), rng.uniform(0.5, np.pi - 0.5))
mujoco.mj_resetData(self.model, self.data)
while True:
disco, meta = polar(), polar()
if np.linalg.norm(meta - disco) > 0.1:
break
q0 = np.array([rng.uniform(0.6, 2.5), rng.uniform(-1.2, 1.2), rng.uniform(-0.8, 0.8)])
self.data.qpos[:3], self.data.ctrl[:] = q0, q0
self.data.qpos[3:6], self.data.qpos[6:10] = [*disco, 0.02], [1, 0, 0, 0]
self.data.mocap_pos[0, :2] = meta
mujoco.mj_forward(self.model, self.data)
if np.linalg.norm(self.punta() - disco) < RADIO_DISCO + RADIO_PUNTA + 0.02:
return self.reiniciar(semilla + 10_000)
def punta(self):
return self.data.site_xpos[self.sitio, :2].copy()
def disco(self):
return self.data.qpos[3:5].copy()
def meta(self):
return self.data.mocap_pos[0, :2].copy()
def paso(self, q_objetivo, redondeo=np.float64):
q = self.data.qpos[:3]
aplicado = np.clip(np.clip(np.asarray(q_objetivo, float), q - self.max_dq, q + self.max_dq), self.lo, self.hi)
aplicado = aplicado.astype(redondeo).astype(np.float64)
self.data.ctrl[:] = aplicado
mujoco.mj_step(self.model, self.data, nstep=self.subpasos)
return aplicado
def imagen(self):
if self.renderer is None:
self.renderer = mujoco.Renderer(self.model, self.lado, self.lado)
self.renderer.update_scene(self.data, camera="arriba")
return self.renderer.render().copy()
estado, fijar_estado = EmpujeT.estado, EmpujeT.fijar_estado
class ExpertoBrazo:
"""Objetivo cartesiano de la punta por reglas geométricas, convertido a ángulos con IK amortiguada."""
def __init__(self, env, velocidad=0.02, lam=0.05):
self.env, self.copia, self.velocidad, self.lam = env, mujoco.MjData(env.model), velocidad, lam
def ik(self, x_objetivo, q):
m, d = self.env.model, self.copia
d.qpos[:] = self.env.data.qpos
d.qpos[:3] = q
J = np.zeros((3, m.nv))
for _ in range(8):
mujoco.mj_kinematics(m, d)
mujoco.mj_comPos(m, d)
e = x_objetivo - d.site_xpos[self.env.sitio, :2]
if np.linalg.norm(e) < 1e-4:
break
mujoco.mj_jacSite(m, d, J, None, self.env.sitio)
Jq = J[:2, :3]
d.qpos[:3] = np.clip(d.qpos[:3] + Jq.T @ np.linalg.solve(Jq @ Jq.T + self.lam**2 * np.eye(2), e), self.env.lo, self.env.hi)
return d.qpos[:3].copy()
def objetivo_punta(self):
punta, disco, meta = self.env.punta(), self.env.disco(), self.env.meta()
seg = meta - disco
s = np.clip(-(disco @ seg) / max(seg @ seg, 1e-12), 0, 1)
if np.linalg.norm(disco + s * seg) < 0.2: # la recta pasa junto a la base: submeta en un arco exterior
a = np.arctan2(disco[1], disco[0]) / 2 + np.arctan2(meta[1], meta[0]) / 2
meta = 0.29 * np.array([np.cos(a), np.sin(a)])
u = meta - disco
dist = np.linalg.norm(u)
u = u / max(dist, 1e-9)
n = np.array([-u[1], u[0]])
contacto = RADIO_DISCO + RADIO_PUNTA
rel = punta - disco
if rel @ u < -0.6 * contacto and abs(rel @ n) < 0.012: # detrás y alineada: empuja
return punta + u * min(self.velocidad, dist + 0.004) - n * (rel @ n) * 0.5
rho = contacto + 0.025
phi = np.arctan2(rel[1], rel[0])
dphi = (np.arctan2(-u[1], -u[0]) - phi + np.pi) % (2 * np.pi) - np.pi
if abs(dphi) < 0.3 and np.linalg.norm(rel) < rho + 0.03:
previo = disco - u * (contacto + 0.003)
else: # orbita alrededor del disco hacia el lado de atrás
ang = phi + np.clip(dphi, -0.6, 0.6)
previo = disco + rho * np.array([np.cos(ang), np.sin(ang)])
delta = previo - punta
return punta + delta * min(1.0, self.velocidad * 1.6 / max(np.linalg.norm(delta), 1e-9))
def __call__(self):
return self.ik(self.objetivo_punta(), self.env.data.qpos[:3].copy())
exitos = 0
for semilla in range(20):
brazo = BrazoEmpuje()
brazo.reiniciar(semilla)
experto, estables = ExpertoBrazo(brazo), 0
for t in range(300):
brazo.paso(experto())
estables = estables + 1 if np.linalg.norm(brazo.disco() - brazo.meta()) < brazo.tolerancia else 0
if estables >= 3:
exitos += 1
break
print("brazo: éxitos del experto en las semillas 0 a 19:", exitos, "/ 20")npm run lab and open the connection link.For ALOHA we download the gym-aloha 0.1.5 wheel from PyPI and extract only its MJCF models and meshes. The wheel’s SHA-256 hash is the one published by PyPI: if the downloaded file does not match, the lab stops instead of executing a different model. The environment’s two modes correspond to the two files for each task: in effector mode, two mocap bodies welded to grippers move the arms; in joint mode, position actuators follow the 14-component commands.
import urllib.request, zipfile
RUEDA = ("https://files.pythonhosted.org/packages/2b/8a/1c6ce361b4a8c36458bb83efc528aa5f06e74ab2a311510c9f1d56e9aacc/"
"gym_aloha-0.1.5-py3-none-any.whl")
RUEDA_SHA256 = "1794dd9a1146268a9b56f4a4931bcba69ca27714c2ac9ac146e471801bf0c7b3"
def modelos_aloha(destino=BASE / "aloha_assets"):
if (destino / "scene.xml").exists():
return destino
datos = urllib.request.urlopen(RUEDA, timeout=60).read()
if hashlib.sha256(datos).hexdigest() != RUEDA_SHA256:
raise ValueError("La rueda descargada no coincide con la huella publicada en PyPI")
destino.mkdir(parents=True, exist_ok=True)
with zipfile.ZipFile(io.BytesIO(datos)) as z:
for nombre in z.namelist():
if nombre.startswith("gym_aloha/assets/") and not nombre.endswith("/"):
(destino / Path(nombre).name).write_bytes(z.read(nombre))
return destino
POSE_INICIAL = np.array([0, -0.96, 1.16, 0, -0.3, 0, 0.02239, -0.02239] * 2)
PINZA_ABIERTA, PINZA_CERRADA = 0.05800, 0.01844 # posición del dedo seguidor (m)
norm_pinza = lambda x: (x - PINZA_CERRADA) / (PINZA_ABIERTA - PINZA_CERRADA)
desnorm_pinza = lambda x: x * (PINZA_ABIERTA - PINZA_CERRADA) + PINZA_CERRADA
FICHEROS = {"transferencia": ("bimanual_viperx_end_effector_transfer_cube.xml", "bimanual_viperx_transfer_cube.xml"),
"insercion": ("bimanual_viperx_end_effector_insertion.xml", "bimanual_viperx_insertion.xml")}
def qmul(a, b):
w1, x1, y1, z1 = a
w2, x2, y2, z2 = b
return np.array([w1*w2 - x1*x2 - y1*y2 - z1*z2, w1*x2 + x1*w2 + y1*z2 - z1*y2,
w1*y2 - x1*z2 + y1*w2 + z1*x2, w1*z2 + x1*y2 - y1*x2 + z1*w2])
def qeje(eje, grados):
h = np.deg2rad(grados) / 2
return np.r_[np.cos(h), np.sin(h) * np.asarray(eje, float)]
def objetos_iniciales(tarea, semilla):
rng = np.random.RandomState(semilla) # mismos rangos que gym-aloha
if tarea == "transferencia":
return np.r_[rng.uniform([0.0, 0.4, 0.05], [0.2, 0.6, 0.05]), 1, 0, 0, 0]
clavija = np.r_[rng.uniform([0.1, 0.4, 0.05], [0.2, 0.6, 0.05]), 1, 0, 0, 0]
enchufe = np.r_[rng.uniform([-0.2, 0.4, 0.05], [-0.1, 0.6, 0.05]), 1, 0, 0, 0]
return np.r_[clavija, enchufe]
def recompensa_aloha(tarea, m, d):
pares = {frozenset((m.geom(c.geom1).name, m.geom(c.geom2).name)) for c in d.contact[:d.ncon]}
hay = lambda a, b: frozenset((a, b)) in pares
if tarea == "transferencia":
izq = hay("red_box", "vx300s_left/10_left_gripper_finger")
der = hay("red_box", "vx300s_right/10_right_gripper_finger")
mesa = hay("red_box", "table")
return 4 if izq and not mesa else 3 if izq else 2 if der and not mesa else 1 if der else 0
paredes = [f"socket-{i}" for i in range(1, 5)]
izq = any(hay(s, "vx300s_left/10_left_gripper_finger") for s in paredes)
der = hay("red_peg", "vx300s_right/10_right_gripper_finger")
en_mesa = hay("red_peg", "table") or any(hay(s, "table") for s in paredes)
if hay("red_peg", "pin"):
return 4
if any(hay("red_peg", s) for s in paredes) and not en_mesa:
return 3
return 2 if izq and der and not en_mesa else 1 if izq and der else 0
class Aloha:
DT, SUBPASOS = 0.02, 10 # 50 Hz, 10 pasos de 2 ms
ESTADO = mujoco.mjtState.mjSTATE_INTEGRATION
def __init__(self, modelos, tarea, modo, alto=120, ancho=160):
self.tarea, self.modo = tarea, modo
self.model = mujoco.MjModel.from_xml_path(str(modelos / FICHEROS[tarea][modo == "articular"]))
if modo == "efector": # copia que solo hace de cinemática inversa: sin fricción seca en los brazos
self.model.dof_frictionloss[:16] = 0
self.data = mujoco.MjData(self.model)
self.tam, self.renderer = (alto, ancho), None
assert abs(self.model.opt.timestep * self.SUBPASOS - self.DT) < 1e-12
def reiniciar(self, objetos):
m, d = self.model, self.data
mujoco.mj_resetData(m, d)
d.qpos[:16] = POSE_INICIAL
d.qpos[16:16 + len(objetos)] = objetos
if self.modo == "efector":
d.mocap_pos[0], d.mocap_quat[0] = [-0.31718881, 0.5, 0.29525084], [1, 0, 0, 0]
d.mocap_pos[1], d.mocap_quat[1] = [0.31718881, 0.49999888, 0.29525084], [1, 0, 0, 0]
d.ctrl[:] = [PINZA_CERRADA, -PINZA_CERRADA, PINZA_CERRADA, -PINZA_CERRADA]
else:
d.ctrl[:] = POSE_INICIAL
mujoco.mj_forward(m, d)
def qpos14(self):
q = self.data.qpos
return np.r_[q[:6], norm_pinza(q[6]), q[8:14], norm_pinza(q[14])]
def paso(self, accion):
d = self.data
if self.modo == "efector": # [xyz, cuaternio, pinza] por brazo
d.mocap_pos[0], d.mocap_quat[0] = accion[:3], accion[3:7]
d.mocap_pos[1], d.mocap_quat[1] = accion[8:11], accion[11:15]
gi, gd = desnorm_pinza(accion[7]), desnorm_pinza(accion[15])
d.ctrl[:] = [gi, -gi, gd, -gd]
else: # 6 articulaciones + pinza normalizada por brazo
gi, gd = desnorm_pinza(accion[6]), desnorm_pinza(accion[13])
d.ctrl[:] = np.r_[accion[:6], gi, -gi, accion[7:13], gd, -gd]
mujoco.mj_step(self.model, d, nstep=self.SUBPASOS)
return recompensa_aloha(self.tarea, self.model, d)
def imagen(self, camara="top"):
if self.renderer is None:
self.renderer = mujoco.Renderer(self.model, *self.tam)
self.renderer.update_scene(self.data, camera=camara)
return self.renderer.render().copy()
estado, fijar_estado = EmpujeT.estado, EmpujeT.fijar_estado
class PuntosDePaso:
"""El experto programado de ACT: poses de cada pinza en instantes fijos, interpoladas linealmente."""
def __init__(self, tarea, objetos, izq0, der0):
W = lambda t, xyz, q, g: dict(t=t, xyz=np.asarray(xyz, float), q=np.asarray(q, float), g=g)
I0, D0 = W(0, izq0[:3], izq0[3:], 0), W(0, der0[:3], der0[3:], 0)
if tarea == "transferencia":
cubo, coger = objetos[:3], qmul(der0[3:], qeje([0, 1, 0], -60))
q_enc, enc = qeje([1, 0, 0], 90), np.array([0, 0.5, 0.25])
self.izq = [I0, W(100, enc + [-0.1, 0, -0.02], q_enc, 1), W(260, enc + [0.02, 0, -0.02], q_enc, 1),
W(310, enc + [0.02, 0, -0.02], q_enc, 0), W(360, enc + [-0.1, 0, -0.02], [1, 0, 0, 0], 0),
W(400, enc + [-0.1, 0, -0.02], [1, 0, 0, 0], 0)]
self.der = [D0, W(90, cubo + [0, 0, 0.08], coger, 1), W(130, cubo + [0, 0, -0.015], coger, 1),
W(170, cubo + [0, 0, -0.015], coger, 0), W(200, enc + [0.05, 0, 0], coger, 0),
W(220, enc, coger, 0), W(310, enc, coger, 1), W(360, enc + [0.1, 0, 0], coger, 1),
W(400, enc + [0.1, 0, 0], coger, 1)]
else:
clavija, enchufe = objetos[:3], objetos[7:10]
qd, qi = qmul(der0[3:], qeje([0, 1, 0], -60)), qmul(der0[3:], qeje([0, 1, 0], 60))
enc, sube, fin = np.array([0, 0.5, 0.15]), 0.00715, 0.04 # ACT usa fin = 0.05
self.izq = [I0, W(120, enchufe + [0, 0, 0.08], qi, 1), W(170, enchufe + [0, 0, -0.03], qi, 1),
W(220, enchufe + [0, 0, -0.03], qi, 0), W(285, enc + [-0.1, 0, 0], qi, 0),
W(340, enc + [-fin, 0, 0], qi, 0), W(400, enc + [-fin, 0, 0], qi, 0)]
self.der = [D0, W(120, clavija + [0, 0, 0.08], qd, 1), W(170, clavija + [0, 0, -0.03], qd, 1),
W(220, clavija + [0, 0, -0.03], qd, 0), W(285, enc + [0.1, 0, sube], qd, 0),
W(340, enc + [fin, 0, sube], qd, 0), W(400, enc + [fin, 0, sube], qd, 0)]
self.t = 0
@staticmethod
def _en(ruta, t):
for a, b in zip(ruta, ruta[1:]):
if a["t"] <= t < b["t"]:
f = (t - a["t"]) / (b["t"] - a["t"])
return np.r_[a["xyz"] + (b["xyz"] - a["xyz"]) * f, a["q"] + (b["q"] - a["q"]) * f, a["g"] + (b["g"] - a["g"]) * f]
u = ruta[-1]
return np.r_[u["xyz"], u["q"], u["g"]]
def __call__(self):
a = np.r_[self._en(self.izq, self.t), self._en(self.der, self.t)]
self.t += 1
return a
def ordenes_experto_aloha(modelos, tarea, semilla, pasos=400):
"""Fase 1: el experto mueve los efectores en la copia con mocap; se leen las articulaciones resultantes."""
objetos = objetos_iniciales(tarea, semilla)
ee = Aloha(modelos, tarea, "efector")
ee.reiniciar(objetos)
d = ee.data
experto = PuntosDePaso(tarea, objetos, np.r_[d.mocap_pos[0], d.mocap_quat[0]], np.r_[d.mocap_pos[1], d.mocap_quat[1]])
ordenes = []
for _ in range(pasos):
q = ee.qpos14()
q[6], q[13] = norm_pinza(d.ctrl[0]), norm_pinza(d.ctrl[2]) # la orden de la pinza, no su posición
ordenes.append(q)
ee.paso(experto())
return objetos, np.array(ordenes)
MODELOS_ALOHA = modelos_aloha()
for tarea in ("transferencia", "insercion"):
objetos, ordenes = ordenes_experto_aloha(MODELOS_ALOHA, tarea, 0)
env = Aloha(MODELOS_ALOHA, tarea, "articular") # fase 2: se reproducen en el entorno articular
env.reiniciar(objetos)
r = [env.paso(o) for o in ordenes]
print(f"{tarea}: órdenes {ordenes.shape}, recompensa máxima {max(r)}, pasos por nivel {np.bincount(r, minlength=5).tolist()}")npm run lab and open the connection link.Teleoperation
A scripted expert provides clean, plentiful data, but only for what someone knew how to program. For tasks nobody knows how to write as rules, which include almost all interesting ones, the source is a person. Demonstration collection is the complete process turning a human or scripted demonstrator’s intent into usable episodes: the device and conversion to actions, control-frequency loop, operator view, success criterion, decision to keep or discard each episode, and recording all of it.
Devices are not equivalent, and each leaves its signature in the data:
- Mouse: provides absolute screen positions, converted by camera calibration to table coordinates. It is natural for Push-T, where action is already a position: the Diffusion Policy repository collects demonstrations with a script in which the agent follows the mouse pointer when the operator brings it close. Its signature: jumps when the operator releases and grabs again, and pauses while thinking.
- Keyboard: provides discrete commands (pressed or not) integrated as constant velocities. It produces stair-step trajectories, with infinite acceleration on pressing and releasing.
- Gamepad: two continuous axes per stick integrated as velocities, with a dead zone around zero so hand tremor does not move the robot. This is a common middle ground for simulated arms.
- Leader and follower: a passive arm with the same kinematics as the robot, whose joints are read and sent as target positions, ALOHA’s leader-follower teleoperation technique. It enables fine bimanual manipulation at 50 Hz, and is how ACT’s simulated human demonstrations were recorded: real leader arms moved the simulated robot while the operator watched the render on a monitor.
For ALOHA we will not attempt bimanual gamepad teleoperation: fourteen degrees of freedom with two sticks do not produce quality demonstrations. We use LeRobot’s 50 human demonstrations per task, recorded with leader and follower, and write our own teleoperation for T pushing (mouse, keyboard, or gamepad) and the arm (keyboard or gamepad over tip position, converted to angles by the expert’s same inverse kinematics).
Three design choices distinguish a usable teleoperation interface from one producing damaging data:
- The loop governs. The interface runs at the task’s control frequency with a clock that waits to complete each period (
Clock.tick(hz)), and records the actual period. If rendering or reading the device takes longer than a period, the operator sees a simulation slower than real time and overcorrects; the record makes this detectable. - The operator sees what the policy will see. Showing the same saved camera, enlarged, prevents a human from using information the policy will not have (another angle or numeric T pose). ACT did the same when teleoperating in simulation while watching the render.
- Staying still is an action. When the operator releases the mouse, the recorded action is to hold position. Those pauses enter the data, and a memoryless policy imitating them can stop in similar states. Decide before recording whether to trim them, and record that decision.
Human demonstration quality is not measured by success alone. In the opening figure, the proportion of steps with a stationary action is 3% for human Push-T demonstrations versus 19% for the expert, whose pushes end with two waiting steps; humans, by contrast, vary much more in contact point and push order. Mandlekar et al. (2021) studied this in robomimic: with datasets from multiple operators of unequal expertise, policies perform worse than with one expert operator, and models with temporal memory such as BC-RNN make more use of human demonstrations than ones deciding only from current observation, because human behavior is not Markovian.
The teleoperation code follows. Devices process pygame events, including keyboard events, rather than instantaneous key state: this lets the same class work with real and simulated events. The cell verifies it with simulated events in a virtual window (SDL’s dummy driver), checking that the loop starts, converts inputs to actions, and records the episode; it does not check ergonomics with a real device, which only you can evaluate by teleoperating.
INTERACTIVO = os.environ.get("P13_L01_TELEOP") in ("empuje_t", "brazo")
if not INTERACTIVO:
os.environ["SDL_VIDEODRIVER"] = "dummy" # ventana virtual para la prueba con eventos simulados
import pygame
class Raton:
"""Posición absoluta: mientras el botón izquierdo está pulsado, el objetivo es el puntero."""
def __init__(self):
self.pulsado, self.px = False, None
def procesar(self, ev):
if ev.type == pygame.MOUSEBUTTONDOWN and ev.button == 1:
self.pulsado, self.px = True, ev.pos
elif ev.type == pygame.MOUSEBUTTONUP and ev.button == 1:
self.pulsado = False
elif ev.type == pygame.MOUSEMOTION:
self.px = ev.pos
def objetivo(self, actual, anterior, dt, pantalla_a_mesa):
return pantalla_a_mesa(self.px) if self.pulsado and self.px is not None else actual # soltar = quedarse quieto
class Teclado:
"""Flechas como velocidad constante; se integra sobre el objetivo anterior, no sobre la posición medida."""
TECLAS = {pygame.K_RIGHT: (1, 0), pygame.K_LEFT: (-1, 0), pygame.K_UP: (0, 1), pygame.K_DOWN: (0, -1)}
def __init__(self, velocidad=0.08, y_hacia_abajo=False):
self.v, self.pulsadas, self.signo_y = velocidad, set(), -1 if y_hacia_abajo else 1
def procesar(self, ev):
if ev.type == pygame.KEYDOWN and ev.key in self.TECLAS:
self.pulsadas.add(ev.key)
elif ev.type == pygame.KEYUP:
self.pulsadas.discard(ev.key)
def objetivo(self, actual, anterior, dt, pantalla_a_mesa):
d = np.sum([self.TECLAS[k] for k in self.pulsadas], axis=0) if self.pulsadas else np.zeros(2)
base = actual if anterior is None else anterior
nuevo = base + self.v * dt * np.array([d[0], self.signo_y * d[1]])
return actual + np.clip(nuevo - actual, -0.03, 0.03) # el objetivo no se aleja más de 3 cm
class Mando:
"""Palanca izquierda como velocidad, con zona muerta radial."""
def __init__(self, velocidad=0.1, zona_muerta=0.15, y_hacia_abajo=False):
self.v, self.zm, self.ejes, self.signo_y = velocidad, zona_muerta, np.zeros(2), 1 if y_hacia_abajo else -1
pygame.joystick.init()
self.joystick = pygame.joystick.Joystick(0) if pygame.joystick.get_count() else None
def procesar(self, ev):
if ev.type == pygame.JOYAXISMOTION and ev.axis in (0, 1):
self.ejes[ev.axis] = ev.value
def objetivo(self, actual, anterior, dt, pantalla_a_mesa):
r = np.linalg.norm(self.ejes)
u = np.zeros(2) if r < self.zm else self.ejes / r * min(1.0, (r - self.zm) / (1 - self.zm))
base = actual if anterior is None else anterior
nuevo = base + self.v * dt * np.array([u[0], self.signo_y * u[1]])
return actual + np.clip(nuevo - actual, -0.03, 0.03)
class Teleoperacion:
"""Política humana: lee el dispositivo, enseña la cámara de la política y devuelve la acción del contrato."""
def __init__(self, tarea, dispositivo, escala=5, eventos_simulados=None):
pygame.init()
self.tarea, self.dispositivo, self.escala = tarea, dispositivo, escala
alto, ancho = tarea.tam_camara
self.pantalla = pygame.display.set_mode((ancho * escala, alto * escala))
pygame.display.set_caption(f"Atlas p13: {tarea.nombre} (Esc para terminar)")
self.reloj, self.periodos_ms, self.anterior = pygame.time.Clock(), [], None
self.simulados = eventos_simulados or {}
def __call__(self, tarea, t):
for ev in self.simulados.get(t, []):
pygame.event.post(ev)
for ev in pygame.event.get():
if ev.type == pygame.QUIT or (ev.type == pygame.KEYDOWN and ev.key == pygame.K_ESCAPE):
return None # el operador cancela el episodio
self.dispositivo.procesar(ev)
img = tarea.ultima_imagen
superficie = pygame.surfarray.make_surface(np.ascontiguousarray(img.swapaxes(0, 1)))
self.pantalla.blit(pygame.transform.scale(superficie, self.pantalla.get_size()), (0, 0))
pygame.display.flip()
actual = tarea.punto_control()
px_a_mesa = lambda px: tarea.pantalla_a_mesa(np.array(px) / self.escala)
self.anterior = self.dispositivo.objetivo(actual, self.anterior, 1 / tarea.hz, px_a_mesa)
self.periodos_ms.append(self.reloj.tick(tarea.hz)) # espera hasta completar el periodo
return tarea.accion_desde_punto(self.anterior)
def cerrar(self):
pygame.quit()
print("pygame", pygame.version.ver, "| mandos conectados:", (pygame.joystick.init(), pygame.joystick.get_count())[1])npm run lab and open the connection link.Lab, part two: record, save, and replay
Each task is wrapped in an adapter with the same interface: reiniciar, observar, actuar, estado, fijar_estado, and feature descriptions. The adapter converts units (meters to millimeters in T pushing) and decides what the policy sees and what is saved as privileged environment state. That separation guards against the most common simulated-robotics leakage: training a policy on a variable unavailable at deployment. What goes into observation.state is what a real robot would have (pusher position, joint angles); exact object pose goes into observation.environment_state, used for debugging, the expert, and replay, and not to be given to a vision policy.
def f32(n, nombres=None):
return {"dtype": "float32", "shape": [n], "names": nombres}
def caracteristicas_comunes(n_accion, nombres_accion=None):
return {"action": f32(n_accion, nombres_accion), "next.reward": f32(1),
"next.success": {"dtype": "bool", "shape": [1], "names": None},
"next.done": {"dtype": "bool", "shape": [1], "names": None}}
class TareaEmpujeT:
nombre, texto, robot, hz, pasos_max, tam_camara = "empuje_t", "Empuja la T hasta la pose verde", "empujador_2d", 10, 300, (96, 96)
clave_imagen = "observation.image"
def __init__(self):
self.env, self.huella = EmpujeT(), huella(PUSHT_XML)
self.caracteristicas = {"observation.state": f32(2, ["x", "y"]),
"observation.environment_state": f32(16),
self.clave_imagen: {"dtype": "image", "shape": [96, 96, 3], "names": ["height", "width", "channel"]},
**caracteristicas_comunes(2, ["x", "y"])}
def reiniciar(self, semilla):
self.env.reiniciar(semilla)
def observar(self, imagenes=True):
obs = {"observation.state": self.env.agente() * 1000, "observation.environment_state": self.env.vertices() * 1000}
if imagenes:
obs[self.clave_imagen] = self.ultima_imagen = self.env.imagen()
return obs
def actuar(self, accion_mm):
aplicada = np.clip(np.asarray(accion_mm, float), 0, 512).astype(np.float32) # los bits que se guardan
self.env.paso(aplicada.astype(np.float64) / 1000)
c = cobertura(self.env.pose())
return aplicada, min(c / 0.95, 1.0), c >= self.env.umbral, c >= self.env.umbral
def estado(self):
return self.env.estado()
def fijar_estado(self, s):
self.env.fijar_estado(s)
# teleoperación: la pantalla es la imagen ampliada, con y hacia abajo como en gym-pusht
def punto_control(self):
return self.env.agente()
def pantalla_a_mesa(self, px):
return np.asarray(px, float) / 96 * 0.512
def accion_desde_punto(self, punto):
return np.asarray(punto) * 1000
class TareaBrazo:
nombre, texto, robot, hz, pasos_max, tam_camara = "brazo", "Empuja el disco hasta el círculo verde", "brazo_plano_3gdl", 20, 300, (96, 96)
clave_imagen = "observation.images.top"
def __init__(self):
self.env, self.huella = BrazoEmpuje(), huella(BRAZO_XML)
self.ik = ExpertoBrazo(self.env)
self.caracteristicas = {"observation.state": f32(6, ["hombro", "codo", "muneca", "v_hombro", "v_codo", "v_muneca"]),
"observation.environment_state": f32(6, ["punta_x", "punta_y", "disco_x", "disco_y", "meta_x", "meta_y"]),
self.clave_imagen: {"dtype": "image", "shape": [96, 96, 3], "names": ["height", "width", "channel"]},
**caracteristicas_comunes(3, ["hombro", "codo", "muneca"])}
def reiniciar(self, semilla):
self.env.reiniciar(semilla)
self.estables = 0
def observar(self, imagenes=True):
e = self.env
obs = {"observation.state": np.r_[e.data.qpos[:3], e.data.qvel[:3]],
"observation.environment_state": np.r_[e.punta(), e.disco(), e.meta()]}
if imagenes:
obs[self.clave_imagen] = self.ultima_imagen = e.imagen()
return obs
def actuar(self, q):
aplicada = self.env.paso(q, redondeo=np.float32)
dist = float(np.linalg.norm(self.env.disco() - self.env.meta()))
self.estables = self.estables + 1 if dist < self.env.tolerancia else 0
return aplicada, -dist, self.estables >= 3, self.estables >= 3
def estado(self):
return self.env.estado()
def fijar_estado(self, s):
self.env.fijar_estado(s)
self.estables = 0
# teleoperación: la pantalla es la cámara cenital (y hacia arriba), que cubre 0.95 m de lado
def punto_control(self):
return self.env.punta()
def pantalla_a_mesa(self, px):
lado = 2 * 1.15 * np.tan(np.deg2rad(22.5))
return np.array([px[0] / 96 * lado - lado / 2, 0.22 + lado / 2 - px[1] / 96 * lado])
def accion_desde_punto(self, punto):
return self.ik.ik(np.asarray(punto), self.env.data.qpos[:3].copy())
class TareaAloha:
hz, pasos_max, robot, tam_camara = 50, 400, "aloha_viperx_sim", (120, 160)
clave_imagen = "observation.images.top"
TEXTOS = {"transferencia": "Pasa el cubo rojo de la pinza derecha a la izquierda",
"insercion": "Inserta la clavija roja en el enchufe azul"}
def __init__(self, tarea):
self.tarea, self.nombre, self.texto = tarea, f"aloha_{tarea}", self.TEXTOS[tarea]
self.env = Aloha(MODELOS_ALOHA, tarea, "articular")
self.huella = hashlib.sha256((MODELOS_ALOHA / FICHEROS[tarea][1]).read_bytes()).hexdigest()
n_obj = 7 if tarea == "transferencia" else 14
brazo = ["cintura", "hombro", "codo", "giro_antebrazo", "muneca", "giro_muneca", "pinza"]
nombres = [f"izq_{n}" for n in brazo] + [f"der_{n}" for n in brazo]
self.caracteristicas = {"observation.state": f32(14, nombres), "observation.environment_state": f32(n_obj),
self.clave_imagen: {"dtype": "image", "shape": [120, 160, 3], "names": ["height", "width", "channel"]},
**caracteristicas_comunes(14, nombres)}
def reiniciar(self, semilla):
self.env.reiniciar(objetos_iniciales(self.tarea, semilla))
def observar(self, imagenes=True):
obs = {"observation.state": self.env.qpos14(), "observation.environment_state": self.env.data.qpos[16:].copy()}
if imagenes:
obs[self.clave_imagen] = self.ultima_imagen = self.env.imagen()
return obs
def actuar(self, accion):
aplicada = np.asarray(accion, np.float32)
r = self.env.paso(aplicada.astype(np.float64))
return aplicada, float(r), r == 4, False # ACT graba siempre los 400 pasos
def estado(self):
return self.env.estado()
def fijar_estado(self, s):
self.env.fijar_estado(s)
def experto_para(tarea, semilla):
"""Devuelve la política programada de la tarea, ya preparada para esa semilla."""
if isinstance(tarea, TareaEmpujeT):
e = ExpertoEmpujeT(tarea.env, semilla=semilla)
return lambda tarea, t: e() * 1000
if isinstance(tarea, TareaBrazo):
e = ExpertoBrazo(tarea.env)
return lambda tarea, t: e()
_, ordenes = ordenes_experto_aloha(MODELOS_ALOHA, tarea.tarea, semilla, tarea.pasos_max)
return lambda tarea, t: ordenes[t]
TAREAS = [TareaEmpujeT(), TareaBrazo(), TareaAloha("transferencia"), TareaAloha("insercion")]
for ta in TAREAS:
print(f"{ta.nombre:20s} {ta.hz:3d} Hz acción {ta.caracteristicas['action']['shape']} "
f"estado {ta.caracteristicas['observation.state']['shape']} cámara {ta.tam_camara}")npm run lab and open the connection link.The recorder applies the episode definition literally. At each step it takes a timestamp, observes (with image), asks the policy (expert or person) for an action, takes another timestamp, and acts. It saves the applied action and, separately, the simulator’s initial integration state: positions, velocities, actuator commands, mocap positions, and solver warm start. With that state and actions, replay does not depend on the seed regenerating the same initial state, which cannot be guaranteed if reiniciar code changes.
One detail is not cosmetic. The format stores actions in float32 and the simulator works in float64. If the environment receives a double-precision action and the file stores its rounded version, replay applies actions differing by one part in ten million and contacts amplify the difference: in the first version of this recorder, without rounding, T-pushing replay diverged from the recording by up to 2.6 mm and one of three episodes stopped succeeding. Therefore adapters round applied action to float32 before sending it to the simulator: the environment receives exactly the bits saved.
def grabar(tarea, semilla, politica, operador, imagenes=True):
tarea.reiniciar(semilla)
inicial = tarea.estado()
filas = {k: [] for k in tarea.caracteristicas}
marcas_obs, marcas_acc, exito, cancelado = [], [], False, False
for t in range(tarea.pasos_max):
t_obs = time.monotonic_ns()
obs = tarea.observar(imagenes)
accion = politica(tarea, t)
if accion is None:
cancelado = True
break
marcas_obs.append(t_obs)
marcas_acc.append(time.monotonic_ns())
aplicada, r, exito_t, fin = tarea.actuar(accion)
exito |= bool(exito_t)
for k, v in obs.items():
filas[k].append(v)
filas["action"].append(aplicada)
filas["next.reward"].append(r)
filas["next.success"].append(bool(exito_t))
filas["next.done"].append(bool(fin) or t == tarea.pasos_max - 1)
if fin:
break
if filas["action"]:
filas["next.done"][-1] = True
datos = {k: np.asarray(v) for k, v in filas.items() if len(v)}
meta = {"semilla": int(semilla), "operador": operador, "exito": exito, "cancelado": cancelado,
"pasos": len(filas["action"]), "hz": tarea.hz, "mujoco": mujoco.__version__,
"modelo_sha256": tarea.huella, "estado_inicial": inicial.tolist(),
"marcas_obs_ns": marcas_obs, "marcas_accion_ns": marcas_acc}
return {"datos": datos, "meta": meta}
ta = TAREAS[0]
ep = grabar(ta, 0, experto_para(ta, 0), "programado")
print({k: v.shape for k, v in ep["datos"].items()})
print("éxito", ep["meta"]["exito"], "| pasos", ep["meta"]["pasos"],
"| acción quieta en el", f"{np.mean(np.linalg.norm(np.diff(ep['datos']['action'], axis=0), axis=1) < 1):.0%}", "de los pasos")npm run lab and open the connection link.LeRobot format
The format separates three scales. Step (one data row), episode (a contiguous row range described in episode metadata), and dataset (global information and statistics). Episodes sharing files permits reading millions of steps without opening millions of files; the cost is that segmentation is known only from metadata, never a filename. Types matter as much as shapes: vector features are fixed-length float32 lists, timestamps float32 seconds since episode start (exactly frame_index / fps at uniform frequency), and indices int64. For an idea of sizes, Parquet’s types and columnar storage are the same topic as in tabular data.
We write the format from scratch with pyarrow and verify it two ways: reading output with our own reader and replaying episodes. The schema reproduces what LeRobot 0.6.1 writes with use_videos=False, including Hugging Face metadata that make the image column decode as an image; while preparing this lesson we verified LeRobot 0.6.1 loads the datasets written by this cell and returns exactly the same actions, states, indices, and pixels.
Statistics are computed only on training episodes. The writer calculates each episode’s statistics when added and, on closing, aggregates those of the training range: global mean and variance are obtained exactly from per-episode statistics by variance decomposition, and with and the episode’s population standard deviation, and global quantiles are approximated by the weighted mean of per-episode quantiles (the mean of quantiles is not the mixture quantile). For images, to avoid visiting every pixel (LeRobot also subsamples), each episode’s statistics come from a sample of up to 100 frames, weighted by episode length, so that result is an estimate rather than the exact value across all frames. The split is written in info.json as "splits": {"train": "0:80", "test": "80:100"}.
import pyarrow as pa, pyarrow.compute as pc, pyarrow.parquet as pq, pandas as pd
from PIL import Image
CUANTILES = (0.01, 0.10, 0.50, 0.90, 0.99)
def estadisticas(x):
x = np.asarray(x, dtype=np.float64).reshape(len(x), -1)
s = {"min": x.min(0), "max": x.max(0), "mean": x.mean(0), "std": x.std(0), "count": np.array([len(x)])}
for q in CUANTILES:
s[f"q{round(q * 100):02d}"] = np.quantile(x, q, axis=0)
return s
def estadisticas_imagen(imgs, max_muestras=100):
idx = np.unique(np.linspace(0, len(imgs) - 1, min(len(imgs), max_muestras)).round().astype(int))
s = estadisticas(imgs[idx].reshape(-1, 3) / 255.0)
return {k: (np.array([len(imgs)]) if k == "count" else v.reshape(3, 1, 1)) for k, v in s.items()}
def agregar(lista):
n = np.array([s["count"][0] for s in lista], float)
w = n / n.sum()
media = sum(wi * s["mean"] for wi, s in zip(w, lista))
var = sum(wi * (s["std"] ** 2 + (s["mean"] - media) ** 2) for wi, s in zip(w, lista))
out = {"min": np.min([s["min"] for s in lista], 0), "max": np.max([s["max"] for s in lista], 0),
"mean": media, "std": np.sqrt(var), "count": np.array([int(n.sum())])}
for q in CUANTILES:
k = f"q{round(q * 100):02d}"
out[k] = sum(wi * s[k] for wi, s in zip(w, lista))
return out
def _png(img):
b = io.BytesIO()
Image.fromarray(img).save(b, format="PNG")
return b.getvalue()
INDICES = {"timestamp": {"dtype": "float32", "shape": [1], "names": None},
**{k: {"dtype": "int64", "shape": [1], "names": None} for k in ("frame_index", "episode_index", "index", "task_index")}}
class EscritorLeRobot:
def __init__(self, raiz, tarea, mb_por_fichero=100):
self.raiz, self.tarea, self.limite = Path(raiz), tarea, mb_por_fichero * 2**20
self.features = {**tarea.caracteristicas, **INDICES}
if self.raiz.exists():
raise FileExistsError(f"{self.raiz} ya existe: elige otro destino")
(self.raiz / "meta").mkdir(parents=True)
self.episodios, self.stats_ep, self.buffer, self.bytes_buffer = [], [], [], 0
self.fichero, self.total = 0, 0
self.procedencia = (self.raiz / "meta" / "atlas_procedencia.jsonl").open("w", encoding="utf-8")
def _hf_feature(self, spec):
if spec["dtype"] == "image":
return {"_type": "Image"}
if spec["shape"] == [1]:
return {"dtype": spec["dtype"], "_type": "Value"}
return {"feature": {"dtype": spec["dtype"], "_type": "Value"}, "length": spec["shape"][0], "_type": "List"}
def _columna(self, k, valores):
spec = self.features[k]
if spec["dtype"] == "image":
tipo = pa.struct([("bytes", pa.binary()), ("path", pa.string())])
return pa.array([{"bytes": b, "path": None} for b in valores], type=tipo)
tipo = {"float32": pa.float32(), "int64": pa.int64(), "bool": pa.bool_()}[spec["dtype"]]
v = np.asarray(valores)
if spec["shape"] == [1]:
return pa.array(v.reshape(-1), type=tipo)
return pa.FixedSizeListArray.from_arrays(pa.array(v.reshape(-1), type=tipo), spec["shape"][0])
def _volcar(self):
if not self.buffer:
return
cols = {k: [] for k in self.features}
for fila in self.buffer:
for k in self.features:
cols[k].extend(fila[k])
tabla = pa.table({k: self._columna(k, v) for k, v in cols.items()})
hf = {"info": {"features": {k: self._hf_feature(s) for k, s in self.features.items()}}}
tabla = tabla.replace_schema_metadata({b"huggingface": json.dumps(hf).encode()})
ruta = self.raiz / f"data/chunk-{self.fichero // 1000:03d}/file-{self.fichero % 1000:03d}.parquet"
ruta.parent.mkdir(parents=True, exist_ok=True)
pq.write_table(tabla, ruta)
self.buffer, self.bytes_buffer, self.fichero = [], 0, self.fichero + 1
def anadir(self, episodio):
d, n, e = episodio["datos"], episodio["meta"]["pasos"], len(self.episodios)
fila = {k: list(d[k]) for k in self.tarea.caracteristicas if k != self.tarea.clave_imagen}
fila[self.tarea.clave_imagen] = [_png(im) for im in d[self.tarea.clave_imagen]]
fila.update(timestamp=list(np.arange(n, dtype=np.float32) / np.float32(self.tarea.hz)),
frame_index=list(range(n)), episode_index=[e] * n,
index=list(range(self.total, self.total + n)), task_index=[0] * n)
tam = sum(len(b) for b in fila[self.tarea.clave_imagen]) + 8 * n * sum(
int(np.prod(s["shape"])) for s in self.features.values() if s["dtype"] != "image")
if self.buffer and self.bytes_buffer + tam > self.limite:
self._volcar()
self.buffer.append(fila)
self.bytes_buffer += tam
st = {k: (estadisticas_imagen(d[k]) if k == self.tarea.clave_imagen else estadisticas(fila[k] if k not in d else d[k]))
for k in self.features}
self.stats_ep.append(st)
self.episodios.append({"episode_index": e, "tasks": [self.tarea.texto], "length": n,
"data/chunk_index": self.fichero // 1000, "data/file_index": self.fichero % 1000,
"dataset_from_index": self.total, "dataset_to_index": self.total + n})
self.total += n
meta = {k: v for k, v in episodio["meta"].items() if not k.startswith("marcas")}
meta.update(episode_index=e, periodo_real_ms=float(np.mean(np.diff(episodio["meta"]["marcas_obs_ns"]))) / 1e6 if n > 1 else None)
self.procedencia.write(json.dumps(meta, ensure_ascii=False) + "\n")
def cerrar(self, n_entrenamiento):
self._volcar()
self.procedencia.close()
E = len(self.episodios)
if not 0 < n_entrenamiento <= E:
raise ValueError("La partición de entrenamiento debe tener al menos un episodio")
lista = lambda a: np.asarray(a).tolist()
filas = []
for ep, st in zip(self.episodios, self.stats_ep):
fila = dict(ep)
for k, s in st.items():
for nombre, v in s.items():
fila[f"stats/{k}/{nombre}"] = lista(v)
fila["meta/episodes/chunk_index"], fila["meta/episodes/file_index"] = 0, 0
filas.append(fila)
ruta_ep = self.raiz / "meta/episodes/chunk-000/file-000.parquet"
ruta_ep.parent.mkdir(parents=True)
pq.write_table(pa.Table.from_pylist(filas), ruta_ep)
pd.DataFrame({"task_index": [0]}, index=pd.Index([self.tarea.texto], name="task")).to_parquet(self.raiz / "meta/tasks.parquet")
stats = {k: {n: lista(v) for n, v in agregar([s[k] for s in self.stats_ep[:n_entrenamiento]]).items()} for k in self.features}
(self.raiz / "meta/stats.json").write_text(json.dumps(stats, indent=1), encoding="utf-8")
info = {"codebase_version": "v3.0", "robot_type": self.tarea.robot, "total_episodes": E, "total_frames": self.total,
"total_tasks": 1, "chunks_size": 1000, "data_files_size_in_mb": self.limite // 2**20, "video_files_size_in_mb": 200,
"fps": self.tarea.hz, "splits": {"train": f"0:{n_entrenamiento}", **({"test": f"{n_entrenamiento}:{E}"} if n_entrenamiento < E else {})},
"data_path": "data/chunk-{chunk_index:03d}/file-{file_index:03d}.parquet", "video_path": None,
"features": self.features}
(self.raiz / "meta/info.json").write_text(json.dumps(info, indent=1, ensure_ascii=False), encoding="utf-8")
return infonpm run lab and open the connection link.The reader reverses the process without LeRobot: it opens metadata, groups rows by episode, and checks structure (contiguous global indices, frame_index from 0 to , timestamps equal to frame_index / fps). Replay restores saved initial state, applies dataset actions, and compares recomputed proprioceptive and environment states step by step against recorded ones, converted to float32 as in the file.
def leer_lerobot(raiz, imagenes=False):
raiz = Path(raiz)
info = json.loads((raiz / "meta/info.json").read_text(encoding="utf-8"))
stats = json.loads((raiz / "meta/stats.json").read_text(encoding="utf-8"))
eps = pq.read_table(raiz / "meta/episodes/chunk-000/file-000.parquet").to_pylist()
columnas = [k for k, s in info["features"].items() if imagenes or s["dtype"] != "image"]
tablas = {}
episodios = []
for ep in eps:
clave = (ep["data/chunk_index"], ep["data/file_index"])
if clave not in tablas:
tablas[clave] = pq.read_table(raiz / info["data_path"].format(chunk_index=clave[0], file_index=clave[1]), columns=columnas)
t = tablas[clave]
t = t.filter(pc.equal(t["episode_index"], ep["episode_index"]))
d = {k: np.array(t[k].to_pylist()) if info["features"][k]["dtype"] != "image" else
np.stack([np.asarray(Image.open(io.BytesIO(x["bytes"]))) for x in t[k].to_pylist()]) for k in columnas}
assert d["index"].tolist() == list(range(ep["dataset_from_index"], ep["dataset_to_index"]))
assert d["frame_index"].tolist() == list(range(ep["length"]))
assert np.allclose(d["timestamp"], d["frame_index"] / info["fps"], atol=1e-6)
episodios.append(d)
procedencia = [json.loads(l) for l in (raiz / "meta/atlas_procedencia.jsonl").read_text(encoding="utf-8").splitlines()]
return info, stats, episodios, procedencia
def reproducir(tarea, datos, meta):
tarea.reiniciar(meta["semilla"])
tarea.fijar_estado(np.array(meta["estado_inicial"]))
error, exito = 0.0, False
for t, accion in enumerate(datos["action"]):
obs = tarea.observar(imagenes=False)
for k in ("observation.state", "observation.environment_state"):
error = max(error, float(np.max(np.abs(obs[k].astype(np.float32) - datos[k][t]))))
_, _, exito_t, _ = tarea.actuar(accion)
exito |= bool(exito_t)
return error, exito
def wilson(k, n, z=1.96):
p = k / n
centro = (p + z * z / (2 * n)) / (1 + z * z / n)
radio = z / (1 + z * z / n) * np.sqrt(p * (1 - p) / n + z * z / (4 * n * n))
return centro - radio, centro + radio
print("Wilson 95 % para 20 de 20:", np.round(wilson(20, 20), 3), "| para 3 de 3:", np.round(wilson(3, 3), 3))npm run lab and open the connection link.Collection
The next cell is the full-size lab. For each task it requests episodes from the expert with consecutive seeds until gathering N_DEMOS successes (or exhausting three times that many attempts), saves successful ones in a LeRobot dataset with the first 80% as training and last 20% as test, and records failures with their seed in a separate file: they are deterministic, so the seed suffices to reproduce them. Expert success rate is reported over all attempts with its Wilson interval. Extrapolating the short run, completo mode takes roughly ten to fifteen minutes on a laptop and occupies roughly half a gigabyte, almost all ALOHA PNG images (about 2 MB per episode).
def recoger_programadas(tarea, n_exitos, raiz):
if raiz.exists():
if MODO != "corto":
raise FileExistsError(f"{raiz} ya existe: no se sobrescribe un conjunto completo")
shutil.rmtree(raiz)
escritor = EscritorLeRobot(raiz, tarea)
fallos, semilla, t0 = [], 0, time.perf_counter()
while len(escritor.episodios) < n_exitos and semilla < 3 * n_exitos:
ep = grabar(tarea, semilla, experto_para(tarea, semilla), "programado")
if ep["meta"]["exito"]:
escritor.anadir(ep)
else:
fallos.append({"semilla": semilla, "pasos": ep["meta"]["pasos"],
"recompensa_max": float(ep["datos"]["next.reward"].max())})
semilla += 1
n = len(escritor.episodios)
escritor.cerrar(n_entrenamiento=max(1, int(round(0.8 * n))))
(raiz / "meta/atlas_fallos.json").write_text(json.dumps(fallos, ensure_ascii=False), encoding="utf-8")
return {"exitos": n, "intentos": semilla, "segundos": time.perf_counter() - t0}
RESUMEN = {}
for ta in TAREAS:
r = recoger_programadas(ta, N_DEMOS, LAB / f"{ta.nombre}_programadas")
lo, hi = wilson(r["exitos"], r["intentos"])
RESUMEN[ta.nombre] = r
print(f"{ta.nombre:20s} éxitos {r['exitos']}/{r['intentos']} intentos Wilson 95 % [{lo:.2f}, {hi:.2f}] {r['segundos']:.1f} s")npm run lab and open the connection link.Now reread each dataset from disk and replay all its episodes. The check has two parts: the reader reconstructs the declared structure and physics recreates recorded states. On the same machine and MuJoCo version, expected error is exactly zero; a difference on another machine, on the order of rounding error and growing over time due to contact chaos, does not necessarily indicate recorder failure, and tolerance is chosen with that knowledge rather than adjusted until it passes.
for ta in TAREAS:
raiz = LAB / f"{ta.nombre}_programadas"
info, stats, episodios, procedencia = leer_lerobot(raiz)
errores, exitos = [], 0
for d, meta in zip(episodios, procedencia):
assert meta["modelo_sha256"] == ta.huella, "el modelo cambió desde la grabación"
err, ok = reproducir(ta, d, meta)
errores.append(err)
exitos += ok
tam = sum(f.stat().st_size for f in raiz.rglob("*") if f.is_file()) / 2**20
RESUMEN[ta.nombre].update(error=max(errores), mb=tam)
print(f"{ta.nombre:20s} {info['total_episodes']} episodios, {info['total_frames']} pasos, partición {info['splits']}, "
f"{tam:.1f} MB | reproducción: error máximo {max(errores):.1e}, éxitos recreados {exitos}/{len(episodios)}")
print("estadísticas de acción del empuje en T (solo entrenamiento):",
{k: np.round(v, 1).tolist() for k, v in json.loads((LAB / "empuje_t_programadas/meta/stats.json").read_text())["action"].items() if k in ("mean", "std", "count")})npm run lab and open the connection link.Human demonstrations
Human T-pushing and ALOHA demonstrations published by LeRobot are already in v3.0 format. We download only their tables and metadata (about 15 MB, without videos), pinning the exact downloaded revision for repeatability, and compare human and scripted ones. They cannot be replayed in our simulation: Push-T demonstrations were recorded in Pymunk with different contact physics, and ALOHA datasets do not save the initial pose of cube, peg, or socket, without which no action sequence recreates the episode. For T-pushing coverage we recover T pose from its eight vertices (observation.environment_state of lerobot/pusht_keypoints) using planar Kabsch fitting, and measure it with our simulation’s same function.
from huggingface_hub import HfApi, snapshot_download
def descargar(repo):
revision = HfApi().dataset_info(repo).sha
ruta = snapshot_download(repo, repo_type="dataset", revision=revision, allow_patterns=["meta/*", "data/*"],
local_dir=BASE / "hub" / repo.split("/")[1])
return Path(ruta), revision
def tabla(ruta):
return pd.concat([pd.read_parquet(f) for f in sorted(ruta.glob("data/*/*.parquet"))])
def pose_desde_vertices(v):
"""Kabsch en 2D: rotación y traslación que llevan los vértices locales (mm) a los observados."""
P, Q = VERTICES * 1000, v.reshape(8, 2)
pc, qc = P.mean(0), Q.mean(0)
H = (P - pc).T @ (Q - qc)
th = np.arctan2(H[0, 1] - H[1, 0], H[0, 0] + H[1, 1])
return np.r_[qc - rot(th) @ pc, th]
ruta, rev = descargar("lerobot/pusht_keypoints")
df = tabla(ruta)
humanas = []
for _, g in df.groupby("episode_index"):
a = np.stack(g["action"].values)
fin = pose_desde_vertices(np.stack(g["observation.environment_state"].values)[-1])
humanas.append({"T": len(g), "quieta": np.mean(np.linalg.norm(np.diff(a, axis=0), axis=1) < 1),
"cob_final": cobertura(np.r_[fin[:2] / 1000, fin[2]]), "exito_conjunto": bool(g["next.success"].any())})
h = pd.DataFrame(humanas)
print(f"lerobot/pusht_keypoints @ {rev[:8]}: {len(h)} episodios humanos, {h['T'].mean():.0f} ± {h['T'].std(ddof=0):.0f} pasos")
print(f" acción quieta (< 1 px por paso): {h['quieta'].mean():.1%} de los pasos")
print(f" cobertura final: media {h['cob_final'].mean():.3f}, máximo {h['cob_final'].max():.3f}; "
f"episodios con next.success en el conjunto: {h['exito_conjunto'].sum()}")
info, _, propias, _ = leer_lerobot(LAB / "empuje_t_programadas")
quieta = np.mean([np.mean(np.linalg.norm(np.diff(d["action"], axis=0), axis=1) < 1) for d in propias])
print(f"programadas propias ({info['total_episodes']}): {np.mean([len(d['action']) for d in propias]):.0f} pasos de media, acción quieta {quieta:.1%}")
def instante_agarre(a, j=13, hz=50):
g = a[:, j]
abre = np.argmax(g > g.min() + 0.7 * (g.max() - g.min()))
return (abre + np.argmax(g[abre:] < g.min() + 0.3 * (g.max() - g.min()))) / hz
for fuente in ("human", "scripted"):
for tarea in ("transfer_cube", "insertion"):
ruta, rev = descargar(f"lerobot/aloha_sim_{tarea}_{fuente}")
acciones = [np.stack(g["action"].values) for _, g in tabla(ruta).groupby("episode_index")]
t_agarre = np.array([instante_agarre(a) for a in acciones])
print(f"aloha_sim_{tarea}_{fuente} @ {rev[:8]}: {len(acciones)} episodios de {len(acciones[0])} pasos; "
f"cierre de la pinza derecha {t_agarre.mean():.2f} ± {t_agarre.std():.2f} s")npm run lab and open the connection link.The output contains the finding previewed by the figure. The 206 human episodes end with the T very close to the target (mean final pose less than one millimeter away, with dispersion of about 5 mm and 0.06 rad across episodes), but with mean coverage 0.85 and none above 0.93, and the dataset’s own next.success column is false throughout. This is not a reader error: with 30 mm-wide bars, moving the T 5 mm along one axis already leaves 11% of its area outside, and rotating it 0.06 rad leaves 10%; with position and angle errors of those sizes together, 0.85 coverage is expected. Operators judged the task complete by eye, and the environment’s 0.95 criterion is stricter than their eyes. Diffusion Policy reports target coverage rather than binary success in Push-T (with images, in its best configuration, 0.91 at the best checkpoint and 0.84 averaged over the last ten), precisely because the binary threshold penalizes differences that are not visible.
Two consequences for the rest of the project. A policy perfectly imitating these people will have success near zero under the 0.95 criterion, without being poorly trained. And our expert, which plans with the simulator and reaches the threshold, is not comparable to those humans on the same metric without saying so. Fix the success criterion before collecting data, verify demonstrations meet it, and if you mix sources, report how many satisfy it in each.
Teleoperate your own demonstrations
The lab’s last cell records human demonstrations with the teleoperation defined above. Without P13_L01_TELEOP it runs the automatic test: one T-pushing episode with simulated mouse events (click the pusher and drag it toward the T) and one arm episode with simulated arrows, both in the virtual window; it checks that pusher and tip follow commands and the episode is recorded and written in format. With P13_L01_TELEOP=empuje_t or P13_L01_TELEOP=brazo and optionally P13_L01_DISPOSITIVO set to raton, teclado, or mando, it opens the real window and records episodes until gathering N_DEMOS accepted. After each episode the window waits for a key: G saves it and D discards it, with the reason retained in provenance. Episodes canceled with Escape and failed episodes are recorded too.
def ev(tipo, **kw):
return pygame.event.Event(tipo, **kw)
def prueba_simulada():
# Empuje en T con ratón: pulsar sobre el empujador y arrastrar 12 pasos hacia el centro de la T
ta = TAREAS[0]
ta.reiniciar(1)
ag = ta.env.agente() / 0.512 * 96 * 5
centro = ta.env.pose()[:2] / 0.512 * 96 * 5
guion = {0: [ev(pygame.MOUSEBUTTONDOWN, button=1, pos=tuple(ag.round()))]}
for t in range(1, 13):
guion[t] = [ev(pygame.MOUSEMOTION, pos=tuple((ag + (centro - ag) * t / 12).round()), rel=(0, 0), buttons=(1, 0, 0))]
guion[13] = [ev(pygame.MOUSEBUTTONUP, button=1, pos=tuple(centro.round()))]
guion[20] = [ev(pygame.KEYDOWN, key=pygame.K_ESCAPE, mod=0, unicode="", scancode=0)]
tele = Teleoperacion(ta, Raton(), eventos_simulados=guion)
ep = grabar(ta, 1, tele, "prueba_eventos_simulados")
tele.cerrar()
a = ep["datos"]["action"]
print(f"ratón simulado: {ep['meta']['pasos']} pasos grabados, cancelado={ep['meta']['cancelado']}, "
f"objetivo final {np.round(a[12], 1).tolist()} mm (centro de la T {np.round(centro / 5 / 96 * 512, 1).tolist()}), "
f"periodo medio {np.mean(tele.periodos_ms[1:]):.0f} ms")
# Brazo con teclado: flecha derecha durante 10 pasos
tb = TAREAS[1]
guion = {0: [ev(pygame.KEYDOWN, key=pygame.K_RIGHT, mod=0, unicode="", scancode=0)],
10: [ev(pygame.KEYUP, key=pygame.K_RIGHT, mod=0, unicode="", scancode=0)],
14: [ev(pygame.KEYDOWN, key=pygame.K_ESCAPE, mod=0, unicode="", scancode=0)]}
tele = Teleoperacion(tb, Teclado(), eventos_simulados=guion)
ep2 = grabar(tb, 1, tele, "prueba_eventos_simulados")
tele.cerrar()
punta = ep2["datos"]["observation.environment_state"][:, :2]
print(f"teclado simulado: {ep2['meta']['pasos']} pasos, la punta se movió {1000 * (punta[-1] - punta[0]).round(3)} mm")
raiz = LAB / "prueba_teleoperacion"
shutil.rmtree(raiz, ignore_errors=True)
w = EscritorLeRobot(raiz, ta)
w.anadir(ep)
w.cerrar(n_entrenamiento=1)
print("escrito y releído:", leer_lerobot(raiz)[0]["total_frames"], "pasos")
def recoger_humanas(tarea, dispositivo, n, raiz, semilla0=10_000):
escritor, semilla, descartes = EscritorLeRobot(raiz, tarea), semilla0, []
tele = Teleoperacion(tarea, dispositivo)
try:
while len(escritor.episodios) < n:
tele.anterior = None
ep = grabar(tarea, semilla, tele, "humano")
semilla += 1
decision = None
while decision is None: # G guarda, D descarta
for e in pygame.event.get():
if e.type == pygame.KEYDOWN and e.key in (pygame.K_g, pygame.K_d):
decision = "guardar" if e.key == pygame.K_g else "descartar"
elif e.type == pygame.QUIT:
decision = "salir"
pygame.time.wait(20)
print(f"semilla {semilla - 1}: éxito={ep['meta']['exito']}, pasos={ep['meta']['pasos']}, {decision}")
if decision == "salir":
break
if decision == "guardar" and ep["meta"]["pasos"] > 0:
escritor.anadir(ep)
else:
descartes.append({"semilla": semilla - 1, "exito": ep["meta"]["exito"], "cancelado": ep["meta"]["cancelado"]})
finally:
tele.cerrar()
n_ok = len(escritor.episodios)
if n_ok:
escritor.cerrar(n_entrenamiento=max(1, int(round(0.8 * n_ok))))
(raiz / "meta/atlas_descartes.json").write_text(json.dumps(descartes), encoding="utf-8")
return n_ok, descartes
if INTERACTIVO:
tarea = {"empuje_t": TAREAS[0], "brazo": TAREAS[1]}[os.environ["P13_L01_TELEOP"]]
nombre = os.environ.get("P13_L01_DISPOSITIVO", "raton" if tarea is TAREAS[0] else "teclado")
disp = {"raton": Raton, "teclado": lambda: Teclado(y_hacia_abajo=tarea is TAREAS[0]),
"mando": lambda: Mando(y_hacia_abajo=tarea is TAREAS[0])}[nombre]()
n_ok, descartes = recoger_humanas(tarea, disp, N_DEMOS, LAB / f"{tarea.nombre}_humanas_{nombre}")
print("demostraciones humanas guardadas:", n_ok, "| descartadas:", len(descartes))
else:
prueba_simulada()npm run lab and open the connection link.Lab outcome
With completo mode, the lab leaves four scripted datasets of 100 successful demonstrations in ~/atlas-lab/p13-l01/completo/ (T pushing, arm, ALOHA transfer and insertion), each with 80 training and 20 test episodes, training-only statistics, provenance, and recorded failures; the human teleoperation datasets you record (100 per task for T pushing and arm); and the published human demonstrations in ~/atlas-lab/p13-l01/hub/: 206 for Push-T and 50 per ALOHA task, the 50 ACT used. No more public simulated human ALOHA demonstrations exist beyond those, and recording your own requires leader arms: this is the only point where the project falls below 100 human demonstrations per task, worth knowing when comparing scaling curves in lesson 8.
What to expect on execution, as a reasoned expectation rather than a measurement: in the short 40-episode run used for the figure, the T-pushing expert solved all 40, and in the arm cell’s 20-seed test its expert solved 19. With seeds 0 through 19, the ALOHA expert succeeded on 19 transfers out of 20 and 10 insertions out of 20; the ten failed insertions received no reward because one gripper failed to catch its object: in six, the left missed the socket; in four, the right missed the peg. With a rate near one half, gathering 100 successful insertions needs about 200 attempts, within the cell’s limit of 300; the Wilson interval for 10 of 20, , does not rule out a true rate somewhat below one third, in which case the cell would exhaust attempts with fewer than 100 and state so in its summary. With 100 or more attempts per task, each rate’s Wilson interval will have half-width around 10 percentage points or less. Replay should yield zero error on your machine.
for nombre, r in RESUMEN.items():
lo, hi = wilson(r["exitos"], r["intentos"])
print(f"{nombre:20s} {r['exitos']:3d} demostraciones | experto {r['exitos']}/{r['intentos']} "
f"[{lo:.2f}, {hi:.2f}] | error de reproducción {r['error']:.1e} | {r['mb']:.1f} MB")npm run lab and open the connection link.Writing the same data with the library
With LeRobot installed (pip install lerobot, in its own environment because it pulls many dependencies), writing uses its API: LeRobotDataset.create declares features, add_frame adds a step with the task key, save_episode closes an episode, computes its statistics and writes it, and finalize closes files. By default images are video-encoded, reducing size by an order of magnitude at the cost of lossy compression: if you later compare pixels, fix codec and tolerance. stats.json statistics are computed over the whole dataset, so to respect the split either write training and test as separate datasets or recalculate stats.json using training episodes as our writer does. Never upload a dataset to the Hub without deciding to: save locally with root and do not call push_to_hub.
from lerobot.datasets import LeRobotDataset
ta = TAREAS[0]
features = {k: {**s, "shape": tuple(s["shape"])} for k, s in ta.caracteristicas.items()}
ds = LeRobotDataset.create(repo_id="local/empuje_t_programadas", fps=ta.hz, root=LAB / "empuje_t_lerobot",
features=features, robot_type=ta.robot, use_videos=False)
for semilla in range(N_DEMOS):
ep = grabar(ta, semilla, experto_para(ta, semilla), "programado")
if not ep["meta"]["exito"]:
continue
d = ep["datos"]
for t in range(ep["meta"]["pasos"]):
frame = {"task": ta.texto}
for k, spec in ta.caracteristicas.items():
v = np.asarray(d[k][t])
frame[k] = v if spec["dtype"] == "image" else v.astype(spec["dtype"]).reshape(spec["shape"])
ds.add_frame(frame)
ds.save_episode()
ds.finalize()
leido = LeRobotDataset("local/empuje_t_programadas", root=LAB / "empuje_t_lerobot")
print(leido.meta.total_episodes, len(leido), leido[0]["action"])
Common mistakes
Exercises
import numpy as np
def compute_norm_stats(dataset):
passSummary
A demonstration is a synchronized record: observation captured before deciding, action received by the environment, and initial state enabling replay. Scripted experts with privileged simulator access provide reliable data and a measurable success rate with interval; teleoperation provides diversity and, with it, pauses and modes the policy must model. LeRobot format separates steps, episodes, and metadata, and normalization statistics are computed only on training episodes. Before training anything, check episodes can be reread, replay recreates states, and they meet the success criterion you will use for evaluation.