Algorithmresearch
DeepMimic
Also called example-guided deep reinforcement learning of character skills.
Train a physics-based character policy by reinforcement learning with a reward for tracking a reference motion clip, with reference state initialization and early termination.
- Time
- O(k s) episode
- Space
- O(k) extra
- Where
- k = the control steps of an episode; s = the simulation steps per control step
- Model
- Real RAM
- Properties
- randomizednot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Xue Bin Peng, Pieter Abbeel, Sergey Levine, Michiel van de Panne, 2018
DeepMimic trains a neural network policy that makes a simulated character perform a skill from a motion clip: a walk, a backflip, a spin kick. The character is a rigid body model with PD controlled joints in a physics simulation, so it can fall, be pushed, and react. At each control step the policy sees the state of the character and the phase of the clip, and outputs target angles for the joint PD controllers. The reward is high when the simulated pose, joint velocities, end effectors and center of mass are close to the clip at the same phase, and it can include a task term, such as a target direction. Two simple episode rules make the training work for hard skills: reference state initialization (RSI) starts each episode at a random phase of the clip, in the reference state; early termination (ET) ends an episode when the character falls. The policy is trained with PPO; Peng, Abbeel, Levine and van de Panne presented the method in 2018.
In plain words
You want a game character with a real body to do a backflip like an actor in a captured clip. You do not write the muscle commands yourself. Instead, you let a program try again and again, and you give it points for every moment it looks like the actor at the same moment of the clip. To help it, you let it start some tries in the middle of the flip, not only at the start, so it can learn the landing before it can do the jump. When it falls on its back, you stop that try at once, so it does not collect points while it lies on the floor. After many millions of tries, it does the flip, and it can also recover when something pushes it.
The problem
The problem is a Markov decision process. The state holds the positions, rotations and velocities of the links, relative to the root, and the phase of the clip. The action is a target orientation for every joint, tracked by a PD controller in the simulation. The policy is a Gaussian whose mean is a neural network; the goal is the largest expected discounted return .
The reward of the paper is
with the pose term (the rotation angle between the reference and the simulated joint orientation), the velocity term , the end effector term for hands and feet, and the center of mass term . A hat marks the reference clip. The weights and scales are tuning chosen in the paper. The policy acts at 30 Hz and the simulation runs at 1.2 kHz.
The algorithm
The training loop collects episodes with the current policy, estimates advantages with GAE() and fits the value function with TD() targets, and updates the policy with the clipped objective of PPO. One episode is:
EPISODE(π, clip, K) ▷ policy, reference, control steps- 1
t ← uniform phase of the clip; s ← the clip state at t ▷ RSI (or t ← 0) for k ← 0 to K - 1- 2
a ← sample from π(· | s, phase of t) ▷ PD targets in DeepMimic - 3
simulate s for 1/30 s at 1.2 kHz with the PD torques; t ← t + 1/30 - 4
rₖ ← 0.7 r^I(s, clip(t)) + 0.3 r^G(s) ▷ r^I alone if there is no task - 5
if a fall is detected then rₖ ← 0 and end the episode ▷ ET; the rest is 0 - 6
return the rewards and the return Σₖ γᵏ rₖ
Reference state initialization. With a fixed start at phase 0, the policy must master the beginning of a skill before it ever sees the later parts; for a backflip, it rarely reaches the landing. RSI starts each episode at a phase drawn uniformly from the clip, in the reference state of that phase, so every part of the clip appears as a start state from the first iteration.
Early termination. When a fall is detected (in the paper, when certain links such as the torso or head touch the ground), the episode ends and the remaining rewards are zero. Without it, the data is full of states lying on the ground, and these states still earn a positive reward.
The code. The code in this page is a toy, not DeepMimic: it has no network and no PPO. The character is one rigid rod on a motor at its base (an inverted pendulum), the reference is a sine wave of the rod angle, and the policy is a given function that outputs a torque directly. It keeps the reward with the paper's weights and scales (for one joint, the rotation angle of the pose term is the angle difference), the 30 Hz control with 1.2 kHz simulation, RSI and ET. Its discount and its fall height are toy choices.
Example
The toy rod has mass 10 kg and length 1 m, the reference is , and an episode has 60 control steps (2 s). With the largest possible return is .
- A PD policy on the reference with gravity compensation (a hand made stand in for a trained network), started by RSI with seed 7, gets the return 19.02, with a mean reward of 0.996 per step and no fall.
- The zero torque policy from the same start falls and ET ends the episode at step 18, with the return 7.91.
- The zero torque policy from phase 0 falls at step 15. With ET the return is 9.29. Without ET the episode goes on, the rod lies on the ground for 45 of the 60 steps, every one of these steps still earns a reward of at least 0.067, and the return grows to 10.22.
The last case shows why ET matters: without it, lying on the ground pays.
Correctness
The proof file shows facts about the reward and the episode rules, which follow the paper.
- , with exactly when every pose, velocity, end effector and center of mass difference is zero; the same holds for with a task reward in (Theorem 1).
- Every RSI start state lies on the reference and has the reward 1, and the start phase is uniform (Theorem 2).
- With ET, no state at or after the fall adds to the return, and every return is in (Theorem 3).
- Without ET, a fallen state still has a positive reward, because every term of is positive.
Nothing is proved about the learning. PPO with neural network policies has no convergence guarantee for this problem. That RSI and ET speed up training and that the result looks like the clip are measurements and visual judgments in the paper.
Proof: The DeepMimic imitation reward lies in [0, 1] with its maximum on the reference, and RSI and early termination do what they statefull
We use the notation of the page. The arithmetic is exact. This file is about the reward and the episode rules of the toy, which follow the paper. It does not prove anything about the learning: PPO with neural network policies has no convergence guarantee for this problem, and the toy has no learner.
The reward
The imitation reward is with , , and , where a hat marks the reference, is the rotation angle between two joint orientations, the are the end effector positions and is the center of mass. With a task reward , the reward is .
Theorem 1. , and if and only if every pose difference, velocity difference, end effector difference and center of mass difference is zero. With a task, , and if and only if and .
Proof. Each term is with and , so it lies in and equals 1 exactly when . The weights are positive and sum to 1, so is a convex combination of numbers in ; it is in , and it is 1 exactly when all four terms are 1. The same argument with the weights and gives the claim for .
Lemma 1. If the state equals the reference pose and velocity at the current time, then .
Proof. The end effectors and the center of mass are functions of the pose, so their differences are also zero, and Theorem 1 applies.
Reference state initialization
The reference is periodic with period . RSI draws a phase uniformly from and starts in the reference state at time ; the fixed start uses .
Theorem 2. Every RSI start state lies on the reference motion, and its reward, measured before the first action, is 1. For any phase interval , the probability that the start phase is in is .
Proof. The start state is the reference state at by definition, and Lemma 1 gives the reward. The phase is uniform on .
So every part of the clip, also the late parts that a policy reaches only after it learns the early parts, appears as a start state with a positive probability. That this speeds up learning is a measurement in the paper, not a theorem.
Early termination
The episode has control steps with rewards and the discount . With early termination, the episode ends at the first step at which the character is in a fallen state, and the toy sets for .
Theorem 3. With early termination, the return is , so no state at or after the fall adds to it. Every return lies in .
Proof. The rewards from on are zero. Each reward is in by Theorem 1, so the return is between 0 and .
Without early termination, a fallen state can still earn a positive reward, because every term of is positive (Theorem 1). The test measures this on the toy: a rod with no torque falls, and without termination it earns a larger return than with termination, and the difference comes only from the steps at and after the fall.
Complexity
One episode of control steps with simulation steps each costs simulation steps plus policy evaluations, and stores rewards and states for the update. In the toy, , so a 2 s episode is 2400 simulation steps. The paper trains for tens of millions of samples per skill, which takes days of computer time; the cost is dominated by the simulation.
Properties
- Stochastic. The policy samples actions, and RSI samples the start phase; the toy is repeatable only with a fixed seed.
- Not exact. A trained policy tracks the clip only approximately, and it can differ from the clip where the clip is not possible for the body.
- Offline training, online use. Training needs many episodes, but the trained policy runs in real time, one network evaluation per control step.
- Physics based. The character reacts to pushes and to changes of the ground, because the simulation applies the laws of rigid body mechanics and the policy reacts to the state.
Variants and improvements
- Tasks. The task reward adds goals such as a heading, a target to strike, or a ball to throw at a target.
- Many clips. The paper also uses a reward that takes the best match over several clips, a skill selector, and a composite of policies.
- Other bodies. The paper retargets skills to an Atlas robot model and to non human characters by the same reward.
- Adversarial imitation. Later work replaces the hand made tracking reward by a learned discriminator, so that the character imitates the style of a data set instead of one clip at a time.
- Hand designed control. SIMBICON uses a state machine and a feedback law in place of a learned policy, with no clip.
When to use it
Use DeepMimic when a simulated character must perform skills from motion capture or keyframed clips, including dynamic ones like flips and kicks, and must react to forces. It needs a physics model of the character, a clip for each skill, and much computer time to train. For a kinematic character that never has to react to forces, motion matching is much cheaper.
Pitfalls
- No ET. Without early termination, states on the ground fill the data and still pay a reward.
- No RSI. With a fixed start, hard skills such as a backflip may never be learned, because the policy never reaches the late phases.
- Impossible clips. A clip that the simulated body cannot follow, because of different masses or joint limits, gives a policy that tracks it badly.
- Reward scales. The scales inside the exponentials decide how fast each term drops; poor values give a reward that is nearly flat or nearly zero.
- The phase input. Without the phase, the policy cannot know which part of the clip to track.
- The toy. The code shows the reward and the episode rules only; it does not learn.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/deepmimic/. The authors are listed in prov/MY80RM.jsonl.
"""A toy of the DeepMimic episode: imitation reward, reference state
initialization (RSI) and early termination (ET).
This is not DeepMimic. There is no neural network and no PPO here. The
character is one rigid rod on a motor at its base (an inverted pendulum in
the x-y plane, y up), and the policy is any function of the state and the
phase. What the toy keeps from Peng et al. (2018) is the structure of one
episode:
* the reference motion is a periodic clip q_hat(t) = A sin(2 pi t / T);
* the imitation reward is
r_I = 0.65 r_p + 0.1 r_v + 0.15 r_e + 0.1 r_c,
r_p = exp(-2 (q_hat - q)^2), pose
r_v = exp(-0.1 (qd_hat - qd)^2), velocity
r_e = exp(-40 |e_hat - e|^2), end effector (the tip)
r_c = exp(-10 |c_hat - c|^2), center of mass (the mid point)
and with a task reward r_G the reward is 0.7 r_I + 0.3 r_G. The weights
and scales are the paper's; for one joint the quaternion difference of
the pose term is the angle difference;
* the policy acts at 30 Hz and the physics steps at 1.2 kHz;
* RSI starts each episode at a random phase of the clip, in the reference
state of that phase; the other choice starts at phase 0;
* ET ends the episode when the tip falls below a height; that step and
every later step then have reward 0.
The rod: mass m, length l, angle q from straight up, counterclockwise,
moment of inertia m l^2 / 3 about the base. The motor torque is clamped to
tau_max. The ground is at the base height: when |q| reaches pi / 2 the rod
lies on the ground and stays there (q held, qd = 0).
"""
import math
G = 9.81
class Rod:
def __init__(self, m=10.0, l=1.0, damping=0.5, tau_max=150.0):
self.m, self.l, self.b, self.tau_max = m, l, damping, tau_max
self.I = m * l * l / 3.0
def tip(self, q):
return (-self.l * math.sin(q), self.l * math.cos(q))
def com(self, q):
return (-0.5 * self.l * math.sin(q), 0.5 * self.l * math.cos(q))
def step(self, q, qd, tau, dt):
"""One symplectic Euler step with the ground stop."""
tau = max(-self.tau_max, min(self.tau_max, tau))
qdd = (tau + self.m * G * 0.5 * self.l * math.sin(q) - self.b * qd) / self.I
qd = qd + dt * qdd
q = q + dt * qd
if abs(q) >= math.pi / 2:
q = math.copysign(math.pi / 2, q)
qd = 0.0
return q, qd
class Reference:
def __init__(self, amplitude=0.4, period=2.0):
self.A, self.T = amplitude, period
def q(self, t):
return self.A * math.sin(2 * math.pi * t / self.T)
def qd(self, t):
return self.A * 2 * math.pi / self.T * math.cos(2 * math.pi * t / self.T)
def imitation_reward(rod, ref, t, q, qd):
qh, qdh = ref.q(t), ref.qd(t)
rp = math.exp(-2.0 * (qh - q) ** 2)
rv = math.exp(-0.1 * (qdh - qd) ** 2)
eh, e = rod.tip(qh), rod.tip(q)
re = math.exp(-40.0 * ((eh[0] - e[0]) ** 2 + (eh[1] - e[1]) ** 2))
ch, c = rod.com(qh), rod.com(q)
rc = math.exp(-10.0 * ((ch[0] - c[0]) ** 2 + (ch[1] - c[1]) ** 2))
return 0.65 * rp + 0.1 * rv + 0.15 * re + 0.1 * rc
def reward(rod, ref, t, q, qd, r_goal=None):
r_i = imitation_reward(rod, ref, t, q, qd)
if r_goal is None:
return r_i
return 0.7 * r_i + 0.3 * r_goal
def initial_state(ref, rng=None):
"""RSI if rng is given: a uniform phase and the reference state there."""
t0 = rng.uniform(0.0, ref.T) if rng is not None else 0.0
return t0, ref.q(t0), ref.qd(t0)
def episode(rod, ref, policy, steps=60, rng=None, early_termination=True,
fall_height=0.5, control_hz=30, sim_hz=1200, gamma=0.95):
"""Run one episode of `steps` control steps.
Return a dict with the rewards per control step (0 after termination),
the discounted return, the step of termination (None if none), and the
number of control steps spent in a fallen state."""
t, q, qd = initial_state(ref, rng) # @line L1
sub = sim_hz // control_hz
dt = 1.0 / sim_hz
rewards = []
ended = None
fallen_steps = 0
for k in range(steps):
if ended is not None:
rewards.append(0.0)
continue
tau = policy(t, q, qd) # @line L2
for _ in range(sub):
q, qd = rod.step(q, qd, tau, dt) # @line L3
t += dt
r = reward(rod, ref, t, q, qd) # @line L4
fallen = rod.tip(q)[1] < fall_height
fallen_steps += fallen
if fallen and early_termination:
ended = k # @line L5
r = 0.0
rewards.append(r)
ret = sum(gamma ** k * r for k, r in enumerate(rewards)) # @line L6
return {"rewards": rewards, "return": ret, "ended": ended, "fallen_steps": fallen_steps}
def pd_policy(rod, ref, kp=400.0, kd=40.0):
"""A hand made tracking policy: PD on the reference plus gravity
compensation. It stands in for a trained network."""
def policy(t, q, qd):
return (kp * (ref.q(t) - q) + kd * (ref.qd(t) - qd)
- rod.m * G * 0.5 * rod.l * math.sin(q))
return policy
def zero_policy(t, q, qd):
return 0.0
test_deepmimic.py 84 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/deepmimic/. The authors are listed in prov/MY80RM.jsonl.
"""Tests of the DeepMimic toy: reward, RSI and early termination.
The reward lies in [0, 1] and is 1 exactly on the reference. RSI states
lie on the reference clip and spread over its phases. With ET, the step of
the fall and every later step get reward 0; without ET a falling policy
keeps collecting reward while it lies on the ground. A tracking policy has
a higher return than zero torque (measured on this toy).
"""
import math
import random
import deepmimic as dm
def test_reward_range_and_maximum():
rod, ref = dm.Rod(), dm.Reference()
rng = random.Random(1)
for _ in range(500):
t = rng.uniform(0, 4)
q, qd = rng.uniform(-1.5, 1.5), rng.uniform(-5, 5)
r = dm.reward(rod, ref, t, q, qd)
assert 0.0 < r < 1.0
g = rng.random()
rg = dm.reward(rod, ref, t, q, qd, r_goal=g)
assert abs(rg - (0.7 * r + 0.3 * g)) < 1e-15
assert dm.reward(rod, ref, t, ref.q(t), ref.qd(t)) == 1.0
# the pose term has the largest weight
t = 0.3
near = dm.reward(rod, ref, t, ref.q(t) + 0.1, ref.qd(t))
far = dm.reward(rod, ref, t, ref.q(t) + 0.5, ref.qd(t))
assert far < near < 1.0
def test_rsi_states_lie_on_the_reference():
ref = dm.Reference(amplitude=0.4, period=2.0)
rng = random.Random(2)
phases = []
for _ in range(400):
t0, q, qd = dm.initial_state(ref, rng)
assert 0.0 <= t0 < ref.T
assert q == ref.q(t0) and qd == ref.qd(t0)
phases.append(t0 / ref.T)
counts = [sum(1 for p in phases if k / 4 <= p < (k + 1) / 4) for k in range(4)]
assert min(counts) > 60
assert dm.initial_state(ref) == (0.0, 0.0, ref.qd(0.0))
def test_early_termination_zeroes_later_rewards():
rod, ref = dm.Rod(), dm.Reference()
with_et = dm.episode(rod, ref, dm.zero_policy, steps=60, early_termination=True)
k = with_et["ended"]
assert k is not None and k < 60
assert all(r == 0.0 for r in with_et["rewards"][k:])
assert all(r > 0.0 for r in with_et["rewards"][:k])
without = dm.episode(rod, ref, dm.zero_policy, steps=60, early_termination=False)
assert without["ended"] is None
assert without["fallen_steps"] > 30
# lying on the ground still earns reward without ET
assert sum(without["rewards"][k:]) > 1.0
assert without["return"] > with_et["return"]
def test_tracking_policy_beats_zero_torque():
rod, ref = dm.Rod(), dm.Reference()
rng = random.Random(3)
pd = dm.pd_policy(rod, ref)
for _ in range(5):
seed = rng.randrange(10 ** 6)
a = dm.episode(rod, ref, pd, steps=60, rng=random.Random(seed))
b = dm.episode(rod, ref, dm.zero_policy, steps=60, rng=random.Random(seed))
assert a["ended"] is None and a["fallen_steps"] == 0
assert a["return"] > b["return"]
assert sum(a["rewards"]) / 60 > 0.9
def test_rod_ground_stop():
rod = dm.Rod()
q, qd = 1.5, 3.0
for _ in range(100):
q, qd = rod.step(q, qd, 0.0, 1e-3)
assert q == math.pi / 2 and qd == 0.0
History
Xue Bin Peng, Pieter Abbeel, Sergey Levine and Michiel van de Panne presented DeepMimic at SIGGRAPH 2018. It joined two lines of work: physics based character controllers such as SIMBICON (2007) and its successors, and deep reinforcement learning for continuous control with PPO (2017) and generalized advantage estimation (2015). Later work by Peng and others replaced the tracking reward with adversarial motion priors and built large libraries of skills on the same base.
References
- Xue Bin Peng, Pieter Abbeel, Sergey Levine and Michiel van de Panne, DeepMimic, example-guided deep reinforcement learning of physics-based character skills, ACM Transactions on Graphics 37(4) (SIGGRAPH 2018), the imitation reward and its weights, the task reward, the PD target actions at 30 Hz with the simulation at 1.2 kHz, Section 6.1 (reference state initialization), Section 6.2 (early termination), and the training with PPO
- John Schulman, Filip Wolski, Prafulla Dhariwal, Alec Radford and Oleg Klimov, Proximal policy optimization algorithms, arXiv 1707.06347, 2017, the clipped surrogate objective of PPO
- John Schulman, Philipp Moritz, Sergey Levine, Michael Jordan and Pieter Abbeel, High-dimensional continuous control using generalized advantage estimation, arXiv 1506.02438, 2015, the advantage estimator GAE(lambda)
- KangKang Yin, Kevin Loken and Michiel van de Panne, SIMBICON, simple biped locomotion control, ACM Transactions on Graphics 26(3) (SIGGRAPH 2007), article 105, the hand designed PD controllers that learned tracking policies replace
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag MY80RM Edit this page History Report an error Markdown