"""IDFF samplers: Algorithm 1 (static data) and Algorithm 4 (time series) of the paper.""" import math import torch from torch.func import jvp from .core import gamma_schedule def contracted_score_derivative(score_fn, x, u, order): """Return (grad_x^order s)(x)[u]^order, i.e. the contracted term m^(order + 1) of Eq. momentum_contraction. ``order = 1`` gives the Hessian-vector product (grad_x s) u used at K = 2. Higher orders are obtained by nesting forward-mode JVPs, so no tensor of order > 1 is ever formed. """ f = score_fn for _ in range(order): f = _directional_derivative(f, u) return f(x) def _directional_derivative(f, u): def g(y): return jvp(f, (y,), (u,))[1] return g def _unit(v): norm = v.reshape(v.shape[0], -1).norm(dim=1).clamp_min(1e-12) return v / norm.reshape(-1, *([1] * (v.dim() - 1))) @torch.no_grad() def sample(model, x0, nfe, K=1, gamma_bar=0.2, alphas=None, schedule="beta22", diffusion_scale=2.0, score_drift=True, model_kwargs=None, generator=None, return_trajectory=False): """Integrate the IDFF SDE (Eq. idff_sde) with Euler-Maruyama (Algorithm 1). dx = [gamma_t^0 v_hat + gamma_t^1 m^(1) + sum_{k=2..K} gamma_t^k m^(k)] dt + g_t dW, with v_hat = (x1_hat - x) / (1 - t), m^(1) = s_hat, m^(k) = (grad^{k-1} s_hat)[u]^{k-1}, u = v_hat / ||v_hat||, gamma_t^0 = 1 (the paper's default), gamma_t^1 from ``schedule``, gamma_t^k = alpha_k gamma_t^1 dt^(k-1) for k >= 2, and g_t^2 = diffusion_scale * gamma_t^1. The defaults (K = 1, diffusion_scale = 2, score_drift = True) are the configuration whose continuous-time marginals equal the CFM marginals exactly (Theorem first_order_preservation). Other settings reproduce the ablations: ``K=0`` or ``gamma_bar=0`` is the deterministic CFM sampler, ``score_drift=False`` is "Stochastic CFM" (noise without the score drift), and ``diffusion_scale=0`` is the score drift without diffusion compensation. Time grid: step i uses t_i = i / nfe, so exactly ``nfe`` network evaluations are made (K >= 2 adds one JVP per step and order). The coefficients are set to zero on the final step, as the paper prescribes, so the last update is a pure CFM Euler step from t = 1 - dt; that step equals the denoiser read-out x1_hat(x, 1 - dt), which is what is returned. Args: model: ``model(x, t, **model_kwargs) -> (x1_hat, s_hat)``. x0: initial samples (N(0, I) for static data). nfe: number of network evaluations (= Euler-Maruyama steps). alphas: dict {k: alpha_k} for k >= 2; defaults to 0.05 for every order. generator: optional torch.Generator for the Brownian increments. return_trajectory: also return the stacked iterates, shape (nfe + 1, *x0.shape). """ if nfe < 1: raise ValueError("nfe must be >= 1") alphas = alphas or {} model_kwargs = model_kwargs or {} dt = 1.0 / nfe x = x0.clone() traj = [x] if return_trajectory else None for i in range(nfe): t = i * dt tb = torch.full((x.shape[0],), t, device=x.device, dtype=x.dtype) x1_hat, s_hat = model(x, tb, **model_kwargs) if i == nfe - 1: x = x1_hat else: v = (x1_hat - x) / (1.0 - t) g1 = gamma_schedule(t, gamma_bar, schedule) if K >= 1 else 0.0 drift = v if g1 > 0 and score_drift: drift = drift + g1 * s_hat if K >= 2 and g1 > 0: u = _unit(v) def score_fn(y, tb=tb): return model(y, tb, **model_kwargs)[1] for k in range(2, K + 1): gk = alphas.get(k, 0.05) * g1 * dt ** (k - 1) drift = drift + gk * contracted_score_derivative(score_fn, x, u, k - 1) x = x + drift * dt if g1 > 0 and diffusion_scale > 0: noise = torch.randn(x.shape, device=x.device, dtype=x.dtype, generator=generator) x = x + math.sqrt(diffusion_scale * g1 * dt) * noise if return_trajectory: traj.append(x) if return_trajectory: return x, torch.stack(traj) return x @torch.no_grad() def sample_next(model, prev, n, nfe, sigma0, generator=None, **sampler_kwargs): """Sample frame n given frame n-1 (one step of Algorithm 4): x0^n ~ N(prev, sigma0^2 I).""" noise = torch.randn(prev.shape, device=prev.device, dtype=prev.dtype, generator=generator) x0 = prev + sigma0 * noise nb = torch.full((prev.shape[0],), n, device=prev.device, dtype=torch.long) return sample(model, x0, nfe, model_kwargs={"n": nb}, generator=generator, **sampler_kwargs) @torch.no_grad() def sample_sequence(model, length, num_samples, dim, nfe, sigma0, first_frame=None, device="cpu", generator=None, **sampler_kwargs): """Autoregressive time-series sampling (Algorithm 4, IDFF Sampling (Time-Series)). Position 0 starts from N(0, I) unless ``first_frame`` is given (shape (dim,) shared by all samples, or (num_samples, dim) one per sample), in which case the rollout is conditioned on it and continues from position 1. Each later position starts from the previous generated frame, x0^n ~ N(x1^{n-1}, sigma0^2 I). Returns: tensor of shape (length, num_samples, dim). """ frames = [] if first_frame is None: x0 = torch.randn((num_samples, dim), device=device, generator=generator) nb = torch.zeros(num_samples, device=device, dtype=torch.long) prev = sample(model, x0, nfe, model_kwargs={"n": nb}, generator=generator, **sampler_kwargs) else: prev = first_frame.to(device).expand(num_samples, dim).clone() frames.append(prev) for n in range(1, length): prev = sample_next(model, prev, n, nfe, sigma0, generator=generator, **sampler_kwargs) frames.append(prev) return torch.stack(frames)