By Kevin McAleer, 8 Minutes
Page last updated November 24, 2026

Your duck walks. But nobody programmed that walk step by step. So where did it come from? In this lesson we’ll open up the duck’s walking brain and see how it was made. If you’ve done Reinforcement Learning for Beginners, you’ll recognise a lot of it.
Before the duck, I tried the same idea on the smallest thing I could: a pendulum that learns to balance from nothing but a score. Watch that first. It’s Part 1 of my Robot Duck Taught Itself to Walk series, and it explains the RL loop in plain English.
The write-up on the blog has the full setup, and the code is in my rl-duck repo.
Back in the RL course we met the agent, its observations, its actions and its reward (see the anatomy of robotic RL). Here’s how they map onto the duck.
| RL idea | On the Open Duck Mini |
|---|---|
| Policy | A neural network, saved as the .onnx file you ran in lesson 11 |
| Observation | Motor positions and speeds, the IMU, the foot switches, and the joystick command |
| Action | Target positions for the joints |
| Reward | A score for following the joystick command and for walking like the reference motion |
In the RL course our policy was a Q-table, a lookup table of states and actions. That works for a handful of states. The duck’s observation is lots of numbers that change smoothly, so a table can’t hold it. Instead, the policy is a neural network, as we saw in scaling up to deep RL. It was trained with PPO, through MuJoCo Playground’s Brax trainer. If you want the details, check runner.py in the Open_Duck_Playground repo.
Here’s a problem. If you only reward a robot for moving forward, it’ll find a way to move forward. It might shuffle, hop or throw itself along. RL is very good at finding loopholes in a reward (we saw this in designing the reward function).
The Open Duck team borrowed an idea from Disney’s BDX paper: an imitation reward. As well as the task rewards, such as following the velocity command, the policy is paid for staying close to a reference motion, an example of what a good walk looks like.
Where does the reference motion come from? The Open_Duck_reference_motion_generator, built on a robotics library called Placo, generates walking gaits for a range of speeds: forward and back (dx), sideways (dy) and turning (dtheta). The ranges are set in auto_gait.json. It then fits polynomials to those gaits and saves them as polynomial_coefficients.pkl, which the trainer uses as its reference motion.
So the policy learns two things at once: go where the joystick says, and do it in a way that looks like this walk.
Let’s make the idea concrete with a tiny simulation. It uses only Python’s standard library, so it runs on any computer. One knee joint should follow a sine wave, our “reference motion”. We score four pretend policies by how closely they follow it at each step.
This is a toy. The real reward in the Playground covers every joint and adds the task rewards on top. But the core idea, pay more when you’re closer to the reference, is the same.
import math
STEPS_PER_SECOND = 50 # how often our toy "robot" picks a new knee angle
STRIDE_SECONDS = 1.0 # one full step cycle takes one second
SHARPNESS = 20.0 # how quickly the reward falls off as the error grows
def reference_knee(t):
"""The gait we want to copy: the knee swings like a sine wave (radians)."""
return 0.5 * math.sin(2 * math.pi * t / STRIDE_SECONDS)
def imitation_reward(actual, target):
"""1.0 for a perfect match, sliding towards 0.0 as the error grows."""
error = actual - target
return math.exp(-SHARPNESS * error * error)
# Three pretend policies, each a rule for choosing the knee angle at time t
def copycat(t):
return reference_knee(t) # follows the reference exactly
def sloppy(t):
return 0.8 * reference_knee(t) + 0.05 # right shape, a bit small and offset
def statue(t):
return 0.0 # never moves the knee at all
def late(t):
return reference_knee(t - 0.25) # right shape, a quarter of a step late
policies = {"copycat": copycat, "sloppy": sloppy, "statue": statue, "late": late}
steps = int(STEPS_PER_SECOND * STRIDE_SECONDS)
for name, policy in policies.items():
total = 0.0
for step in range(steps):
t = step / STEPS_PER_SECOND
total += imitation_reward(policy(t), reference_knee(t))
average = total / steps
bar = "#" * round(average * 40)
print(f"{name:8} average reward {average:.2f} {bar}")
Run it and you’ll see something like this:
copycat average reward 1.00 ########################################
sloppy average reward 0.87 ###################################
statue average reward 0.27 ###########
late average reward 0.18 #######
How it works:
reference_knee(t) is the walk we want to copy.imitation_reward() turns the error between the real angle and the reference into a score. We square the error so being too high and too low count the same, then use math.exp(-SHARPNESS * error * error) so a perfect match scores 1.0 and the score drops quickly as the error grows.Look at late. It moves exactly the right way, just a quarter of a step late, and it scores worse than statue, which doesn’t move at all. Timing matters: an imitation reward checks when you move, not only how.
A policy trained in simulation can fail badly on a real robot, because the simulator is never perfect. We met this as the sim-to-real gap. The Open Duck team closed it in several ways.
| Problem | What the team did |
|---|---|
| The simulated robot must match the real shape | The Onshape CAD is turned into a simulation model with onshape-to-robot (from Rhoban) |
| Printed parts have infill, so they’re lighter than solid parts | The part masses were overridden with estimates from the slicer |
| Real servos are not perfect motors | Rhoban’s BAM (Better Actuator Models) was used to measure the STS3215. Its damping, kp, frictionloss, armature and forcerange go into the MuJoCo model |
| Gears have a little play in them | The flat_terrain_backlash task models backlash, the slop in the gears |
| Every real duck and floor is a bit different | Domain randomisation varies friction, masses and more in training, so the policy can’t rely on any one exact value |
The motor model is already done, so you don’t need to redo it. Domain randomisation lives in playground/common/randomize.py in the Playground repo, if you want to see what gets varied.
Domain randomisation is a lovely idea. If the policy only ever saw one exact friction, it might learn a walk that only works at that friction. Train it across many, and it has to learn a walk that works on all of them, which includes, with luck, your floor.
SHARPNESS to 5.0 and then to 80.0. How do the scores change? What does a sharper reward mean for a learning robot?reference_knee(t) + 0.1 * math.sin(20 * t). Where does it land?Problem: Thinking the duck learns on your floor. Solution: Remember the learning happened earlier, in simulation. On the Pi, the policy only acts. Why: Running the policy is cheap. Training it needs thousands of simulated robots and a GPU, which is lesson 13.
Problem: Assuming a bigger reward always means a better walk. Solution: Watch the robot as well as the numbers. Why: A policy can score well by exploiting a gap in the reward, which is exactly what the imitation reward helps prevent.
Quick quiz 1 of 3
What does the imitation reward pay the policy for?
Quick quiz 2 of 3
In the toy, why does the late policy score worse than the statue?
Quick quiz 3 of 3
What is domain randomisation for?
Comments