Reflow¶
The procedure that straightens trajectories: generate (z, ODE(z)) pairs with the
current model, retrain on those pairs, repeat.
Correctness requirement
Reflow training must use the same z that produced each generated target. The
pairing is deterministic and induced by the model; resampling noise independently
decouples the pairs and silently reduces reflow to training on the model's own
samples.
reflow
¶
Reflow — Iterative Path Straightening¶
Rectified Flow (Liu et al., 2023) has two parts, and they are easy to conflate:
-
The objective. Training with a linear path and independent coupling. This is what
create_flow_matching(flow, variant='rectified')gives you, and mathematically it is the same as standard flow matching with a linear path. It does not, on its own, straighten anything. -
Reflow. The procedure in this module. Take the trained model, generate pairs \((z, \mathrm{ODE}(z))\) by integrating from noise, then retrain on those pairs. Repeat. This is what actually straightens trajectories and makes few-step Euler sampling accurate.
The correctness requirement that makes or breaks reflow: training must use the same \(z\) that produced each generated target. Reflow works because the pairing is deterministic and induced by the model; if training resamples noise independently, the pairs decouple and the procedure degrades into training on the model's own samples, which straightens nothing.
This module therefore emits an explicit x_0 for every pair and requires
the objective to consume it via
BatchSource.
Usage:
from flowpde.flows import BatchSource
from flowpde.trainers import generate_reflow_pairs, reflow
# The objective must read x_0 from the batch.
objective.source = BatchSource()
pairs = generate_reflow_pairs(objective, train_loader, n_steps=100)
loader = DataLoader(pairs, batch_size=32, shuffle=True)
trainer.train(loader, epochs=50, ...)
or, for the whole loop:
reflow(objective, train_loader, optimizer_factory=make_optimizer,
num_iterations=2, epochs_per_iteration=50)
ReflowDataset
¶
Bases: Dataset
Precomputed (x_0, x_1, condition) triples produced by a trained flow.
Each item is a batch dict carrying the source point alongside the usual
target and condition, so a BatchSource-configured objective trains on
the exact pairing the model generated.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x_0
|
Tensor
|
Source points, shape |
required |
x_1
|
Tensor
|
Generated targets, shape |
required |
condition
|
Tensor
|
Conditioning tensors, shape |
required |
target_key
|
str
|
Key for the target in emitted samples. |
'target'
|
condition_key
|
str
|
Key for the condition in emitted samples. |
'input'
|
source_key
|
str
|
Key for |
'x_0'
|
Source code in flowpde/trainers/reflow.py
generate_reflow_pairs(objective, data_loader, n_steps=100, solver='euler', condition_key=None, target_key=None, source_key='x_0', seed=None, max_batches=None)
¶
Generate (z, ODE(z)) pairs from the current model.
For every condition in data_loader, draw \(z \sim
\mathcal{N}(0, I)\) and integrate the learned ODE to obtain
\(x_1' = \mathrm{ODE}(z \mid f)\). The ground-truth targets in the
loader are ignored — only the conditions are reused. Reflow trains on the
model's own transport map, not on the data.
Use a high n_steps here: pair quality bounds what reflow can achieve,
and errors introduced now are baked into the next iteration's targets.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
objective
|
Any
|
Flow objective exposing |
required |
data_loader
|
Iterable
|
Loader supplying conditions. |
required |
n_steps
|
int
|
ODE steps used to generate targets. |
100
|
solver
|
str
|
ODE solver name. |
'euler'
|
condition_key
|
Optional[str]
|
Batch key for conditions. Defaults to the objective's. |
None
|
target_key
|
Optional[str]
|
Batch key for targets, used only to infer the target shape. Defaults to the objective's. |
None
|
source_key
|
str
|
Key under which |
'x_0'
|
seed
|
Optional[int]
|
Seed for the generated noise, for reproducible pairs. |
None
|
max_batches
|
Optional[int]
|
Optionally cap the number of batches consumed. |
None
|
Returns:
| Type | Description |
|---|---|
ReflowDataset
|
A |
Source code in flowpde/trainers/reflow.py
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 | |
reflow(objective, data_loader, optimizer_factory, num_iterations=1, epochs_per_iteration=50, n_steps=100, solver='euler', batch_size=32, save_dir=None, print_stats_interval=10, trainer_kwargs=None, seed=None)
¶
Run the full reflow loop: generate pairs, retrain, repeat.
Each iteration regenerates pairs with the current model, so trajectories
straighten progressively. Optimizer state is rebuilt every iteration via
optimizer_factory because the target distribution changes between
iterations and stale moment estimates work against the new objective.
The objective's source is switched to
BatchSource for the duration and
restored afterwards, so sampling behaviour is unchanged on return.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
objective
|
Any
|
Flow objective to straighten, already trained. |
required |
data_loader
|
Iterable
|
Loader supplying conditions (targets are ignored). |
required |
optimizer_factory
|
Callable[[Iterable], Optimizer]
|
Callable taking model parameters and returning a
fresh optimizer, e.g. |
required |
num_iterations
|
int
|
Number of reflow iterations. |
1
|
epochs_per_iteration
|
int
|
Training epochs per iteration. |
50
|
n_steps
|
int
|
ODE steps used when generating pairs. |
100
|
solver
|
str
|
ODE solver used when generating pairs. |
'euler'
|
batch_size
|
int
|
Batch size for training on generated pairs. |
32
|
save_dir
|
Optional[str]
|
Optional directory; each iteration writes to a
|
None
|
print_stats_interval
|
int
|
Passed through to the trainer. |
10
|
trainer_kwargs
|
Optional[Dict[str, Any]]
|
Extra keyword arguments for |
None
|
seed
|
Optional[int]
|
Seed for pair generation. |
None
|
Returns:
| Type | Description |
|---|---|
List[Dict[str, Any]]
|
One record per iteration with the pair count and final loss. |
Source code in flowpde/trainers/reflow.py
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 | |