```python
import torch
fn = lambda z, r, t: 2 * z + r - 3 * t
x = torch.tensor([[1.0, 0.0]])
e = torch.tensor([[0.0, 2.0]])
r = torch.tensor([[0.25]])
t = torch.tensor([[0.75]])
loss, u_tgt = meanflow_loss(fn, x, e, r, t)
print((round(loss.item(), 2), [round(a, 3) for a in u_tgt.flatten().tolist()]))
```
Output:
(9.25, [1.5, 1.5])
Reasoning:
z_t = (0.25, 1.5) and v_t = (-1, 2). The network output is 2 z_t + r - 3 t = (-1.5, 1.0) and its derivative along (v_t, 0, 1) is 2 v_t - 3 = (-5, 1). The target is v_t - 0.5 * (-5, 1) = (1.5, 1.5), the error is (-3, -0.5) and the loss is 9 + 0.25.
The MeanFlow Training Loss With torch.func.jvp and a Stop-Gradient
A MeanFlow network uθ(z,r,t) is trained to predict the average velocity of a flow between two times r≤t. Time 0 is data and time 1 is noise. For a data batch x, noise ϵ and times (r,t) the paper's training step is:
zt=(1−t)x+tϵ and the conditional velocity vt=ϵ−x.
One Jacobian-vector product of the network with the tangent (vt,0,1) for the inputs (z,r,t). It returns the output uθ(zt,r,t) and the total derivative dtduθ=vt∂zuθ+∂tuθ.
The target utgt=vt−(t−r)dtduθ.
The loss uθ(zt,r,t)−sg(utgt)22, where sg is the stop-gradient: the target is a constant for backpropagation.
Write meanflow_loss(fn, x, e, r, t):
fn(z, r, t): a callable (for example an nn.Module) that returns a tensor with the shape of z.
x, e: tensors of shape (B, ...). r, t: tensors of shape (B, 1, ..., 1) with as many axes as x, so they broadcast against it.
Return (loss, u_tgt). loss is a scalar tensor: for each sample sum the squared error over all its dimensions, then average over the batch. u_tgt has the shape of x and carries no gradient.
Use torch.func.jvp for step 2. Gradients must still reach the parameters of fn through the output uθ(zt,r,t).