Upload 9 files
Browse files- modi_vae/.DS_Store +0 -0
- modi_vae/__pycache__/autoencoder.cpython-39.pyc +0 -0
- modi_vae/__pycache__/model_init.cpython-39.pyc +0 -0
- modi_vae/__pycache__/models.cpython-39.pyc +0 -0
- modi_vae/__pycache__/new_dataset.cpython-39.pyc +0 -0
- modi_vae/autoencoder.py +95 -0
- modi_vae/model_init.py +154 -0
- modi_vae/models.py +901 -0
- modi_vae/networks.py +80 -0
modi_vae/.DS_Store
ADDED
|
Binary file (6.15 kB). View file
|
|
|
modi_vae/__pycache__/autoencoder.cpython-39.pyc
ADDED
|
Binary file (3.16 kB). View file
|
|
|
modi_vae/__pycache__/model_init.cpython-39.pyc
ADDED
|
Binary file (4.79 kB). View file
|
|
|
modi_vae/__pycache__/models.cpython-39.pyc
ADDED
|
Binary file (22.6 kB). View file
|
|
|
modi_vae/__pycache__/new_dataset.cpython-39.pyc
ADDED
|
Binary file (4.8 kB). View file
|
|
|
modi_vae/autoencoder.py
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import pytorch_lightning as pl
|
| 3 |
+
import torch.nn.functional as F
|
| 4 |
+
from contextlib import contextmanager
|
| 5 |
+
|
| 6 |
+
from ldm.modules.distributions.distributions import DiagonalGaussianDistribution
|
| 7 |
+
|
| 8 |
+
from ldm.util import instantiate_from_config
|
| 9 |
+
from ldm.modules.ema import LitEma
|
| 10 |
+
|
| 11 |
+
try:
|
| 12 |
+
from modules.models import Encoder, Decoder
|
| 13 |
+
except:
|
| 14 |
+
from my_vae.models import Encoder, Decoder
|
| 15 |
+
|
| 16 |
+
class AutoencoderKL(pl.LightningModule):
|
| 17 |
+
def __init__(self,
|
| 18 |
+
embed_dim=4,
|
| 19 |
+
ckpt_path=None,
|
| 20 |
+
ignore_keys=[],
|
| 21 |
+
image_key="image",
|
| 22 |
+
colorize_nlabels=None,
|
| 23 |
+
monitor=None,
|
| 24 |
+
ema_decay=None,
|
| 25 |
+
learn_logvar=False,
|
| 26 |
+
load_checkpoint=True
|
| 27 |
+
):
|
| 28 |
+
super().__init__()
|
| 29 |
+
self.encoder = Encoder(double_z=True, z_channels=4, resolution=256, in_channels=3, out_ch=3, ch=128, ch_mult=[1,2,4,4], num_res_blocks=2, attn_resolutions=[], dropout=0.0)
|
| 30 |
+
self.decoder = Decoder(double_z=True, z_channels=4, resolution=256, in_channels=3, out_ch=3, ch=128, ch_mult=[1,2,4,4], num_res_blocks=2, attn_resolutions=[], dropout=0.0)
|
| 31 |
+
|
| 32 |
+
self.quant_conv = torch.nn.Conv2d(2*4, 2*embed_dim, 1)
|
| 33 |
+
self.post_quant_conv = torch.nn.Conv2d(embed_dim, 4, 1)
|
| 34 |
+
self.embed_dim = embed_dim
|
| 35 |
+
if colorize_nlabels is not None:
|
| 36 |
+
assert type(colorize_nlabels)==int
|
| 37 |
+
self.register_buffer("colorize", torch.randn(3, colorize_nlabels, 1, 1))
|
| 38 |
+
if monitor is not None:
|
| 39 |
+
self.monitor = monitor
|
| 40 |
+
|
| 41 |
+
if load_checkpoint:
|
| 42 |
+
state_dict = torch.load('/data07/v-wenjwang/ControlNet/CIConv/models/control_sd15_ini.ckpt', map_location=torch.device("cpu"))
|
| 43 |
+
new_state_dict = {}
|
| 44 |
+
for s in state_dict:
|
| 45 |
+
if "first_stage_model" in s:
|
| 46 |
+
new_state_dict[s.replace("first_stage_model.", "")] = state_dict[s]
|
| 47 |
+
self.load_state_dict(new_state_dict, strict=False)
|
| 48 |
+
|
| 49 |
+
def encode(self, x):
|
| 50 |
+
h, hs = self.encoder(x)
|
| 51 |
+
moments = self.quant_conv(h)
|
| 52 |
+
posterior = DiagonalGaussianDistribution(moments)
|
| 53 |
+
return posterior, hs
|
| 54 |
+
|
| 55 |
+
def decode(self, z, hs):
|
| 56 |
+
z = self.post_quant_conv(z)
|
| 57 |
+
dec = self.decoder(z, hs)
|
| 58 |
+
return dec
|
| 59 |
+
|
| 60 |
+
def forward(self, input, sample_posterior=True):
|
| 61 |
+
posterior, hs = self.encode(input)
|
| 62 |
+
if sample_posterior:
|
| 63 |
+
z = posterior.sample()
|
| 64 |
+
else:
|
| 65 |
+
z = posterior.mode()
|
| 66 |
+
dec = self.decode(z, hs)
|
| 67 |
+
return dec, posterior
|
| 68 |
+
|
| 69 |
+
if __name__ == "__main__":
|
| 70 |
+
from data.laion_dataset import create_webdataset
|
| 71 |
+
import torchvision
|
| 72 |
+
|
| 73 |
+
image_dataset = create_webdataset(
|
| 74 |
+
data_dir="/data06/v-wenjwang/COCO-2017/*/*.*",
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
import webdataset as wds
|
| 78 |
+
image_dataloader = wds.WebLoader(
|
| 79 |
+
dataset = image_dataset,
|
| 80 |
+
batch_size = 1,
|
| 81 |
+
num_workers = 8,
|
| 82 |
+
pin_memory = True,
|
| 83 |
+
prefetch_factor = 2,
|
| 84 |
+
)
|
| 85 |
+
|
| 86 |
+
model = AutoencoderKL().cuda()
|
| 87 |
+
|
| 88 |
+
for data in image_dataloader:
|
| 89 |
+
img = data["distorted"].cuda()
|
| 90 |
+
img = model(img)[0]
|
| 91 |
+
|
| 92 |
+
torchvision.utils.save_image(img*0.5+0.5, "distorted.png")
|
| 93 |
+
torchvision.utils.save_image(data["distorted"]*0.5+0.5, "original.png")
|
| 94 |
+
|
| 95 |
+
break
|
modi_vae/model_init.py
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
import torch.nn.functional as F
|
| 4 |
+
import pytorch_lightning as pl
|
| 5 |
+
|
| 6 |
+
from ldm.modules.distributions.distributions import DiagonalGaussianDistribution
|
| 7 |
+
try:
|
| 8 |
+
from modules.models import Encoder, Decoder
|
| 9 |
+
except:
|
| 10 |
+
from my_vae.models import Encoder, Decoder
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class AutoencoderKL(pl.LightningModule):
|
| 14 |
+
def __init__(self,
|
| 15 |
+
embed_dim=4,
|
| 16 |
+
ckpt_path=None,
|
| 17 |
+
ignore_keys=[],
|
| 18 |
+
image_key="image",
|
| 19 |
+
colorize_nlabels=None,
|
| 20 |
+
monitor=None,
|
| 21 |
+
ema_decay=None,
|
| 22 |
+
learn_logvar=False,
|
| 23 |
+
load_checkpoint=True,
|
| 24 |
+
lr=1e-4,
|
| 25 |
+
):
|
| 26 |
+
super().__init__()
|
| 27 |
+
self.save_hyperparameters(ignore=["ckpt_path", "ignore_keys", "colorize_nlabels"])
|
| 28 |
+
self.image_key = image_key
|
| 29 |
+
self.lr = lr
|
| 30 |
+
|
| 31 |
+
self.encoder = Encoder(double_z=True, z_channels=4, resolution=256, in_channels=3,
|
| 32 |
+
out_ch=3, ch=128, ch_mult=[1,2,4,4], num_res_blocks=2,
|
| 33 |
+
attn_resolutions=[], dropout=0.0)
|
| 34 |
+
self.decoder = Decoder(double_z=True, z_channels=4, resolution=256, in_channels=3,
|
| 35 |
+
out_ch=3, ch=128, ch_mult=[1,2,4,4], num_res_blocks=2,
|
| 36 |
+
attn_resolutions=[], dropout=0.0)
|
| 37 |
+
|
| 38 |
+
self.quant_conv = nn.Conv2d(2*4, 2*embed_dim, 1)
|
| 39 |
+
self.post_quant_conv = nn.Conv2d(embed_dim, 4, 1)
|
| 40 |
+
self.embed_dim = embed_dim
|
| 41 |
+
|
| 42 |
+
if colorize_nlabels is not None:
|
| 43 |
+
assert isinstance(colorize_nlabels, int)
|
| 44 |
+
self.register_buffer("colorize", torch.randn(3, colorize_nlabels, 1, 1))
|
| 45 |
+
if monitor is not None:
|
| 46 |
+
self.monitor = monitor
|
| 47 |
+
|
| 48 |
+
if load_checkpoint:
|
| 49 |
+
state_dict = torch.load('/home/xxing/model/ControlNet/checkpoints/main-epoch=00-step=7000.ckpt', map_location=torch.device("cpu"))["state_dict"]
|
| 50 |
+
new_state_dict = {}
|
| 51 |
+
for s in state_dict:
|
| 52 |
+
if "my_vae" in s:
|
| 53 |
+
new_state_dict[s.replace("my_vae.", "")] = state_dict[s]
|
| 54 |
+
self.load_state_dict(new_state_dict)
|
| 55 |
+
print("Successfully load new auto-encoder")
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
# By default, prepare for decoder-only finetuning
|
| 59 |
+
self.freeze_encoder()
|
| 60 |
+
|
| 61 |
+
# ---------- core VAE pieces ----------
|
| 62 |
+
def encode(self, x):
|
| 63 |
+
h, hs = self.encoder(x)
|
| 64 |
+
moments = self.quant_conv(h)
|
| 65 |
+
posterior = DiagonalGaussianDistribution(moments)
|
| 66 |
+
return posterior, hs
|
| 67 |
+
|
| 68 |
+
def decode(self, z, hs):
|
| 69 |
+
z = self.post_quant_conv(z)
|
| 70 |
+
dec = self.decoder(z, hs)
|
| 71 |
+
return dec
|
| 72 |
+
|
| 73 |
+
def forward(self, input, sample_posterior=True):
|
| 74 |
+
posterior, hs = self.encode(input)
|
| 75 |
+
z = posterior.sample() if sample_posterior else posterior.mode()
|
| 76 |
+
dec = self.decode(z, hs)
|
| 77 |
+
return dec, posterior
|
| 78 |
+
|
| 79 |
+
# ---------- training for decoder only ----------
|
| 80 |
+
@torch.no_grad()
|
| 81 |
+
def _encode_nograd(self, x):
|
| 82 |
+
"""Encode without gradients; used to prevent updates to encoder/quant_conv."""
|
| 83 |
+
posterior, hs = self.encode(x)
|
| 84 |
+
# Detach so gradients don't flow back to encoder/quant_conv
|
| 85 |
+
z = posterior.sample().detach()
|
| 86 |
+
hs = [h.detach() if isinstance(h, torch.Tensor) else h for h in hs]
|
| 87 |
+
return z, hs
|
| 88 |
+
|
| 89 |
+
def training_step(self, batch, batch_idx):
|
| 90 |
+
# Expect batch to be a dict with 'image' or a tensor directly
|
| 91 |
+
x = batch[self.image_key] if isinstance(batch, dict) else batch # [B,3,H,W] in [-1,1] or [0,1]
|
| 92 |
+
z, _ = self._encode_nograd(x[:,:3,...])
|
| 93 |
+
_, hs = self._encode_nograd(x[:,3:,...])
|
| 94 |
+
x_hat = self.decode(z, hs)
|
| 95 |
+
|
| 96 |
+
# Simple reconstruction loss (L1). If inputs are in [-1,1], it's fine for L1 too.
|
| 97 |
+
rec_loss = F.l1_loss(x_hat, x[:,:3,...])
|
| 98 |
+
|
| 99 |
+
# (Optional) small MSE term to stabilize
|
| 100 |
+
mse_loss = F.mse_loss(x_hat, x[:,:3,...])
|
| 101 |
+
loss = rec_loss + 0.1 * mse_loss
|
| 102 |
+
|
| 103 |
+
self.log_dict({
|
| 104 |
+
"train/l1": rec_loss,
|
| 105 |
+
"train/mse": mse_loss,
|
| 106 |
+
"train/loss": loss
|
| 107 |
+
}, prog_bar=True, on_step=True, on_epoch=True, batch_size=x.shape[0])
|
| 108 |
+
return loss
|
| 109 |
+
|
| 110 |
+
def validation_step(self, batch, batch_idx):
|
| 111 |
+
x = batch[self.image_key] if isinstance(batch, dict) else batch
|
| 112 |
+
z,_ = self._encode_nograd(x[:,:3,...])
|
| 113 |
+
_, hs = self._encode_nograd(x[:,3:,...])
|
| 114 |
+
|
| 115 |
+
x_hat = self.decode(z, hs)
|
| 116 |
+
rec_loss = F.l1_loss(x_hat, x[:,:3,...])
|
| 117 |
+
mse_loss = F.mse_loss(x_hat, x[:,:3,...])
|
| 118 |
+
loss = rec_loss + 0.1 * mse_loss
|
| 119 |
+
self.log_dict({
|
| 120 |
+
"val/l1": rec_loss,
|
| 121 |
+
"val/mse": mse_loss,
|
| 122 |
+
"val/loss": loss
|
| 123 |
+
}, prog_bar=True, on_epoch=True, batch_size=x.shape[0])
|
| 124 |
+
|
| 125 |
+
def configure_optimizers(self):
|
| 126 |
+
# Only optimize decoder + post_quant_conv
|
| 127 |
+
params = list(self.decoder.parameters()) + list(self.post_quant_conv.parameters())
|
| 128 |
+
opt = torch.optim.Adam(params, lr=self.lr, betas=(0.9, 0.999))
|
| 129 |
+
return opt
|
| 130 |
+
|
| 131 |
+
def freeze_encoder(self):
|
| 132 |
+
"""Freeze encoder and quant_conv (no grads)."""
|
| 133 |
+
for p in self.encoder.parameters():
|
| 134 |
+
p.requires_grad = False
|
| 135 |
+
for p in self.quant_conv.parameters():
|
| 136 |
+
p.requires_grad = False
|
| 137 |
+
# Ensure decoder & post_quant_conv are trainable
|
| 138 |
+
for p in self.decoder.parameters():
|
| 139 |
+
p.requires_grad = True
|
| 140 |
+
for p in self.post_quant_conv.parameters():
|
| 141 |
+
p.requires_grad = True
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
# import torch
|
| 145 |
+
# import torchvision.transforms as T
|
| 146 |
+
|
| 147 |
+
# # Compose transforms
|
| 148 |
+
# transform = T.Compose([
|
| 149 |
+
# T.ColorJitter(brightness=0.3, contrast=0.3, saturation=0.3, hue=0.1), # illumination jitter
|
| 150 |
+
# T.Lambda(lambda x: x + 0.05 * torch.randn_like(x)) # Gaussian noise
|
| 151 |
+
# ])
|
| 152 |
+
|
| 153 |
+
# # Example: I is [C,H,W] in [0,1] or [-1,1]
|
| 154 |
+
# I_aug = transform(I).clamp(-1, 1) # keep in valid range
|
modi_vae/models.py
ADDED
|
@@ -0,0 +1,901 @@
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# pytorch_diffusion + derived encoder decoder
|
| 2 |
+
import math
|
| 3 |
+
import torch
|
| 4 |
+
import torch.nn as nn
|
| 5 |
+
import numpy as np
|
| 6 |
+
from einops import rearrange
|
| 7 |
+
from typing import Optional, Any
|
| 8 |
+
|
| 9 |
+
from ldm.modules.attention import MemoryEfficientCrossAttention
|
| 10 |
+
|
| 11 |
+
try:
|
| 12 |
+
import xformers
|
| 13 |
+
import xformers.ops
|
| 14 |
+
XFORMERS_IS_AVAILBLE = True
|
| 15 |
+
except:
|
| 16 |
+
XFORMERS_IS_AVAILBLE = False
|
| 17 |
+
print("No module 'xformers'. Proceeding without it.")
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def get_timestep_embedding(timesteps, embedding_dim):
|
| 21 |
+
"""
|
| 22 |
+
This matches the implementation in Denoising Diffusion Probabilistic Models:
|
| 23 |
+
From Fairseq.
|
| 24 |
+
Build sinusoidal embeddings.
|
| 25 |
+
This matches the implementation in tensor2tensor, but differs slightly
|
| 26 |
+
from the description in Section 3.5 of "Attention Is All You Need".
|
| 27 |
+
"""
|
| 28 |
+
assert len(timesteps.shape) == 1
|
| 29 |
+
|
| 30 |
+
half_dim = embedding_dim // 2
|
| 31 |
+
emb = math.log(10000) / (half_dim - 1)
|
| 32 |
+
emb = torch.exp(torch.arange(half_dim, dtype=torch.float32) * -emb)
|
| 33 |
+
emb = emb.to(device=timesteps.device)
|
| 34 |
+
emb = timesteps.float()[:, None] * emb[None, :]
|
| 35 |
+
emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=1)
|
| 36 |
+
if embedding_dim % 2 == 1: # zero pad
|
| 37 |
+
emb = torch.nn.functional.pad(emb, (0,1,0,0))
|
| 38 |
+
return emb
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def nonlinearity(x):
|
| 42 |
+
# swish
|
| 43 |
+
return x*torch.sigmoid(x)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def Normalize(in_channels, num_groups=32):
|
| 47 |
+
return torch.nn.GroupNorm(num_groups=num_groups, num_channels=in_channels, eps=1e-6, affine=True)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
class Merge(nn.Module):
|
| 51 |
+
def __init__(self, in_channels, out_channels):
|
| 52 |
+
super().__init__()
|
| 53 |
+
self.conv = torch.nn.Conv2d(in_channels,
|
| 54 |
+
out_channels,
|
| 55 |
+
kernel_size=3,
|
| 56 |
+
stride=1,
|
| 57 |
+
padding=1)
|
| 58 |
+
|
| 59 |
+
torch.nn.init.dirac_(self.conv.weight.data)
|
| 60 |
+
torch.nn.init.zeros_(self.conv.bias.data)
|
| 61 |
+
|
| 62 |
+
def forward(self, x, y):
|
| 63 |
+
features = torch.cat([x,y], dim=1)
|
| 64 |
+
output = self.conv(features)
|
| 65 |
+
return output
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
class BigMerge(nn.Module):
|
| 69 |
+
def __init__(self, in_channels, out_channels):
|
| 70 |
+
super().__init__()
|
| 71 |
+
self.conv1 = nn.Conv2d(in_channels, 32, kernel_size = 3, padding = 1)
|
| 72 |
+
self.conv2 = nn.Conv2d(32, out_channels, kernel_size = 3, padding = 1)
|
| 73 |
+
self.relu = nn.ReLU()
|
| 74 |
+
|
| 75 |
+
torch.nn.init.zeros_(self.conv2.weight.data)
|
| 76 |
+
torch.nn.init.zeros_(self.conv2.bias.data)
|
| 77 |
+
|
| 78 |
+
def forward(self, x, y):
|
| 79 |
+
x_ = self.conv1(torch.cat([x,y], dim=1))
|
| 80 |
+
x_ = self.relu(x_)
|
| 81 |
+
x_ = self.conv2(x_)
|
| 82 |
+
return x + x_
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
class Upsample(nn.Module):
|
| 86 |
+
def __init__(self, in_channels, with_conv, i_level):
|
| 87 |
+
super().__init__()
|
| 88 |
+
self.with_conv = with_conv
|
| 89 |
+
if self.with_conv:
|
| 90 |
+
self.conv = torch.nn.Conv2d(in_channels,
|
| 91 |
+
in_channels,
|
| 92 |
+
kernel_size=3,
|
| 93 |
+
stride=1,
|
| 94 |
+
padding=1)
|
| 95 |
+
|
| 96 |
+
if i_level == 3:
|
| 97 |
+
merged_channel = 512+512
|
| 98 |
+
elif i_level == 2:
|
| 99 |
+
merged_channel = 512+256
|
| 100 |
+
elif i_level == 1:
|
| 101 |
+
merged_channel = 256+128
|
| 102 |
+
self.new_merge = Merge(merged_channel, in_channels)
|
| 103 |
+
|
| 104 |
+
def forward(self, x, y):
|
| 105 |
+
x = torch.nn.functional.interpolate(x, scale_factor=2.0, mode="nearest")
|
| 106 |
+
if self.with_conv:
|
| 107 |
+
x = self.conv(x)
|
| 108 |
+
return self.new_merge(x,y)
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
class Downsample(nn.Module):
|
| 112 |
+
def __init__(self, in_channels, with_conv):
|
| 113 |
+
super().__init__()
|
| 114 |
+
self.with_conv = with_conv
|
| 115 |
+
if self.with_conv:
|
| 116 |
+
# no asymmetric padding in torch conv, must do it ourselves
|
| 117 |
+
self.conv = torch.nn.Conv2d(in_channels,
|
| 118 |
+
in_channels,
|
| 119 |
+
kernel_size=3,
|
| 120 |
+
stride=2,
|
| 121 |
+
padding=0)
|
| 122 |
+
|
| 123 |
+
def forward(self, x):
|
| 124 |
+
if self.with_conv:
|
| 125 |
+
pad = (0,1,0,1)
|
| 126 |
+
x = torch.nn.functional.pad(x, pad, mode="constant", value=0)
|
| 127 |
+
x = self.conv(x)
|
| 128 |
+
else:
|
| 129 |
+
x = torch.nn.functional.avg_pool2d(x, kernel_size=2, stride=2)
|
| 130 |
+
return x
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
class ResnetBlock(nn.Module):
|
| 134 |
+
def __init__(self, *, in_channels, out_channels=None, conv_shortcut=False,
|
| 135 |
+
dropout, temb_channels=512):
|
| 136 |
+
super().__init__()
|
| 137 |
+
self.in_channels = in_channels
|
| 138 |
+
out_channels = in_channels if out_channels is None else out_channels
|
| 139 |
+
self.out_channels = out_channels
|
| 140 |
+
self.use_conv_shortcut = conv_shortcut
|
| 141 |
+
|
| 142 |
+
self.norm1 = Normalize(in_channels)
|
| 143 |
+
self.conv1 = torch.nn.Conv2d(in_channels,
|
| 144 |
+
out_channels,
|
| 145 |
+
kernel_size=3,
|
| 146 |
+
stride=1,
|
| 147 |
+
padding=1)
|
| 148 |
+
if temb_channels > 0:
|
| 149 |
+
self.temb_proj = torch.nn.Linear(temb_channels,
|
| 150 |
+
out_channels)
|
| 151 |
+
self.norm2 = Normalize(out_channels)
|
| 152 |
+
self.dropout = torch.nn.Dropout(dropout)
|
| 153 |
+
self.conv2 = torch.nn.Conv2d(out_channels,
|
| 154 |
+
out_channels,
|
| 155 |
+
kernel_size=3,
|
| 156 |
+
stride=1,
|
| 157 |
+
padding=1)
|
| 158 |
+
if self.in_channels != self.out_channels:
|
| 159 |
+
if self.use_conv_shortcut:
|
| 160 |
+
self.conv_shortcut = torch.nn.Conv2d(in_channels,
|
| 161 |
+
out_channels,
|
| 162 |
+
kernel_size=3,
|
| 163 |
+
stride=1,
|
| 164 |
+
padding=1)
|
| 165 |
+
else:
|
| 166 |
+
self.nin_shortcut = torch.nn.Conv2d(in_channels,
|
| 167 |
+
out_channels,
|
| 168 |
+
kernel_size=1,
|
| 169 |
+
stride=1,
|
| 170 |
+
padding=0)
|
| 171 |
+
|
| 172 |
+
def forward(self, x, temb):
|
| 173 |
+
h = x
|
| 174 |
+
h = self.norm1(h)
|
| 175 |
+
h = nonlinearity(h)
|
| 176 |
+
h = self.conv1(h)
|
| 177 |
+
|
| 178 |
+
if temb is not None:
|
| 179 |
+
h = h + self.temb_proj(nonlinearity(temb))[:,:,None,None]
|
| 180 |
+
|
| 181 |
+
h = self.norm2(h)
|
| 182 |
+
h = nonlinearity(h)
|
| 183 |
+
h = self.dropout(h)
|
| 184 |
+
h = self.conv2(h)
|
| 185 |
+
|
| 186 |
+
if self.in_channels != self.out_channels:
|
| 187 |
+
if self.use_conv_shortcut:
|
| 188 |
+
x = self.conv_shortcut(x)
|
| 189 |
+
else:
|
| 190 |
+
x = self.nin_shortcut(x)
|
| 191 |
+
|
| 192 |
+
return x+h
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
class AttnBlock(nn.Module):
|
| 196 |
+
def __init__(self, in_channels):
|
| 197 |
+
super().__init__()
|
| 198 |
+
self.in_channels = in_channels
|
| 199 |
+
|
| 200 |
+
self.norm = Normalize(in_channels)
|
| 201 |
+
self.q = torch.nn.Conv2d(in_channels,
|
| 202 |
+
in_channels,
|
| 203 |
+
kernel_size=1,
|
| 204 |
+
stride=1,
|
| 205 |
+
padding=0)
|
| 206 |
+
self.k = torch.nn.Conv2d(in_channels,
|
| 207 |
+
in_channels,
|
| 208 |
+
kernel_size=1,
|
| 209 |
+
stride=1,
|
| 210 |
+
padding=0)
|
| 211 |
+
self.v = torch.nn.Conv2d(in_channels,
|
| 212 |
+
in_channels,
|
| 213 |
+
kernel_size=1,
|
| 214 |
+
stride=1,
|
| 215 |
+
padding=0)
|
| 216 |
+
self.proj_out = torch.nn.Conv2d(in_channels,
|
| 217 |
+
in_channels,
|
| 218 |
+
kernel_size=1,
|
| 219 |
+
stride=1,
|
| 220 |
+
padding=0)
|
| 221 |
+
|
| 222 |
+
def forward(self, x):
|
| 223 |
+
h_ = x
|
| 224 |
+
h_ = self.norm(h_)
|
| 225 |
+
q = self.q(h_)
|
| 226 |
+
k = self.k(h_)
|
| 227 |
+
v = self.v(h_)
|
| 228 |
+
|
| 229 |
+
# compute attention
|
| 230 |
+
b,c,h,w = q.shape
|
| 231 |
+
q = q.reshape(b,c,h*w)
|
| 232 |
+
q = q.permute(0,2,1) # b,hw,c
|
| 233 |
+
k = k.reshape(b,c,h*w) # b,c,hw
|
| 234 |
+
w_ = torch.bmm(q,k) # b,hw,hw w[b,i,j]=sum_c q[b,i,c]k[b,c,j]
|
| 235 |
+
w_ = w_ * (int(c)**(-0.5))
|
| 236 |
+
w_ = torch.nn.functional.softmax(w_, dim=2)
|
| 237 |
+
|
| 238 |
+
# attend to values
|
| 239 |
+
v = v.reshape(b,c,h*w)
|
| 240 |
+
w_ = w_.permute(0,2,1) # b,hw,hw (first hw of k, second of q)
|
| 241 |
+
h_ = torch.bmm(v,w_) # b, c,hw (hw of q) h_[b,c,j] = sum_i v[b,c,i] w_[b,i,j]
|
| 242 |
+
h_ = h_.reshape(b,c,h,w)
|
| 243 |
+
|
| 244 |
+
h_ = self.proj_out(h_)
|
| 245 |
+
|
| 246 |
+
return x+h_
|
| 247 |
+
|
| 248 |
+
class MemoryEfficientAttnBlock(nn.Module):
|
| 249 |
+
"""
|
| 250 |
+
Uses xformers efficient implementation,
|
| 251 |
+
see https://github.com/MatthieuTPHR/diffusers/blob/d80b531ff8060ec1ea982b65a1b8df70f73aa67c/src/diffusers/models/attention.py#L223
|
| 252 |
+
Note: this is a single-head self-attention operation
|
| 253 |
+
"""
|
| 254 |
+
#
|
| 255 |
+
def __init__(self, in_channels):
|
| 256 |
+
super().__init__()
|
| 257 |
+
self.in_channels = in_channels
|
| 258 |
+
|
| 259 |
+
self.norm = Normalize(in_channels)
|
| 260 |
+
self.q = torch.nn.Conv2d(in_channels,
|
| 261 |
+
in_channels,
|
| 262 |
+
kernel_size=1,
|
| 263 |
+
stride=1,
|
| 264 |
+
padding=0)
|
| 265 |
+
self.k = torch.nn.Conv2d(in_channels,
|
| 266 |
+
in_channels,
|
| 267 |
+
kernel_size=1,
|
| 268 |
+
stride=1,
|
| 269 |
+
padding=0)
|
| 270 |
+
self.v = torch.nn.Conv2d(in_channels,
|
| 271 |
+
in_channels,
|
| 272 |
+
kernel_size=1,
|
| 273 |
+
stride=1,
|
| 274 |
+
padding=0)
|
| 275 |
+
self.proj_out = torch.nn.Conv2d(in_channels,
|
| 276 |
+
in_channels,
|
| 277 |
+
kernel_size=1,
|
| 278 |
+
stride=1,
|
| 279 |
+
padding=0)
|
| 280 |
+
self.attention_op: Optional[Any] = None
|
| 281 |
+
|
| 282 |
+
def forward(self, x):
|
| 283 |
+
h_ = x
|
| 284 |
+
h_ = self.norm(h_)
|
| 285 |
+
q = self.q(h_)
|
| 286 |
+
k = self.k(h_)
|
| 287 |
+
v = self.v(h_)
|
| 288 |
+
|
| 289 |
+
# compute attention
|
| 290 |
+
B, C, H, W = q.shape
|
| 291 |
+
q, k, v = map(lambda x: rearrange(x, 'b c h w -> b (h w) c'), (q, k, v))
|
| 292 |
+
|
| 293 |
+
q, k, v = map(
|
| 294 |
+
lambda t: t.unsqueeze(3)
|
| 295 |
+
.reshape(B, t.shape[1], 1, C)
|
| 296 |
+
.permute(0, 2, 1, 3)
|
| 297 |
+
.reshape(B * 1, t.shape[1], C)
|
| 298 |
+
.contiguous(),
|
| 299 |
+
(q, k, v),
|
| 300 |
+
)
|
| 301 |
+
out = xformers.ops.memory_efficient_attention(q, k, v, attn_bias=None, op=self.attention_op)
|
| 302 |
+
|
| 303 |
+
out = (
|
| 304 |
+
out.unsqueeze(0)
|
| 305 |
+
.reshape(B, 1, out.shape[1], C)
|
| 306 |
+
.permute(0, 2, 1, 3)
|
| 307 |
+
.reshape(B, out.shape[1], C)
|
| 308 |
+
)
|
| 309 |
+
out = rearrange(out, 'b (h w) c -> b c h w', b=B, h=H, w=W, c=C)
|
| 310 |
+
out = self.proj_out(out)
|
| 311 |
+
return x+out
|
| 312 |
+
|
| 313 |
+
|
| 314 |
+
class MemoryEfficientCrossAttentionWrapper(MemoryEfficientCrossAttention):
|
| 315 |
+
def forward(self, x, context=None, mask=None):
|
| 316 |
+
b, c, h, w = x.shape
|
| 317 |
+
x = rearrange(x, 'b c h w -> b (h w) c')
|
| 318 |
+
out = super().forward(x, context=context, mask=mask)
|
| 319 |
+
out = rearrange(out, 'b (h w) c -> b c h w', h=h, w=w, c=c)
|
| 320 |
+
return x + out
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
def make_attn(in_channels, attn_type="vanilla", attn_kwargs=None):
|
| 324 |
+
assert attn_type in ["vanilla", "vanilla-xformers", "memory-efficient-cross-attn", "linear", "none"], f'attn_type {attn_type} unknown'
|
| 325 |
+
if XFORMERS_IS_AVAILBLE and attn_type == "vanilla":
|
| 326 |
+
attn_type = "vanilla-xformers"
|
| 327 |
+
print(f"making attention of type '{attn_type}' with {in_channels} in_channels")
|
| 328 |
+
if attn_type == "vanilla":
|
| 329 |
+
assert attn_kwargs is None
|
| 330 |
+
return AttnBlock(in_channels)
|
| 331 |
+
elif attn_type == "vanilla-xformers":
|
| 332 |
+
print(f"building MemoryEfficientAttnBlock with {in_channels} in_channels...")
|
| 333 |
+
return MemoryEfficientAttnBlock(in_channels)
|
| 334 |
+
elif type == "memory-efficient-cross-attn":
|
| 335 |
+
attn_kwargs["query_dim"] = in_channels
|
| 336 |
+
return MemoryEfficientCrossAttentionWrapper(**attn_kwargs)
|
| 337 |
+
elif attn_type == "none":
|
| 338 |
+
return nn.Identity(in_channels)
|
| 339 |
+
else:
|
| 340 |
+
raise NotImplementedError()
|
| 341 |
+
|
| 342 |
+
|
| 343 |
+
class Model(nn.Module):
|
| 344 |
+
def __init__(self, *, ch, out_ch, ch_mult=(1,2,4,8), num_res_blocks,
|
| 345 |
+
attn_resolutions, dropout=0.0, resamp_with_conv=True, in_channels,
|
| 346 |
+
resolution, use_timestep=True, use_linear_attn=False, attn_type="vanilla"):
|
| 347 |
+
super().__init__()
|
| 348 |
+
if use_linear_attn: attn_type = "linear"
|
| 349 |
+
self.ch = ch
|
| 350 |
+
self.temb_ch = self.ch*4
|
| 351 |
+
self.num_resolutions = len(ch_mult)
|
| 352 |
+
self.num_res_blocks = num_res_blocks
|
| 353 |
+
self.resolution = resolution
|
| 354 |
+
self.in_channels = in_channels
|
| 355 |
+
|
| 356 |
+
self.use_timestep = use_timestep
|
| 357 |
+
if self.use_timestep:
|
| 358 |
+
# timestep embedding
|
| 359 |
+
self.temb = nn.Module()
|
| 360 |
+
self.temb.dense = nn.ModuleList([
|
| 361 |
+
torch.nn.Linear(self.ch,
|
| 362 |
+
self.temb_ch),
|
| 363 |
+
torch.nn.Linear(self.temb_ch,
|
| 364 |
+
self.temb_ch),
|
| 365 |
+
])
|
| 366 |
+
|
| 367 |
+
# downsampling
|
| 368 |
+
self.conv_in = torch.nn.Conv2d(in_channels,
|
| 369 |
+
self.ch,
|
| 370 |
+
kernel_size=3,
|
| 371 |
+
stride=1,
|
| 372 |
+
padding=1)
|
| 373 |
+
|
| 374 |
+
curr_res = resolution
|
| 375 |
+
in_ch_mult = (1,)+tuple(ch_mult)
|
| 376 |
+
self.down = nn.ModuleList()
|
| 377 |
+
for i_level in range(self.num_resolutions):
|
| 378 |
+
block = nn.ModuleList()
|
| 379 |
+
attn = nn.ModuleList()
|
| 380 |
+
block_in = ch*in_ch_mult[i_level]
|
| 381 |
+
block_out = ch*ch_mult[i_level]
|
| 382 |
+
for i_block in range(self.num_res_blocks):
|
| 383 |
+
block.append(ResnetBlock(in_channels=block_in,
|
| 384 |
+
out_channels=block_out,
|
| 385 |
+
temb_channels=self.temb_ch,
|
| 386 |
+
dropout=dropout))
|
| 387 |
+
block_in = block_out
|
| 388 |
+
if curr_res in attn_resolutions:
|
| 389 |
+
attn.append(make_attn(block_in, attn_type=attn_type))
|
| 390 |
+
down = nn.Module()
|
| 391 |
+
down.block = block
|
| 392 |
+
down.attn = attn
|
| 393 |
+
if i_level != self.num_resolutions-1:
|
| 394 |
+
down.downsample = Downsample(block_in, resamp_with_conv)
|
| 395 |
+
curr_res = curr_res // 2
|
| 396 |
+
self.down.append(down)
|
| 397 |
+
|
| 398 |
+
# middle
|
| 399 |
+
self.mid = nn.Module()
|
| 400 |
+
self.mid.block_1 = ResnetBlock(in_channels=block_in,
|
| 401 |
+
out_channels=block_in,
|
| 402 |
+
temb_channels=self.temb_ch,
|
| 403 |
+
dropout=dropout)
|
| 404 |
+
self.mid.attn_1 = make_attn(block_in, attn_type=attn_type)
|
| 405 |
+
self.mid.block_2 = ResnetBlock(in_channels=block_in,
|
| 406 |
+
out_channels=block_in,
|
| 407 |
+
temb_channels=self.temb_ch,
|
| 408 |
+
dropout=dropout)
|
| 409 |
+
|
| 410 |
+
# upsampling
|
| 411 |
+
self.up = nn.ModuleList()
|
| 412 |
+
for i_level in reversed(range(self.num_resolutions)):
|
| 413 |
+
block = nn.ModuleList()
|
| 414 |
+
attn = nn.ModuleList()
|
| 415 |
+
block_out = ch*ch_mult[i_level]
|
| 416 |
+
skip_in = ch*ch_mult[i_level]
|
| 417 |
+
for i_block in range(self.num_res_blocks+1):
|
| 418 |
+
if i_block == self.num_res_blocks:
|
| 419 |
+
skip_in = ch*in_ch_mult[i_level]
|
| 420 |
+
block.append(ResnetBlock(in_channels=block_in+skip_in,
|
| 421 |
+
out_channels=block_out,
|
| 422 |
+
temb_channels=self.temb_ch,
|
| 423 |
+
dropout=dropout))
|
| 424 |
+
block_in = block_out
|
| 425 |
+
if curr_res in attn_resolutions:
|
| 426 |
+
attn.append(make_attn(block_in, attn_type=attn_type))
|
| 427 |
+
up = nn.Module()
|
| 428 |
+
up.block = block
|
| 429 |
+
up.attn = attn
|
| 430 |
+
if i_level != 0:
|
| 431 |
+
up.upsample = Upsample(block_in, resamp_with_conv)
|
| 432 |
+
curr_res = curr_res * 2
|
| 433 |
+
self.up.insert(0, up) # prepend to get consistent order
|
| 434 |
+
|
| 435 |
+
# end
|
| 436 |
+
self.norm_out = Normalize(block_in)
|
| 437 |
+
self.conv_out = torch.nn.Conv2d(block_in,
|
| 438 |
+
out_ch,
|
| 439 |
+
kernel_size=3,
|
| 440 |
+
stride=1,
|
| 441 |
+
padding=1)
|
| 442 |
+
|
| 443 |
+
def forward(self, x, t=None, context=None):
|
| 444 |
+
#assert x.shape[2] == x.shape[3] == self.resolution
|
| 445 |
+
if context is not None:
|
| 446 |
+
# assume aligned context, cat along channel axis
|
| 447 |
+
x = torch.cat((x, context), dim=1)
|
| 448 |
+
if self.use_timestep:
|
| 449 |
+
# timestep embedding
|
| 450 |
+
assert t is not None
|
| 451 |
+
temb = get_timestep_embedding(t, self.ch)
|
| 452 |
+
temb = self.temb.dense[0](temb)
|
| 453 |
+
temb = nonlinearity(temb)
|
| 454 |
+
temb = self.temb.dense[1](temb)
|
| 455 |
+
else:
|
| 456 |
+
temb = None
|
| 457 |
+
|
| 458 |
+
# downsampling
|
| 459 |
+
hs = [self.conv_in(x)]
|
| 460 |
+
for i_level in range(self.num_resolutions):
|
| 461 |
+
for i_block in range(self.num_res_blocks):
|
| 462 |
+
h = self.down[i_level].block[i_block](hs[-1], temb)
|
| 463 |
+
if len(self.down[i_level].attn) > 0:
|
| 464 |
+
h = self.down[i_level].attn[i_block](h)
|
| 465 |
+
hs.append(h)
|
| 466 |
+
if i_level != self.num_resolutions-1:
|
| 467 |
+
hs.append(self.down[i_level].downsample(hs[-1]))
|
| 468 |
+
|
| 469 |
+
# middle
|
| 470 |
+
h = hs[-1]
|
| 471 |
+
h = self.mid.block_1(h, temb)
|
| 472 |
+
h = self.mid.attn_1(h)
|
| 473 |
+
h = self.mid.block_2(h, temb)
|
| 474 |
+
|
| 475 |
+
# upsampling
|
| 476 |
+
for i_level in reversed(range(self.num_resolutions)):
|
| 477 |
+
for i_block in range(self.num_res_blocks+1):
|
| 478 |
+
h = self.up[i_level].block[i_block](
|
| 479 |
+
torch.cat([h, hs.pop()], dim=1), temb)
|
| 480 |
+
if len(self.up[i_level].attn) > 0:
|
| 481 |
+
h = self.up[i_level].attn[i_block](h)
|
| 482 |
+
if i_level != 0:
|
| 483 |
+
h = self.up[i_level].upsample(h)
|
| 484 |
+
|
| 485 |
+
# end
|
| 486 |
+
h = self.norm_out(h)
|
| 487 |
+
h = nonlinearity(h)
|
| 488 |
+
h = self.conv_out(h)
|
| 489 |
+
return h
|
| 490 |
+
|
| 491 |
+
def get_last_layer(self):
|
| 492 |
+
return self.conv_out.weight
|
| 493 |
+
|
| 494 |
+
|
| 495 |
+
class Encoder(nn.Module):
|
| 496 |
+
def __init__(self, *, ch, out_ch, ch_mult=(1,2,4,8), num_res_blocks,
|
| 497 |
+
attn_resolutions, dropout=0.0, resamp_with_conv=True, in_channels,
|
| 498 |
+
resolution, z_channels, double_z=True, use_linear_attn=False, attn_type="vanilla",
|
| 499 |
+
**ignore_kwargs):
|
| 500 |
+
super().__init__()
|
| 501 |
+
if use_linear_attn: attn_type = "linear"
|
| 502 |
+
self.ch = ch
|
| 503 |
+
self.temb_ch = 0
|
| 504 |
+
self.num_resolutions = len(ch_mult)
|
| 505 |
+
self.num_res_blocks = num_res_blocks
|
| 506 |
+
self.resolution = resolution
|
| 507 |
+
self.in_channels = in_channels
|
| 508 |
+
|
| 509 |
+
# downsampling
|
| 510 |
+
self.conv_in = torch.nn.Conv2d(in_channels,
|
| 511 |
+
self.ch,
|
| 512 |
+
kernel_size=3,
|
| 513 |
+
stride=1,
|
| 514 |
+
padding=1)
|
| 515 |
+
|
| 516 |
+
curr_res = resolution
|
| 517 |
+
in_ch_mult = (1,)+tuple(ch_mult)
|
| 518 |
+
self.in_ch_mult = in_ch_mult
|
| 519 |
+
self.down = nn.ModuleList()
|
| 520 |
+
for i_level in range(self.num_resolutions):
|
| 521 |
+
block = nn.ModuleList()
|
| 522 |
+
attn = nn.ModuleList()
|
| 523 |
+
block_in = ch*in_ch_mult[i_level]
|
| 524 |
+
block_out = ch*ch_mult[i_level]
|
| 525 |
+
for i_block in range(self.num_res_blocks):
|
| 526 |
+
block.append(ResnetBlock(in_channels=block_in,
|
| 527 |
+
out_channels=block_out,
|
| 528 |
+
temb_channels=self.temb_ch,
|
| 529 |
+
dropout=dropout))
|
| 530 |
+
block_in = block_out
|
| 531 |
+
if curr_res in attn_resolutions:
|
| 532 |
+
attn.append(make_attn(block_in, attn_type=attn_type))
|
| 533 |
+
down = nn.Module()
|
| 534 |
+
down.block = block
|
| 535 |
+
down.attn = attn
|
| 536 |
+
if i_level != self.num_resolutions-1:
|
| 537 |
+
down.downsample = Downsample(block_in, resamp_with_conv)
|
| 538 |
+
curr_res = curr_res // 2
|
| 539 |
+
self.down.append(down)
|
| 540 |
+
|
| 541 |
+
# middle
|
| 542 |
+
self.mid = nn.Module()
|
| 543 |
+
self.mid.block_1 = ResnetBlock(in_channels=block_in,
|
| 544 |
+
out_channels=block_in,
|
| 545 |
+
temb_channels=self.temb_ch,
|
| 546 |
+
dropout=dropout)
|
| 547 |
+
self.mid.attn_1 = make_attn(block_in, attn_type=attn_type)
|
| 548 |
+
self.mid.block_2 = ResnetBlock(in_channels=block_in,
|
| 549 |
+
out_channels=block_in,
|
| 550 |
+
temb_channels=self.temb_ch,
|
| 551 |
+
dropout=dropout)
|
| 552 |
+
|
| 553 |
+
# end
|
| 554 |
+
self.norm_out = Normalize(block_in)
|
| 555 |
+
self.conv_out = torch.nn.Conv2d(block_in,
|
| 556 |
+
2*z_channels if double_z else z_channels,
|
| 557 |
+
kernel_size=3,
|
| 558 |
+
stride=1,
|
| 559 |
+
padding=1)
|
| 560 |
+
|
| 561 |
+
def forward(self, x):
|
| 562 |
+
# timestep embedding
|
| 563 |
+
temb = None
|
| 564 |
+
|
| 565 |
+
# downsampling
|
| 566 |
+
hs = [self.conv_in(x)]
|
| 567 |
+
hs_ = [x]
|
| 568 |
+
for i_level in range(self.num_resolutions):
|
| 569 |
+
for i_block in range(self.num_res_blocks):
|
| 570 |
+
h = self.down[i_level].block[i_block](hs[-1], temb)
|
| 571 |
+
if len(self.down[i_level].attn) > 0:
|
| 572 |
+
h = self.down[i_level].attn[i_block](h)
|
| 573 |
+
hs.append(h)
|
| 574 |
+
if i_level != self.num_resolutions-1:
|
| 575 |
+
hs_.append(hs[-1])
|
| 576 |
+
hs.append(self.down[i_level].downsample(hs[-1]))
|
| 577 |
+
|
| 578 |
+
# middle
|
| 579 |
+
h = hs[-1]
|
| 580 |
+
h = self.mid.block_1(h, temb)
|
| 581 |
+
h = self.mid.attn_1(h)
|
| 582 |
+
h = self.mid.block_2(h, temb)
|
| 583 |
+
|
| 584 |
+
# end
|
| 585 |
+
h = self.norm_out(h)
|
| 586 |
+
h = nonlinearity(h)
|
| 587 |
+
h = self.conv_out(h)
|
| 588 |
+
return h, hs_
|
| 589 |
+
|
| 590 |
+
|
| 591 |
+
class Decoder(nn.Module):
|
| 592 |
+
def __init__(self, *, ch, out_ch, ch_mult=(1,2,4,8), num_res_blocks,
|
| 593 |
+
attn_resolutions, dropout=0.0, resamp_with_conv=True, in_channels,
|
| 594 |
+
resolution, z_channels, give_pre_end=False, tanh_out=False, use_linear_attn=False,
|
| 595 |
+
attn_type="vanilla", **ignorekwargs):
|
| 596 |
+
super().__init__()
|
| 597 |
+
if use_linear_attn: attn_type = "linear"
|
| 598 |
+
self.ch = ch
|
| 599 |
+
self.temb_ch = 0
|
| 600 |
+
self.num_resolutions = len(ch_mult)
|
| 601 |
+
self.num_res_blocks = num_res_blocks
|
| 602 |
+
self.resolution = resolution
|
| 603 |
+
self.in_channels = in_channels
|
| 604 |
+
self.give_pre_end = give_pre_end
|
| 605 |
+
self.tanh_out = tanh_out
|
| 606 |
+
|
| 607 |
+
# compute in_ch_mult, block_in and curr_res at lowest res
|
| 608 |
+
in_ch_mult = (1,)+tuple(ch_mult)
|
| 609 |
+
block_in = ch*ch_mult[self.num_resolutions-1]
|
| 610 |
+
curr_res = resolution // 2**(self.num_resolutions-1)
|
| 611 |
+
self.z_shape = (1,z_channels,curr_res,curr_res)
|
| 612 |
+
print("Working with z of shape {} = {} dimensions.".format(
|
| 613 |
+
self.z_shape, np.prod(self.z_shape)))
|
| 614 |
+
|
| 615 |
+
# z to block_in
|
| 616 |
+
self.conv_in = torch.nn.Conv2d(z_channels,
|
| 617 |
+
block_in,
|
| 618 |
+
kernel_size=3,
|
| 619 |
+
stride=1,
|
| 620 |
+
padding=1)
|
| 621 |
+
|
| 622 |
+
# middle
|
| 623 |
+
self.mid = nn.Module()
|
| 624 |
+
self.mid.block_1 = ResnetBlock(in_channels=block_in,
|
| 625 |
+
out_channels=block_in,
|
| 626 |
+
temb_channels=self.temb_ch,
|
| 627 |
+
dropout=dropout)
|
| 628 |
+
self.mid.attn_1 = make_attn(block_in, attn_type=attn_type)
|
| 629 |
+
self.mid.block_2 = ResnetBlock(in_channels=block_in,
|
| 630 |
+
out_channels=block_in,
|
| 631 |
+
temb_channels=self.temb_ch,
|
| 632 |
+
dropout=dropout)
|
| 633 |
+
|
| 634 |
+
# upsampling
|
| 635 |
+
self.up = nn.ModuleList()
|
| 636 |
+
for i_level in reversed(range(self.num_resolutions)):
|
| 637 |
+
block = nn.ModuleList()
|
| 638 |
+
attn = nn.ModuleList()
|
| 639 |
+
block_out = ch*ch_mult[i_level]
|
| 640 |
+
for i_block in range(self.num_res_blocks+1):
|
| 641 |
+
block.append(ResnetBlock(in_channels=block_in,
|
| 642 |
+
out_channels=block_out,
|
| 643 |
+
temb_channels=self.temb_ch,
|
| 644 |
+
dropout=dropout))
|
| 645 |
+
block_in = block_out
|
| 646 |
+
if curr_res in attn_resolutions:
|
| 647 |
+
attn.append(make_attn(block_in, attn_type=attn_type))
|
| 648 |
+
up = nn.Module()
|
| 649 |
+
up.block = block
|
| 650 |
+
up.attn = attn
|
| 651 |
+
if i_level != 0:
|
| 652 |
+
up.upsample = Upsample(block_in, resamp_with_conv, i_level)
|
| 653 |
+
curr_res = curr_res * 2
|
| 654 |
+
self.up.insert(0, up) # prepend to get consistent order
|
| 655 |
+
|
| 656 |
+
# end
|
| 657 |
+
self.norm_out = Normalize(block_in)
|
| 658 |
+
self.conv_out = torch.nn.Conv2d(block_in,
|
| 659 |
+
out_ch,
|
| 660 |
+
kernel_size=3,
|
| 661 |
+
stride=1,
|
| 662 |
+
padding=1)
|
| 663 |
+
|
| 664 |
+
self.new_last_procee = BigMerge(6,3)
|
| 665 |
+
|
| 666 |
+
def forward(self, z, hs):
|
| 667 |
+
#assert z.shape[1:] == self.z_shape[1:]
|
| 668 |
+
self.last_z_shape = z.shape
|
| 669 |
+
|
| 670 |
+
# timestep embedding
|
| 671 |
+
temb = None
|
| 672 |
+
|
| 673 |
+
# z to block_in
|
| 674 |
+
h = self.conv_in(z)
|
| 675 |
+
|
| 676 |
+
# middle
|
| 677 |
+
h = self.mid.block_1(h, temb)
|
| 678 |
+
h = self.mid.attn_1(h)
|
| 679 |
+
h = self.mid.block_2(h, temb)
|
| 680 |
+
|
| 681 |
+
# upsampling
|
| 682 |
+
for i_level in reversed(range(self.num_resolutions)):
|
| 683 |
+
for i_block in range(self.num_res_blocks+1):
|
| 684 |
+
h = self.up[i_level].block[i_block](h, temb)
|
| 685 |
+
if len(self.up[i_level].attn) > 0:
|
| 686 |
+
h = self.up[i_level].attn[i_block](h)
|
| 687 |
+
# print(h.shape)
|
| 688 |
+
if i_level != 0:
|
| 689 |
+
h = self.up[i_level].upsample(h, hs.pop())
|
| 690 |
+
|
| 691 |
+
# end
|
| 692 |
+
if self.give_pre_end:
|
| 693 |
+
return h
|
| 694 |
+
|
| 695 |
+
h = self.norm_out(h)
|
| 696 |
+
h = nonlinearity(h)
|
| 697 |
+
h = self.conv_out(h)
|
| 698 |
+
if self.tanh_out:
|
| 699 |
+
h = torch.tanh(h)
|
| 700 |
+
|
| 701 |
+
return self.new_last_procee(h, hs.pop())
|
| 702 |
+
|
| 703 |
+
|
| 704 |
+
class SimpleDecoder(nn.Module):
|
| 705 |
+
def __init__(self, in_channels, out_channels, *args, **kwargs):
|
| 706 |
+
super().__init__()
|
| 707 |
+
self.model = nn.ModuleList([nn.Conv2d(in_channels, in_channels, 1),
|
| 708 |
+
ResnetBlock(in_channels=in_channels,
|
| 709 |
+
out_channels=2 * in_channels,
|
| 710 |
+
temb_channels=0, dropout=0.0),
|
| 711 |
+
ResnetBlock(in_channels=2 * in_channels,
|
| 712 |
+
out_channels=4 * in_channels,
|
| 713 |
+
temb_channels=0, dropout=0.0),
|
| 714 |
+
ResnetBlock(in_channels=4 * in_channels,
|
| 715 |
+
out_channels=2 * in_channels,
|
| 716 |
+
temb_channels=0, dropout=0.0),
|
| 717 |
+
nn.Conv2d(2*in_channels, in_channels, 1),
|
| 718 |
+
Upsample(in_channels, with_conv=True)])
|
| 719 |
+
# end
|
| 720 |
+
self.norm_out = Normalize(in_channels)
|
| 721 |
+
self.conv_out = torch.nn.Conv2d(in_channels,
|
| 722 |
+
out_channels,
|
| 723 |
+
kernel_size=3,
|
| 724 |
+
stride=1,
|
| 725 |
+
padding=1)
|
| 726 |
+
|
| 727 |
+
def forward(self, x):
|
| 728 |
+
for i, layer in enumerate(self.model):
|
| 729 |
+
if i in [1,2,3]:
|
| 730 |
+
x = layer(x, None)
|
| 731 |
+
else:
|
| 732 |
+
x = layer(x)
|
| 733 |
+
|
| 734 |
+
h = self.norm_out(x)
|
| 735 |
+
h = nonlinearity(h)
|
| 736 |
+
x = self.conv_out(h)
|
| 737 |
+
return x
|
| 738 |
+
|
| 739 |
+
|
| 740 |
+
class UpsampleDecoder(nn.Module):
|
| 741 |
+
def __init__(self, in_channels, out_channels, ch, num_res_blocks, resolution,
|
| 742 |
+
ch_mult=(2,2), dropout=0.0):
|
| 743 |
+
super().__init__()
|
| 744 |
+
# upsampling
|
| 745 |
+
self.temb_ch = 0
|
| 746 |
+
self.num_resolutions = len(ch_mult)
|
| 747 |
+
self.num_res_blocks = num_res_blocks
|
| 748 |
+
block_in = in_channels
|
| 749 |
+
curr_res = resolution // 2 ** (self.num_resolutions - 1)
|
| 750 |
+
self.res_blocks = nn.ModuleList()
|
| 751 |
+
self.upsample_blocks = nn.ModuleList()
|
| 752 |
+
for i_level in range(self.num_resolutions):
|
| 753 |
+
res_block = []
|
| 754 |
+
block_out = ch * ch_mult[i_level]
|
| 755 |
+
for i_block in range(self.num_res_blocks + 1):
|
| 756 |
+
res_block.append(ResnetBlock(in_channels=block_in,
|
| 757 |
+
out_channels=block_out,
|
| 758 |
+
temb_channels=self.temb_ch,
|
| 759 |
+
dropout=dropout))
|
| 760 |
+
block_in = block_out
|
| 761 |
+
self.res_blocks.append(nn.ModuleList(res_block))
|
| 762 |
+
if i_level != self.num_resolutions - 1:
|
| 763 |
+
self.upsample_blocks.append(Upsample(block_in, True))
|
| 764 |
+
curr_res = curr_res * 2
|
| 765 |
+
|
| 766 |
+
# end
|
| 767 |
+
self.norm_out = Normalize(block_in)
|
| 768 |
+
self.conv_out = torch.nn.Conv2d(block_in,
|
| 769 |
+
out_channels,
|
| 770 |
+
kernel_size=3,
|
| 771 |
+
stride=1,
|
| 772 |
+
padding=1)
|
| 773 |
+
|
| 774 |
+
def forward(self, x):
|
| 775 |
+
# upsampling
|
| 776 |
+
h = x
|
| 777 |
+
for k, i_level in enumerate(range(self.num_resolutions)):
|
| 778 |
+
for i_block in range(self.num_res_blocks + 1):
|
| 779 |
+
h = self.res_blocks[i_level][i_block](h, None)
|
| 780 |
+
if i_level != self.num_resolutions - 1:
|
| 781 |
+
h = self.upsample_blocks[k](h)
|
| 782 |
+
h = self.norm_out(h)
|
| 783 |
+
h = nonlinearity(h)
|
| 784 |
+
h = self.conv_out(h)
|
| 785 |
+
return h
|
| 786 |
+
|
| 787 |
+
|
| 788 |
+
class LatentRescaler(nn.Module):
|
| 789 |
+
def __init__(self, factor, in_channels, mid_channels, out_channels, depth=2):
|
| 790 |
+
super().__init__()
|
| 791 |
+
# residual block, interpolate, residual block
|
| 792 |
+
self.factor = factor
|
| 793 |
+
self.conv_in = nn.Conv2d(in_channels,
|
| 794 |
+
mid_channels,
|
| 795 |
+
kernel_size=3,
|
| 796 |
+
stride=1,
|
| 797 |
+
padding=1)
|
| 798 |
+
self.res_block1 = nn.ModuleList([ResnetBlock(in_channels=mid_channels,
|
| 799 |
+
out_channels=mid_channels,
|
| 800 |
+
temb_channels=0,
|
| 801 |
+
dropout=0.0) for _ in range(depth)])
|
| 802 |
+
self.attn = AttnBlock(mid_channels)
|
| 803 |
+
self.res_block2 = nn.ModuleList([ResnetBlock(in_channels=mid_channels,
|
| 804 |
+
out_channels=mid_channels,
|
| 805 |
+
temb_channels=0,
|
| 806 |
+
dropout=0.0) for _ in range(depth)])
|
| 807 |
+
|
| 808 |
+
self.conv_out = nn.Conv2d(mid_channels,
|
| 809 |
+
out_channels,
|
| 810 |
+
kernel_size=1,
|
| 811 |
+
)
|
| 812 |
+
|
| 813 |
+
def forward(self, x):
|
| 814 |
+
x = self.conv_in(x)
|
| 815 |
+
for block in self.res_block1:
|
| 816 |
+
x = block(x, None)
|
| 817 |
+
x = torch.nn.functional.interpolate(x, size=(int(round(x.shape[2]*self.factor)), int(round(x.shape[3]*self.factor))))
|
| 818 |
+
x = self.attn(x)
|
| 819 |
+
for block in self.res_block2:
|
| 820 |
+
x = block(x, None)
|
| 821 |
+
x = self.conv_out(x)
|
| 822 |
+
return x
|
| 823 |
+
|
| 824 |
+
|
| 825 |
+
class MergedRescaleEncoder(nn.Module):
|
| 826 |
+
def __init__(self, in_channels, ch, resolution, out_ch, num_res_blocks,
|
| 827 |
+
attn_resolutions, dropout=0.0, resamp_with_conv=True,
|
| 828 |
+
ch_mult=(1,2,4,8), rescale_factor=1.0, rescale_module_depth=1):
|
| 829 |
+
super().__init__()
|
| 830 |
+
intermediate_chn = ch * ch_mult[-1]
|
| 831 |
+
self.encoder = Encoder(in_channels=in_channels, num_res_blocks=num_res_blocks, ch=ch, ch_mult=ch_mult,
|
| 832 |
+
z_channels=intermediate_chn, double_z=False, resolution=resolution,
|
| 833 |
+
attn_resolutions=attn_resolutions, dropout=dropout, resamp_with_conv=resamp_with_conv,
|
| 834 |
+
out_ch=None)
|
| 835 |
+
self.rescaler = LatentRescaler(factor=rescale_factor, in_channels=intermediate_chn,
|
| 836 |
+
mid_channels=intermediate_chn, out_channels=out_ch, depth=rescale_module_depth)
|
| 837 |
+
|
| 838 |
+
def forward(self, x):
|
| 839 |
+
x = self.encoder(x)
|
| 840 |
+
x = self.rescaler(x)
|
| 841 |
+
return x
|
| 842 |
+
|
| 843 |
+
|
| 844 |
+
class MergedRescaleDecoder(nn.Module):
|
| 845 |
+
def __init__(self, z_channels, out_ch, resolution, num_res_blocks, attn_resolutions, ch, ch_mult=(1,2,4,8),
|
| 846 |
+
dropout=0.0, resamp_with_conv=True, rescale_factor=1.0, rescale_module_depth=1):
|
| 847 |
+
super().__init__()
|
| 848 |
+
tmp_chn = z_channels*ch_mult[-1]
|
| 849 |
+
self.decoder = Decoder(out_ch=out_ch, z_channels=tmp_chn, attn_resolutions=attn_resolutions, dropout=dropout,
|
| 850 |
+
resamp_with_conv=resamp_with_conv, in_channels=None, num_res_blocks=num_res_blocks,
|
| 851 |
+
ch_mult=ch_mult, resolution=resolution, ch=ch)
|
| 852 |
+
self.rescaler = LatentRescaler(factor=rescale_factor, in_channels=z_channels, mid_channels=tmp_chn,
|
| 853 |
+
out_channels=tmp_chn, depth=rescale_module_depth)
|
| 854 |
+
|
| 855 |
+
def forward(self, x):
|
| 856 |
+
x = self.rescaler(x)
|
| 857 |
+
x = self.decoder(x)
|
| 858 |
+
return x
|
| 859 |
+
|
| 860 |
+
|
| 861 |
+
class Upsampler(nn.Module):
|
| 862 |
+
def __init__(self, in_size, out_size, in_channels, out_channels, ch_mult=2):
|
| 863 |
+
super().__init__()
|
| 864 |
+
assert out_size >= in_size
|
| 865 |
+
num_blocks = int(np.log2(out_size//in_size))+1
|
| 866 |
+
factor_up = 1.+ (out_size % in_size)
|
| 867 |
+
print(f"Building {self.__class__.__name__} with in_size: {in_size} --> out_size {out_size} and factor {factor_up}")
|
| 868 |
+
self.rescaler = LatentRescaler(factor=factor_up, in_channels=in_channels, mid_channels=2*in_channels,
|
| 869 |
+
out_channels=in_channels)
|
| 870 |
+
self.decoder = Decoder(out_ch=out_channels, resolution=out_size, z_channels=in_channels, num_res_blocks=2,
|
| 871 |
+
attn_resolutions=[], in_channels=None, ch=in_channels,
|
| 872 |
+
ch_mult=[ch_mult for _ in range(num_blocks)])
|
| 873 |
+
|
| 874 |
+
def forward(self, x):
|
| 875 |
+
x = self.rescaler(x)
|
| 876 |
+
x = self.decoder(x)
|
| 877 |
+
return x
|
| 878 |
+
|
| 879 |
+
|
| 880 |
+
class Resize(nn.Module):
|
| 881 |
+
def __init__(self, in_channels=None, learned=False, mode="bilinear"):
|
| 882 |
+
super().__init__()
|
| 883 |
+
self.with_conv = learned
|
| 884 |
+
self.mode = mode
|
| 885 |
+
if self.with_conv:
|
| 886 |
+
print(f"Note: {self.__class__.__name} uses learned downsampling and will ignore the fixed {mode} mode")
|
| 887 |
+
raise NotImplementedError()
|
| 888 |
+
assert in_channels is not None
|
| 889 |
+
# no asymmetric padding in torch conv, must do it ourselves
|
| 890 |
+
self.conv = torch.nn.Conv2d(in_channels,
|
| 891 |
+
in_channels,
|
| 892 |
+
kernel_size=4,
|
| 893 |
+
stride=2,
|
| 894 |
+
padding=1)
|
| 895 |
+
|
| 896 |
+
def forward(self, x, scale_factor=1.0):
|
| 897 |
+
if scale_factor==1.0:
|
| 898 |
+
return x
|
| 899 |
+
else:
|
| 900 |
+
x = torch.nn.functional.interpolate(x, mode=self.mode, align_corners=False, scale_factor=scale_factor)
|
| 901 |
+
return x
|
modi_vae/networks.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any, Dict, Iterable, Optional, Union
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
import torch.nn as nn
|
| 5 |
+
import torch.nn.functional as F
|
| 6 |
+
|
| 7 |
+
class EMAModel(nn.Module):
|
| 8 |
+
def __init__(self, model, decay=0.9999, use_num_updates=True):
|
| 9 |
+
super().__init__()
|
| 10 |
+
if decay < 0.0 or decay > 1.0:
|
| 11 |
+
raise ValueError('Decay must be between 0 and 1')
|
| 12 |
+
|
| 13 |
+
self.m_name2s_name = {}
|
| 14 |
+
self.decay = decay
|
| 15 |
+
# self.num_updates = 0 if use_num_updates else -1
|
| 16 |
+
self.register_buffer('num_updates', torch.zeros(1, dtype=torch.int64))
|
| 17 |
+
if not use_num_updates:
|
| 18 |
+
self.num_updates -= 1
|
| 19 |
+
|
| 20 |
+
for name, p in model.named_parameters():
|
| 21 |
+
if p.requires_grad:
|
| 22 |
+
# remove as '.'-character is not allowed in buffers
|
| 23 |
+
s_name = name.replace('.', '')
|
| 24 |
+
self.m_name2s_name.update({name: s_name})
|
| 25 |
+
self.register_buffer(s_name, p.clone().detach().data)
|
| 26 |
+
# remove as '.'-character is not allowed in buffers
|
| 27 |
+
self.collected_params = []
|
| 28 |
+
|
| 29 |
+
def forward(self, model):
|
| 30 |
+
decay = self.decay
|
| 31 |
+
|
| 32 |
+
if self.num_updates.item() >= 0:
|
| 33 |
+
self.num_updates += 1
|
| 34 |
+
decay = min(self.decay, (1 + self.num_updates.item()) / (10 + self.num_updates.item()))
|
| 35 |
+
|
| 36 |
+
one_minus_decay = 1.0 - decay
|
| 37 |
+
shadow_params = dict(self.named_buffers())
|
| 38 |
+
|
| 39 |
+
with torch.no_grad():
|
| 40 |
+
m_param = dict(model.named_parameters())
|
| 41 |
+
|
| 42 |
+
for key in m_param:
|
| 43 |
+
if m_param[key].requires_grad:
|
| 44 |
+
sname = self.m_name2s_name[key]
|
| 45 |
+
shadow_params[sname] = shadow_params[sname].type_as(m_param[key])
|
| 46 |
+
shadow_params[sname].sub_(one_minus_decay * (shadow_params[sname] - m_param[key]))
|
| 47 |
+
else:
|
| 48 |
+
assert not key in self.m_name2s_name
|
| 49 |
+
|
| 50 |
+
def copy_to(self, model):
|
| 51 |
+
shadow_params = dict(self.named_buffers())
|
| 52 |
+
m_param = dict(model.named_parameters())
|
| 53 |
+
for key in m_param:
|
| 54 |
+
if m_param[key].requires_grad:
|
| 55 |
+
m_param[key].data.copy_(shadow_params[self.m_name2s_name[key]].data)
|
| 56 |
+
else:
|
| 57 |
+
assert not key in self.m_name2s_name
|
| 58 |
+
|
| 59 |
+
def store(self, model):
|
| 60 |
+
"""
|
| 61 |
+
Save the current parameters for restoring later.
|
| 62 |
+
Args:
|
| 63 |
+
model: A model that parameters will be stored
|
| 64 |
+
"""
|
| 65 |
+
parameters = model.parameters()
|
| 66 |
+
self.collected_params = [param.clone() for param in parameters]
|
| 67 |
+
|
| 68 |
+
def restore(self, model):
|
| 69 |
+
"""
|
| 70 |
+
Restore the parameters stored with the `store` method.
|
| 71 |
+
Useful to validate the model with EMA parameters without affecting the
|
| 72 |
+
original optimization process. Store the parameters before the
|
| 73 |
+
`copy_to` method. After validation (or model saving), use this to
|
| 74 |
+
restore the former parameters.
|
| 75 |
+
Args:
|
| 76 |
+
model: A model that to restore its parameters.
|
| 77 |
+
"""
|
| 78 |
+
parameters = model.parameters()
|
| 79 |
+
for c_param, param in zip(self.collected_params, parameters):
|
| 80 |
+
param.data.copy_(c_param.data)
|