|
import math |
|
from typing import Union |
|
|
|
from diffusers import FlowMatchEulerDiscreteScheduler |
|
import torch |
|
|
|
|
|
class CustomFlowMatchEulerDiscreteScheduler(FlowMatchEulerDiscreteScheduler): |
|
def __init__(self, *args, **kwargs): |
|
super().__init__(*args, **kwargs) |
|
self.init_noise_sigma = 1.0 |
|
|
|
with torch.no_grad(): |
|
|
|
num_timesteps = 1000 |
|
|
|
|
|
|
|
x = torch.arange(num_timesteps, dtype=torch.float32) |
|
y = torch.exp(-2 * ((x - num_timesteps / 2) / num_timesteps) ** 2) |
|
|
|
|
|
y_shifted = y - y.min() |
|
|
|
|
|
bsmntw_weighing = y_shifted * (num_timesteps / y_shifted.sum()) |
|
|
|
|
|
hbsmntw_weighing = y_shifted * (num_timesteps / y_shifted.sum()) |
|
|
|
|
|
hbsmntw_weighing[num_timesteps // 2:] = hbsmntw_weighing[num_timesteps // 2:].max() |
|
|
|
|
|
timesteps = torch.linspace(1000, 0, num_timesteps, device='cpu') |
|
|
|
self.linear_timesteps = timesteps |
|
self.linear_timesteps_weights = bsmntw_weighing |
|
self.linear_timesteps_weights2 = hbsmntw_weighing |
|
pass |
|
|
|
def get_weights_for_timesteps(self, timesteps: torch.Tensor, v2=False) -> torch.Tensor: |
|
|
|
step_indices = [(self.timesteps == t).nonzero().item() for t in timesteps] |
|
|
|
|
|
if v2: |
|
weights = self.linear_timesteps_weights2[step_indices].flatten() |
|
else: |
|
weights = self.linear_timesteps_weights[step_indices].flatten() |
|
|
|
return weights |
|
|
|
def get_sigmas(self, timesteps: torch.Tensor, n_dim, dtype, device) -> torch.Tensor: |
|
sigmas = self.sigmas.to(device=device, dtype=dtype) |
|
schedule_timesteps = self.timesteps.to(device) |
|
timesteps = timesteps.to(device) |
|
step_indices = [(schedule_timesteps == t).nonzero().item() for t in timesteps] |
|
|
|
sigma = sigmas[step_indices].flatten() |
|
while len(sigma.shape) < n_dim: |
|
sigma = sigma.unsqueeze(-1) |
|
|
|
return sigma |
|
|
|
def add_noise( |
|
self, |
|
original_samples: torch.Tensor, |
|
noise: torch.Tensor, |
|
timesteps: torch.Tensor, |
|
) -> torch.Tensor: |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
t_01 = (timesteps / 1000).to(original_samples.device) |
|
noisy_model_input = (1 - t_01) * original_samples + t_01 * noise |
|
|
|
|
|
|
|
|
|
return noisy_model_input |
|
|
|
def scale_model_input(self, sample: torch.Tensor, timestep: Union[float, torch.Tensor]) -> torch.Tensor: |
|
return sample |
|
|
|
def set_train_timesteps(self, num_timesteps, device, linear=False): |
|
if linear: |
|
timesteps = torch.linspace(1000, 0, num_timesteps, device=device) |
|
self.timesteps = timesteps |
|
return timesteps |
|
else: |
|
|
|
|
|
t = torch.sigmoid(torch.randn((num_timesteps,), device=device)) |
|
|
|
|
|
timesteps = ((1 - t) * 1000) |
|
|
|
|
|
timesteps, _ = torch.sort(timesteps, descending=True) |
|
|
|
self.timesteps = timesteps.to(device=device) |
|
|
|
return timesteps |
|
|