A cart tuned on one simulated floor rolls 0.74 m off the end of a wet real dock. Train it on a range of floors and it stops in time, but it now stops short on every floor.
Learn how a robot trained in simulation survives real hardware. Measure the world, randomize it, teach a student to sense it, and correct the simulator with real data.
Pick Wet tile and press Run. Then widen the range until the cart stops on the dock. Then pick Lab tile and see what the width cost. Then we build it piece by piece: the reality gap, system identification, randomization, the teacher and the student, and real to sim.
You need a little Python and what a policy and a reward are. We build the rest from zero.
Re-taught from Lecture 16, Sim2Real robot learning (a guest lecture by Guanya Shi, CMU), of Stanford CS 224R: Deep Reinforcement Learning. The explanations, toys and numbers here are our own; every toy number is illustrative.
Illustrative toy. The cart drives at 3 m/s toward an edge 4 m away. It brakes by sliding, so it needs v²/(2μg) metres to stop. The policy is one brake point, set so the most slippery training floor stops exactly at the edge. The simulator's floor is 0.80; we made up the floor frictions.
Chapter 0
Count what a million tries cost on hardware, and write down the one line every simulator runs
A delivery robot must learn to stop its cart at the end of a loading dock. Reinforcement learning finds the right move by trial and error, and it needs millions of tries. On real hardware, every early mistake is a cart off the dock.
A simulator is a program that steps a model of the robot and its world forward in time. In a simulator a fall costs nothing. Sim2real means training a policy in simulation and then running it on the real robot, with little or no training on the robot.
| What simulation gives | What it removes |
|---|---|
| Cheap, fast, parallel | Months of robot time |
| Safe | Broken hardware |
| Free labels | Sensors for friction, contact force, terrain height: the simulator knows them |
| No wear | Stripped gears and worn joints |
Every simulator does one thing per tick. Call the state of the world at step t x-t: for the cart, its speed. Call the action u-t: the brake command. Call the hidden settings of the world e: friction, mass, motor strength, delay. The physics engine, f-sim, turns these into the next state.
x at t plus one equals f-sim of x-t, u-t and e.
Give the engine the state x-t, the action u-t and the world's settings e. It returns the state one tick later. For a braking cart, the speed drops by mu times g times the tick length.
With made-up numbers: speed 3 m/s, friction 0.8, gravity g = 9.81 m/s², a tick of 0.02 s. The drop is 0.8 × 9.81 × 0.02 = 0.157 m/s, so the next speed is 2.843 m/s.
The real world runs the same kind of step with its own f-real and its own e, which you never know exactly. The reality gap is the difference between the two. Every method in this lesson attacks the e in that line.
The warm bar is one real robot. The blue bar is the simulator. Both must collect 2 billion transitions. The time axis is logarithmic. Drag the sliders.
Illustrative numbers: a control rate of 50 steps per second, and a task that needs 2 billion transitions.
Work it once. One robot at 50 steps per second collects 50 transitions a second. A GPU simulator with 4,096 copies at 5 times real time collects 4,096 × 50 × 5 = 1,024,000 a second. That is 20,480 times more. Two billion transitions take 463 days of nonstop robot time, or 33 minutes in simulation.
The failure. No simulator is perfect. The symptom is a policy that never fails in simulation and falls on its first real run. To measure the gap, send the same commands in simulation and on the robot, and compare the recorded states. The fixes are the rest of this lesson.
Chapter 1
Sort the gap into wrong numbers and missing physics, and see why a small gap can end in a fall
The cart learned its brake point on a simulated floor with friction 0.8. The real floor has friction 0.5. How far off is it?
| Kind of gap | What is wrong | Example | Fix |
|---|---|---|---|
| Parametric | Right equations, wrong numbers | Friction 0.5, not 0.8; mass 5.2 kg, not 5.0 kg | Measure it (Chapter 2) or randomize it (Chapter 3) |
| Non-parametric | An effect the model lacks | Wind on a drone, brake lag, gear backlash | Learn the missing term (Chapter 7) or tolerate it |
First, the wrong number. A sliding cart slows at a steady rate of μ times g. Call its speed when braking starts v. Speed falls at a steady rate, so the average speed is v/2. The time to stop is v/(μg). Distance is average speed times time.
s equals v squared over two mu g.
Square the speed v. Divide by two, by mu and by g. Half the friction means twice the stopping distance s.
With made-up numbers: v = 3 m/s. On the simulated floor, μ = 0.8 and s = 9 / (2 × 0.8 × 9.81) = 0.573 m. On the real floor, μ = 0.5 and s = 0.917 m. The cart brakes 0.573 m before the edge and rolls 0.344 m past it.
A brake point is one decision. A walking robot makes 200 decisions a second, and each error feeds the next. Call the state error at step t ε-t (epsilon-t). In a fast, unstable move, the error grows by a factor ρ (rho) every step.
Epsilon-t equals epsilon-zero times rho to the t.
Start with the first error epsilon-zero. Multiply it by rho once per step. If rho is above 1, the error grows by the same share every step.
With made-up numbers: ε-0 = 0.001 rad and ρ = 1.05. The error passes 1 rad at step 142, which is 0.71 s at 200 steps per second.
The warm line is the real robot's error from the simulated plan, on a log scale. The red line is where it falls. Change the growth per step.
Illustrative: 200 steps per second, and a fall at 1 rad of error.
The failure. A policy that works for the first second, then drifts and falls. To measure it, log the simulated and the real states side by side and plot their gap. On a log scale, steady growth is a straight line. The fix is feedback, plus the methods below. Never replay a simulated trajectory open loop on hardware.
Chapter 2
Record the real robot and choose the parameters that make the simulator replay the record
You can measure the real floor. Brake the real cart, record its speed every tick, and find the friction that makes the simulator replay the same record. That is system identification: fitting the simulator's parameters e to real data.
For each recorded step, give the simulator the real state and the real action, and let it predict the next state. Score the miss against what the robot did. Choose the e with the smallest total miss. Call the best e e-hat.
e-hat equals the arg-min over e of the sum over t of the square of: x-real at t plus one, minus f-sim of x-real-t, u-real-t and e.
For each recorded step, predict the next state with f-sim. Subtract the prediction from x-real at t plus one. Square, and add over t. Try values of e and keep the one with the smallest total: that is e-hat.
With made-up recorded speeds 3.000, 2.902, 2.802 and 2.706 m/s, one every 0.02 s while braking. The drops are 0.098, 0.100 and 0.096, an average of 0.098 m/s. The best friction is 0.098 / (9.81 × 0.02) = 0.50. The total squared miss is 0.0104 at friction 0.8 and 0.000008 at 0.50.
For the cart the total miss is a parabola in μ, so its lowest point has a formula. Set its slope to zero:
Here Δt (delta-t) is one tick, 0.02 s. Most robots have no formula: you search over e by sampling or by gradient descent.
Warm dots are the real speeds. Blue ticks are the simulator's one-step predictions. The lower panel is the total squared miss for every friction. Drag the friction, or press Fit.
Illustrative record: ten braking ticks on a floor of friction 0.50, with small reading noise.
The failure. Data that never uses the parameter. A cart that stands still says nothing about friction, so the total miss is flat. The symptom is a fit that returns a different value every run. To measure it, plot the miss against the parameter and look for a clear dip. The fix is to record motions that use the parameter. The lecture's example, SPI-Active, chooses such motions on purpose.
Chapter 3
Draw a new world for every episode, so the real world is one more sample the policy already handles
You cannot measure every real floor ahead of time. So train on many floors. Domain randomization draws new world parameters e for every training episode, from a range you choose. Each parallel copy of the simulator gets its own floor.
Call the policy's weights θ (theta). Call the policy's average return on one world J(θ, e). Call the distribution you draw worlds from p(e): here, friction spread evenly over a range.
Theta-star equals the arg-max over theta of the expected value, over e drawn from p of e, of J of theta and e.
Draw a world e from p of e. Run the policy there and score it with J. Average the scores over many worlds. Training moves theta to raise that average.
With made-up numbers: three equally likely floors, friction 0.5, 0.8 and 1.1. The return is minus the gap in metres, and minus 10 for a fall. Braking 0.917 m before the edge scores 0, −0.344 and −0.500: average −0.28. Braking at 0.573 m falls on the 0.5 floor: average −3.39. Training picks 0.917 m.
Ordinary reinforcement learning maximizes J for one fixed e. The only change is the outer average. The policy never sees e, so it must find one behaviour that is good enough on every world. That is robust control: one controller for a whole set of systems.
Each lane is one simulated floor. The teal line is the brake point; each dot is where that floor stops the cart. Red means it fell. Drag the brake point, or let training choose.
Illustrative: return is minus the gap in metres, minus 10 for a fall. Real training uses thousands of worlds and a neural policy, not ten and one number.
What teams randomize, in practice:
The failure. A range that misses reality. Every training world succeeds, and the real robot still fails. To measure it, estimate the real value (Chapter 2) and check that it lies inside the range. The fix is to widen the range toward it, or to move its centre.
Chapter 4
Price the width: each floor the range covers costs a little on every other floor
Go back to the hero. A wide range saved the cart on wet tile. On lab tile the same cart stopped almost a metre short. Why does width cost anything?
Call the lowest friction in the training range μ-lo (mu-lo). The randomized cart brakes where a floor of μ-lo would stop it at the edge. On a real floor with friction μ-real above μ-lo, it stops short. Call that shortfall the gap.
Gap equals v squared over two g, times one over mu-lo minus one over mu-real.
The brake point is the stopping distance on mu-lo. The real stop is the stopping distance on mu-real. Subtract the second from the first. If mu-real is below mu-lo, the gap is negative and the cart falls.
With made-up numbers: μ-lo = 0.35 and μ-real = 0.8. The gap is 0.459 × (2.857 − 1.250) = 0.737 m. A cart trained on 0.8 alone has gap 0 there, but on wet tile at 0.35 it overshoots by the same 0.737 m.
The centre line is the dock edge. Red bars to the left are carts that rolled past it. Teal bars to the right are gaps. Drag the lowest training friction.
Illustrative floors and frictions. The cart moves at 3 m/s; the range's upper end does not change the brake point.
In general, one policy shared by every world cannot beat, on average, a policy made for each world. The difference is the price of robustness. The rule from the lecture: randomize widely enough that reality is inside the range, and no wider. If you can measure a parameter, centre the range on the measurement first.
The failure. Over-conservatism: a range so wide that the policy turns timid. It moves slowly, stops far short, or skips moves it could make. To measure it, compare its return on the nominal world with a policy trained on that world alone. The fix is a narrower range, or adaptation (Chapters 5 and 6), so the policy can be bold where it is safe.
Chapter 5
Train a teacher that sees the true world, then distill it into a student that sees only what the robot senses
The randomized cart brakes for the worst floor every time. A cart that knew the friction could brake at the right point on each floor. In simulation the friction is a variable you set, so you can hand it over.
Privileged information is anything the simulator knows that the real robot cannot sense: friction, true mass, terrain height, contact forces. A teacher policy gets it as an input. A student policy gets only what the real robot has: the state and a short history of its own recent sensor readings and actions. Copying the teacher into the student is distillation.
Call the student's weights φ (phi), the state x, the history h and the number of training samples N.
L of phi equals one over N times the sum over i of the square of: pi-student of x-i and h-i, minus pi-teacher of x-i and e-i.
At each sample, ask the teacher, which sees e, and the student, which sees only h. Square the difference of their actions and average. Gradient descent on phi lowers L of phi.
With made-up numbers: floors of friction 0.5, 0.8 and 1.1. The teacher brakes at 0.917, 0.573 and 0.417 m. The student says 0.850, 0.600 and 0.500 m. The misses are −0.067, +0.027 and +0.083; squared and averaged, L = 0.0040 m².
The purple curve is the teacher's brake point for each friction. Yellow dots are the student's; red ones brake too late. Press Train. Then switch off the history, reset and train again.
Illustrative toy: the student is a line fit to one feature, the stopping distance its history suggests. A real student is a network that reads raw sensor history.
| Variant | What changes |
|---|---|
| RMA (Kumar et al., 2021) | The teacher squeezes e into a small vector z. The student predicts z from history and reuses the teacher's base policy. |
| Asymmetric actor-critic (Pinto et al., 2018) | One stage. The critic sees e in training; the actor sees only real inputs. Deployment drops the critic. |
The failure. A student with too little history. Its loss stays high, and its action barely changes from world to world. To measure it, plot the student's action against the true e over many worlds; a flat line means it cannot tell the worlds apart. The fix is a longer history, or motions that reveal e.
Chapter 6
Read the friction from how fast the cart picks up speed, and trade a calm estimate against a late one
How can a history reveal friction? At full throttle a wheel can push only as hard as friction allows. So the cart speeds up at μ times g, and its last few speed readings show μ. Estimating the world this way, while the robot runs, is online adaptation.
Call the speed reading at tick t v-t, the window length k ticks, and one tick Δt (delta-t). Call the estimate mu-hat.
Mu-hat equals v-t minus v at t minus k, over k times g times delta-t.
Take the speed gained over the last k ticks. Divide by the time those ticks took, k times delta-t: that is the acceleration. Divide by g. That is mu-hat.
With made-up readings: 0.50 m/s ten ticks ago and 1.48 m/s now. Mu-hat = 0.98 / (10 × 9.81 × 0.02) = 0.98 / 1.962 = 0.50.
Each reading carries a little noise with spread σ-v (sigma-v). The difference of two readings has spread √2 times σ-v, so the estimate's spread falls as 1/k:
With σ-v = 0.02 m/s, the spread is 0.029 at k = 5 and 0.010 at k = 15. A longer window is calmer, but it answers later: 15 ticks take 0.3 s.
Top: warm dots are noisy speed readings at full throttle. Bottom: the yellow line is mu-hat from the last k readings; the dashed line is the hidden truth. Change the window, or draw a new floor.
Illustrative: reading noise 0.02 m/s, 50 ticks per second. A fitted line over all k readings does a little better than the two endpoints used here.
| Method | Policy input | Strength | Cost |
|---|---|---|---|
| Domain randomization | State only | Simple; no estimate to get wrong | Conservative on every world |
| Teacher and student | State and history | Recovers most of the price of robustness | Two stages; needs a history that reveals e |
In practice you do both: randomize for robustness, and adapt to win back performance. This pairing is robust adaptive control.
The failure. Stale history. If the floor changes from carpet to a wet patch, the window holds old readings for k ticks. The symptom is a slip just after a surface change. To measure it, log mu-hat across a known change and time the lag. The fix is a shorter window, or a student trained on worlds that change during the episode.
Chapter 7
Fit a small correction to real records, add it to the physics, and train again in the corrected simulator
Some gaps are not a wrong number. On the real cart the brake takes about 0.1 s to build full force. The simulator applies it at once. No friction value fixes that.
Real to sim uses real data to correct the simulator, then trains again in the corrected simulator: real to sim to real. For a wrong number, the correction is system identification (Chapter 2). For a missing effect, it is a residual: a small network that predicts how far the simulator's next state is off.
x at t plus one equals f-sim of x-t, u-t and e, plus g-phi of x-t and u-t.
Run the physics step f-sim. Add the residual's correction g-phi. Train phi so that the sum matches the next state in the real records.
With the toy's numbers: speed 3 m/s, friction 0.8, the first tick after the brake command. The simulator predicts 2.843 m/s. The real cart, with its brake still building, reads 2.985 m/s. So g-phi must learn +0.142 m/s for this state.
Speed after the brake command. Blue: the simulator. Warm dots: the real cart. Pink: the simulator plus the residual; pink bars are the residual per tick. Press Fit.
Illustrative toy: friction 0.8, start speed 3 m/s, brake force builds with a 0.1 s time constant. The residual here is a table with one value per tick since the command.
The lag costs 0.26 m: the simulator stops the cart in 0.573 m, and the real cart needs 0.835 m. The best-known residual in legged robots is the actuator net (Hwangbo et al., 2019). It records real motors, with recent position errors and speeds as input and measured torque as output, and replaces the ideal motor model in simulation. The lecture also describes fitting such a residual without a torque sensor, by matching recorded joint trajectories.
The failure. A residual that leaves its data. The corrected simulator matches the logs, and the policy trained on it fails on new motions. To measure it, hold out real runs at speeds or surfaces the residual never saw, and check its error there. The fix is a wider spread of recorded motions, a small residual, and randomization around it.
Chapter 8
Stack randomization, adaptation and real to sim, then deploy on six real floors with a lagging brake
Here is the whole recipe on six real floors. The real world has two gaps at once: friction anywhere from 0.35 to 1.0, and a brake that lags 0.1 s. Switch on the layers and deploy.
Each lane is one real floor. The teal line is that cart's brake point. Turn on layers, then press Deploy.
Illustrative toy. Without randomization the simulator's floor is 0.80. The student estimates friction from its start (Chapter 6, k = 10) and brakes for its estimate minus three spreads. Real to sim adds the brake lag to the simulator.
Try the layers in this order and read each result:
Adaptation alone, without randomization, changes nothing. A student trained on one world has nothing to infer. The layers depend on each other: randomization gives the student worlds to tell apart, and real to sim gives the teacher the right physics.
| Topic | What the lecture covers |
|---|---|
| Rewards from human data | A hand-written reward for pouring or assembling is hard. Retarget a human's motion onto the robot's body, then train an RL policy in simulation to track it, so physics makes it feasible. Named examples include ASAP, BeyondMimic, OmniRetarget and SPIDER. |
| The RL algorithm | On-policy PPO is the usual choice: parallel simulation makes fresh samples cheap, and its clipped update is stable. Newer methods named: SAPG, FastTD3, FPO and BFM-Zero. |
| Sim2Real 1.0 to 4.0 | 1.0: online model-predictive control on simple models. 2.0: RL in a full simulator. 3.0: add real to sim. 4.0: learned world models with offline training and online reasoning together. |
Chapter 9
Keep the terms, the numbers, a checklist and the core code on one page
A simulator steps x-t forward with world parameters e, and the real world uses a different e and some physics the simulator lacks. Measure the numbers you can. Randomize the ones you cannot. Let a student read the world from its history. Correct the simulator with real records, and train again.
| Term | Meaning |
|---|---|
| Reality gap | The difference between f-sim with its e and the real world |
| Parametric gap | Right equations, wrong numbers |
| Non-parametric gap | An effect the simulator does not model |
| System identification | Fit e so the simulator replays real records |
| Domain randomization | Draw a new e for every training episode |
| Privileged information | What the simulator knows and the robot cannot sense |
| Distillation | Train a student to copy a teacher's actions |
| Online adaptation | Estimate e from history while running, with frozen weights |
| Residual | A learned correction added to the physics step |
| What | Number | Why it matters |
|---|---|---|
| Parallel sim against one robot | 33 minutes against 463 days | Why training starts in simulation |
| Stop at 3 m/s, μ 0.8 and 0.5 | 0.573 m and 0.917 m | A wrong number puts the cart 0.344 m past the edge |
| Error 0.001 rad, ρ 1.05 | 1 rad at step 142 | Errors multiply in fast moves |
| Three-world brake point | 0.917 m, average return −0.28 | Randomization brakes for the worst floor |
| Gap with μ-lo 0.35 on 0.8 | 0.737 m | The price of the range |
| Estimate spread, k = 5 and 15 | 0.029 and 0.010 | Calm estimates arrive later |
| Brake lag 0.1 s at μ 0.8 | +0.26 m to stop | A missing effect no friction value fixes |
Randomize at every reset, distill with the teacher's answers as labels, and identify a parameter by least squares.
pythonimport torch RANGES = {"friction": (0.3, 1.1), "mass_scale": (0.8, 1.2), "delay_s": (0.0, 0.04)} def randomize(env, gen): # each parallel copy draws its own world e at every reset u = lambda lo, hi: lo + (hi - lo) * torch.rand(1, generator=gen).item() env.friction = u(*RANGES["friction"]) env.mass = env.base_mass * u(*RANGES["mass_scale"]) env.delay = u(*RANGES["delay_s"]) def distill_step(student, teacher, batch, opt): # batch: states the STUDENT visited in randomized sims (DAgger style) x, hist, e = batch["state"], batch["history"], batch["e"] # [N,d], [N,H,d], [N,3] with torch.no_grad(): target = teacher(x, e) # [N,act], privileged labels loss = ((student(x, hist) - target) ** 2).mean() # L(phi) opt.zero_grad(); loss.backward(); opt.step() return loss.item() def identify_friction(v, dt=0.02, g=9.81): # v: recorded speeds while braking, shape [T] drops = v[:-1] - v[1:] # speed lost each tick return drops.mean() / (g * dt) # mu-hat, the least-squares answer
Now press Present or Teach and explain, from memory, why the randomized cart stops short on lab tile and how a student wins that distance back. Then go back to the dock, pick Wet tile, and find the narrowest range that keeps the cart on it.
This lesson re-teaches Lecture 16, Sim2Real robot learning, a guest lecture by Guanya Shi (CMU), of Stanford CS 224R: Deep Reinforcement Learning. Papers behind it: Tobin et al., domain randomization (2017); Peng et al., dynamics randomization (2018); Pinto et al., asymmetric actor-critic (2018); Hwangbo et al., the actuator net (2019); Kumar et al., RMA (2021). The toys and numbers here are our own.