MKFMIKU commited on
Commit
6eb1be9
β€’
1 Parent(s): ec336f6

Upload 10 files

Browse files
Files changed (10) hide show
  1. README.md +1 -1
  2. app.py +82 -0
  3. diffusion.py +140 -0
  4. diffusion_arch.py +939 -0
  5. examples/00015.jpg +0 -0
  6. examples/00065.jpg +0 -0
  7. ffhq_10m.pt +3 -0
  8. header.html +18 -0
  9. net_g_250000.pth +3 -0
  10. requirements.txt +5 -0
README.md CHANGED
@@ -1,6 +1,6 @@
1
  ---
2
  title: Bi Noising.Diffusion
3
- emoji: πŸ“‰
4
  colorFrom: purple
5
  colorTo: red
6
  sdk: gradio
1
  ---
2
  title: Bi Noising.Diffusion
3
+ emoji: πŸ’Š
4
  colorFrom: purple
5
  colorTo: red
6
  sdk: gradio
app.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+ import torch
4
+ from diffusion import DiffusionPipeline
5
+
6
+ auth_token = os.environ.get("API_TOKEN") or True
7
+
8
+ device = "cuda" if torch.cuda.is_available() else "cpu"
9
+
10
+ pipe = DiffusionPipeline(device)
11
+
12
+ def predict(input, diffusion_step, binoising_step, grid_size):
13
+ for output in pipe(input, diffusion_step, binoising_step, grid_size):
14
+ yield output[0], output[1]
15
+
16
+ def read_content(file_path: str) -> str:
17
+ """read the content of target file
18
+ """
19
+ with open(file_path, 'r', encoding='utf-8') as f:
20
+ content = f.read()
21
+
22
+ return content
23
+
24
+
25
+ css = '''
26
+ .container {max-width: 1150px;margin: auto;padding-top: 1.5rem}
27
+ #image_upload{min-height:256px}
28
+ #image_upload [data-testid="image"], #image_upload [data-testid="image"] > div{min-height: 256px}
29
+ #mask_radio .gr-form{background:transparent; border: none}
30
+ #word_mask{margin-top: .75em !important}
31
+ #word_mask textarea:disabled{opacity: 0.3}
32
+ .footer {margin-bottom: 45px;margin-top: 35px;text-align: center;border-bottom: 1px solid #e5e5e5}
33
+ .footer>p {font-size: .8rem; display: inline-block; padding: 0 10px;transform: translateY(10px);background: white}
34
+ .dark .footer {border-color: #303030}
35
+ .dark .footer>p {background: #0b0f19}
36
+ .acknowledgments h4{margin: 1.25em 0 .25em 0;font-weight: bold;font-size: 115%}
37
+ #image_upload .touch-none{display: flex}
38
+ @keyframes spin {
39
+ from {
40
+ transform: rotate(0deg);
41
+ }
42
+ to {
43
+ transform: rotate(360deg);
44
+ }
45
+ }
46
+ '''
47
+
48
+ image_blocks = gr.Blocks(css=css)
49
+ with image_blocks as demo:
50
+ gr.HTML(read_content("header.html"))
51
+ with gr.Group():
52
+ with gr.Box():
53
+ with gr.Row():
54
+ with gr.Column():
55
+ image = gr.Image(source='upload', elem_id="image_upload", type="pil", image_mode="L", label="Gray Image").style(height=256)
56
+
57
+ diffusion_step = gr.Slider(minimum=10, maximum=200, step=5, value=50, label="Diffusion Time Step")
58
+ binoising_step = gr.Slider(minimum=1, maximum=50, step=1, value=50, label="Bi-Noising Start Step")
59
+ grid_size = gr.Slider(minimum=1, maximum=16, step=1, value=2, label="Grid Size")
60
+
61
+ with gr.Row(elem_id="prompt-container").style(mobile_collapse=False, equal_height=True):
62
+ btn = gr.Button("Colorization").style(
63
+ margin=False,
64
+ full_width=True,
65
+ )
66
+ with gr.Column():
67
+ diffusion_result = gr.Image(elem_id="output-simg", label="Diffusion Result").style(height=256)
68
+ bidiffusion_result = gr.Image(elem_id="output-bimg", label="Bi-Noising Diffsuion Result").style(height=256)
69
+
70
+ # with gr.Column():
71
+
72
+
73
+ with gr.Row():
74
+ gr.Examples(examples=[
75
+ 'examples/00015.jpg',
76
+ 'examples/00065.jpg'
77
+ ], inputs=[image])
78
+
79
+ btn.click(fn=predict, inputs=[image, diffusion_step, binoising_step, grid_size], outputs=[diffusion_result, bidiffusion_result])
80
+
81
+ image_blocks.queue()
82
+ image_blocks.launch(enable_queue=True, share=False, debug=False)
diffusion.py ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import PIL
3
+ from PIL import Image
4
+ import torch
5
+
6
+ from diffusion_arch import ILVRUNetModel, ConditionalUNetModel
7
+ from guided_diffusion.script_util import create_gaussian_diffusion
8
+
9
+ import torch.nn.functional as F
10
+ import torchvision.transforms.functional as TF
11
+ from torchvision.utils import make_grid
12
+
13
+ def preprocess_image(image):
14
+ w, h = image.size
15
+ w, h = map(lambda x: x - x % 32, (w, h)) # resize to integer multiple of 32
16
+ image = image.resize((w, h), resample=PIL.Image.LANCZOS)
17
+ image = np.array(image).astype(np.float32) / 255.0
18
+ image = torch.from_numpy(image.transpose(2,0,1)).unsqueeze(0)
19
+ return 2.0 * image - 1.0
20
+
21
+ def preprocess_mask(mask):
22
+ mask = mask.convert("L")
23
+ w, h = mask.size
24
+ w, h = map(lambda x: x - x % 32, (w, h)) # resize to integer multiple of 32
25
+ mask = mask.resize((w, h), resample=PIL.Image.NEAREST)
26
+ mask = np.array(mask).astype(np.float32) / 255.0
27
+ mask = torch.from_numpy(np.repeat(mask[None, ...], 3, axis=0)).unsqueeze(0)
28
+ mask[mask > 0] = 1
29
+ return mask
30
+
31
+
32
+ class DiffusionPipeline():
33
+ def __init__(self, device):
34
+ super().__init__()
35
+ self.device = device
36
+ diffusion_model = ILVRUNetModel(
37
+ in_channels=3,
38
+ model_channels=128,
39
+ out_channels=6,
40
+ num_res_blocks=1,
41
+ attention_resolutions=[16],
42
+ channel_mult=(1, 1, 2, 2, 4, 4),
43
+ num_classes=None,
44
+ use_checkpoint=False,
45
+ use_fp16=False,
46
+ num_heads=4,
47
+ num_head_channels=64,
48
+ num_heads_upsample=-1,
49
+ use_scale_shift_norm=True,
50
+ resblock_updown=True,
51
+ use_new_attention_order=False
52
+ )
53
+ diffusion_model = diffusion_model.to(device)
54
+ diffusion_model = diffusion_model.eval()
55
+ ilvr_pretraining = torch.load('./ffhq_10m.pt', map_location='cpu')
56
+ diffusion_model.load_state_dict(ilvr_pretraining)
57
+ self.diffusion_model = diffusion_model
58
+
59
+ diffusion_restoration_model = ConditionalUNetModel(
60
+ in_channels=3,
61
+ model_channels=128,
62
+ out_channels=6,
63
+ num_res_blocks=1,
64
+ attention_resolutions=[16],
65
+ dropout=0.0,
66
+ channel_mult=(1, 1, 2, 2, 4, 4),
67
+ num_classes=None,
68
+ use_checkpoint=False,
69
+ use_fp16=False,
70
+ num_heads=4,
71
+ num_head_channels=64,
72
+ num_heads_upsample=-1,
73
+ use_scale_shift_norm=True,
74
+ resblock_updown=True,
75
+ use_new_attention_order=False
76
+ )
77
+ diffusion_restoration_model = diffusion_restoration_model.to(device)
78
+ diffusion_restoration_model = diffusion_restoration_model.eval()
79
+ state_dict = torch.load('./net_g_250000.pth', map_location='cpu')
80
+ diffusion_restoration_model.load_state_dict(state_dict['params'])
81
+ self.diffusion_restoration_model = diffusion_restoration_model
82
+
83
+ @torch.no_grad()
84
+ def __call__(self, lq, diffusion_step, binoising_step, grid_size):
85
+ lq = lq.convert("RGB").resize((256, 256), resample=Image.LANCZOS)
86
+
87
+ eval_gaussian_diffusion = create_gaussian_diffusion(
88
+ steps=1000,
89
+ learn_sigma=True,
90
+ noise_schedule='linear',
91
+ use_kl=False,
92
+ timestep_respacing=str(int(diffusion_step)),
93
+ predict_xstart=False,
94
+ rescale_timesteps=False,
95
+ rescale_learned_sigmas=False,
96
+ )
97
+
98
+ ow, oh = lq.size
99
+
100
+ # preprocess image
101
+ lq_img_th = preprocess_image(lq).to(self.device)
102
+
103
+ lq_img_th = lq_img_th.repeat([grid_size, 1, 1, 1])
104
+
105
+ img = torch.randn_like(lq_img_th, device=self.device)
106
+ s_img = torch.randn_like(lq_img_th, device=self.device)
107
+
108
+ indices = list(range(eval_gaussian_diffusion.num_timesteps))[::-1]
109
+ for i in indices:
110
+ t = torch.tensor([i] * lq_img_th.size(0), device=self.device)
111
+
112
+ out = eval_gaussian_diffusion.p_mean_variance(self.diffusion_restoration_model, s_img, t, model_kwargs={'lq': lq_img_th})
113
+ nonzero_mask = (
114
+ (t != 0).float().view(-1, *([1] * (len(img.shape) - 1)))
115
+ ) # no noise when t == 0
116
+ s_img = out["mean"] + nonzero_mask * torch.exp(0.5 * out["log_variance"]) * torch.randn_like(img, device=self.device)
117
+ s_img_pred = out["pred_xstart"]
118
+
119
+
120
+ if i < binoising_step:
121
+ model_output = eval_gaussian_diffusion._wrap_model(self.diffusion_restoration_model)(img, t, lq=lq_img_th)
122
+
123
+ B, C = img.shape[:2]
124
+ model_output, model_var_values = torch.split(model_output, C, dim=1)
125
+
126
+ pred_xstart = eval_gaussian_diffusion._predict_xstart_from_eps(img, t, model_output).clamp(-1, 1)
127
+ img = eval_gaussian_diffusion.q_sample(pred_xstart, t)
128
+
129
+ out = eval_gaussian_diffusion.p_mean_variance(self.diffusion_model, img, t)
130
+
131
+ nonzero_mask = (
132
+ (t != 0).float().view(-1, *([1] * (len(img.shape) - 1)))
133
+ ) # no noise when t == 0
134
+ img = out["mean"] + nonzero_mask * torch.exp(0.5 * out["log_variance"]) * torch.randn_like(img, device=self.device)
135
+ img_pred = out["pred_xstart"]
136
+
137
+ if i % 2 == 0:
138
+ yield [Image.fromarray(np.uint8((make_grid(s_img_pred) / 2 + 0.5).clamp(0, 1).cpu().numpy().transpose(1,2,0) * 255.)), Image.fromarray(np.uint8((make_grid(img_pred) / 2 + 0.5).clamp(0, 1).cpu().numpy().transpose(1,2,0) * 255.))]
139
+
140
+ yield [Image.fromarray(np.uint8((make_grid(s_img) / 2 + 0.5).clamp(0, 1).cpu().numpy().transpose(1,2,0) * 255.)), Image.fromarray(np.uint8((make_grid(img) / 2 + 0.5).clamp(0, 1).cpu().numpy().transpose(1,2,0) * 255.))]
diffusion_arch.py ADDED
@@ -0,0 +1,939 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from abc import abstractmethod
2
+
3
+ import math
4
+ import numpy as np
5
+ import torch
6
+ import torch.nn as nn
7
+ import torch.nn.functional as F
8
+
9
+ import torchvision
10
+ import torchvision.transforms.functional as TF
11
+
12
+ import numpy as np
13
+
14
+ from guided_diffusion.fp16_util import convert_module_to_f16, convert_module_to_f32
15
+ from guided_diffusion.nn import (
16
+ checkpoint,
17
+ conv_nd,
18
+ linear,
19
+ avg_pool_nd,
20
+ zero_module,
21
+ normalization,
22
+ timestep_embedding,
23
+ )
24
+
25
+ class AttentionPool2d(nn.Module):
26
+ """
27
+ Adapted from CLIP: https://github.com/openai/CLIP/blob/main/clip/model.py
28
+ """
29
+
30
+ def __init__(
31
+ self,
32
+ spacial_dim: int,
33
+ embed_dim: int,
34
+ num_heads_channels: int,
35
+ output_dim: int = None,
36
+ ):
37
+ super().__init__()
38
+ self.positional_embedding = nn.Parameter(
39
+ torch.randn(embed_dim, spacial_dim ** 2 + 1) / embed_dim ** 0.5
40
+ )
41
+ self.qkv_proj = conv_nd(1, embed_dim, 3 * embed_dim, 1)
42
+ self.c_proj = conv_nd(1, embed_dim, output_dim or embed_dim, 1)
43
+ self.num_heads = embed_dim // num_heads_channels
44
+ self.attention = QKVAttention(self.num_heads)
45
+
46
+ def forward(self, x):
47
+ b, c, *_spatial = x.shape
48
+ x = x.reshape(b, c, -1) # NC(HW)
49
+ x = torch.cat([x.mean(dim=-1, keepdim=True), x], dim=-1) # NC(HW+1)
50
+ x = x + self.positional_embedding[None, :, :].to(x.dtype) # NC(HW+1)
51
+ x = self.qkv_proj(x)
52
+ x = self.attention(x)
53
+ x = self.c_proj(x)
54
+ return x[:, :, 0]
55
+
56
+
57
+ class TimestepBlock(nn.Module):
58
+ """
59
+ Any module where forward() takes timestep embeddings as a second argument.
60
+ """
61
+
62
+ @abstractmethod
63
+ def forward(self, x, emb):
64
+ """
65
+ Apply the module to `x` given `emb` timestep embeddings.
66
+ """
67
+
68
+
69
+ class TimestepEmbedSequential(nn.Sequential, TimestepBlock):
70
+ """
71
+ A sequential module that passes timestep embeddings to the children that
72
+ support it as an extra input.
73
+ """
74
+
75
+ def forward(self, x, emb):
76
+ for layer in self:
77
+ if isinstance(layer, TimestepBlock):
78
+ x = layer(x, emb)
79
+ else:
80
+ x = layer(x)
81
+ return x
82
+
83
+ class Upsample(nn.Module):
84
+ """
85
+ An upsampling layer with an optional convolution.
86
+
87
+ :param channels: channels in the inputs and outputs.
88
+ :param use_conv: a bool determining if a convolution is applied.
89
+ :param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then
90
+ upsampling occurs in the inner-two dimensions.
91
+ """
92
+
93
+ def __init__(self, channels, use_conv, dims=2, out_channels=None):
94
+ super().__init__()
95
+ self.channels = channels
96
+ self.out_channels = out_channels or channels
97
+ self.use_conv = use_conv
98
+ self.dims = dims
99
+ if use_conv:
100
+ self.conv = conv_nd(dims, self.channels, self.out_channels, 3, padding=1)
101
+
102
+ def forward(self, x):
103
+ assert x.shape[1] == self.channels
104
+ if self.dims == 3:
105
+ x = F.interpolate(
106
+ x, (x.shape[2], x.shape[3] * 2, x.shape[4] * 2), mode="nearest"
107
+ )
108
+ else:
109
+ x = F.interpolate(x, scale_factor=2, mode="nearest")
110
+ if self.use_conv:
111
+ x = self.conv(x)
112
+ return x
113
+
114
+
115
+ class Downsample(nn.Module):
116
+ """
117
+ A downsampling layer with an optional convolution.
118
+
119
+ :param channels: channels in the inputs and outputs.
120
+ :param use_conv: a bool determining if a convolution is applied.
121
+ :param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then
122
+ downsampling occurs in the inner-two dimensions.
123
+ """
124
+
125
+ def __init__(self, channels, use_conv, dims=2, out_channels=None):
126
+ super().__init__()
127
+ self.channels = channels
128
+ self.out_channels = out_channels or channels
129
+ self.use_conv = use_conv
130
+ self.dims = dims
131
+ stride = 2 if dims != 3 else (1, 2, 2)
132
+ if use_conv:
133
+ self.op = conv_nd(
134
+ dims, self.channels, self.out_channels, 3, stride=stride, padding=1
135
+ )
136
+ else:
137
+ assert self.channels == self.out_channels
138
+ self.op = avg_pool_nd(dims, kernel_size=stride, stride=stride)
139
+
140
+ def forward(self, x):
141
+ assert x.shape[1] == self.channels
142
+ return self.op(x)
143
+
144
+
145
+ class ResBlock(TimestepBlock):
146
+ """
147
+ A residual block that can optionally change the number of channels.
148
+
149
+ :param channels: the number of input channels.
150
+ :param emb_channels: the number of timestep embedding channels.
151
+ :param dropout: the rate of dropout.
152
+ :param out_channels: if specified, the number of out channels.
153
+ :param use_conv: if True and out_channels is specified, use a spatial
154
+ convolution instead of a smaller 1x1 convolution to change the
155
+ channels in the skip connection.
156
+ :param dims: determines if the signal is 1D, 2D, or 3D.
157
+ :param use_checkpoint: if True, use gradient checkpointing on this module.
158
+ :param up: if True, use this block for upsampling.
159
+ :param down: if True, use this block for downsampling.
160
+ """
161
+
162
+ def __init__(
163
+ self,
164
+ channels,
165
+ emb_channels,
166
+ dropout,
167
+ out_channels=None,
168
+ use_conv=False,
169
+ use_scale_shift_norm=False,
170
+ dims=2,
171
+ use_checkpoint=False,
172
+ up=False,
173
+ down=False,
174
+ ):
175
+ super().__init__()
176
+ self.channels = channels
177
+ self.emb_channels = emb_channels
178
+ self.dropout = dropout
179
+ self.out_channels = out_channels or channels
180
+ self.use_conv = use_conv
181
+ self.use_checkpoint = use_checkpoint
182
+ self.use_scale_shift_norm = use_scale_shift_norm
183
+
184
+ self.in_layers = nn.Sequential(
185
+ normalization(channels),
186
+ nn.SiLU(),
187
+ conv_nd(dims, channels, self.out_channels, 3, padding=1),
188
+ )
189
+
190
+ self.updown = up or down
191
+
192
+ if up:
193
+ self.h_upd = Upsample(channels, False, dims)
194
+ self.x_upd = Upsample(channels, False, dims)
195
+ elif down:
196
+ self.h_upd = Downsample(channels, False, dims)
197
+ self.x_upd = Downsample(channels, False, dims)
198
+ else:
199
+ self.h_upd = self.x_upd = nn.Identity()
200
+
201
+ self.emb_layers = nn.Sequential(
202
+ nn.SiLU(),
203
+ linear(
204
+ emb_channels,
205
+ 2 * self.out_channels if use_scale_shift_norm else self.out_channels,
206
+ ),
207
+ )
208
+ self.out_layers = nn.Sequential(
209
+ normalization(self.out_channels),
210
+ nn.SiLU(),
211
+ nn.Dropout(p=dropout),
212
+ zero_module(
213
+ conv_nd(dims, self.out_channels, self.out_channels, 3, padding=1)
214
+ ),
215
+ )
216
+
217
+ if self.out_channels == channels:
218
+ self.skip_connection = nn.Identity()
219
+ elif use_conv:
220
+ self.skip_connection = conv_nd(
221
+ dims, channels, self.out_channels, 3, padding=1
222
+ )
223
+ else:
224
+ self.skip_connection = conv_nd(dims, channels, self.out_channels, 1)
225
+
226
+ def forward(self, x, emb):
227
+ """
228
+ Apply the block to a Tensor, conditioned on a timestep embedding.
229
+
230
+ :param x: an [N x C x ...] Tensor of features.
231
+ :param emb: an [N x emb_channels] Tensor of timestep embeddings.
232
+ :return: an [N x C x ...] Tensor of outputs.
233
+ """
234
+ return checkpoint(
235
+ self._forward, (x, emb), self.parameters(), self.use_checkpoint
236
+ )
237
+
238
+ def _forward(self, x, emb):
239
+ if self.updown:
240
+ in_rest, in_conv = self.in_layers[:-1], self.in_layers[-1]
241
+ h = in_rest(x)
242
+ h = self.h_upd(h)
243
+ x = self.x_upd(x)
244
+ h = in_conv(h)
245
+ else:
246
+ h = self.in_layers(x)
247
+ emb_out = self.emb_layers(emb).type(h.dtype)
248
+ while len(emb_out.shape) < len(h.shape):
249
+ emb_out = emb_out[..., None]
250
+ if self.use_scale_shift_norm:
251
+ out_norm, out_rest = self.out_layers[0], self.out_layers[1:]
252
+ scale, shift = torch.chunk(emb_out, 2, dim=1)
253
+ h = out_norm(h) * (1 + scale) + shift
254
+ h = out_rest(h)
255
+ else:
256
+ h = h + emb_out
257
+ h = self.out_layers(h)
258
+ return self.skip_connection(x) + h
259
+
260
+
261
+ class AttentionBlock(nn.Module):
262
+ """
263
+ An attention block that allows spatial positions to attend to each other.
264
+
265
+ Originally ported from here, but adapted to the N-d case.
266
+ https://github.com/hojonathanho/diffusion/blob/1e0dceb3b3495bbe19116a5e1b3596cd0706c543/diffusion_tf/models/unet.py#L66.
267
+ """
268
+
269
+ def __init__(
270
+ self,
271
+ channels,
272
+ num_heads=1,
273
+ num_head_channels=-1,
274
+ use_checkpoint=False,
275
+ use_new_attention_order=False,
276
+ ):
277
+ super().__init__()
278
+ self.channels = channels
279
+ if num_head_channels == -1:
280
+ self.num_heads = num_heads
281
+ else:
282
+ assert (
283
+ channels % num_head_channels == 0
284
+ ), f"q,k,v channels {channels} is not divisible by num_head_channels {num_head_channels}"
285
+ self.num_heads = channels // num_head_channels
286
+ self.use_checkpoint = use_checkpoint
287
+ self.norm = normalization(channels)
288
+ self.qkv = conv_nd(1, channels, channels * 3, 1)
289
+ if use_new_attention_order:
290
+ # split qkv before split heads
291
+ self.attention = QKVAttention(self.num_heads)
292
+ else:
293
+ # split heads before split qkv
294
+ self.attention = QKVAttentionLegacy(self.num_heads)
295
+
296
+ self.proj_out = zero_module(conv_nd(1, channels, channels, 1))
297
+
298
+ def forward(self, x):
299
+ return checkpoint(self._forward, (x,), self.parameters(), True)
300
+
301
+ def _forward(self, x):
302
+ b, c, *spatial = x.shape
303
+ x = x.reshape(b, c, -1)
304
+ qkv = self.qkv(self.norm(x))
305
+ h = self.attention(qkv)
306
+ h = self.proj_out(h)
307
+ return (x + h).reshape(b, c, *spatial)
308
+
309
+
310
+ def count_flops_attn(model, _x, y):
311
+ """
312
+ A counter for the `thop` package to count the operations in an
313
+ attention operation.
314
+ Meant to be used like:
315
+ macs, params = thop.profile(
316
+ model,
317
+ inputs=(inputs, timestamps),
318
+ custom_ops={QKVAttention: QKVAttention.count_flops},
319
+ )
320
+ """
321
+ b, c, *spatial = y[0].shape
322
+ num_spatial = int(np.prod(spatial))
323
+ # We perform two matmuls with the same number of ops.
324
+ # The first computes the weight matrix, the second computes
325
+ # the combination of the value vectors.
326
+ matmul_ops = 2 * b * (num_spatial ** 2) * c
327
+ model.total_ops += torch.DoubleTensor([matmul_ops])
328
+
329
+
330
+ class QKVAttentionLegacy(nn.Module):
331
+ """
332
+ A module which performs QKV attention. Matches legacy QKVAttention + input/ouput heads shaping
333
+ """
334
+
335
+ def __init__(self, n_heads):
336
+ super().__init__()
337
+ self.n_heads = n_heads
338
+
339
+ def forward(self, qkv):
340
+ """
341
+ Apply QKV attention.
342
+
343
+ :param qkv: an [N x (H * 3 * C) x T] tensor of Qs, Ks, and Vs.
344
+ :return: an [N x (H * C) x T] tensor after attention.
345
+ """
346
+ bs, width, length = qkv.shape
347
+ assert width % (3 * self.n_heads) == 0
348
+ ch = width // (3 * self.n_heads)
349
+ q, k, v = qkv.reshape(bs * self.n_heads, ch * 3, length).split(ch, dim=1)
350
+ scale = 1 / math.sqrt(math.sqrt(ch))
351
+ weight = torch.einsum(
352
+ "bct,bcs->bts", q * scale, k * scale
353
+ ) # More stable with f16 than dividing afterwards
354
+ weight = torch.softmax(weight.float(), dim=-1).type(weight.dtype)
355
+ a = torch.einsum("bts,bcs->bct", weight, v)
356
+ return a.reshape(bs, -1, length)
357
+
358
+ @staticmethod
359
+ def count_flops(model, _x, y):
360
+ return count_flops_attn(model, _x, y)
361
+
362
+
363
+ class QKVAttention(nn.Module):
364
+ """
365
+ A module which performs QKV attention and splits in a different order.
366
+ """
367
+
368
+ def __init__(self, n_heads):
369
+ super().__init__()
370
+ self.n_heads = n_heads
371
+
372
+ def forward(self, qkv):
373
+ """
374
+ Apply QKV attention.
375
+
376
+ :param qkv: an [N x (3 * H * C) x T] tensor of Qs, Ks, and Vs.
377
+ :return: an [N x (H * C) x T] tensor after attention.
378
+ """
379
+ bs, width, length = qkv.shape
380
+ assert width % (3 * self.n_heads) == 0
381
+ ch = width // (3 * self.n_heads)
382
+ q, k, v = qkv.chunk(3, dim=1)
383
+ scale = 1 / math.sqrt(math.sqrt(ch))
384
+ weight = torch.einsum(
385
+ "bct,bcs->bts",
386
+ (q * scale).view(bs * self.n_heads, ch, length),
387
+ (k * scale).view(bs * self.n_heads, ch, length),
388
+ ) # More stable with f16 than dividing afterwards
389
+ weight = torch.softmax(weight.float(), dim=-1).type(weight.dtype)
390
+ a = torch.einsum("bts,bcs->bct", weight, v.reshape(bs * self.n_heads, ch, length))
391
+ return a.reshape(bs, -1, length)
392
+
393
+ @staticmethod
394
+ def count_flops(model, _x, y):
395
+ return count_flops_attn(model, _x, y)
396
+
397
+ class UNetModel(nn.Module):
398
+ """
399
+ The full UNet model with attention and timestep embedding.
400
+
401
+ :param in_channels: channels in the input Tensor.
402
+ :param model_channels: base channel count for the model.
403
+ :param out_channels: channels in the output Tensor.
404
+ :param num_res_blocks: number of residual blocks per downsample.
405
+ :param attention_resolutions: a collection of downsample rates at which
406
+ attention will take place. May be a set, list, or tuple.
407
+ For example, if this contains 4, then at 4x downsampling, attention
408
+ will be used.
409
+ :param dropout: the dropout probability.
410
+ :param channel_mult: channel multiplier for each level of the UNet.
411
+ :param conv_resample: if True, use learned convolutions for upsampling and
412
+ downsampling.
413
+ :param dims: determines if the signal is 1D, 2D, or 3D.
414
+ :param num_classes: if specified (as an int), then this model will be
415
+ class-conditional with `num_classes` classes.
416
+ :param use_checkpoint: use gradient checkpointing to reduce memory usage.
417
+ :param num_heads: the number of attention heads in each attention layer.
418
+ :param num_heads_channels: if specified, ignore num_heads and instead use
419
+ a fixed channel width per attention head.
420
+ :param num_heads_upsample: works with num_heads to set a different number
421
+ of heads for upsampling. Deprecated.
422
+ :param use_scale_shift_norm: use a FiLM-like conditioning mechanism.
423
+ :param resblock_updown: use residual blocks for up/downsampling.
424
+ :param use_new_attention_order: use a different attention pattern for potentially
425
+ increased efficiency.
426
+ """
427
+
428
+ def __init__(
429
+ self,
430
+ in_channels,
431
+ out_channels,
432
+ model_channels,
433
+ num_res_blocks,
434
+ attention_resolutions,
435
+ dropout=0,
436
+ channel_mult=(1, 2, 4, 8),
437
+ conv_resample=True,
438
+ dims=2,
439
+ num_classes=None,
440
+ use_checkpoint=False,
441
+ use_fp16=False,
442
+ num_heads=1,
443
+ num_head_channels=-1,
444
+ num_heads_upsample=-1,
445
+ use_scale_shift_norm=False,
446
+ resblock_updown=False,
447
+ use_new_attention_order=False,
448
+ ):
449
+ super().__init__()
450
+
451
+ if num_heads_upsample == -1:
452
+ num_heads_upsample = num_heads
453
+
454
+ self.in_channels = in_channels
455
+ self.model_channels = model_channels
456
+ self.out_channels = out_channels
457
+ self.num_res_blocks = num_res_blocks
458
+ self.attention_resolutions = attention_resolutions
459
+ self.dropout = dropout
460
+ self.channel_mult = channel_mult
461
+ self.conv_resample = conv_resample
462
+ self.num_classes = num_classes
463
+ self.use_checkpoint = use_checkpoint
464
+ self.dtype = torch.float16 if use_fp16 else torch.float32
465
+ self.num_heads = num_heads
466
+ self.num_head_channels = num_head_channels
467
+ self.num_heads_upsample = num_heads_upsample
468
+
469
+ time_embed_dim = model_channels * 4
470
+ self.dt_embed = nn.Sequential(
471
+ linear(model_channels, time_embed_dim),
472
+ nn.SiLU(),
473
+ linear(time_embed_dim, time_embed_dim),
474
+ )
475
+
476
+ if self.num_classes is not None:
477
+ self.label_emb = nn.Embedding(num_classes, time_embed_dim)
478
+
479
+ ch = input_ch = int(channel_mult[0] * model_channels)
480
+ self.input_blocks = nn.ModuleList(
481
+ [TimestepEmbedSequential(conv_nd(dims, in_channels, ch, 3, padding=1))]
482
+ )
483
+ self._feature_size = ch
484
+ input_block_chans = [ch]
485
+ ds = 1
486
+ for level, mult in enumerate(channel_mult):
487
+ for _ in range(num_res_blocks):
488
+ layers = [
489
+ ResBlock(
490
+ ch,
491
+ time_embed_dim,
492
+ dropout,
493
+ out_channels=int(mult * model_channels),
494
+ dims=dims,
495
+ use_checkpoint=use_checkpoint,
496
+ use_scale_shift_norm=use_scale_shift_norm,
497
+ )
498
+ ]
499
+ ch = int(mult * model_channels)
500
+ if ds in attention_resolutions:
501
+ layers.append(
502
+ AttentionBlock(
503
+ ch,
504
+ use_checkpoint=use_checkpoint,
505
+ num_heads=num_heads,
506
+ num_head_channels=num_head_channels,
507
+ use_new_attention_order=use_new_attention_order,
508
+ )
509
+ )
510
+ self.input_blocks.append(TimestepEmbedSequential(*layers))
511
+ self._feature_size += ch
512
+ input_block_chans.append(ch)
513
+ if level != len(channel_mult) - 1:
514
+ out_ch = ch
515
+ self.input_blocks.append(
516
+ TimestepEmbedSequential(
517
+ ResBlock(
518
+ ch,
519
+ time_embed_dim,
520
+ dropout,
521
+ out_channels=out_ch,
522
+ dims=dims,
523
+ use_checkpoint=use_checkpoint,
524
+ use_scale_shift_norm=use_scale_shift_norm,
525
+ down=True,
526
+ )
527
+ if resblock_updown
528
+ else Downsample(
529
+ ch, conv_resample, dims=dims, out_channels=out_ch
530
+ )
531
+ )
532
+ )
533
+ ch = out_ch
534
+ input_block_chans.append(ch)
535
+ ds *= 2
536
+ self._feature_size += ch
537
+
538
+ self.middle_block = TimestepEmbedSequential(
539
+ ResBlock(
540
+ ch,
541
+ time_embed_dim,
542
+ dropout,
543
+ dims=dims,
544
+ use_checkpoint=use_checkpoint,
545
+ use_scale_shift_norm=use_scale_shift_norm,
546
+ ),
547
+ AttentionBlock(
548
+ ch,
549
+ use_checkpoint=use_checkpoint,
550
+ num_heads=num_heads,
551
+ num_head_channels=num_head_channels,
552
+ use_new_attention_order=use_new_attention_order,
553
+ ),
554
+ ResBlock(
555
+ ch,
556
+ time_embed_dim,
557
+ dropout,
558
+ dims=dims,
559
+ use_checkpoint=use_checkpoint,
560
+ use_scale_shift_norm=use_scale_shift_norm,
561
+ ),
562
+ )
563
+ self._feature_size += ch
564
+
565
+ self.output_blocks = nn.ModuleList([])
566
+ for level, mult in list(enumerate(channel_mult))[::-1]:
567
+ for i in range(num_res_blocks + 1):
568
+ ich = input_block_chans.pop()
569
+ layers = [
570
+ ResBlock(
571
+ ch + ich,
572
+ time_embed_dim,
573
+ dropout,
574
+ out_channels=int(model_channels * mult),
575
+ dims=dims,
576
+ use_checkpoint=use_checkpoint,
577
+ use_scale_shift_norm=use_scale_shift_norm,
578
+ )
579
+ ]
580
+ ch = int(model_channels * mult)
581
+ if ds in attention_resolutions:
582
+ layers.append(
583
+ AttentionBlock(
584
+ ch,
585
+ use_checkpoint=use_checkpoint,
586
+ num_heads=num_heads_upsample,
587
+ num_head_channels=num_head_channels,
588
+ use_new_attention_order=use_new_attention_order,
589
+ )
590
+ )
591
+ if level and i == num_res_blocks:
592
+ out_ch = ch
593
+ layers.append(
594
+ ResBlock(
595
+ ch,
596
+ time_embed_dim,
597
+ dropout,
598
+ out_channels=out_ch,
599
+ dims=dims,
600
+ use_checkpoint=use_checkpoint,
601
+ use_scale_shift_norm=use_scale_shift_norm,
602
+ up=True,
603
+ )
604
+ if resblock_updown
605
+ else Upsample(ch, conv_resample, dims=dims, out_channels=out_ch)
606
+ )
607
+ ds //= 2
608
+ self.output_blocks.append(TimestepEmbedSequential(*layers))
609
+ self._feature_size += ch
610
+
611
+ self.out = nn.Sequential(
612
+ normalization(ch),
613
+ nn.SiLU(),
614
+ zero_module(conv_nd(dims, input_ch, out_channels, 3, padding=1)),
615
+ )
616
+
617
+ def convert_to_fp16(self):
618
+ """
619
+ Convert the torso of the model to float16.
620
+ """
621
+ self.input_blocks.apply(convert_module_to_f16)
622
+ self.middle_block.apply(convert_module_to_f16)
623
+ self.output_blocks.apply(convert_module_to_f16)
624
+
625
+ def convert_to_fp32(self):
626
+ """
627
+ Convert the torso of the model to float32.
628
+ """
629
+ self.input_blocks.apply(convert_module_to_f32)
630
+ self.middle_block.apply(convert_module_to_f32)
631
+ self.output_blocks.apply(convert_module_to_f32)
632
+
633
+ def forward(self, x, dt, y=None):
634
+ """
635
+ Apply the model to an input batch.
636
+
637
+ :param x: an [N x C x ...] Tensor of inputs.
638
+ :param timesteps: a 1-D batch of timesteps.
639
+ :param y: an [N] Tensor of labels, if class-conditional.
640
+ :return: an [N x C x ...] Tensor of outputs.
641
+ """
642
+ assert (y is not None) == (
643
+ self.num_classes is not None
644
+ ), "must specify y if and only if the model is class-conditional"
645
+
646
+ hs = []
647
+ emb = self.dt_embed(timestep_embedding(dt, self.model_channels))
648
+
649
+ if self.num_classes is not None:
650
+ assert y.shape == (x.shape[0],)
651
+ emb = emb + self.label_emb(y)
652
+
653
+ h = x.type(self.dtype)
654
+ for module in self.input_blocks:
655
+ h = module(h, emb)
656
+ hs.append(h)
657
+ h = self.middle_block(h, emb)
658
+ for module in self.output_blocks:
659
+ h = torch.cat([h, hs.pop()], dim=1)
660
+ h = module(h, emb)
661
+ h = h.type(x.dtype)
662
+ return self.out(h)
663
+
664
+
665
+ class ConditionalUNetModel(UNetModel):
666
+ def __init__(self, in_channels, *args, **kwargs):
667
+ super().__init__(in_channels * 2, *args, **kwargs)
668
+
669
+ def forward(self, x, timesteps, lq=None, **kwargs):
670
+ x = torch.cat([x, lq], dim=1)
671
+ return super().forward(x, timesteps, **kwargs)
672
+
673
+
674
+ class ILVRUNetModel(nn.Module):
675
+ """
676
+ The full UNet model with attention and timestep embedding.
677
+
678
+ :param in_channels: channels in the input Tensor.
679
+ :param model_channels: base channel count for the model.
680
+ :param out_channels: channels in the output Tensor.
681
+ :param num_res_blocks: number of residual blocks per downsample.
682
+ :param attention_resolutions: a collection of downsample rates at which
683
+ attention will take place. May be a set, list, or tuple.
684
+ For example, if this contains 4, then at 4x downsampling, attention
685
+ will be used.
686
+ :param dropout: the dropout probability.
687
+ :param channel_mult: channel multiplier for each level of the UNet.
688
+ :param conv_resample: if True, use learned convolutions for upsampling and
689
+ downsampling.
690
+ :param dims: determines if the signal is 1D, 2D, or 3D.
691
+ :param num_classes: if specified (as an int), then this model will be
692
+ class-conditional with `num_classes` classes.
693
+ :param use_checkpoint: use gradient checkpointing to reduce memory usage.
694
+ :param num_heads: the number of attention heads in each attention layer.
695
+ :param num_heads_channels: if specified, ignore num_heads and instead use
696
+ a fixed channel width per attention head.
697
+ :param num_heads_upsample: works with num_heads to set a different number
698
+ of heads for upsampling. Deprecated.
699
+ :param use_scale_shift_norm: use a FiLM-like conditioning mechanism.
700
+ :param resblock_updown: use residual blocks for up/downsampling.
701
+ :param use_new_attention_order: use a different attention pattern for potentially
702
+ increased efficiency.
703
+ """
704
+
705
+ def __init__(
706
+ self,
707
+ in_channels,
708
+ out_channels,
709
+ model_channels,
710
+ num_res_blocks,
711
+ attention_resolutions,
712
+ dropout=0,
713
+ channel_mult=(1, 2, 4, 8),
714
+ conv_resample=True,
715
+ dims=2,
716
+ num_classes=None,
717
+ use_checkpoint=False,
718
+ use_fp16=False,
719
+ num_heads=1,
720
+ num_head_channels=-1,
721
+ num_heads_upsample=-1,
722
+ use_scale_shift_norm=False,
723
+ resblock_updown=False,
724
+ use_new_attention_order=False,
725
+ ):
726
+ super().__init__()
727
+
728
+ if num_heads_upsample == -1:
729
+ num_heads_upsample = num_heads
730
+
731
+ self.in_channels = in_channels
732
+ self.model_channels = model_channels
733
+ self.out_channels = out_channels
734
+ self.num_res_blocks = num_res_blocks
735
+ self.attention_resolutions = attention_resolutions
736
+ self.dropout = dropout
737
+ self.channel_mult = channel_mult
738
+ self.conv_resample = conv_resample
739
+ self.num_classes = num_classes
740
+ self.use_checkpoint = use_checkpoint
741
+ self.dtype = torch.float16 if use_fp16 else torch.float32
742
+ self.num_heads = num_heads
743
+ self.num_head_channels = num_head_channels
744
+ self.num_heads_upsample = num_heads_upsample
745
+
746
+ time_embed_dim = model_channels * 4
747
+ self.time_embed = nn.Sequential(
748
+ linear(model_channels, time_embed_dim),
749
+ nn.SiLU(),
750
+ linear(time_embed_dim, time_embed_dim),
751
+ )
752
+
753
+ if self.num_classes is not None:
754
+ self.label_emb = nn.Embedding(num_classes, time_embed_dim)
755
+
756
+ ch = input_ch = int(channel_mult[0] * model_channels)
757
+ self.input_blocks = nn.ModuleList(
758
+ [TimestepEmbedSequential(conv_nd(dims, in_channels, ch, 3, padding=1))]
759
+ )
760
+ self._feature_size = ch
761
+ input_block_chans = [ch]
762
+ ds = 1
763
+ for level, mult in enumerate(channel_mult):
764
+ for _ in range(num_res_blocks):
765
+ layers = [
766
+ ResBlock(
767
+ ch,
768
+ time_embed_dim,
769
+ dropout,
770
+ out_channels=int(mult * model_channels),
771
+ dims=dims,
772
+ use_checkpoint=use_checkpoint,
773
+ use_scale_shift_norm=use_scale_shift_norm,
774
+ )
775
+ ]
776
+ ch = int(mult * model_channels)
777
+ if ds in attention_resolutions:
778
+ layers.append(
779
+ AttentionBlock(
780
+ ch,
781
+ use_checkpoint=use_checkpoint,
782
+ num_heads=num_heads,
783
+ num_head_channels=num_head_channels,
784
+ use_new_attention_order=use_new_attention_order,
785
+ )
786
+ )
787
+ self.input_blocks.append(TimestepEmbedSequential(*layers))
788
+ self._feature_size += ch
789
+ input_block_chans.append(ch)
790
+ if level != len(channel_mult) - 1:
791
+ out_ch = ch
792
+ self.input_blocks.append(
793
+ TimestepEmbedSequential(
794
+ ResBlock(
795
+ ch,
796
+ time_embed_dim,
797
+ dropout,
798
+ out_channels=out_ch,
799
+ dims=dims,
800
+ use_checkpoint=use_checkpoint,
801
+ use_scale_shift_norm=use_scale_shift_norm,
802
+ down=True,
803
+ )
804
+ if resblock_updown
805
+ else Downsample(
806
+ ch, conv_resample, dims=dims, out_channels=out_ch
807
+ )
808
+ )
809
+ )
810
+ ch = out_ch
811
+ input_block_chans.append(ch)
812
+ ds *= 2
813
+ self._feature_size += ch
814
+
815
+ self.middle_block = TimestepEmbedSequential(
816
+ ResBlock(
817
+ ch,
818
+ time_embed_dim,
819
+ dropout,
820
+ dims=dims,
821
+ use_checkpoint=use_checkpoint,
822
+ use_scale_shift_norm=use_scale_shift_norm,
823
+ ),
824
+ AttentionBlock(
825
+ ch,
826
+ use_checkpoint=use_checkpoint,
827
+ num_heads=num_heads,
828
+ num_head_channels=num_head_channels,
829
+ use_new_attention_order=use_new_attention_order,
830
+ ),
831
+ ResBlock(
832
+ ch,
833
+ time_embed_dim,
834
+ dropout,
835
+ dims=dims,
836
+ use_checkpoint=use_checkpoint,
837
+ use_scale_shift_norm=use_scale_shift_norm,
838
+ ),
839
+ )
840
+ self._feature_size += ch
841
+
842
+ self.output_blocks = nn.ModuleList([])
843
+ for level, mult in list(enumerate(channel_mult))[::-1]:
844
+ for i in range(num_res_blocks + 1):
845
+ ich = input_block_chans.pop()
846
+ layers = [
847
+ ResBlock(
848
+ ch + ich,
849
+ time_embed_dim,
850
+ dropout,
851
+ out_channels=int(model_channels * mult),
852
+ dims=dims,
853
+ use_checkpoint=use_checkpoint,
854
+ use_scale_shift_norm=use_scale_shift_norm,
855
+ )
856
+ ]
857
+ ch = int(model_channels * mult)
858
+ if ds in attention_resolutions:
859
+ layers.append(
860
+ AttentionBlock(
861
+ ch,
862
+ use_checkpoint=use_checkpoint,
863
+ num_heads=num_heads_upsample,
864
+ num_head_channels=num_head_channels,
865
+ use_new_attention_order=use_new_attention_order,
866
+ )
867
+ )
868
+ if level and i == num_res_blocks:
869
+ out_ch = ch
870
+ layers.append(
871
+ ResBlock(
872
+ ch,
873
+ time_embed_dim,
874
+ dropout,
875
+ out_channels=out_ch,
876
+ dims=dims,
877
+ use_checkpoint=use_checkpoint,
878
+ use_scale_shift_norm=use_scale_shift_norm,
879
+ up=True,
880
+ )
881
+ if resblock_updown
882
+ else Upsample(ch, conv_resample, dims=dims, out_channels=out_ch)
883
+ )
884
+ ds //= 2
885
+ self.output_blocks.append(TimestepEmbedSequential(*layers))
886
+ self._feature_size += ch
887
+
888
+ self.out = nn.Sequential(
889
+ normalization(ch),
890
+ nn.SiLU(),
891
+ zero_module(conv_nd(dims, input_ch, out_channels, 3, padding=1)),
892
+ )
893
+
894
+ def convert_to_fp16(self):
895
+ """
896
+ Convert the torso of the model to float16.
897
+ """
898
+ self.input_blocks.apply(convert_module_to_f16)
899
+ self.middle_block.apply(convert_module_to_f16)
900
+ self.output_blocks.apply(convert_module_to_f16)
901
+
902
+ def convert_to_fp32(self):
903
+ """
904
+ Convert the torso of the model to float32.
905
+ """
906
+ self.input_blocks.apply(convert_module_to_f32)
907
+ self.middle_block.apply(convert_module_to_f32)
908
+ self.output_blocks.apply(convert_module_to_f32)
909
+
910
+ def forward(self, x, dt, y=None):
911
+ """
912
+ Apply the model to an input batch.
913
+
914
+ :param x: an [N x C x ...] Tensor of inputs.
915
+ :param timesteps: a 1-D batch of timesteps.
916
+ :param y: an [N] Tensor of labels, if class-conditional.
917
+ :return: an [N x C x ...] Tensor of outputs.
918
+ """
919
+ assert (y is not None) == (
920
+ self.num_classes is not None
921
+ ), "must specify y if and only if the model is class-conditional"
922
+
923
+ hs = []
924
+ emb = self.time_embed(timestep_embedding(dt, self.model_channels))
925
+
926
+ if self.num_classes is not None:
927
+ assert y.shape == (x.shape[0],)
928
+ emb = emb + self.label_emb(y)
929
+
930
+ h = x.type(self.dtype)
931
+ for module in self.input_blocks:
932
+ h = module(h, emb)
933
+ hs.append(h)
934
+ h = self.middle_block(h, emb)
935
+ for module in self.output_blocks:
936
+ h = torch.cat([h, hs.pop()], dim=1)
937
+ h = module(h, emb)
938
+ h = h.type(x.dtype)
939
+ return self.out(h)
examples/00015.jpg ADDED
examples/00065.jpg ADDED
ffhq_10m.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:81d535743156ec6be34d8668e6920da94f0614074d7793a16c8fa9e306237faa
3
+ size 374417833
header.html ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <div style="text-align: center; max-width: 650px; margin: 0 auto;">
2
+ <div style="
3
+ display: inline-flex;
4
+ gap: 0.8rem;
5
+ font-size: 1.75rem;
6
+ justify-content: center;
7
+ margin-bottom: 10px;
8
+ ">
9
+ <h1 style="font-weight: 900; align-items: center; margin-bottom: 7px; margin-top: 20px;">
10
+ πŸ’Š Bi-Noising for Image-to-Image (I2I) Diffusion
11
+ </h1>
12
+ </div>
13
+ <div>
14
+ <p style="align-items: center; margin-bottom: 7px;">
15
+ <a href="https://arxiv.org/abs/2212.07352">https://arxiv.org/abs/2212.07352</a>. A new plug-and-play prior for diffusion guidance, which can fix biased noise during sampling. <br> It is shown to be effective on all existing diffusion restoration models including, ILVR, SR3, Guided-Diffusion, etc.
16
+ </p>
17
+ </div>
18
+ </div>
net_g_250000.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9e5e955fc3d8c8d3e5103a03514cd0dba9411f110156cd725151531b1385ba50
3
+ size 748819289
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
1
+ gradio
2
+ numpy
3
+ torch
4
+ torchvision
5
+ -e git+https://github.com/openai/guided-diffusion@main#egg=guided-diffusion