Sim2Real

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.

Stop the cart before the edge

0.00

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

Why Train in Simulation

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 givesWhat it removes
Cheap, fast, parallelMonths of robot time
SafeBroken hardware
Free labelsSensors for friction, contact force, terrain height: the simulator knows them
No wearStripped 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.

Say it aloud

x at t plus one equals f-sim of x-t, u-t and e.

xt+1
x at t plus one the state one tick later.
fsim
f-sim the physics engine: the rules that step the world forward.
xt
x-t the state now. For the cart, its speed in m/s.
ut
u-t the action now: brake on or off.
e
e the environment parameters. For the cart, the floor's friction μ (mu).
In plain words

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 numbers

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.

Count the robot time

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.

4,096
5×

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.

The road

  1. The reality gap: wrong numbers, missing physics, and errors that multiply.
  2. System identification: fit the simulator's numbers to real data.
  3. Domain randomization: train on many worlds, the hero's slider.
  4. How wide to randomize: the price the hero showed on Lab tile.
  5. A privileged teacher and a student: distill what only the simulator knows.
  6. Adapting online: read the world from your own history.
  7. Real to sim: learn the physics the simulator misses.
  8. The full pipeline: every layer on six real floors.
  9. The field guide: terms, numbers, a checklist and the code.
Why does reinforcement learning for robots usually start in simulation?

Chapter 1

The Reality Gap

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 gapWhat is wrongExampleFix
ParametricRight equations, wrong numbersFriction 0.5, not 0.8; mass 5.2 kg, not 5.0 kgMeasure it (Chapter 2) or randomize it (Chapter 3)
Non-parametricAn effect the model lacksWind on a drone, brake lag, gear backlashLearn 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.

Say it aloud

s equals v squared over two mu g.

s
s the stopping distance, in metres.
v2
v squared the speed when braking starts, times itself. Here v = 3 m/s.
μ
mu the floor's friction coefficient, from about 0.3 (wet) to 1.0 (rubber) here.
g
g gravity, 9.81 m/s².
In plain words

Square the speed v. Divide by two, by mu and by g. Half the friction means twice the stopping distance s.

With numbers

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.

Say it aloud

Epsilon-t equals epsilon-zero times rho to the t.

εt
epsilon-t how far the real state is from the simulated plan at step t, here in radians of joint angle.
ε0
epsilon-zero the first, small mismatch.
ρt
rho to the t the growth factor per step, multiplied by itself once per step.
In plain words

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 numbers

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.

Watch a small error grow

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.

1.050

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.

A drone policy flies well indoors and drifts badly outdoors in wind. Which gap is non-parametric?

Chapter 2

System Identification: Fix the Numbers

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.

Say it aloud

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.

ê
e-hat the identified parameters: our best guess of the real e.
argmine
the arg-min over e the value of e that makes what follows smallest.
Σt
the sum over t one term for each recorded step.
xrealt+1
x-real at t plus one the next state the robot recorded.
fsim(…)
f-sim of the real state, the real action and e the simulator's prediction of that state.
( )2
squared makes every miss positive and punishes big misses more.
In plain words

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 numbers

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:

μ = (the average drop per tick, vt − vt+1) / (g Δt)

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.

Fit the friction to the record

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.

0.80

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.

You record the cart while it stands still with the brake on. Why can you not identify the friction?

Chapter 3

Domain Randomization: Train on Many Worlds

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.

Say it aloud

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.

θ*
theta-star the weights that training ends with.
argmaxθ
the arg-max over theta the weights that make what follows largest.
Ee∼p(e)
the expected value over e drawn from p of e the average over many worlds drawn at random from the range.
J(θ, e)
J of theta and e the policy's average return in world e.
In plain words

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 numbers

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.

Train one brake point on ten worlds

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.

0.57

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.

Training worlds have friction from 0.4 to 1.2, and a fall costs far more than a short stop. Where does the trained cart brake?

Chapter 4

How Wide to Make the Ranges

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.

Say it aloud

Gap equals v squared over two g, times one over mu-lo minus one over mu-real.

gap
gap how far before the edge the cart stops, in metres. Negative means it fell.
v2/2g
v squared over two g the stopping distance on a floor of friction 1: 0.459 m at 3 m/s.
1/μlo
one over mu-lo mu-lo is the lowest friction in the training range.
1/μreal
one over mu-real mu-real is the friction of the real floor.
In plain words

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 numbers

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.

Price the range on five real floors

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.

0.60

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.

The cart moves at 3 m/s (v²/2g = 0.459 m). It trained with μ-lo = 0.4 and meets a floor of 0.8. How far short does it stop?

Chapter 5

