Spaces:
Running
on
Zero
Running
on
Zero
Create vae.py
Browse files- lib_layerdiffuse/vae.py +447 -0
lib_layerdiffuse/vae.py
ADDED
@@ -0,0 +1,447 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch.nn as nn
|
2 |
+
import torch
|
3 |
+
import cv2
|
4 |
+
import numpy as np
|
5 |
+
import safetensors.torch as sf
|
6 |
+
from accelerate.logging import get_logger
|
7 |
+
logger = get_logger(__name__, log_level="INFO")
|
8 |
+
|
9 |
+
from tqdm import tqdm
|
10 |
+
from typing import Optional, Tuple
|
11 |
+
from diffusers.configuration_utils import ConfigMixin, register_to_config
|
12 |
+
from diffusers.models.modeling_utils import ModelMixin
|
13 |
+
from diffusers.models.unets.unet_2d_blocks import UNetMidBlock2D, get_down_block, get_up_block
|
14 |
+
from diffusers.models.autoencoders.vae import DiagonalGaussianDistribution
|
15 |
+
|
16 |
+
import torchvision
|
17 |
+
|
18 |
+
|
19 |
+
def zero_module(module):
|
20 |
+
"""
|
21 |
+
Zero out the parameters of a module and return it.
|
22 |
+
"""
|
23 |
+
for p in module.parameters():
|
24 |
+
p.detach().zero_()
|
25 |
+
return module
|
26 |
+
|
27 |
+
|
28 |
+
class LatentTransparencyOffsetEncoder(torch.nn.Module):
|
29 |
+
def __init__(self, latent_c=4, *args, **kwargs):
|
30 |
+
super().__init__(*args, **kwargs)
|
31 |
+
self.blocks = torch.nn.Sequential(
|
32 |
+
torch.nn.Conv2d(4, 32, kernel_size=3, padding=1, stride=1),
|
33 |
+
nn.SiLU(),
|
34 |
+
torch.nn.Conv2d(32, 32, kernel_size=3, padding=1, stride=1),
|
35 |
+
nn.SiLU(),
|
36 |
+
torch.nn.Conv2d(32, 64, kernel_size=3, padding=1, stride=2),
|
37 |
+
nn.SiLU(),
|
38 |
+
torch.nn.Conv2d(64, 64, kernel_size=3, padding=1, stride=1),
|
39 |
+
nn.SiLU(),
|
40 |
+
torch.nn.Conv2d(64, 128, kernel_size=3, padding=1, stride=2),
|
41 |
+
nn.SiLU(),
|
42 |
+
torch.nn.Conv2d(128, 128, kernel_size=3, padding=1, stride=1),
|
43 |
+
nn.SiLU(),
|
44 |
+
torch.nn.Conv2d(128, 256, kernel_size=3, padding=1, stride=2),
|
45 |
+
nn.SiLU(),
|
46 |
+
torch.nn.Conv2d(256, 256, kernel_size=3, padding=1, stride=1),
|
47 |
+
nn.SiLU(),
|
48 |
+
zero_module(torch.nn.Conv2d(256, latent_c, kernel_size=3, padding=1, stride=1)),
|
49 |
+
)
|
50 |
+
|
51 |
+
def __call__(self, x):
|
52 |
+
return self.blocks(x)
|
53 |
+
|
54 |
+
|
55 |
+
# 1024 * 1024 * 3 -> 16 * 16 * 512 -> 1024 * 1024 * 3
|
56 |
+
class UNet1024(ModelMixin, ConfigMixin):
|
57 |
+
@register_to_config
|
58 |
+
def __init__(
|
59 |
+
self,
|
60 |
+
in_channels: int = 3,
|
61 |
+
out_channels: int = 3,
|
62 |
+
down_block_types: Tuple[str] = ("DownBlock2D", "DownBlock2D", "DownBlock2D", "DownBlock2D", "AttnDownBlock2D", "AttnDownBlock2D", "AttnDownBlock2D"),
|
63 |
+
up_block_types: Tuple[str] = ("AttnUpBlock2D", "AttnUpBlock2D", "AttnUpBlock2D", "UpBlock2D", "UpBlock2D", "UpBlock2D", "UpBlock2D"),
|
64 |
+
block_out_channels: Tuple[int] = (32, 32, 64, 128, 256, 512, 512),
|
65 |
+
layers_per_block: int = 2,
|
66 |
+
mid_block_scale_factor: float = 1,
|
67 |
+
downsample_padding: int = 1,
|
68 |
+
downsample_type: str = "conv",
|
69 |
+
upsample_type: str = "conv",
|
70 |
+
dropout: float = 0.0,
|
71 |
+
act_fn: str = "silu",
|
72 |
+
attention_head_dim: Optional[int] = 8,
|
73 |
+
norm_num_groups: int = 4,
|
74 |
+
norm_eps: float = 1e-5,
|
75 |
+
latent_c: int = 4,
|
76 |
+
):
|
77 |
+
super().__init__()
|
78 |
+
|
79 |
+
# input
|
80 |
+
self.conv_in = nn.Conv2d(in_channels, block_out_channels[0], kernel_size=3, padding=(1, 1))
|
81 |
+
self.latent_conv_in = zero_module(nn.Conv2d(latent_c, block_out_channels[2], kernel_size=1))
|
82 |
+
|
83 |
+
self.down_blocks = nn.ModuleList([])
|
84 |
+
self.mid_block = None
|
85 |
+
self.up_blocks = nn.ModuleList([])
|
86 |
+
|
87 |
+
# down
|
88 |
+
output_channel = block_out_channels[0]
|
89 |
+
for i, down_block_type in enumerate(down_block_types):
|
90 |
+
input_channel = output_channel
|
91 |
+
output_channel = block_out_channels[i]
|
92 |
+
is_final_block = i == len(block_out_channels) - 1
|
93 |
+
|
94 |
+
down_block = get_down_block(
|
95 |
+
down_block_type,
|
96 |
+
num_layers=layers_per_block,
|
97 |
+
in_channels=input_channel,
|
98 |
+
out_channels=output_channel,
|
99 |
+
temb_channels=None,
|
100 |
+
add_downsample=not is_final_block,
|
101 |
+
resnet_eps=norm_eps,
|
102 |
+
resnet_act_fn=act_fn,
|
103 |
+
resnet_groups=norm_num_groups,
|
104 |
+
attention_head_dim=attention_head_dim if attention_head_dim is not None else output_channel,
|
105 |
+
downsample_padding=downsample_padding,
|
106 |
+
resnet_time_scale_shift="default",
|
107 |
+
downsample_type=downsample_type,
|
108 |
+
dropout=dropout,
|
109 |
+
)
|
110 |
+
self.down_blocks.append(down_block)
|
111 |
+
|
112 |
+
# mid
|
113 |
+
self.mid_block = UNetMidBlock2D(
|
114 |
+
in_channels=block_out_channels[-1],
|
115 |
+
temb_channels=None,
|
116 |
+
dropout=dropout,
|
117 |
+
resnet_eps=norm_eps,
|
118 |
+
resnet_act_fn=act_fn,
|
119 |
+
output_scale_factor=mid_block_scale_factor,
|
120 |
+
resnet_time_scale_shift="default",
|
121 |
+
attention_head_dim=attention_head_dim if attention_head_dim is not None else block_out_channels[-1],
|
122 |
+
resnet_groups=norm_num_groups,
|
123 |
+
attn_groups=None,
|
124 |
+
add_attention=True,
|
125 |
+
)
|
126 |
+
|
127 |
+
# up
|
128 |
+
reversed_block_out_channels = list(reversed(block_out_channels))
|
129 |
+
output_channel = reversed_block_out_channels[0]
|
130 |
+
for i, up_block_type in enumerate(up_block_types):
|
131 |
+
prev_output_channel = output_channel
|
132 |
+
output_channel = reversed_block_out_channels[i]
|
133 |
+
input_channel = reversed_block_out_channels[min(i + 1, len(block_out_channels) - 1)]
|
134 |
+
|
135 |
+
is_final_block = i == len(block_out_channels) - 1
|
136 |
+
|
137 |
+
up_block = get_up_block(
|
138 |
+
up_block_type,
|
139 |
+
num_layers=layers_per_block + 1,
|
140 |
+
in_channels=input_channel,
|
141 |
+
out_channels=output_channel,
|
142 |
+
prev_output_channel=prev_output_channel,
|
143 |
+
temb_channels=None,
|
144 |
+
add_upsample=not is_final_block,
|
145 |
+
resnet_eps=norm_eps,
|
146 |
+
resnet_act_fn=act_fn,
|
147 |
+
resnet_groups=norm_num_groups,
|
148 |
+
attention_head_dim=attention_head_dim if attention_head_dim is not None else output_channel,
|
149 |
+
resnet_time_scale_shift="default",
|
150 |
+
upsample_type=upsample_type,
|
151 |
+
dropout=dropout,
|
152 |
+
)
|
153 |
+
self.up_blocks.append(up_block)
|
154 |
+
prev_output_channel = output_channel
|
155 |
+
|
156 |
+
# out
|
157 |
+
self.conv_norm_out = nn.GroupNorm(num_channels=block_out_channels[0], num_groups=norm_num_groups, eps=norm_eps)
|
158 |
+
self.conv_act = nn.SiLU()
|
159 |
+
self.conv_out = nn.Conv2d(block_out_channels[0], out_channels, kernel_size=3, padding=1)
|
160 |
+
|
161 |
+
def forward(self, x, latent):
|
162 |
+
sample_latent = self.latent_conv_in(latent)
|
163 |
+
sample = self.conv_in(x)
|
164 |
+
emb = None
|
165 |
+
|
166 |
+
down_block_res_samples = (sample,)
|
167 |
+
for i, downsample_block in enumerate(self.down_blocks):
|
168 |
+
if i == 3:
|
169 |
+
sample = sample + sample_latent
|
170 |
+
|
171 |
+
sample, res_samples = downsample_block(hidden_states=sample, temb=emb)
|
172 |
+
down_block_res_samples += res_samples
|
173 |
+
|
174 |
+
sample = self.mid_block(sample, emb)
|
175 |
+
|
176 |
+
for upsample_block in self.up_blocks:
|
177 |
+
res_samples = down_block_res_samples[-len(upsample_block.resnets) :]
|
178 |
+
down_block_res_samples = down_block_res_samples[: -len(upsample_block.resnets)]
|
179 |
+
sample = upsample_block(sample, res_samples, emb)
|
180 |
+
|
181 |
+
sample = self.conv_norm_out(sample)
|
182 |
+
sample = self.conv_act(sample)
|
183 |
+
sample = self.conv_out(sample)
|
184 |
+
return sample
|
185 |
+
|
186 |
+
|
187 |
+
def checkerboard(shape):
|
188 |
+
return np.indices(shape).sum(axis=0) % 2
|
189 |
+
|
190 |
+
|
191 |
+
def build_alpha_pyramid(color, alpha, dk=1.2):
|
192 |
+
# Written by lvmin at Stanford
|
193 |
+
# Massive iterative Gaussian filters are mathematically consistent to pyramid.
|
194 |
+
|
195 |
+
pyramid = []
|
196 |
+
current_premultiplied_color = color * alpha
|
197 |
+
current_alpha = alpha
|
198 |
+
|
199 |
+
while True:
|
200 |
+
pyramid.append((current_premultiplied_color, current_alpha))
|
201 |
+
|
202 |
+
H, W, C = current_alpha.shape
|
203 |
+
if min(H, W) == 1:
|
204 |
+
break
|
205 |
+
|
206 |
+
current_premultiplied_color = cv2.resize(current_premultiplied_color, (int(W / dk), int(H / dk)), interpolation=cv2.INTER_AREA)
|
207 |
+
current_alpha = cv2.resize(current_alpha, (int(W / dk), int(H / dk)), interpolation=cv2.INTER_AREA)[:, :, None]
|
208 |
+
return pyramid[::-1]
|
209 |
+
|
210 |
+
|
211 |
+
def pad_rgb(np_rgba_hwc_uint8):
|
212 |
+
# Written by lvmin at Stanford
|
213 |
+
# Massive iterative Gaussian filters are mathematically consistent to pyramid.
|
214 |
+
|
215 |
+
np_rgba_hwc = np_rgba_hwc_uint8.astype(np.float32) #/ 255.0
|
216 |
+
pyramid = build_alpha_pyramid(color=np_rgba_hwc[..., :3], alpha=np_rgba_hwc[..., 3:])
|
217 |
+
|
218 |
+
top_c, top_a = pyramid[0]
|
219 |
+
fg = np.sum(top_c, axis=(0, 1), keepdims=True) / np.sum(top_a, axis=(0, 1), keepdims=True).clip(1e-8, 1e32)
|
220 |
+
|
221 |
+
for layer_c, layer_a in pyramid:
|
222 |
+
layer_h, layer_w, _ = layer_c.shape
|
223 |
+
fg = cv2.resize(fg, (layer_w, layer_h), interpolation=cv2.INTER_LINEAR)
|
224 |
+
fg = layer_c + fg * (1.0 - layer_a)
|
225 |
+
|
226 |
+
return fg
|
227 |
+
|
228 |
+
|
229 |
+
def dist_sample_deterministic(dist: DiagonalGaussianDistribution, perturbation: torch.Tensor):
|
230 |
+
# Modified from diffusers.models.autoencoders.vae.DiagonalGaussianDistribution.sample()
|
231 |
+
x = dist.mean + dist.std * perturbation.to(dist.std)
|
232 |
+
return x
|
233 |
+
|
234 |
+
class TransparentVAE(torch.nn.Module):
|
235 |
+
def __init__(self, sd_vae, dtype=torch.float16, encoder_file=None, decoder_file=None, alpha=300.0, latent_c=16, *args, **kwargs):
|
236 |
+
super().__init__(*args, **kwargs)
|
237 |
+
self.dtype = dtype
|
238 |
+
|
239 |
+
self.sd_vae = sd_vae
|
240 |
+
self.sd_vae.to(dtype=self.dtype)
|
241 |
+
self.sd_vae.requires_grad_(False)
|
242 |
+
|
243 |
+
self.encoder = LatentTransparencyOffsetEncoder(latent_c=latent_c)
|
244 |
+
if encoder_file is not None:
|
245 |
+
temp = sf.load_file(encoder_file)
|
246 |
+
# del temp['blocks.16.weight']
|
247 |
+
# del temp['blocks.16.bias']
|
248 |
+
self.encoder.load_state_dict(temp, strict=True)
|
249 |
+
del temp
|
250 |
+
self.encoder.to(dtype=self.dtype)
|
251 |
+
self.alpha = alpha
|
252 |
+
|
253 |
+
self.decoder = UNet1024(in_channels=3, out_channels=4, latent_c=latent_c)
|
254 |
+
if decoder_file is not None:
|
255 |
+
temp = sf.load_file(decoder_file)
|
256 |
+
# del temp['latent_conv_in.weight']
|
257 |
+
# del temp['latent_conv_in.bias']
|
258 |
+
self.decoder.load_state_dict(temp, strict=True)
|
259 |
+
del temp
|
260 |
+
self.decoder.to(dtype=self.dtype)
|
261 |
+
self.latent_c = latent_c
|
262 |
+
|
263 |
+
|
264 |
+
def sd_decode(self, latent):
|
265 |
+
return self.sd_vae.decode(latent)
|
266 |
+
|
267 |
+
def decode(self, latent, aug=True):
|
268 |
+
origin_pixel = self.sd_vae.decode(latent).sample
|
269 |
+
origin_pixel = (origin_pixel * 0.5 + 0.5)
|
270 |
+
if not aug:
|
271 |
+
y = self.decoder(origin_pixel.to(self.dtype), latent.to(self.dtype))
|
272 |
+
return origin_pixel, y
|
273 |
+
list_y = []
|
274 |
+
for i in range(int(latent.shape[0])):
|
275 |
+
y = self.estimate_augmented(origin_pixel[i:i + 1].to(self.dtype), latent[i:i + 1].to(self.dtype))
|
276 |
+
list_y.append(y)
|
277 |
+
y = torch.concat(list_y, dim=0)
|
278 |
+
return origin_pixel, y
|
279 |
+
|
280 |
+
def encode(self, img_rgba, img_rgb, padded_img_rgb, use_offset=True):
|
281 |
+
a_bchw_01 = img_rgba[:, 3:, :, :]
|
282 |
+
vae_feed = img_rgb.to(device=self.sd_vae.device, dtype=self.sd_vae.dtype)
|
283 |
+
latent_dist = self.sd_vae.encode(vae_feed).latent_dist
|
284 |
+
offset_feed = torch.cat([padded_img_rgb, a_bchw_01], dim=1).to(device=self.sd_vae.device, dtype=self.dtype)
|
285 |
+
offset = self.encoder(offset_feed) * self.alpha
|
286 |
+
if use_offset:
|
287 |
+
latent = dist_sample_deterministic(dist=latent_dist, perturbation=offset)
|
288 |
+
latent = self.sd_vae.config.scaling_factor * (latent - self.sd_vae.config.shift_factor)
|
289 |
+
else:
|
290 |
+
latent = latent_dist.sample()
|
291 |
+
latent = self.sd_vae.config.scaling_factor * (latent - self.sd_vae.config.shift_factor)
|
292 |
+
return latent
|
293 |
+
|
294 |
+
def forward(self, img_rgba, img_rgb, padded_img_rgb, use_offset=True):
|
295 |
+
return self.decode(self.encode(img_rgba, img_rgb, padded_img_rgb, use_offset))
|
296 |
+
|
297 |
+
@property
|
298 |
+
def device(self):
|
299 |
+
return next(self.parameters()).device
|
300 |
+
|
301 |
+
@torch.no_grad()
|
302 |
+
def estimate_augmented(self, pixel, latent):
|
303 |
+
args = [
|
304 |
+
[False, 0], [False, 1], [False, 2], [False, 3], [True, 0], [True, 1], [True, 2], [True, 3],
|
305 |
+
]
|
306 |
+
|
307 |
+
result = []
|
308 |
+
|
309 |
+
for flip, rok in tqdm(args):
|
310 |
+
feed_pixel = pixel.clone()
|
311 |
+
feed_latent = latent.clone()
|
312 |
+
|
313 |
+
if flip:
|
314 |
+
feed_pixel = torch.flip(feed_pixel, dims=(3,))
|
315 |
+
feed_latent = torch.flip(feed_latent, dims=(3,))
|
316 |
+
|
317 |
+
feed_pixel = torch.rot90(feed_pixel, k=rok, dims=(2, 3))
|
318 |
+
feed_latent = torch.rot90(feed_latent, k=rok, dims=(2, 3))
|
319 |
+
|
320 |
+
eps = self.decoder(feed_pixel, feed_latent).clip(0, 1)
|
321 |
+
eps = torch.rot90(eps, k=-rok, dims=(2, 3))
|
322 |
+
|
323 |
+
if flip:
|
324 |
+
eps = torch.flip(eps, dims=(3,))
|
325 |
+
|
326 |
+
result += [eps]
|
327 |
+
|
328 |
+
result = torch.stack(result, dim=0)
|
329 |
+
median = torch.median(result, dim=0).values
|
330 |
+
return median
|
331 |
+
|
332 |
+
|
333 |
+
|
334 |
+
class TransparentVAEDecoder(torch.nn.Module):
|
335 |
+
def __init__(self, filename, dtype=torch.float16, *args, **kwargs):
|
336 |
+
super().__init__(*args, **kwargs)
|
337 |
+
sd = sf.load_file(filename)
|
338 |
+
model = UNet1024(in_channels=3, out_channels=4)
|
339 |
+
model.load_state_dict(sd, strict=True)
|
340 |
+
model.to(dtype=dtype)
|
341 |
+
model.eval()
|
342 |
+
self.model = model
|
343 |
+
self.dtype = dtype
|
344 |
+
return
|
345 |
+
|
346 |
+
@torch.no_grad()
|
347 |
+
def estimate_single_pass(self, pixel, latent):
|
348 |
+
y = self.model(pixel, latent)
|
349 |
+
return y
|
350 |
+
|
351 |
+
@torch.no_grad()
|
352 |
+
def estimate_augmented(self, pixel, latent):
|
353 |
+
args = [
|
354 |
+
[False, 0], [False, 1], [False, 2], [False, 3], [True, 0], [True, 1], [True, 2], [True, 3],
|
355 |
+
]
|
356 |
+
|
357 |
+
result = []
|
358 |
+
|
359 |
+
for flip, rok in tqdm(args):
|
360 |
+
feed_pixel = pixel.clone()
|
361 |
+
feed_latent = latent.clone()
|
362 |
+
|
363 |
+
if flip:
|
364 |
+
feed_pixel = torch.flip(feed_pixel, dims=(3,))
|
365 |
+
feed_latent = torch.flip(feed_latent, dims=(3,))
|
366 |
+
|
367 |
+
feed_pixel = torch.rot90(feed_pixel, k=rok, dims=(2, 3))
|
368 |
+
feed_latent = torch.rot90(feed_latent, k=rok, dims=(2, 3))
|
369 |
+
|
370 |
+
eps = self.estimate_single_pass(feed_pixel, feed_latent).clip(0, 1)
|
371 |
+
eps = torch.rot90(eps, k=-rok, dims=(2, 3))
|
372 |
+
|
373 |
+
if flip:
|
374 |
+
eps = torch.flip(eps, dims=(3,))
|
375 |
+
|
376 |
+
result += [eps]
|
377 |
+
|
378 |
+
result = torch.stack(result, dim=0)
|
379 |
+
median = torch.median(result, dim=0).values
|
380 |
+
return median
|
381 |
+
|
382 |
+
@torch.no_grad()
|
383 |
+
def forward(self, sd_vae, latent):
|
384 |
+
pixel = sd_vae.decode(latent).sample
|
385 |
+
pixel = (pixel * 0.5 + 0.5).clip(0, 1).to(self.dtype)
|
386 |
+
latent = latent.to(self.dtype)
|
387 |
+
result_list = []
|
388 |
+
vis_list = []
|
389 |
+
|
390 |
+
for i in range(int(latent.shape[0])):
|
391 |
+
y = self.estimate_augmented(pixel[i:i + 1], latent[i:i + 1])
|
392 |
+
|
393 |
+
y = y.clip(0, 1).movedim(1, -1)
|
394 |
+
alpha = y[..., :1]
|
395 |
+
fg = y[..., 1:]
|
396 |
+
|
397 |
+
B, H, W, C = fg.shape
|
398 |
+
cb = checkerboard(shape=(H // 64, W // 64))
|
399 |
+
cb = cv2.resize(cb, (W, H), interpolation=cv2.INTER_NEAREST)
|
400 |
+
cb = (0.5 + (cb - 0.5) * 0.1)[None, ..., None]
|
401 |
+
cb = torch.from_numpy(cb).to(fg)
|
402 |
+
|
403 |
+
vis = (fg * alpha + cb * (1 - alpha))[0]
|
404 |
+
vis = (vis * 255.0).detach().cpu().float().numpy().clip(0, 255).astype(np.uint8)
|
405 |
+
vis_list.append(vis)
|
406 |
+
|
407 |
+
png = torch.cat([fg, alpha], dim=3)[0]
|
408 |
+
png = (png * 255.0).detach().cpu().float().numpy().clip(0, 255).astype(np.uint8)
|
409 |
+
result_list.append(png)
|
410 |
+
|
411 |
+
return result_list, vis_list
|
412 |
+
|
413 |
+
|
414 |
+
class TransparentVAEEncoder(torch.nn.Module):
|
415 |
+
def __init__(self, filename, dtype=torch.float16, alpha=300.0, *args, **kwargs):
|
416 |
+
super().__init__(*args, **kwargs)
|
417 |
+
sd = sf.load_file(filename)
|
418 |
+
self.dtype = dtype
|
419 |
+
|
420 |
+
model = LatentTransparencyOffsetEncoder()
|
421 |
+
model.load_state_dict(sd, strict=True)
|
422 |
+
model.to(dtype=self.dtype)
|
423 |
+
model.eval()
|
424 |
+
|
425 |
+
self.model = model
|
426 |
+
|
427 |
+
# similar to LoRA's alpha to avoid initial zero-initialized outputs being too small
|
428 |
+
self.alpha = alpha
|
429 |
+
return
|
430 |
+
|
431 |
+
@torch.no_grad()
|
432 |
+
def forward(self, sd_vae, list_of_np_rgba_hwc_uint8, use_offset=True):
|
433 |
+
list_of_np_rgb_padded = [pad_rgb(x) for x in list_of_np_rgba_hwc_uint8]
|
434 |
+
rgb_padded_bchw_01 = torch.from_numpy(np.stack(list_of_np_rgb_padded, axis=0)).float().movedim(-1, 1)
|
435 |
+
rgba_bchw_01 = torch.from_numpy(np.stack(list_of_np_rgba_hwc_uint8, axis=0)).float().movedim(-1, 1) / 255.0
|
436 |
+
rgb_bchw_01 = rgba_bchw_01[:, :3, :, :]
|
437 |
+
a_bchw_01 = rgba_bchw_01[:, 3:, :, :]
|
438 |
+
vae_feed = (rgb_bchw_01 * 2.0 - 1.0) * a_bchw_01
|
439 |
+
vae_feed = vae_feed.to(device=sd_vae.device, dtype=sd_vae.dtype)
|
440 |
+
latent_dist = sd_vae.encode(vae_feed).latent_dist
|
441 |
+
offset_feed = torch.cat([a_bchw_01, rgb_padded_bchw_01], dim=1).to(device=sd_vae.device, dtype=self.dtype)
|
442 |
+
offset = self.model(offset_feed) * self.alpha
|
443 |
+
if use_offset:
|
444 |
+
latent = dist_sample_deterministic(dist=latent_dist, perturbation=offset)
|
445 |
+
else:
|
446 |
+
latent = latent_dist.sample()
|
447 |
+
return latent
|