magvits_data / code /s1 /edm.py
arcadiaaaaa
Add files using upload-large-folder tool
11b4f27 verified
Raw History Blame Contribute Delete
6.17 kB
import numpy as np
import torch
def normalize(x, dim=None, eps=1e-4):
if dim is None:
dim = list(range(1, x.ndim))
norm = torch.linalg.vector_norm(x, dim=dim, keepdim=True, dtype=torch.float32)
norm = torch.add(eps, norm, alpha=np.sqrt(norm.numel() / x.numel()))
return x / norm.to(x.dtype)
class MPFourier(torch.nn.Module):
def __init__(self, num_channels, bandwidth=1):
super().__init__()
self.register_buffer('freqs', 2 * np.pi * torch.randn(num_channels) * bandwidth)
self.register_buffer('phases', 2 * np.pi * torch.rand(num_channels))
def forward(self, x):
y = x.to(torch.float32)
y = y.ger(self.freqs.to(torch.float32))
y = y + self.phases.to(torch.float32)
y = y.cos() * np.sqrt(2)
return y.to(x.dtype)
#----------------------------------------------------------------------------
# Magnitude-preserving convolution or fully-connected layer (Equation 47)
# with force weight normalization (Equation 66).
class MPConv(torch.nn.Module):
def __init__(self, in_channels, out_channels, kernel):
super().__init__()
self.out_channels = out_channels
self.weight = torch.nn.Parameter(torch.randn(out_channels, in_channels, *kernel))
def forward(self, x, gain=1):
w = self.weight.to(torch.float32)
if self.training:
with torch.no_grad():
self.weight.copy_(normalize(w)) # forced weight normalization
w = normalize(w) # traditional weight normalization
w = w * (gain / np.sqrt(w[0].numel())) # magnitude-preserving scaling
w = w.to(x.dtype)
assert w.ndim == 2
return x @ w.t()
class EDM2NetworkWrapper(torch.nn.Module):
def __init__(self,
net,
use_fp16 = True, # Run the model at FP16 precision?
sigma_data = 0.5, # Expected standard deviation of the training data.
logvar_channels = 128, # Intermediate dimensionality for uncertainty estimation.
**unet_kwargs, # Keyword arguments for UNet.
):
super().__init__()
self.use_fp16 = use_fp16
self.sigma_data = sigma_data
self.net = net
self.logvar_fourier = MPFourier(logvar_channels)
self.logvar_linear = MPConv(logvar_channels, 1, kernel=[])
def forward(self, x, sigma, force_fp32=False, return_logvar=False, **kwargs):
x = x.to(torch.float32)
sigma = sigma.to(torch.float32).reshape(-1,1,1)
dtype = torch.float16 if (self.use_fp16 and not force_fp32 and x.device.type == 'cuda') else torch.float32
# Preconditioning weights.
c_skip = self.sigma_data ** 2 / (sigma ** 2 + self.sigma_data ** 2)
c_out = sigma * self.sigma_data / (sigma ** 2 + self.sigma_data ** 2).sqrt()
c_in = 1 / (self.sigma_data ** 2 + sigma ** 2).sqrt()
c_noise = sigma.flatten().log() / 4
# Run the model.
x_in = (c_in * x).to(dtype)
F_x = self.net(x_in, c_noise, **kwargs)
D_x = c_skip * x + c_out * F_x.to(torch.float32)
# Estimate uncertainty if requested.
if return_logvar:
logvar = self.logvar_linear(self.logvar_fourier(c_noise)).reshape(-1,1,1)
return D_x, logvar # u(sigma) in Equation 21
return D_x
from tqdm import tqdm
def edm_sampler(
net, noise, cond,
num_steps=32, sigma_min=0.002, sigma_max=80, rho=7,
S_churn=0, S_min=0, S_max=float('inf'), S_noise=1,
dtype=torch.float32, randn_like=torch.randn_like,
guidance=1.0,
):
# Guided denoiser.
def denoise(x, t):
Dx = net(x, t, cond=cond).to(dtype)
if guidance == 1:
return Dx
uncond = torch.zeros_like(cond).to(dtype).to(cond.device)
ref_Dx = net(x, t, cond=uncond).to(dtype)
return ref_Dx.lerp(Dx, guidance)
# Time step discretization.
step_indices = torch.arange(num_steps, dtype=dtype, device=noise.device)
t_steps = (sigma_max ** (1 / rho) + step_indices / (num_steps - 1) * (sigma_min ** (1 / rho) - sigma_max ** (1 / rho))) ** rho
t_steps = torch.cat([t_steps, torch.zeros_like(t_steps[:1])]) # t_N = 0
# Main sampling loop.
x_next = noise.to(dtype) * t_steps[0]
for i, (t_cur, t_next) in tqdm(enumerate(zip(t_steps[:-1], t_steps[1:]))): # 0, ..., N-1
x_cur = x_next
# Increase noise temporarily.
if S_churn > 0 and S_min <= t_cur <= S_max:
gamma = min(S_churn / num_steps, np.sqrt(2) - 1)
t_hat = t_cur + gamma * t_cur
x_hat = x_cur + (t_hat ** 2 - t_cur ** 2).sqrt() * S_noise * randn_like(x_cur)
else:
t_hat = t_cur
x_hat = x_cur
# Euler step.
d_cur = (x_hat - denoise(x_hat, t_hat)) / t_hat
x_next = x_hat + (t_next - t_hat) * d_cur
# Apply 2nd order correction.
if i < num_steps - 1:
d_prime = (x_next - denoise(x_next, t_next)) / t_next
x_next = x_hat + (t_next - t_hat) * (0.5 * d_cur + 0.5 * d_prime)
return x_next
if __name__ == "__main__":
from wavenet import WaveNet
io_channels = 16
cond_channels = 192
net = WaveNet(
in_dims=io_channels,
n_layers=20,
n_chans=384,
n_hidden=cond_channels
)
edm_net = EDM2NetworkWrapper(net)
print(edm_net)
diffusion_input = torch.randn(1,io_channels, 100)
cond = torch.randn(1, cond_channels, 100)
P_std = 1.0
P_mean = -0.4
sigma_data = 0.4
rnd_normal = torch.randn([diffusion_input.shape[0], 1, 1], device=diffusion_input.device)
sigma = (rnd_normal * P_std + P_mean).exp()
weight = (sigma ** 2 + sigma_data ** 2) / (sigma * sigma_data) ** 2
noise = torch.randn_like(diffusion_input) * sigma
denoised, logvar = edm_net(diffusion_input + noise, sigma, cond=cond, return_logvar=True)
loss = (weight / logvar.exp()) * ((denoised - diffusion_input) ** 2) + logvar
loss = loss.mean()
print(loss)
noise = torch.randn([1, io_channels, 100]).to(cond.device)
fakes = edm_sampler(edm_net, noise, cond, num_steps=32)
print(fakes.shape)