A Privileged Teacher and a Student

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.

  1. In simulation, train the teacher with RL (usually PPO) on randomized worlds, with e as an input.
  2. In simulation, train the student. Run the student, ask the teacher what it would do at each state the student visits, and fit the student to those answers. That is DAgger, from imitation learning.
  3. On the robot, run only the student. The teacher never leaves the simulator.

Call the student's weights φ (phi), the state x, the history h and the number of training samples N.

Say it aloud

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.

L(φ)
L of phi the distillation loss of a student with weights phi.
(1/N) Σi
one over N times the sum over i the average over N samples from many randomized worlds.
πstudent(xi, hi)
pi-student of x-i and h-i the student's action from the state and its history. Here: a brake point.
πteacher(xi, ei)
pi-teacher of x-i and e-i the teacher's action, from the state and the true world e.
In plain words

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 numbers

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².

Distill the teacher into a student

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.

VariantWhat 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.

Why can the teacher use the true friction while the deployed policy cannot?

Chapter 6

Adapting Online: What the History Reveals

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.

Say it aloud

Mu-hat equals v-t minus v at t minus k, over k times g times delta-t.

μ
mu-hat the student's estimate of the floor's friction.
vt
v-t the speed reading now, in m/s.
vt−k
v at t minus k the reading k ticks ago.
k
k the window: how many ticks of history the estimate uses.
Δt
delta-t one tick, 0.02 s. With g = 9.81 m/s².
In plain words

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 numbers

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:

spread of μ = √2 · σv / (k · g · Δt)

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.

Estimate the friction from the speed-up

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.

5

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.

MethodPolicy inputStrengthCost
Domain randomizationState onlySimple; no estimate to get wrongConservative on every world
Teacher and studentState and historyRecovers most of the price of robustnessTwo 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.

You raise the window from 5 to 20 ticks. What happens to the estimate?

Chapter 7

Real to Sim: Learn What the Simulator Misses

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.

Say it aloud

x at t plus one equals f-sim of x-t, u-t and e, plus g-phi of x-t and u-t.

xt+1
x at t plus one the corrected prediction of the next state.
fsim(xt, ut, e)
f-sim of x-t, u-t and e the physics engine's prediction, as before.
gφ
g-phi the residual network, with weights phi, trained on real records.
xt, ut
x-t and u-t the state and action. Here the state includes the last few brake commands, because a lagging brake depends on them.
In plain words

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 numbers

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.

Fit the residual for a lagging brake

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.

The real brake lags 0.1 s. Which fix matches this gap?

Chapter 8

The Full Pipeline

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.

Deploy on six real floors

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:

  1. Nothing on. Every cart falls. Even rubber needs 0.71 m with the lag, and the cart brakes at 0.57 m.
  2. Randomize. Five of six survive, with large gaps. Wet tile still falls: the range covers its friction, but not the lag.
  3. Add teacher and student. Every cart falls again. The student copies a teacher that learned in a simulator without the lag.
  4. Add real to sim. All six stop, with gaps from about 2 cm on rubber to about 20 cm on wet tile.

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.

Beyond this toy

TopicWhat the lecture covers
Rewards from human dataA 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 algorithmOn-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.01.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.
In the showcase, why does adding the teacher and student to randomization make every cart fall, until real to sim is on?

Chapter 9

The Field Guide

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.

Terms

TermMeaning
Reality gapThe difference between f-sim with its e and the real world
Parametric gapRight equations, wrong numbers
Non-parametric gapAn effect the simulator does not model
System identificationFit e so the simulator replays real records
Domain randomizationDraw a new e for every training episode
Privileged informationWhat the simulator knows and the robot cannot sense
DistillationTrain a student to copy a teacher's actions
Online adaptationEstimate e from history while running, with frozen weights
ResidualA learned correction added to the physics step

The numbers from this page

WhatNumberWhy it matters
Parallel sim against one robot33 minutes against 463 daysWhy training starts in simulation
Stop at 3 m/s, μ 0.8 and 0.50.573 m and 0.917 mA wrong number puts the cart 0.344 m past the edge
Error 0.001 rad, ρ 1.051 rad at step 142Errors multiply in fast moves
Three-world brake point0.917 m, average return −0.28Randomization brakes for the worst floor
Gap with μ-lo 0.35 on 0.80.737 mThe price of the range
Estimate spread, k = 5 and 150.029 and 0.010Calm estimates arrive later
Brake lag 0.1 s at μ 0.8+0.26 m to stopA missing effect no friction value fixes

When a sim-trained policy fails on the robot

The core code

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

Keep going

The takeaway. Make the policy robust to the gap, let it sense the gap, or shrink the gap with real data. The best systems do all three, in layers.
Your sim-trained policy fails on the robot, and the real friction lies outside your training range. What do you try first?

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.

Credit and source

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.

CS 224R: Sim2Real Robot Learning
The course site · Domain randomization · RMA · Back to Gleams