def flow_map_error(u, teacher, x0, eps, s, t):
"""Per-example squared error of the average velocity u(x_t, s, t) against
the stop-gradient target v - (t - s) du/dt; v from teacher, or eps - x0."""
x_t = d2l.GaussianPath.linear().sample(x0, t, eps)
if teacher is None:
v = eps - x0
else:
with torch.no_grad():
v = teacher(x_t, t)
u_t, du_dt = torch.func.jvp(lambda x, r: u(x, s, r), (x_t, t),
(v, torch.ones_like(t)))
gap = (t - s).reshape(-1, *[1] * (x0.dim() - 1))
target = (v - gap * du_dt).detach()
return ((u_t - target) ** 2).flatten(1).sum(1)