Straight Lines From Static

Diffusion ModelsEasy+10 XP+10

Straight Lines From Static

Diffusion reaches an image by a long, winding route of many small denoising steps. Rectified flow, used by several recent image generators, trains on straight lines instead, so that far fewer steps are needed.

Training (already done). Pair a noise sample zzz with a real image ddd. The straight line between them is

xt=(1−t) z+t d,0≤t≤1x_t = (1 - t)\,z + t\,d, \qquad 0 \le t \le 1xt​=(1−t)z+td,0≤t≤1

so t=0t = 0t=0 is pure noise and t=1t = 1t=1 is the image. Along this line the velocity, the change in xtx_txt​ per unit of ttt, is the same everywhere: d−zd - zd−z. The network is trained with plain squared error to predict that velocity from the point xtx_txt​ and the time ttt.

Sampling (your job). Start from fresh noise at t=0t = 0t=0 and follow the network's velocity until t=1t = 1t=1, using Euler's method: split the trip into NNN equal steps of size Δt=1/N\Delta t = 1/NΔt=1/N. At each step, ask the network for the velocity at the current point and the current time, then move in a straight line in that direction for Δt\Delta tΔt:

x←x+Δt⋅v(x,t),t←t+Δtx \leftarrow x + \Delta t \cdot v(x, t), \qquad t \leftarrow t + \Delta tx←x+Δt⋅v(x,t),t←t+Δt

Task: write flow_sample(noise, velocity, steps).

  • noise: the starting sample, a list of numbers.
  • velocity: the trained network, as a function. velocity(x, t) takes the current list and the current time, and returns a velocity list of the same length.
  • steps: NNN, at least 1.

Return the sample after all NNN steps, every value rounded to 4 decimal places.

The test velocities are small stand-ins. For example, if the whole dataset were the single image target, a perfectly trained network would output lambda x, t: [(m - v) / (1 - t) for m, v in zip(target, x)].

Examples

flow_sample([0.3, -0.8], lambda x, t: [(m - v) / (1 - t) for m, v in zip([1.0, 0.5], x)], 4)
returns [1.0, 0.5]
flow_sample([0.0, 1.0], lambda x, t: [3 * t * t, -2 * t], 2)
returns [0.375, 0.5]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run