A policy learns to dock a cart in a simulator with a floor of friction 1.0. On a real floor it docks only between 0.86 and 1.20. Train it on many floors and it docks from 0.46 up, but slower. Let it feel the floor and it docks everywhere.
Pick a policy and drag the real friction. Watch where the cart stops. Then we build, piece by piece, why we simulate, what the simulator gets wrong, and the four tools that carry a policy across the gap.
You need what a policy is (Lecture 1) and a little Python. No control theory. We build the rest from zero.
Lecture 21 of 25 in Introduction to Robot Learning, CMU 16-831 (Spring 2024), taught by Guanya Shi. Slides on the course lectures page. Every idea is re-taught here in our own words and devices. Previous: Lecture 20, Exploration.
Illustrative toy, replayed at half speed. The cart arrives at 3 m/s and must stop in the 15 cm dock before the wall. Braking decelerates at friction × 9.81 m/s². "Many floors" trained on frictions 0.5 to 1.5. "Feels the floor" taps the brake for 0.12 s and reads the friction from how fast it slows. The strip below the track shows every friction at once.
Chapter 0
Add the small differences of a real robot one at a time, and watch a tuned policy stop working
You train a policy for a week. In simulation it never fails. You load the same weights onto the real robot, and it fails in seconds. Nothing in the network changed. The world around it did.
The reality gap is the difference between the simulated world a policy trained in and the real world it runs in. Sim2real is the work of making a policy trained in simulation work on hardware.
A controller tuned in the simulator drives a cart to the yellow line. Pink is the simulator. Teal is the real cart. Switch on the differences a real robot has.
Illustrative toy. The controller pushes at 100 per metre of error and brakes at 12 per m/s of speed, tuned on a 1 kg cart. Sticky friction is a 3 N force that resists motion.
The late motor does the most harm: alone it takes the overshoot from 8 cm to 27 cm. All four together give 30 cm and leave the cart 1.1 cm off the line. A real robot has all of them at once.
The hero shows the same failure in one number. The cart's policy learned where to start braking on a floor of friction 1.0. How far does a cart slide once it brakes? Call its speed v, the floor's friction μ, and gravity g.
d equals v squared, divided by two times mu times g.
Square the speed v. Divide by two, by the friction mu and by g. The result d is the slide. Halve mu and the slide doubles.
With the toy's numbers: v = 3 m/s and μ = 1.0 give d = 9 / (2 × 1.0 × 9.81) = 0.459 m. On a real floor of μ = 0.6, d = 9 / 11.77 = 0.765 m. The cart slides 31 cm past its aim, through the 7.5 cm of margin, into the wall.
The symptom is a policy that scores well in simulation and fails on hardware. To measure it, run the same policy in both and log the gap on one number, such as overshoot or final error. The fixes are the rest of this lesson.
Chapter 1
Price the data a policy needs in robot days, then in simulator seconds
If simulation creates the reality gap, why not train on the real robot? Because reinforcement learning needs a lot of experience. A walking policy can need ten million steps.
How long does that take? Call the number of steps N, the steps per second of one robot f, and the number of robots that run at once R.
T equals N divided by f times R.
Multiply the rate f by the number of copies R to get steps per second. Divide the steps you need, N, by that. The result is T.
With made-up numbers: N = 10,000,000, f = 50, R = 1 gives T = 200,000 s, about 2.3 days of nonstop running. With R = 4,096 simulated copies at the same f, T = 49 s.
Set how many steps the policy needs and how many simulated copies run at once. Both bars use 50 steps per second for each copy.
The equation only. Real simulators often step faster than real time, which makes the gap larger still.
Time is one of four gifts. The lecture lists them.
| Simulated data is | What it buys |
|---|---|
| Cheap, fast, scalable | Thousands of copies on one GPU. The lecture cites a quadrotor policy trained in 18 seconds on a laptop. |
| Safe | RL explores with random actions. In simulation a crash costs nothing. |
| Labelled | The simulator knows the true state: friction under each foot, the wind, a payload's mass. |
| No wear and tear | Every episode starts with a new robot. |
The third gift, free labels, matters most later. A simulator is an oracle: it can tell the policy facts no real sensor can measure. Chapter 6 builds on it.
The symptom is a project stuck on data: a policy that needs months of robot time. To measure it, price the run with the equation above. The fix is to train in simulation and pay for the reality gap instead.
Chapter 2
Turn the simulator's knobs to match real data, and find the gap that no knob can close
A simulator is the world's rule for the next state, written as code. The lecture writes it with one extra input. Call the state at step t st and the action at. The environment parameters e are the numbers that describe this world, such as mass, friction and motor strength.
s-t-plus-one equals f of s-t, a-t and e.
Give f the state s-t, the action a-t and the world's numbers e. It returns the next state s-t-plus-one. A wrong e gives a wrong prediction even if f is right.
With made-up numbers: speed s-t = 0.5 m/s, push a-t = 2 N, e = (mass 1.0 kg, damping 0.5), Δt = 0.05 s. Next speed = 0.5 + (2 − 0.25) / 1.0 × 0.05 = 0.588 m/s. If the real mass is 1.3 kg, the real speed is 0.567 m/s.
The gap between f-with-our-e and the real world splits two ways, and each wants a different fix.
| Mismatch | What is wrong | Example | A knob can fix it? |
|---|---|---|---|
| Parametric | The equations f are right. The numbers e are wrong. | Mass 2.0 kg in the CAD file, 2.3 kg with cables and battery | Yes: fit e, or randomize it |
| Non-parametric | f is missing an effect. | Turbulent air around a drone, tyre slip, gear backlash | No: the term is not in f |
Blue dots are the logged speeds of a real cart under a push of 0.5 N and of 2 N. Pink is the simulator. Turn its two knobs, or press Auto-fit. Then switch the real cart.
Illustrative toy. The "missing effect" cart has a drag that grows with speed squared (1.5 N per (m/s)²). The simulator has no such term. Auto-fit searches both knobs.
With the wrong number, the best fit is exact: mass 1.30, error 0. With the missing effect, the best fit still misses by about 0.10 m/s. The linear drag cannot bend into the square-law curve for both pushes at once.
The symptom is a simulator whose error stays above a floor at every setting. To measure it, fit its parameters to logged real data and look at the error left. A floor above the sensor noise means a missing effect: randomize around it, learn a residual, or add the physics.
Chapter 3
Roll a new world every episode, and score two policies across all of them
Do not tune one simulator to match reality. Change the simulator every episode. Each episode gets a new mass, a new friction, a new motor delay, new textures and new light. One policy must succeed in all of them. This is domain randomization.
Their first test was vision. They trained an object detector only on simulated images with odd random textures, light and camera angles. On real photos it located objects to within 1.5 cm. Today people randomize the dynamics, the sensors, the actuators and the visuals.
What does the policy optimise now? Call the environment parameters e, the chance of drawing them p(e), and the score of policy π in world e J(π, e).
pi-star equals the argmax over pi of the expected value, over e drawn from p of e, of J of pi and e.
Draw a world e from p(e). Run the policy pi and score it with J. Average over many worlds. Train pi to make that average as large as it can.
With the hero's cart and three equally likely worlds, friction 0.6, 1.0 and 1.4. "One floor" scores J = 0, 1, 0: average 0.33. "Many floors" scores 1, 1, 1: average 1.0. It wins on the objective the real world grades.
Each press draws 20 floors from the pink training range and runs both policies on each. Then deploy both to the real floor, which neither saw.
Illustrative toy: the hero's cart. Worlds are uniform on friction 0.5 to 1.5. The real floor has friction 0.72.
Why does it work? The lecture calls domain randomization an approximation of robust control: one controller that works for a whole set of systems. Robust control proves a worst-case bound. Randomization trains on the set and lets the policy find behaviour that survives all of it.
The code lab trains two policies, one on a single gain and one on a range, and scores them on held-out "real" gains.
The symptom is a policy that transfers well to some real conditions and fails on others. To measure it, test on held-out worlds and report the worst case, not the average. The fix is to randomize the parameters that differ in the failing cases.
Chapter 4
Widen the training range, and watch the policy first reach reality, then slow down
Randomization has a price, and it hides in the width of the range. It fails two ways.
The cart shows the blunt compromise in physics. Trained on frictions from μlo up, the safe policy brakes as if the floor were μlo. On a grippier real floor it stops short and must creep the rest. How far short? Call the speed v, gravity g, the lowest friction in the range μlo and the real friction μ.
Delta equals v squared over two g, times one over mu-lo minus one over mu.
The planned slide is v squared over two g, divided by mu-lo. The real slide uses mu instead. Delta is the difference. A wider range lowers mu-lo, so Delta grows and the creep takes longer.
With the toy's numbers: v = 3 m/s, μlo = 0.5, real μ = 0.7. Δ = 0.459 × (2 − 1.43) = 0.26 m. At 0.3 m/s the creep adds 0.87 s. If μlo were above 0.7, Δ would turn negative: the cart slides into the wall.
The policy trains on frictions from 1 − width to 1 + width. Drag the width. The curve counts docks per minute on the real floor; zero means it crashed.
Illustrative toy: the hero's cart. Each run adds 1 s to reset. In this toy a wide range only slows the policy; a real network can also fail to train.
The best width is the smallest range that still contains reality. Narrower crashes; wider creeps. The lab sweeps the same trade on a different toy.
The symptom is a policy that is safe but slow, or that does not converge in training. To measure it, sweep the width and plot real success against it. The fix is a range wide enough to contain reality and no wider; system identification (Chapter 5) tells you where reality is.
Chapter 5
Log the real robot, then solve backward for the number the simulator should use
Randomization makes the policy tolerate the gap. System identification shrinks the gap: it measures the real robot and sets the simulator's numbers to match.
Take the simplest case: one motor gain. You send command ui and log response yi, for runs i = 1 to n. The robot obeys y = g · u plus sensor noise, and you want the gain ĝ that makes the squared errors smallest.
g-hat equals the sum over i of u-i times y-i, divided by the sum over i of u-i squared.
Multiply each command u-i by its response y-i and add. Divide by the sum of the squared commands. That ratio g-hat is the least-squares gain: no other number makes the total squared error smaller.
With made-up logs: commands 0.5, 1.0, −0.8 and responses 0.70, 1.33, −1.10. The top is 0.35 + 1.33 + 0.88 = 2.56. The bottom is 0.25 + 1 + 0.64 = 1.89. g-hat = 2.56 / 1.89 = 1.35, against a simulator default of 1.0.
Where does it come from? The total squared error is the sum of (y-i − g · u-i) squared. It is a bowl in g. Set its slope to zero and solve for g: the ratio above.
Blue dots are 40 logged real runs. The pink line is the simulator's prediction for the gain you set. Drag it, or press Fit. Raise the noise and fit again.
Illustrative toy. The real gain is 1.35, hidden from the fit. Commands are uniform from −1 to 1.
System ID has a hard limit: it fixes only wrong numbers. If the simulator has no aerodynamics term, no fit adds one (Chapter 2). So fit what you can model, and randomize around what you cannot. The lecture calls the pair robust adaptive control.
The symptom is a fitted simulator that still disagrees with the robot. To measure it, fit on some logs and test on others. If the error on held-out logs stays high, the model is missing an effect: add a residual model or randomize.
Chapter 6
Let a teacher cheat with the simulator's truth, then train a student to guess that truth from its own history
A randomized policy ignores which world it is in. A better policy would work out the world and adjust. That is an approximation of adaptive control, and it stacks with randomization.
The trouble: to adapt to the friction or the wind, the policy must know it. The real robot has no friction sensor. The fix leans on Chapter 1's free labels and runs in three phases.
The student need not copy actions. In RMA, it copies the teacher's compressed code of the world. Call the teacher's code for world e z(e), the student's guess from history h ẑ(h), and the number of training samples N.
L equals one over N times the sum over i of z-hat of h-i minus z of e-i, squared.
For each moment i, take the student's guess z-hat from history and the teacher's code z from the truth. Square the difference. Average over all N moments. Train the student to make L small.
With made-up numbers: two moments. Teacher codes 0.8 and −0.3, student guesses 0.6 and −0.1. Each miss is 0.2, each square 0.04. L = (0.04 + 0.04) / 2 = 0.04.
Warm is the hidden wind. The teacher reads it directly. The student averages a window of noisy blue measurements into the pink estimate. Set the window length.
Illustrative toy over 10 s. Each measurement of the wind from the robot's motion carries noise of 0.35 N. The error bar is the average miss of the wind estimate; a fixed policy assumes no wind.
A short window follows the noise. A long window lags behind every change. Near 0.3 s the student's error is about a quarter of the fixed policy's. Real students use a learned network over the history, but they face the same trade.
The pattern recurs across the field: Learning by Cheating for driving, RMA for legged robots, Agile But Safe for safe running, DATT for drones. Each distils privileged facts into something the robot can compute from its own senses.
The symptom is a student that matches the teacher in simulation and drifts on the robot. To measure it, log the student's estimate against any ground truth you can get, such as a known payload. The fix is to randomize the sensor noise and delay the student sees, so its history looks like the robot's.
Chapter 7
Let the network choose commands, not forces, and let a classical controller absorb the mismatch
Simulators are least accurate at the lowest level: how a foot's contact force turns into motion in the next millisecond. So do not learn that level. Learn a higher-level policy that outputs abstract commands, such as a body velocity or a gait timing. A classical controller with good physics turns them into forces.
Both policies learned to move a 1 kg robot 1 m in 2 s in simulation. Purple replays the forces. Teal sends a motion plan to a low-level feedback controller. Change the real mass.
Illustrative toy. The force policy pushes 1 N for 1 s, then −1 N for 1 s. The low-level controller adds 8 per m/s of speed error and 3 per metre of position error.
Work the number for the force policy. On a 1.3 kg robot every acceleration shrinks by 1/1.3. The motion keeps its shape and scales, so it stops at 1/1.3 = 0.77 m: 23 cm short. The feedback controller sees the lag and pushes harder. It ends within 1 cm.
This is the design of CAJun, a quadruped that jumps again and again. A learned policy picks the body velocity, the gait timing and a swing-leg correction. A model predictive controller solves for the ground forces. The lecture reports that it needs little randomization and trains in about 20 minutes.
No tool closes the gap alone. A common last step is real-world fine-tuning: start from the simulation policy and keep learning from a little real data. The risky early exploration already happened in simulation.
| Tool | What it does to the gap |
|---|---|
| Domain randomization | Makes the policy tolerate it |
| System identification | Shrinks it |
| Learning to adapt | Senses it and cancels it online |
| Higher-level policy | Keeps the learned part away from it |
| Real-world fine-tuning | Removes what is left, with real data |
The symptom is an end-to-end torque policy that is jerky or unstable on hardware. To measure it, compare commanded and achieved motion at the joints. The fix is to move the learned part up a level, behind a controller you trust.
Chapter 8
Race a drone through gates in air it never trained in, and add the tools one at a time
In 2023 a system called Swift beat human world champions at first-person drone racing (Kaufmann and colleagues, Nature). Its policy trained with RL in simulation. It won several races against each of three champions and set the fastest recorded race time.
Racing is a hard test of sim2real. At the limit of flight the air is turbulent and hard to model, a late reaction misses a gate, and the camera is noisy. Swift used the tools of this lesson.
The teal drone chases the bright yellow gate. Warm arrows are air the simulator never had. Raise it, then switch on the two tools.
Illustrative toy, not Swift's controller. The air has a steady part, a side push and a lift loss at speed, that a residual model learns from logs. It also has a slow swirl that only an online estimate can follow. A gate missed for 2.4 s counts as a miss.
Try this order at full air. With no tools the drone clears about 4 gates in 24. The residual model alone clears about 14 in 24. The online estimate alone clears them all, at about 93 gates a minute. Both together reach about 127 a minute: the residual model removes the steady part at once, so the estimate only chases the swirl.
The symptom is a policy that flies well slowly and misses gates at speed. To measure it, log real flights and compare them with the simulator's prediction for the same commands. The fix is Swift's: fit the steady part of that difference, and estimate the rest online.
Chapter 9
Keep the terms, the numbers, a checklist and the core recipe in code
Every method here answers one question: how does a policy born in simulation survive the real world? They attack the gap from different sides, and they stack.
| Term | One line | Number to remember |
|---|---|---|
| Reality gap | The difference between the training simulator and the real world. | Cart: docks only for friction 0.86 to 1.20 |
| Stopping distance | d = v² / (2μg). | 3 m/s: 0.459 m at μ 1.0, 0.765 m at 0.6 |
| Data cost | T = N / (f · R). | 10M steps at 50 Hz: 2.3 days, or 49 s on 4,096 copies |
| Parametric mismatch | Right equations, wrong numbers e. | Fit error goes to 0 |
| Non-parametric mismatch | An effect missing from f. | Fit error floor 0.10 m/s |
| Domain randomization | Maximise the average score over random worlds. | Average 0.33 vs 1.0 on three floors |
| Range width | Δ = (v² / 2g)(1/μlo − 1/μ). | 0.26 m short, 0.87 s of creep |
| System identification | ĝ = Σ u y / Σ u². | 2.56 / 1.89 = 1.35 |
| Privileged teacher | The student matches the teacher's code from history: L = average squared miss. | L = 0.04 |
| Higher-level policy | Learn commands; a classical controller makes the forces. | Force replay 23 cm short at 1.3 kg; feedback within 1 cm |
pythondef train_randomized(policy, sim, ranges, episodes): for ep in range(episodes): e = {k: rng.uniform(lo, hi) for k, (lo, hi) in ranges.items()} # a new world each episode sim.set_params(e) # mass, friction, delay, noise ... traj = rollout(policy, sim) # s_{t+1} = f(s_t, a_t, e) policy.update(traj) # RL step on the average over worlds def fit_gain(u, y): # system identification, one parameter return (u @ y) / (u @ u) # least squares through the origin
This lesson follows Lecture 21, "Robot Simulation and Sim2Real", of CMU 16-831 Introduction to Robot Learning, Spring 2024, taught by Guanya Shi. The slides are on the lectures page.
Papers named here: Tobin et al., Domain Randomization for Transferring Deep Neural Networks from Simulation to the Real World (2017); Kumar et al., RMA: Rapid Motor Adaptation for Legged Robots (2021); Kaufmann et al., Champion-level drone racing using deep reinforcement learning (Nature, 2023). The cart, drone and other toys are our own.
Now press Present or Teach. From memory, explain why we simulate, the two mismatches, and the four tools. Then go back to the cart, set the friction to 0.4, and say why only one policy docks.