Skip to content

utils

Numerical stability

numerical

Numerical stability utilities for mixed-precision training.

General-purpose helpers for preventing NaN/Inf values in deep learning computations, particularly under FP16/BF16 autocast.

StabilityConfig

Default numerical stability bounds.

get_eps

get_eps(dtype)

Return an appropriate epsilon for the given dtype.

Source code in deltaflow/utils/numerical.py
def get_eps(dtype: torch.dtype) -> float:
    """Return an appropriate epsilon for the given dtype."""
    if dtype in (torch.float16, torch.bfloat16):
        return StabilityConfig.EPS_FP16
    return StabilityConfig.EPS_FP32

safe_normalize

safe_normalize(x, dim=-1, eps=None)

L2-normalize with numerical stability (avoids division by ~zero norms).

Source code in deltaflow/utils/numerical.py
def safe_normalize(x: torch.Tensor, dim: int = -1, eps: Optional[float] = None) -> torch.Tensor:
    """L2-normalize with numerical stability (avoids division by ~zero norms)."""
    if eps is None:
        eps = get_eps(x.dtype)
    norm = x.norm(p=2, dim=dim, keepdim=True)
    norm = torch.clamp(norm, min=eps)
    return x / norm

safe_sqrt

safe_sqrt(x, eps=None)

Compute a square root, clamping the input to be non-negative first.

Source code in deltaflow/utils/numerical.py
def safe_sqrt(x: torch.Tensor, eps: Optional[float] = None) -> torch.Tensor:
    """Compute a square root, clamping the input to be non-negative first."""
    min_val = eps if eps is not None else 0.0
    return torch.sqrt(torch.clamp(x, min=min_val))

clamp_noise

clamp_noise(noise, bound=None)

Clamp a noise tensor to prevent extreme values under FP16.

Source code in deltaflow/utils/numerical.py
def clamp_noise(noise: torch.Tensor, bound: Optional[float] = None) -> torch.Tensor:
    """Clamp a noise tensor to prevent extreme values under FP16."""
    bound = bound if bound is not None else StabilityConfig.NOISE_BOUND
    return torch.clamp(noise, -bound, bound)

clamp_prediction

clamp_prediction(pred, bound=None)

Clamp model predictions to prevent extreme values.

Source code in deltaflow/utils/numerical.py
def clamp_prediction(pred: torch.Tensor, bound: Optional[float] = None) -> torch.Tensor:
    """Clamp model predictions to prevent extreme values."""
    bound = bound if bound is not None else StabilityConfig.PREDICTION_BOUND
    return torch.clamp(pred, -bound, bound)

clamp_loss

clamp_loss(loss, max_val=None)

Clamp a scalar loss to prevent gradient explosion.

Source code in deltaflow/utils/numerical.py
def clamp_loss(loss: torch.Tensor, max_val: Optional[float] = None) -> torch.Tensor:
    """Clamp a scalar loss to prevent gradient explosion."""
    max_val = max_val if max_val is not None else StabilityConfig.LOSS_BOUND
    return torch.clamp(loss, min=0.0, max=max_val)

clamp_cosine_similarity

clamp_cosine_similarity(sim)

Clamp cosine similarity to the valid range [-1, 1].

Source code in deltaflow/utils/numerical.py
def clamp_cosine_similarity(sim: torch.Tensor) -> torch.Tensor:
    """Clamp cosine similarity to the valid range [-1, 1]."""
    return torch.clamp(sim, -StabilityConfig.COSINE_SIM_BOUND, StabilityConfig.COSINE_SIM_BOUND)

Tensor shapes

tensor

Small tensor-shape helpers shared by interpolants, solvers, and inverse problems.

broadcast_time

broadcast_time(t, x)

Reshape a time (or any per-sample scalar) so it broadcasts against x.

  • A per-sample tensor of shape (B,) becomes (B, 1, ..., 1) with x.dim() dimensions, e.g. (B,) -> (B, 1, 1, 1) for images.
  • A Python float or 0-d tensor becomes a 0-d tensor on x's device.
