Skip to main content
NewEpisode 3a is out: Carry the conversation onWatch →
All posts
SuperMimic

Pathwise vs likelihood-ratio gradients: a worked example

Compare REINFORCE-style and pathwise gradient estimates in a reproducible point-mass experiment, then connect the result to SuperMimic.

The SuperMimic paper (arXiv 2610.28480) insists on analytic gradients. This post walks through episode 1 of the course, which explains why by following one point mass and one number.

BuildAutonomy is an independent reading of the paper, not affiliated with its authors. The point-mass results are from the course's teaching implementation, tinymimic; they are not the paper's humanoid results. Full-scale code excerpts come from the third-party reproduction at a1508d4, not an official author implementation.

The paper's diagnosis

Start with the bill. SONIC, the baseline, trained for 7 days on 128 GPUs, roughly 21,000 GPU-hours. Every motion runs on the same body with the same physics. Even so, model-free RL ends up, in the paper's words, "repeatedly estimating action consequences from noisy simulator rollouts." Noisy estimates mean many samples, and many samples mean many GPUs. The paper's fix is a different kind of gradient. Here we measure the difference ourselves.

One point mass

A 1 kg mass sits 1 m from the target, at rest. We push it for 32 steps of 0.05 s (32 is the paper's imagination horizon, H). The policy is a spring and a damper: force = -kp·x - kd·v. It starts untuned, at kp = 2 and kd = 1. Each step costs the squared distance plus a tiny charge for force, and the return is the negated sum.

Point mass 1 m from target pushed for 32 steps of 0.05 s, the imagination horizon H This toy uses 32 steps × 0.05 s = 1.6 s. It borrows the step count H = 32; that does not make the toy's physical time step the paper's. (SuperMimic ep01)

# tinymimic/src/tinymimic/pointmass.py, rollout()
    for t in range(H):
        mean = -(theta[0] * x + theta[1] * v)
        a = mean + SIGMA * eps[:, t]
        # log N(a; mean, sigma^2), up to a constant
        logp = logp - 0.5 * ((a.detach() - mean) / SIGMA) ** 2
        if not through_dynamics:
            a = a.detach()
        v = v + DT * a
        x = x + DT * v
        ret = ret - (x**2 + 0.001 * a**2)
    return ret, logp

Training needs one thing: which way to turn the two knobs. A high-sample Monte Carlo reference estimate, using one million rollouts, is 3.40 for kp and −1.51 for kd. In other words, stiffen the spring and ease off the damping.

Road 1: warmer, colder (likelihood ratio)

This is a REINFORCE-style likelihood-ratio estimator with a leave-one-out return baseline. It illustrates the score-function approach behind policy-gradient methods; the experiment does not implement or benchmark the full PPO algorithm. The policy adds random noise to its force, so every rollout pushes a little differently. Then it only hears the score, like the game "warmer, colder": you learn how good a move was, never which way to go. Rollouts that scored above average get their noise reinforced. Averaged over many rollouts that points the right way. Averaged over a few, it wobbles. The paper's one-line summary: PPO treats the dynamics as a black box.

def likelihood_ratio_grad(theta: torch.Tensor, eps: torch.Tensor) -> torch.Tensor:
    theta = theta.detach().requires_grad_(True)
    ret, logp = rollout(theta, eps, through_dynamics=False)
    n = ret.shape[0]
    baseline = (ret.sum() - ret) / (n - 1)
    adv = (ret - baseline).detach()
    (g,) = torch.autograd.grad((adv * logp).mean(), theta)
    return g

through_dynamics=False treats the visited states as fixed data. The baseline is the average score of the other rollouts.

likelihood_ratio_grad code in tinymimic pointmass.py next to a diagram of noisy rollouts scored against a baseline Road 1 in tinymimic: score the noisy rollouts and push up the ones that beat the average. (SuperMimic ep01)

Road 2: a map (BPTT)

If the physics is differentiable, the score comes with a map that shows how the final distance would change if a given push were slightly harder. Step 32 depends on step 31, which depends on step 30, and the chain rule walks back through all of them. One rollout already says which way to turn both knobs. This is Section 3.3: BPTT differentiates the return with respect to each action.

def pathwise_grad(theta: torch.Tensor, eps: torch.Tensor) -> torch.Tensor:
    theta = theta.detach().requires_grad_(True)
    ret, _ = rollout(theta, eps)
    (g,) = torch.autograd.grad(ret.mean(), theta)
    return g

Both methods target the same expected-return gradient for this smooth toy and use the same rollout function, noise distribution, and sample budget. The experiment draws separate noise batches for the estimators; it is not a paired comparison using identical sampled trajectories. Under this toy's differentiation assumptions, both estimators are unbiased. The pathwise method keeps the derivative through the dynamics.

The race

Give each road 16 rollouts and run 200 trials. The median relative gradient error is about 39% for road 1 and 1.7% for road 2. For each estimate, the metric is ||g_estimate − g_reference||₂ / ||g_reference||₂; the reference itself is a finite-sample estimate. In 17 of the 200 runs, road 1 even points the wrong way for kd. Road 2 never does.

Scatter of 200 gradient estimates: likelihood ratio 39% typical error versus pathwise BPTT 1.7% with 16 rollouts 200 runs of 16 rollouts each: road 1 at 39% typical error, road 2 at 1.7%. (SuperMimic ep01)

Now sweep the rollout count from 2 to 4096. Both error curves fall with the same slope: four times the samples halves the error. That's the square-root law, and neither road escapes it. But the curves sit far apart. Road 2 reaches 5% error with 2 rollouts, while road 1 needs about 1000, roughly 500× more. The error is 23× bigger, so the sample count is 500× bigger, because of that square root.

Log-log plot of gradient error versus number of rollouts for likelihood ratio and pathwise estimators Both curves follow the square-root law, about 500× apart in samples. (SuperMimic ep01)

That 500 is a toy number, not the paper's. Figure 5b runs the same race on a humanoid doing walk, run and sprint motions. There the PPO side also rolls out inside a learned world model (the paper calls it PPO-WM), so both sides get fast imagined rollouts. SuperMimic reaches PPO's best return with about 64× fewer imagined steps.

A bug that looks fine

The companion experiment also includes a deliberately incorrect version of road 1 that leaves through_dynamics=True. The states stayed linked to the knobs, so autograd mixed a piece of road 2 into road 1. In the real run the error fell, then stopped at about 30%, even with 4096 rollouts. In this controlled comparison, the persistent error floor is evidence of bias from the incorrect differentiation graph. A plateau by itself is not a universal proof of bias: reference error, numerical limits, or finite trials can also limit an experiment. The fix is one line, a.detach(), which cuts the graph at each action.

Turn the noise down

The policy's noise is 0.3 N. Which road improves if you change it?

  • Road 1 is 35% off at 0.1, 34% at 0.3 and 36% at 1.0, so this particular sweep shows little change in relative error over those three tested noise levels. Its signal is the noise: less noise gives smaller score differences, and the two shrink together.
  • Road 2 is 5.3% off at 1.0, 1.5% at 0.3 and 0.5% at 0.1. With zero action noise and a fixed initial state, the toy's pathwise derivative becomes deterministic, up to numerical error. That does not remove learned-model error or other randomness in a real training system.

Section 3.1 uses a deterministic policy during imagination, without exploration noise added to the action. The toy illustrates why avoiding that noise can help; it does not prove that every source of variance disappears from SuperMimic's training. Noise is added only when collecting simulator data, and the paper says it serves only the model fit. The reproduction does the same split. _imag_step calls pi with no noise:

# vibed/supermimic/train.py
def _imag_step(S, o_hist, a_prev, f, xi, xi_n, g):
    a = pi(o_hist, g)
    S1 = wm.step(S, a, xi_n)

while collect() adds action_noise, which is 0.1 in the run the course uses:

            a = pi(obs_hist, g)
            a = torch.clamp(a + args.action_noise * torch.randn_like(a), -20, 20)
            out = env.step(a)

Why not differentiate the simulator?

Road 2 needs a useful differentiable rollout model. Contact events can make naive differentiation through a simulator unreliable; this does not mean every contact model or differentiable simulator is unusable. Drop a ball from anywhere between 0.5 and 1.5 m and look at its height 1.5 s later. It bounces, keeping 80% of its speed each time, in a simple simulator with 10 ms steps:

# tinymimic/src/tinymimic/contact.py
    for _ in range(STEPS):
        v = v - G * DT
        z = z + DT * v
        hit = z < 0
        z = torch.where(hit, -z, z)                    # reflect back above the floor
        v = torch.where(hit, -RESTITUTION * v, v)      # bounce, losing 20 % of the speed
        zs.append(z)

Two drops half a millimetre apart can end 17 cm apart. When you ask autograd for the slope, it answers +1 or −1 every time. Compared with a finite-difference trend over a 5 cm window, its sign disagrees about 40% of the time in this toy. That comparison is between a local branch derivative and a finite-window sensitivity, not a claim that autograd miscomputes the derivative of the branch it executed.

Bouncing ball final height versus drop height with autograd slopes of plus or minus one, sign wrong 40 percent of the time Autograd's slope through a bounce: ±1 every time, with the sign wrong 40% of the time. (SuperMimic ep01)

The reason is that autograd differentiates the branch that ran. It can't see that a higher drop changes when the branch runs, and when one bounce shifts, everything after it shifts too. Real simulators use softer contact models, but contact stays hard to differentiate. The paper sidesteps the problem: it learns a smooth model of the physics and differentiates that. That keeps it compatible with simulators that have "non-smooth contacts and non-differentiable implementations." MuJoCo Warp only supplies data, and its gradients are never used.

The same road at full scale

Here's road 2 in the reproduction's policy_update, for a 29-joint humanoid instead of a point mass:

# vibed/supermimic/train.py, policy_update()
    set_requires_grad(wm, False)
    set_requires_grad(critic, False)
    ...
    for t in range(HZ):
        Aps.append(a_prev)
        S, a_prev, o_hist, f, g = imag_step(S, o_hist, a_prev, f, xi, xi_n, g)
        Ss.append(S), As.append(a_prev), Fs.append(f), Gs.append(g)
    ...
    J = (disc * c_t * r).sum(0)
    ...
    if not args.no_critic:
        J = J + (args.gamma**HZ) * c * critic(_critic_input(S, f, xi_n, g))
    loss = -J.mean()
    ...
    loss.backward()

The world model and critic are frozen, so only the policy learns. The loop calls imag_step 32 times. loss.backward() plays the role of our autograd.grad.

What this doesn't show

The point mass is linear and smooth, and the 500× is a toy number. PPO uses additional machinery such as a clipped surrogate objective and learned value estimates. Clipping controls policy updates and is not simply a guarantee of lower estimator variance. The toy's sample ratios should not be presented as an end-to-end PPO speedup. Road 2 has its own price: the model must be accurate, because a wrong model draws a wrong map.

Try it: a longer horizon

Section 3.3 says the variance is lower "over short horizons." So raise H from 32 to 128:

  • With the stable policy, road 2's error creeps up from 1.5% to 4.1%. It's still far ahead of road 1.
  • With kd = −0.3, a policy that pumps energy in, the gradient's size explodes: 8.9 at 32 steps, 777 at 128.

That's why the paper clips the policy gradient twice (Table A.5). The reproduction does it right after backward:

    gn = nn.utils.clip_grad_norm_(pi.parameters(), 1.0)
    nn.utils.clip_grad_value_(pi.parameters(), 0.1)
    if torch.isfinite(gn):
        opt_pi.step()

Reproduce the toy comparison

Download the teaching code and recorded results. The bundle contains the point-mass model, contact example, experiment scripts, and the JSON results behind the reported percentages. It does not contain the humanoid training implementation.

With Python 3.11–3.13 and uv, extract the archive, enter its gradient-experiments directory, then run:

uv run python experiments/ep01_gradient_noise.py
uv run python experiments/ep01_sigma_sweep.py
uv run python experiments/ep01_horizon.py

The full sweeps include many autograd evaluations and can take time on a CPU. The recorded JSON files let you inspect the reported results without rerunning them. Small numerical differences across PyTorch versions and platforms are possible.

The paper's approximately 64× imagined-step comparison is in Figure 5b; the third-party code excerpts are pinned to train.py at a1508d4.

Takeaways

  1. It's the same gradient by two roads, and backprop gets far more out of each sample.
  2. Removing action exploration noise makes this fixed-start toy's pathwise gradient deterministic. In a learned world model, model bias and other training variability remain.
  3. The simulator is never differentiated. A learned, smooth model supplies the gradient.

▶ Watch episode 1 with the live plots: SuperMimic, Explained, ep01. Next: episode 2, the training loop that keeps the model and the policy improving together.