models¶
models
¶
Model components: velocity-field backbone wrappers, projector heads, EMA, and the DiT transformer with adaLN-Zero conditioning.
TinyVelocityField
¶
Bases: BaseVelocityField
A tiny convolutional velocity field for tests and toy runs.
Not a real backbone - just enough capacity to keep unit tests
self-contained. For real training use WrappedBackbone around a
proper UNet / DiT implementation.
Source code in deltaflow/models/backbone.py
WrappedBackbone
¶
Bases: BaseVelocityField
Adapter that turns any nn.Module backbone into a velocity field.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
backbone
|
Module
|
the underlying network (UNet, DiT, ...). |
required |
forward_fn
|
Optional[Callable]
|
callable |
None
|
time_scale
|
float
|
multiplier applied to |
1.0
|
Source code in deltaflow/models/backbone.py
DiT
¶
DiT(input_size=32, patch_size=4, in_channels=1, hidden_size=256, depth=4, num_heads=4, mlp_ratio=4.0, num_classes=10, class_dropout_prob=0.1, time_scale=1000.0)
Bases: BaseVelocityField
A class-conditional Diffusion Transformer velocity field.
The field patchifies an image x of shape (B, C, H, W) into a token
sequence, adds a learned position embedding, runs it through depth
DiTBlock layers conditioned on time + class embeddings, and unpatchifies
the output back to a velocity of the same shape as x. It satisfies the
BaseVelocityField contract, so it drops straight into DeltaFlow's losses
and solvers.
Conditioning is passed through the opaque **cond channel as cond["y"]
(integer class labels of shape (B,)). When y is omitted the field
runs unconditionally via the learned null token.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_size
|
int
|
spatial size of the (square) input image. |
32
|
patch_size
|
int
|
side length of each square patch; must divide |
4
|
in_channels
|
int
|
number of image channels. |
1
|
hidden_size
|
int
|
transformer token width. |
256
|
depth
|
int
|
number of |
4
|
num_heads
|
int
|
attention heads per block. |
4
|
mlp_ratio
|
float
|
feed-forward expansion ratio. |
4.0
|
num_classes
|
int
|
number of conditioning classes (a null token is added on top for classifier-free guidance). |
10
|
class_dropout_prob
|
float
|
train-time label-dropout probability for CFG. |
0.1
|
time_scale
|
float
|
multiplier applied to |
1000.0
|
Source code in deltaflow/models/dit.py
initialize_weights
¶
Xavier-init linear layers, then zero-init every adaLN-Zero gate.
Source code in deltaflow/models/dit.py
forward
¶
Predict the velocity v_theta(x, t, y).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Tensor
|
input image batch |
required |
t
|
Tensor
|
time of shape |
required |
y
|
Optional[Tensor]
|
optional integer class labels |
None
|
force_drop_ids
|
Optional[Tensor]
|
optional mask selecting which labels to force to the null token (used by the unconditional branch of CFG). |
None
|
Source code in deltaflow/models/dit.py
forward_with_cfg
¶
Classifier-free-guided velocity for sampling.
Runs the field once with the real labels and once with the null token, then extrapolates
with guidance weight s = cfg_scale. The two passes are batched
together, so this costs one forward over a doubled batch.
Source code in deltaflow/models/dit.py
DiTBlock
¶
Bases: Module
A transformer block modulated by adaLN-Zero conditioning.
Both sub-layers (self-attention and MLP) are wrapped as
x = x + gate * sublayer(modulate(norm(x), shift, scale)),
where (shift, scale, gate) are produced per sub-layer from the shared
conditioning embedding c. The six modulation vectors come from a single
SiLU -> Linear head whose weights are zero-initialized (see
DiT.initialize_weights), so at initialization every gate is zero and the
block is the identity map.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hidden_size
|
int
|
token channel width. |
required |
num_heads
|
int
|
attention heads. |
required |
mlp_ratio
|
float
|
hidden expansion of the feed-forward MLP. |
4.0
|
Source code in deltaflow/models/dit.py
FinalLayer
¶
Bases: Module
adaLN-Zero output head that maps tokens back to patch pixels.
The final normalization is modulated by (shift, scale) from the
conditioning embedding, then a linear layer projects each token to
patch_size**2 * out_channels values. Both the modulation head and the
output projection are zero-initialized so the field predicts v = 0 at the
start of training.
Source code in deltaflow/models/dit.py
LabelEmbedding
¶
Bases: Module
Class-label embedding with a learned null token for guidance.
The embedding table has num_classes + 1 rows; the extra row is the
null (unconditional) token used by classifier-free guidance. During
training a fraction dropout_prob of labels are replaced by the null
token, teaching the field both the conditional and unconditional velocity
with one set of weights.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
num_classes
|
int
|
number of real classes. |
required |
hidden_size
|
int
|
embedding width. |
required |
dropout_prob
|
float
|
probability of dropping a label to the null token at
train time (set |
0.1
|
Source code in deltaflow/models/dit.py
token_drop
¶
Replace a random subset of labels with the null token.
If force_drop_ids is given (a boolean/0-1 mask), those positions are
dropped deterministically instead, which is how the unconditional branch
is requested at sampling time.
Source code in deltaflow/models/dit.py
TimestepEmbedding
¶
Bases: Module
Reusable sinusoidal timestep embedding followed by a small MLP.
The continuous flow-matching time t in [0, 1] (DeltaFlow convention:
t=0 is noise, t=1 is data) is first multiplied by time_scale to
spread it across the sinusoidal frequency band, then embedded with the usual
transformer sinusoids and projected by a two-layer MLP.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hidden_size
|
int
|
output (and MLP) width. |
required |
frequency_dim
|
int
|
width of the raw sinusoidal features before the MLP. |
256
|
time_scale
|
float
|
multiplier applied to |
1000.0
|
max_period
|
int
|
controls the lowest sinusoidal frequency. |
10000
|
Source code in deltaflow/models/dit.py
EMA
¶
Exponential moving average helper for a shadow copy of a model.
Usage::
ema = EMA(beta=0.995)
ema_model = copy.deepcopy(model).eval().requires_grad_(False)
# after every optimizer step:
ema.update_model_average(ema_model, model)
Source code in deltaflow/models/ema.py
MultiScaleProjector
¶
Bases: Module
Collection of per-level projection heads.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
feature_dims
|
Dict[str, int]
|
|
required |
hidden_dim
|
int
|
hidden width shared by every per-level projector. |
512
|
out_dim
|
int
|
shared output embedding dimension. |
256
|
layer_set
|
Sequence[str]
|
which layer names to project, defaults to
|
_DEFAULT_LAYER_SET
|
Source code in deltaflow/models/projector.py
pool_feature
staticmethod
¶
project_delta_h
¶
Compute delta_h = h_cond - h_uncond and project each level.
Returns a dict of (optionally L2-normalized) embeddings, one per
layer present in both feature dicts and in self.projectors.
Source code in deltaflow/models/projector.py
ProjectorHead
¶
Bases: Module
Two-layer MLP projector (in_dim -> hidden_dim -> out_dim, GELU).
Source code in deltaflow/models/projector.py
modulate
¶
Apply adaLN modulation x * (1 + scale) + shift with broadcasting.
x has shape (B, N, D) (batch, tokens, channels), while shift and
scale have shape (B, D). The 1 + keeps the transform centred on
the identity, so a zero-initialized modulation MLP leaves x unchanged.