Source code in deltaflow/utils/tensor.py
def broadcast_time(t: Union[float, torch.Tensor], x: torch.Tensor) -> torch.Tensor:
    """Reshape a time (or any per-sample scalar) so it broadcasts against ``x``.

    - A per-sample tensor of shape ``(B,)`` becomes ``(B, 1, ..., 1)`` with
      ``x.dim()`` dimensions, e.g. ``(B,) -> (B, 1, 1, 1)`` for images.
    - A Python float or 0-d tensor becomes a 0-d tensor on ``x``'s device.
    """
    if not isinstance(t, torch.Tensor):
        return torch.tensor(t, device=x.device, dtype=x.dtype)
    if t.dim() == 0:
        return t
    return t.view(-1, *([1] * (x.dim() - 1)))

Optimal transport

ot

Discrete optimal-transport assignment helpers.

The mini-batch OT coupling used by deltaflow.interpolants.ot.OTInterpolant and deltaflow.trainer.coupling reduces to a single reusable primitive, a squared-L2 assignment between two equal-size batches. It lives here so the interpolant, the training-time coupling, and the visualization examples can share one implementation.

Exact optimal assignment is computed with the Hungarian algorithm (scipy.optimize.linear_sum_assignment).

batch_ot_permutation

batch_ot_permutation(x0, x1)

Return a permutation perm such that x0[perm] is OT-coupled to x1.

Costs are squared L2 distances on the flattened per-sample tensors.

Source code in deltaflow/utils/ot.py
def batch_ot_permutation(x0: torch.Tensor, x1: torch.Tensor) -> torch.Tensor:
    """Return a permutation ``perm`` such that ``x0[perm]`` is OT-coupled to ``x1``.

    Costs are squared L2 distances on the flattened per-sample tensors.
    """
    b = x0.shape[0]
    if b == 1:
        return torch.zeros(1, dtype=torch.long, device=x0.device)

    x0f = x0.reshape(b, -1).float()
    x1f = x1.reshape(b, -1).float()
    cost = torch.cdist(x0f, x1f) ** 2  # (B, B), cost[i, j] = |x0[i] - x1[j]|^2

    _, col_ind = linear_sum_assignment(cost.detach().cpu().numpy())
    # Rows come back sorted, so col_ind[i] is the x1 index paired with x0[i].
    # Inverting it gives, for each x1[j], the x0 index assigned to it.
    col = torch.as_tensor(col_ind, dtype=torch.long, device=x0.device)
    return torch.argsort(col)

Image I/O

image_io

Image file I/O shared by the image datasets.

Pillow is an optional extra (pip install torchdeltaflow[images]), so it is the only dependency resolved lazily. Every image-loading module goes through this adapter rather than importing Pillow itself, which keeps the optional dependency handling in exactly one place.

require_pillow

require_pillow()

Return the PIL.Image module, or raise an actionable ImportError.

Source code in deltaflow/utils/image_io.py
def require_pillow() -> ModuleType:
    """Return the ``PIL.Image`` module, or raise an actionable `ImportError`."""
    try:
        return importlib.import_module("PIL.Image")
    except ImportError as err:
        raise ImportError(_PILLOW_INSTALL_HINT) from err

list_images

list_images(root, extensions=IMAGE_EXTENSIONS)

Recursively list image files under root in a deterministic order.

Source code in deltaflow/utils/image_io.py
def list_images(root: Union[str, Path], extensions: Sequence[str] = IMAGE_EXTENSIONS) -> List[Path]:
    """Recursively list image files under ``root`` in a deterministic order."""
    exts = tuple(e.lower() for e in extensions)
    return sorted(p for p in Path(root).rglob("*") if p.suffix.lower() in exts)

open_image

open_image(path, mode, size=None)

Open path as a PIL image in mode, optionally resized to size x size.

Source code in deltaflow/utils/image_io.py
def open_image(path: Union[str, Path], mode: str, size: Optional[int] = None):
    """Open ``path`` as a PIL image in ``mode``, optionally resized to ``size x size``."""
    img = require_pillow().open(path).convert(mode)
    if size is not None:
        img = img.resize((size, size))
    return img