Spaces:
Paused
Paused
Delete cldm
Browse files- cldm/cldm.py +0 -435
- cldm/ddim_hacked.py +0 -317
- cldm/hack.py +0 -111
- cldm/logger.py +0 -76
- cldm/model.py +0 -28
cldm/cldm.py
DELETED
@@ -1,435 +0,0 @@
|
|
1 |
-
import einops
|
2 |
-
import torch
|
3 |
-
import torch as th
|
4 |
-
import torch.nn as nn
|
5 |
-
|
6 |
-
from ldm.modules.diffusionmodules.util import (
|
7 |
-
conv_nd,
|
8 |
-
linear,
|
9 |
-
zero_module,
|
10 |
-
timestep_embedding,
|
11 |
-
)
|
12 |
-
|
13 |
-
from einops import rearrange, repeat
|
14 |
-
from torchvision.utils import make_grid
|
15 |
-
from ldm.modules.attention import SpatialTransformer
|
16 |
-
from ldm.modules.diffusionmodules.openaimodel import UNetModel, TimestepEmbedSequential, ResBlock, Downsample, AttentionBlock
|
17 |
-
from ldm.models.diffusion.ddpm import LatentDiffusion
|
18 |
-
from ldm.util import log_txt_as_img, exists, instantiate_from_config
|
19 |
-
from ldm.models.diffusion.ddim import DDIMSampler
|
20 |
-
|
21 |
-
|
22 |
-
class ControlledUnetModel(UNetModel):
|
23 |
-
def forward(self, x, timesteps=None, context=None, control=None, only_mid_control=False, **kwargs):
|
24 |
-
hs = []
|
25 |
-
with torch.no_grad():
|
26 |
-
t_emb = timestep_embedding(timesteps, self.model_channels, repeat_only=False)
|
27 |
-
emb = self.time_embed(t_emb)
|
28 |
-
h = x.type(self.dtype)
|
29 |
-
for module in self.input_blocks:
|
30 |
-
h = module(h, emb, context)
|
31 |
-
hs.append(h)
|
32 |
-
h = self.middle_block(h, emb, context)
|
33 |
-
|
34 |
-
if control is not None:
|
35 |
-
h += control.pop()
|
36 |
-
|
37 |
-
for i, module in enumerate(self.output_blocks):
|
38 |
-
if only_mid_control or control is None:
|
39 |
-
h = torch.cat([h, hs.pop()], dim=1)
|
40 |
-
else:
|
41 |
-
h = torch.cat([h, hs.pop() + control.pop()], dim=1)
|
42 |
-
h = module(h, emb, context)
|
43 |
-
|
44 |
-
h = h.type(x.dtype)
|
45 |
-
return self.out(h)
|
46 |
-
|
47 |
-
|
48 |
-
class ControlNet(nn.Module):
|
49 |
-
def __init__(
|
50 |
-
self,
|
51 |
-
image_size,
|
52 |
-
in_channels,
|
53 |
-
model_channels,
|
54 |
-
hint_channels,
|
55 |
-
num_res_blocks,
|
56 |
-
attention_resolutions,
|
57 |
-
dropout=0,
|
58 |
-
channel_mult=(1, 2, 4, 8),
|
59 |
-
conv_resample=True,
|
60 |
-
dims=2,
|
61 |
-
use_checkpoint=False,
|
62 |
-
use_fp16=False,
|
63 |
-
num_heads=-1,
|
64 |
-
num_head_channels=-1,
|
65 |
-
num_heads_upsample=-1,
|
66 |
-
use_scale_shift_norm=False,
|
67 |
-
resblock_updown=False,
|
68 |
-
use_new_attention_order=False,
|
69 |
-
use_spatial_transformer=False, # custom transformer support
|
70 |
-
transformer_depth=1, # custom transformer support
|
71 |
-
context_dim=None, # custom transformer support
|
72 |
-
n_embed=None, # custom support for prediction of discrete ids into codebook of first stage vq model
|
73 |
-
legacy=True,
|
74 |
-
disable_self_attentions=None,
|
75 |
-
num_attention_blocks=None,
|
76 |
-
disable_middle_self_attn=False,
|
77 |
-
use_linear_in_transformer=False,
|
78 |
-
):
|
79 |
-
super().__init__()
|
80 |
-
if use_spatial_transformer:
|
81 |
-
assert context_dim is not None, 'Fool!! You forgot to include the dimension of your cross-attention conditioning...'
|
82 |
-
|
83 |
-
if context_dim is not None:
|
84 |
-
assert use_spatial_transformer, 'Fool!! You forgot to use the spatial transformer for your cross-attention conditioning...'
|
85 |
-
from omegaconf.listconfig import ListConfig
|
86 |
-
if type(context_dim) == ListConfig:
|
87 |
-
context_dim = list(context_dim)
|
88 |
-
|
89 |
-
if num_heads_upsample == -1:
|
90 |
-
num_heads_upsample = num_heads
|
91 |
-
|
92 |
-
if num_heads == -1:
|
93 |
-
assert num_head_channels != -1, 'Either num_heads or num_head_channels has to be set'
|
94 |
-
|
95 |
-
if num_head_channels == -1:
|
96 |
-
assert num_heads != -1, 'Either num_heads or num_head_channels has to be set'
|
97 |
-
|
98 |
-
self.dims = dims
|
99 |
-
self.image_size = image_size
|
100 |
-
self.in_channels = in_channels
|
101 |
-
self.model_channels = model_channels
|
102 |
-
if isinstance(num_res_blocks, int):
|
103 |
-
self.num_res_blocks = len(channel_mult) * [num_res_blocks]
|
104 |
-
else:
|
105 |
-
if len(num_res_blocks) != len(channel_mult):
|
106 |
-
raise ValueError("provide num_res_blocks either as an int (globally constant) or "
|
107 |
-
"as a list/tuple (per-level) with the same length as channel_mult")
|
108 |
-
self.num_res_blocks = num_res_blocks
|
109 |
-
if disable_self_attentions is not None:
|
110 |
-
# should be a list of booleans, indicating whether to disable self-attention in TransformerBlocks or not
|
111 |
-
assert len(disable_self_attentions) == len(channel_mult)
|
112 |
-
if num_attention_blocks is not None:
|
113 |
-
assert len(num_attention_blocks) == len(self.num_res_blocks)
|
114 |
-
assert all(map(lambda i: self.num_res_blocks[i] >= num_attention_blocks[i], range(len(num_attention_blocks))))
|
115 |
-
print(f"Constructor of UNetModel received num_attention_blocks={num_attention_blocks}. "
|
116 |
-
f"This option has LESS priority than attention_resolutions {attention_resolutions}, "
|
117 |
-
f"i.e., in cases where num_attention_blocks[i] > 0 but 2**i not in attention_resolutions, "
|
118 |
-
f"attention will still not be set.")
|
119 |
-
|
120 |
-
self.attention_resolutions = attention_resolutions
|
121 |
-
self.dropout = dropout
|
122 |
-
self.channel_mult = channel_mult
|
123 |
-
self.conv_resample = conv_resample
|
124 |
-
self.use_checkpoint = use_checkpoint
|
125 |
-
self.dtype = th.float16 if use_fp16 else th.float32
|
126 |
-
self.num_heads = num_heads
|
127 |
-
self.num_head_channels = num_head_channels
|
128 |
-
self.num_heads_upsample = num_heads_upsample
|
129 |
-
self.predict_codebook_ids = n_embed is not None
|
130 |
-
|
131 |
-
time_embed_dim = model_channels * 4
|
132 |
-
self.time_embed = nn.Sequential(
|
133 |
-
linear(model_channels, time_embed_dim),
|
134 |
-
nn.SiLU(),
|
135 |
-
linear(time_embed_dim, time_embed_dim),
|
136 |
-
)
|
137 |
-
|
138 |
-
self.input_blocks = nn.ModuleList(
|
139 |
-
[
|
140 |
-
TimestepEmbedSequential(
|
141 |
-
conv_nd(dims, in_channels, model_channels, 3, padding=1)
|
142 |
-
)
|
143 |
-
]
|
144 |
-
)
|
145 |
-
self.zero_convs = nn.ModuleList([self.make_zero_conv(model_channels)])
|
146 |
-
|
147 |
-
self.input_hint_block = TimestepEmbedSequential(
|
148 |
-
conv_nd(dims, hint_channels, 16, 3, padding=1),
|
149 |
-
nn.SiLU(),
|
150 |
-
conv_nd(dims, 16, 16, 3, padding=1),
|
151 |
-
nn.SiLU(),
|
152 |
-
conv_nd(dims, 16, 32, 3, padding=1, stride=2),
|
153 |
-
nn.SiLU(),
|
154 |
-
conv_nd(dims, 32, 32, 3, padding=1),
|
155 |
-
nn.SiLU(),
|
156 |
-
conv_nd(dims, 32, 96, 3, padding=1, stride=2),
|
157 |
-
nn.SiLU(),
|
158 |
-
conv_nd(dims, 96, 96, 3, padding=1),
|
159 |
-
nn.SiLU(),
|
160 |
-
conv_nd(dims, 96, 256, 3, padding=1, stride=2),
|
161 |
-
nn.SiLU(),
|
162 |
-
zero_module(conv_nd(dims, 256, model_channels, 3, padding=1))
|
163 |
-
)
|
164 |
-
|
165 |
-
self._feature_size = model_channels
|
166 |
-
input_block_chans = [model_channels]
|
167 |
-
ch = model_channels
|
168 |
-
ds = 1
|
169 |
-
for level, mult in enumerate(channel_mult):
|
170 |
-
for nr in range(self.num_res_blocks[level]):
|
171 |
-
layers = [
|
172 |
-
ResBlock(
|
173 |
-
ch,
|
174 |
-
time_embed_dim,
|
175 |
-
dropout,
|
176 |
-
out_channels=mult * model_channels,
|
177 |
-
dims=dims,
|
178 |
-
use_checkpoint=use_checkpoint,
|
179 |
-
use_scale_shift_norm=use_scale_shift_norm,
|
180 |
-
)
|
181 |
-
]
|
182 |
-
ch = mult * model_channels
|
183 |
-
if ds in attention_resolutions:
|
184 |
-
if num_head_channels == -1:
|
185 |
-
dim_head = ch // num_heads
|
186 |
-
else:
|
187 |
-
num_heads = ch // num_head_channels
|
188 |
-
dim_head = num_head_channels
|
189 |
-
if legacy:
|
190 |
-
# num_heads = 1
|
191 |
-
dim_head = ch // num_heads if use_spatial_transformer else num_head_channels
|
192 |
-
if exists(disable_self_attentions):
|
193 |
-
disabled_sa = disable_self_attentions[level]
|
194 |
-
else:
|
195 |
-
disabled_sa = False
|
196 |
-
|
197 |
-
if not exists(num_attention_blocks) or nr < num_attention_blocks[level]:
|
198 |
-
layers.append(
|
199 |
-
AttentionBlock(
|
200 |
-
ch,
|
201 |
-
use_checkpoint=use_checkpoint,
|
202 |
-
num_heads=num_heads,
|
203 |
-
num_head_channels=dim_head,
|
204 |
-
use_new_attention_order=use_new_attention_order,
|
205 |
-
) if not use_spatial_transformer else SpatialTransformer(
|
206 |
-
ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim,
|
207 |
-
disable_self_attn=disabled_sa, use_linear=use_linear_in_transformer,
|
208 |
-
use_checkpoint=use_checkpoint
|
209 |
-
)
|
210 |
-
)
|
211 |
-
self.input_blocks.append(TimestepEmbedSequential(*layers))
|
212 |
-
self.zero_convs.append(self.make_zero_conv(ch))
|
213 |
-
self._feature_size += ch
|
214 |
-
input_block_chans.append(ch)
|
215 |
-
if level != len(channel_mult) - 1:
|
216 |
-
out_ch = ch
|
217 |
-
self.input_blocks.append(
|
218 |
-
TimestepEmbedSequential(
|
219 |
-
ResBlock(
|
220 |
-
ch,
|
221 |
-
time_embed_dim,
|
222 |
-
dropout,
|
223 |
-
out_channels=out_ch,
|
224 |
-
dims=dims,
|
225 |
-
use_checkpoint=use_checkpoint,
|
226 |
-
use_scale_shift_norm=use_scale_shift_norm,
|
227 |
-
down=True,
|
228 |
-
)
|
229 |
-
if resblock_updown
|
230 |
-
else Downsample(
|
231 |
-
ch, conv_resample, dims=dims, out_channels=out_ch
|
232 |
-
)
|
233 |
-
)
|
234 |
-
)
|
235 |
-
ch = out_ch
|
236 |
-
input_block_chans.append(ch)
|
237 |
-
self.zero_convs.append(self.make_zero_conv(ch))
|
238 |
-
ds *= 2
|
239 |
-
self._feature_size += ch
|
240 |
-
|
241 |
-
if num_head_channels == -1:
|
242 |
-
dim_head = ch // num_heads
|
243 |
-
else:
|
244 |
-
num_heads = ch // num_head_channels
|
245 |
-
dim_head = num_head_channels
|
246 |
-
if legacy:
|
247 |
-
# num_heads = 1
|
248 |
-
dim_head = ch // num_heads if use_spatial_transformer else num_head_channels
|
249 |
-
self.middle_block = TimestepEmbedSequential(
|
250 |
-
ResBlock(
|
251 |
-
ch,
|
252 |
-
time_embed_dim,
|
253 |
-
dropout,
|
254 |
-
dims=dims,
|
255 |
-
use_checkpoint=use_checkpoint,
|
256 |
-
use_scale_shift_norm=use_scale_shift_norm,
|
257 |
-
),
|
258 |
-
AttentionBlock(
|
259 |
-
ch,
|
260 |
-
use_checkpoint=use_checkpoint,
|
261 |
-
num_heads=num_heads,
|
262 |
-
num_head_channels=dim_head,
|
263 |
-
use_new_attention_order=use_new_attention_order,
|
264 |
-
) if not use_spatial_transformer else SpatialTransformer( # always uses a self-attn
|
265 |
-
ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim,
|
266 |
-
disable_self_attn=disable_middle_self_attn, use_linear=use_linear_in_transformer,
|
267 |
-
use_checkpoint=use_checkpoint
|
268 |
-
),
|
269 |
-
ResBlock(
|
270 |
-
ch,
|
271 |
-
time_embed_dim,
|
272 |
-
dropout,
|
273 |
-
dims=dims,
|
274 |
-
use_checkpoint=use_checkpoint,
|
275 |
-
use_scale_shift_norm=use_scale_shift_norm,
|
276 |
-
),
|
277 |
-
)
|
278 |
-
self.middle_block_out = self.make_zero_conv(ch)
|
279 |
-
self._feature_size += ch
|
280 |
-
|
281 |
-
def make_zero_conv(self, channels):
|
282 |
-
return TimestepEmbedSequential(zero_module(conv_nd(self.dims, channels, channels, 1, padding=0)))
|
283 |
-
|
284 |
-
def forward(self, x, hint, timesteps, context, **kwargs):
|
285 |
-
t_emb = timestep_embedding(timesteps, self.model_channels, repeat_only=False)
|
286 |
-
emb = self.time_embed(t_emb)
|
287 |
-
|
288 |
-
guided_hint = self.input_hint_block(hint, emb, context)
|
289 |
-
|
290 |
-
outs = []
|
291 |
-
|
292 |
-
h = x.type(self.dtype)
|
293 |
-
for module, zero_conv in zip(self.input_blocks, self.zero_convs):
|
294 |
-
if guided_hint is not None:
|
295 |
-
h = module(h, emb, context)
|
296 |
-
h += guided_hint
|
297 |
-
guided_hint = None
|
298 |
-
else:
|
299 |
-
h = module(h, emb, context)
|
300 |
-
outs.append(zero_conv(h, emb, context))
|
301 |
-
|
302 |
-
h = self.middle_block(h, emb, context)
|
303 |
-
outs.append(self.middle_block_out(h, emb, context))
|
304 |
-
|
305 |
-
return outs
|
306 |
-
|
307 |
-
|
308 |
-
class ControlLDM(LatentDiffusion):
|
309 |
-
|
310 |
-
def __init__(self, control_stage_config, control_key, only_mid_control, *args, **kwargs):
|
311 |
-
super().__init__(*args, **kwargs)
|
312 |
-
self.control_model = instantiate_from_config(control_stage_config)
|
313 |
-
self.control_key = control_key
|
314 |
-
self.only_mid_control = only_mid_control
|
315 |
-
self.control_scales = [1.0] * 13
|
316 |
-
|
317 |
-
@torch.no_grad()
|
318 |
-
def get_input(self, batch, k, bs=None, *args, **kwargs):
|
319 |
-
x, c = super().get_input(batch, self.first_stage_key, *args, **kwargs)
|
320 |
-
control = batch[self.control_key]
|
321 |
-
if bs is not None:
|
322 |
-
control = control[:bs]
|
323 |
-
control = control.to(self.device)
|
324 |
-
control = einops.rearrange(control, 'b h w c -> b c h w')
|
325 |
-
control = control.to(memory_format=torch.contiguous_format).float()
|
326 |
-
return x, dict(c_crossattn=[c], c_concat=[control])
|
327 |
-
|
328 |
-
def apply_model(self, x_noisy, t, cond, *args, **kwargs):
|
329 |
-
assert isinstance(cond, dict)
|
330 |
-
diffusion_model = self.model.diffusion_model
|
331 |
-
|
332 |
-
cond_txt = torch.cat(cond['c_crossattn'], 1)
|
333 |
-
|
334 |
-
if cond['c_concat'] is None:
|
335 |
-
eps = diffusion_model(x=x_noisy, timesteps=t, context=cond_txt, control=None, only_mid_control=self.only_mid_control)
|
336 |
-
else:
|
337 |
-
control = self.control_model(x=x_noisy, hint=torch.cat(cond['c_concat'], 1), timesteps=t, context=cond_txt)
|
338 |
-
control = [c * scale for c, scale in zip(control, self.control_scales)]
|
339 |
-
eps = diffusion_model(x=x_noisy, timesteps=t, context=cond_txt, control=control, only_mid_control=self.only_mid_control)
|
340 |
-
|
341 |
-
return eps
|
342 |
-
|
343 |
-
@torch.no_grad()
|
344 |
-
def get_unconditional_conditioning(self, N):
|
345 |
-
return self.get_learned_conditioning([""] * N)
|
346 |
-
|
347 |
-
@torch.no_grad()
|
348 |
-
def log_images(self, batch, N=4, n_row=2, sample=False, ddim_steps=50, ddim_eta=0.0, return_keys=None,
|
349 |
-
quantize_denoised=True, inpaint=True, plot_denoise_rows=False, plot_progressive_rows=True,
|
350 |
-
plot_diffusion_rows=False, unconditional_guidance_scale=9.0, unconditional_guidance_label=None,
|
351 |
-
use_ema_scope=True,
|
352 |
-
**kwargs):
|
353 |
-
use_ddim = ddim_steps is not None
|
354 |
-
|
355 |
-
log = dict()
|
356 |
-
z, c = self.get_input(batch, self.first_stage_key, bs=N)
|
357 |
-
c_cat, c = c["c_concat"][0][:N], c["c_crossattn"][0][:N]
|
358 |
-
N = min(z.shape[0], N)
|
359 |
-
n_row = min(z.shape[0], n_row)
|
360 |
-
log["reconstruction"] = self.decode_first_stage(z)
|
361 |
-
log["control"] = c_cat * 2.0 - 1.0
|
362 |
-
log["conditioning"] = log_txt_as_img((512, 512), batch[self.cond_stage_key], size=16)
|
363 |
-
|
364 |
-
if plot_diffusion_rows:
|
365 |
-
# get diffusion row
|
366 |
-
diffusion_row = list()
|
367 |
-
z_start = z[:n_row]
|
368 |
-
for t in range(self.num_timesteps):
|
369 |
-
if t % self.log_every_t == 0 or t == self.num_timesteps - 1:
|
370 |
-
t = repeat(torch.tensor([t]), '1 -> b', b=n_row)
|
371 |
-
t = t.to(self.device).long()
|
372 |
-
noise = torch.randn_like(z_start)
|
373 |
-
z_noisy = self.q_sample(x_start=z_start, t=t, noise=noise)
|
374 |
-
diffusion_row.append(self.decode_first_stage(z_noisy))
|
375 |
-
|
376 |
-
diffusion_row = torch.stack(diffusion_row) # n_log_step, n_row, C, H, W
|
377 |
-
diffusion_grid = rearrange(diffusion_row, 'n b c h w -> b n c h w')
|
378 |
-
diffusion_grid = rearrange(diffusion_grid, 'b n c h w -> (b n) c h w')
|
379 |
-
diffusion_grid = make_grid(diffusion_grid, nrow=diffusion_row.shape[0])
|
380 |
-
log["diffusion_row"] = diffusion_grid
|
381 |
-
|
382 |
-
if sample:
|
383 |
-
# get denoise row
|
384 |
-
samples, z_denoise_row = self.sample_log(cond={"c_concat": [c_cat], "c_crossattn": [c]},
|
385 |
-
batch_size=N, ddim=use_ddim,
|
386 |
-
ddim_steps=ddim_steps, eta=ddim_eta)
|
387 |
-
x_samples = self.decode_first_stage(samples)
|
388 |
-
log["samples"] = x_samples
|
389 |
-
if plot_denoise_rows:
|
390 |
-
denoise_grid = self._get_denoise_row_from_list(z_denoise_row)
|
391 |
-
log["denoise_row"] = denoise_grid
|
392 |
-
|
393 |
-
if unconditional_guidance_scale > 1.0:
|
394 |
-
uc_cross = self.get_unconditional_conditioning(N)
|
395 |
-
uc_cat = c_cat # torch.zeros_like(c_cat)
|
396 |
-
uc_full = {"c_concat": [uc_cat], "c_crossattn": [uc_cross]}
|
397 |
-
samples_cfg, _ = self.sample_log(cond={"c_concat": [c_cat], "c_crossattn": [c]},
|
398 |
-
batch_size=N, ddim=use_ddim,
|
399 |
-
ddim_steps=ddim_steps, eta=ddim_eta,
|
400 |
-
unconditional_guidance_scale=unconditional_guidance_scale,
|
401 |
-
unconditional_conditioning=uc_full,
|
402 |
-
)
|
403 |
-
x_samples_cfg = self.decode_first_stage(samples_cfg)
|
404 |
-
log[f"samples_cfg_scale_{unconditional_guidance_scale:.2f}"] = x_samples_cfg
|
405 |
-
|
406 |
-
return log
|
407 |
-
|
408 |
-
@torch.no_grad()
|
409 |
-
def sample_log(self, cond, batch_size, ddim, ddim_steps, **kwargs):
|
410 |
-
ddim_sampler = DDIMSampler(self)
|
411 |
-
b, c, h, w = cond["c_concat"][0].shape
|
412 |
-
shape = (self.channels, h // 8, w // 8)
|
413 |
-
samples, intermediates = ddim_sampler.sample(ddim_steps, batch_size, shape, cond, verbose=False, **kwargs)
|
414 |
-
return samples, intermediates
|
415 |
-
|
416 |
-
def configure_optimizers(self):
|
417 |
-
lr = self.learning_rate
|
418 |
-
params = list(self.control_model.parameters())
|
419 |
-
if not self.sd_locked:
|
420 |
-
params += list(self.model.diffusion_model.output_blocks.parameters())
|
421 |
-
params += list(self.model.diffusion_model.out.parameters())
|
422 |
-
opt = torch.optim.AdamW(params, lr=lr)
|
423 |
-
return opt
|
424 |
-
|
425 |
-
def low_vram_shift(self, is_diffusing):
|
426 |
-
if is_diffusing:
|
427 |
-
self.model = self.model.cuda()
|
428 |
-
self.control_model = self.control_model.cuda()
|
429 |
-
self.first_stage_model = self.first_stage_model.cpu()
|
430 |
-
self.cond_stage_model = self.cond_stage_model.cpu()
|
431 |
-
else:
|
432 |
-
self.model = self.model.cpu()
|
433 |
-
self.control_model = self.control_model.cpu()
|
434 |
-
self.first_stage_model = self.first_stage_model.cuda()
|
435 |
-
self.cond_stage_model = self.cond_stage_model.cuda()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
cldm/ddim_hacked.py
DELETED
@@ -1,317 +0,0 @@
|
|
1 |
-
"""SAMPLING ONLY."""
|
2 |
-
|
3 |
-
import torch
|
4 |
-
import numpy as np
|
5 |
-
from tqdm import tqdm
|
6 |
-
|
7 |
-
from ldm.modules.diffusionmodules.util import make_ddim_sampling_parameters, make_ddim_timesteps, noise_like, extract_into_tensor
|
8 |
-
|
9 |
-
|
10 |
-
class DDIMSampler(object):
|
11 |
-
def __init__(self, model, schedule="linear", **kwargs):
|
12 |
-
super().__init__()
|
13 |
-
self.model = model
|
14 |
-
self.ddpm_num_timesteps = model.num_timesteps
|
15 |
-
self.schedule = schedule
|
16 |
-
|
17 |
-
def register_buffer(self, name, attr):
|
18 |
-
if type(attr) == torch.Tensor:
|
19 |
-
if attr.device != torch.device("cuda"):
|
20 |
-
attr = attr.to(torch.device("cuda"))
|
21 |
-
setattr(self, name, attr)
|
22 |
-
|
23 |
-
def make_schedule(self, ddim_num_steps, ddim_discretize="uniform", ddim_eta=0., verbose=True):
|
24 |
-
self.ddim_timesteps = make_ddim_timesteps(ddim_discr_method=ddim_discretize, num_ddim_timesteps=ddim_num_steps,
|
25 |
-
num_ddpm_timesteps=self.ddpm_num_timesteps,verbose=verbose)
|
26 |
-
alphas_cumprod = self.model.alphas_cumprod
|
27 |
-
assert alphas_cumprod.shape[0] == self.ddpm_num_timesteps, 'alphas have to be defined for each timestep'
|
28 |
-
to_torch = lambda x: x.clone().detach().to(torch.float32).to(self.model.device)
|
29 |
-
|
30 |
-
self.register_buffer('betas', to_torch(self.model.betas))
|
31 |
-
self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod))
|
32 |
-
self.register_buffer('alphas_cumprod_prev', to_torch(self.model.alphas_cumprod_prev))
|
33 |
-
|
34 |
-
# calculations for diffusion q(x_t | x_{t-1}) and others
|
35 |
-
self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod.cpu())))
|
36 |
-
self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod.cpu())))
|
37 |
-
self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod.cpu())))
|
38 |
-
self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu())))
|
39 |
-
self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod.cpu() - 1)))
|
40 |
-
|
41 |
-
# ddim sampling parameters
|
42 |
-
ddim_sigmas, ddim_alphas, ddim_alphas_prev = make_ddim_sampling_parameters(alphacums=alphas_cumprod.cpu(),
|
43 |
-
ddim_timesteps=self.ddim_timesteps,
|
44 |
-
eta=ddim_eta,verbose=verbose)
|
45 |
-
self.register_buffer('ddim_sigmas', ddim_sigmas)
|
46 |
-
self.register_buffer('ddim_alphas', ddim_alphas)
|
47 |
-
self.register_buffer('ddim_alphas_prev', ddim_alphas_prev)
|
48 |
-
self.register_buffer('ddim_sqrt_one_minus_alphas', np.sqrt(1. - ddim_alphas))
|
49 |
-
sigmas_for_original_sampling_steps = ddim_eta * torch.sqrt(
|
50 |
-
(1 - self.alphas_cumprod_prev) / (1 - self.alphas_cumprod) * (
|
51 |
-
1 - self.alphas_cumprod / self.alphas_cumprod_prev))
|
52 |
-
self.register_buffer('ddim_sigmas_for_original_num_steps', sigmas_for_original_sampling_steps)
|
53 |
-
|
54 |
-
@torch.no_grad()
|
55 |
-
def sample(self,
|
56 |
-
S,
|
57 |
-
batch_size,
|
58 |
-
shape,
|
59 |
-
conditioning=None,
|
60 |
-
callback=None,
|
61 |
-
normals_sequence=None,
|
62 |
-
img_callback=None,
|
63 |
-
quantize_x0=False,
|
64 |
-
eta=0.,
|
65 |
-
mask=None,
|
66 |
-
x0=None,
|
67 |
-
temperature=1.,
|
68 |
-
noise_dropout=0.,
|
69 |
-
score_corrector=None,
|
70 |
-
corrector_kwargs=None,
|
71 |
-
verbose=True,
|
72 |
-
x_T=None,
|
73 |
-
log_every_t=100,
|
74 |
-
unconditional_guidance_scale=1.,
|
75 |
-
unconditional_conditioning=None, # this has to come in the same format as the conditioning, # e.g. as encoded tokens, ...
|
76 |
-
dynamic_threshold=None,
|
77 |
-
ucg_schedule=None,
|
78 |
-
**kwargs
|
79 |
-
):
|
80 |
-
if conditioning is not None:
|
81 |
-
if isinstance(conditioning, dict):
|
82 |
-
ctmp = conditioning[list(conditioning.keys())[0]]
|
83 |
-
while isinstance(ctmp, list): ctmp = ctmp[0]
|
84 |
-
cbs = ctmp.shape[0]
|
85 |
-
if cbs != batch_size:
|
86 |
-
print(f"Warning: Got {cbs} conditionings but batch-size is {batch_size}")
|
87 |
-
|
88 |
-
elif isinstance(conditioning, list):
|
89 |
-
for ctmp in conditioning:
|
90 |
-
if ctmp.shape[0] != batch_size:
|
91 |
-
print(f"Warning: Got {cbs} conditionings but batch-size is {batch_size}")
|
92 |
-
|
93 |
-
else:
|
94 |
-
if conditioning.shape[0] != batch_size:
|
95 |
-
print(f"Warning: Got {conditioning.shape[0]} conditionings but batch-size is {batch_size}")
|
96 |
-
|
97 |
-
self.make_schedule(ddim_num_steps=S, ddim_eta=eta, verbose=verbose)
|
98 |
-
# sampling
|
99 |
-
C, H, W = shape
|
100 |
-
size = (batch_size, C, H, W)
|
101 |
-
print(f'Data shape for DDIM sampling is {size}, eta {eta}')
|
102 |
-
|
103 |
-
samples, intermediates = self.ddim_sampling(conditioning, size,
|
104 |
-
callback=callback,
|
105 |
-
img_callback=img_callback,
|
106 |
-
quantize_denoised=quantize_x0,
|
107 |
-
mask=mask, x0=x0,
|
108 |
-
ddim_use_original_steps=False,
|
109 |
-
noise_dropout=noise_dropout,
|
110 |
-
temperature=temperature,
|
111 |
-
score_corrector=score_corrector,
|
112 |
-
corrector_kwargs=corrector_kwargs,
|
113 |
-
x_T=x_T,
|
114 |
-
log_every_t=log_every_t,
|
115 |
-
unconditional_guidance_scale=unconditional_guidance_scale,
|
116 |
-
unconditional_conditioning=unconditional_conditioning,
|
117 |
-
dynamic_threshold=dynamic_threshold,
|
118 |
-
ucg_schedule=ucg_schedule
|
119 |
-
)
|
120 |
-
return samples, intermediates
|
121 |
-
|
122 |
-
@torch.no_grad()
|
123 |
-
def ddim_sampling(self, cond, shape,
|
124 |
-
x_T=None, ddim_use_original_steps=False,
|
125 |
-
callback=None, timesteps=None, quantize_denoised=False,
|
126 |
-
mask=None, x0=None, img_callback=None, log_every_t=100,
|
127 |
-
temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None,
|
128 |
-
unconditional_guidance_scale=1., unconditional_conditioning=None, dynamic_threshold=None,
|
129 |
-
ucg_schedule=None):
|
130 |
-
device = self.model.betas.device
|
131 |
-
b = shape[0]
|
132 |
-
if x_T is None:
|
133 |
-
img = torch.randn(shape, device=device)
|
134 |
-
else:
|
135 |
-
img = x_T
|
136 |
-
|
137 |
-
if timesteps is None:
|
138 |
-
timesteps = self.ddpm_num_timesteps if ddim_use_original_steps else self.ddim_timesteps
|
139 |
-
elif timesteps is not None and not ddim_use_original_steps:
|
140 |
-
subset_end = int(min(timesteps / self.ddim_timesteps.shape[0], 1) * self.ddim_timesteps.shape[0]) - 1
|
141 |
-
timesteps = self.ddim_timesteps[:subset_end]
|
142 |
-
|
143 |
-
intermediates = {'x_inter': [img], 'pred_x0': [img]}
|
144 |
-
time_range = reversed(range(0,timesteps)) if ddim_use_original_steps else np.flip(timesteps)
|
145 |
-
total_steps = timesteps if ddim_use_original_steps else timesteps.shape[0]
|
146 |
-
print(f"Running DDIM Sampling with {total_steps} timesteps")
|
147 |
-
|
148 |
-
iterator = tqdm(time_range, desc='DDIM Sampler', total=total_steps)
|
149 |
-
|
150 |
-
for i, step in enumerate(iterator):
|
151 |
-
index = total_steps - i - 1
|
152 |
-
ts = torch.full((b,), step, device=device, dtype=torch.long)
|
153 |
-
|
154 |
-
if mask is not None:
|
155 |
-
assert x0 is not None
|
156 |
-
img_orig = self.model.q_sample(x0, ts) # TODO: deterministic forward pass?
|
157 |
-
img = img_orig * mask + (1. - mask) * img
|
158 |
-
|
159 |
-
if ucg_schedule is not None:
|
160 |
-
assert len(ucg_schedule) == len(time_range)
|
161 |
-
unconditional_guidance_scale = ucg_schedule[i]
|
162 |
-
|
163 |
-
outs = self.p_sample_ddim(img, cond, ts, index=index, use_original_steps=ddim_use_original_steps,
|
164 |
-
quantize_denoised=quantize_denoised, temperature=temperature,
|
165 |
-
noise_dropout=noise_dropout, score_corrector=score_corrector,
|
166 |
-
corrector_kwargs=corrector_kwargs,
|
167 |
-
unconditional_guidance_scale=unconditional_guidance_scale,
|
168 |
-
unconditional_conditioning=unconditional_conditioning,
|
169 |
-
dynamic_threshold=dynamic_threshold)
|
170 |
-
img, pred_x0 = outs
|
171 |
-
if callback: callback(i)
|
172 |
-
if img_callback: img_callback(pred_x0, i)
|
173 |
-
|
174 |
-
if index % log_every_t == 0 or index == total_steps - 1:
|
175 |
-
intermediates['x_inter'].append(img)
|
176 |
-
intermediates['pred_x0'].append(pred_x0)
|
177 |
-
|
178 |
-
return img, intermediates
|
179 |
-
|
180 |
-
@torch.no_grad()
|
181 |
-
def p_sample_ddim(self, x, c, t, index, repeat_noise=False, use_original_steps=False, quantize_denoised=False,
|
182 |
-
temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None,
|
183 |
-
unconditional_guidance_scale=1., unconditional_conditioning=None,
|
184 |
-
dynamic_threshold=None):
|
185 |
-
b, *_, device = *x.shape, x.device
|
186 |
-
|
187 |
-
if unconditional_conditioning is None or unconditional_guidance_scale == 1.:
|
188 |
-
model_output = self.model.apply_model(x, t, c)
|
189 |
-
else:
|
190 |
-
model_t = self.model.apply_model(x, t, c)
|
191 |
-
model_uncond = self.model.apply_model(x, t, unconditional_conditioning)
|
192 |
-
model_output = model_uncond + unconditional_guidance_scale * (model_t - model_uncond)
|
193 |
-
|
194 |
-
if self.model.parameterization == "v":
|
195 |
-
e_t = self.model.predict_eps_from_z_and_v(x, t, model_output)
|
196 |
-
else:
|
197 |
-
e_t = model_output
|
198 |
-
|
199 |
-
if score_corrector is not None:
|
200 |
-
assert self.model.parameterization == "eps", 'not implemented'
|
201 |
-
e_t = score_corrector.modify_score(self.model, e_t, x, t, c, **corrector_kwargs)
|
202 |
-
|
203 |
-
alphas = self.model.alphas_cumprod if use_original_steps else self.ddim_alphas
|
204 |
-
alphas_prev = self.model.alphas_cumprod_prev if use_original_steps else self.ddim_alphas_prev
|
205 |
-
sqrt_one_minus_alphas = self.model.sqrt_one_minus_alphas_cumprod if use_original_steps else self.ddim_sqrt_one_minus_alphas
|
206 |
-
sigmas = self.model.ddim_sigmas_for_original_num_steps if use_original_steps else self.ddim_sigmas
|
207 |
-
# select parameters corresponding to the currently considered timestep
|
208 |
-
a_t = torch.full((b, 1, 1, 1), alphas[index], device=device)
|
209 |
-
a_prev = torch.full((b, 1, 1, 1), alphas_prev[index], device=device)
|
210 |
-
sigma_t = torch.full((b, 1, 1, 1), sigmas[index], device=device)
|
211 |
-
sqrt_one_minus_at = torch.full((b, 1, 1, 1), sqrt_one_minus_alphas[index],device=device)
|
212 |
-
|
213 |
-
# current prediction for x_0
|
214 |
-
if self.model.parameterization != "v":
|
215 |
-
pred_x0 = (x - sqrt_one_minus_at * e_t) / a_t.sqrt()
|
216 |
-
else:
|
217 |
-
pred_x0 = self.model.predict_start_from_z_and_v(x, t, model_output)
|
218 |
-
|
219 |
-
if quantize_denoised:
|
220 |
-
pred_x0, _, *_ = self.model.first_stage_model.quantize(pred_x0)
|
221 |
-
|
222 |
-
if dynamic_threshold is not None:
|
223 |
-
raise NotImplementedError()
|
224 |
-
|
225 |
-
# direction pointing to x_t
|
226 |
-
dir_xt = (1. - a_prev - sigma_t**2).sqrt() * e_t
|
227 |
-
noise = sigma_t * noise_like(x.shape, device, repeat_noise) * temperature
|
228 |
-
if noise_dropout > 0.:
|
229 |
-
noise = torch.nn.functional.dropout(noise, p=noise_dropout)
|
230 |
-
x_prev = a_prev.sqrt() * pred_x0 + dir_xt + noise
|
231 |
-
return x_prev, pred_x0
|
232 |
-
|
233 |
-
@torch.no_grad()
|
234 |
-
def encode(self, x0, c, t_enc, use_original_steps=False, return_intermediates=None,
|
235 |
-
unconditional_guidance_scale=1.0, unconditional_conditioning=None, callback=None):
|
236 |
-
timesteps = np.arange(self.ddpm_num_timesteps) if use_original_steps else self.ddim_timesteps
|
237 |
-
num_reference_steps = timesteps.shape[0]
|
238 |
-
|
239 |
-
assert t_enc <= num_reference_steps
|
240 |
-
num_steps = t_enc
|
241 |
-
|
242 |
-
if use_original_steps:
|
243 |
-
alphas_next = self.alphas_cumprod[:num_steps]
|
244 |
-
alphas = self.alphas_cumprod_prev[:num_steps]
|
245 |
-
else:
|
246 |
-
alphas_next = self.ddim_alphas[:num_steps]
|
247 |
-
alphas = torch.tensor(self.ddim_alphas_prev[:num_steps])
|
248 |
-
|
249 |
-
x_next = x0
|
250 |
-
intermediates = []
|
251 |
-
inter_steps = []
|
252 |
-
for i in tqdm(range(num_steps), desc='Encoding Image'):
|
253 |
-
t = torch.full((x0.shape[0],), timesteps[i], device=self.model.device, dtype=torch.long)
|
254 |
-
if unconditional_guidance_scale == 1.:
|
255 |
-
noise_pred = self.model.apply_model(x_next, t, c)
|
256 |
-
else:
|
257 |
-
assert unconditional_conditioning is not None
|
258 |
-
e_t_uncond, noise_pred = torch.chunk(
|
259 |
-
self.model.apply_model(torch.cat((x_next, x_next)), torch.cat((t, t)),
|
260 |
-
torch.cat((unconditional_conditioning, c))), 2)
|
261 |
-
noise_pred = e_t_uncond + unconditional_guidance_scale * (noise_pred - e_t_uncond)
|
262 |
-
|
263 |
-
xt_weighted = (alphas_next[i] / alphas[i]).sqrt() * x_next
|
264 |
-
weighted_noise_pred = alphas_next[i].sqrt() * (
|
265 |
-
(1 / alphas_next[i] - 1).sqrt() - (1 / alphas[i] - 1).sqrt()) * noise_pred
|
266 |
-
x_next = xt_weighted + weighted_noise_pred
|
267 |
-
if return_intermediates and i % (
|
268 |
-
num_steps // return_intermediates) == 0 and i < num_steps - 1:
|
269 |
-
intermediates.append(x_next)
|
270 |
-
inter_steps.append(i)
|
271 |
-
elif return_intermediates and i >= num_steps - 2:
|
272 |
-
intermediates.append(x_next)
|
273 |
-
inter_steps.append(i)
|
274 |
-
if callback: callback(i)
|
275 |
-
|
276 |
-
out = {'x_encoded': x_next, 'intermediate_steps': inter_steps}
|
277 |
-
if return_intermediates:
|
278 |
-
out.update({'intermediates': intermediates})
|
279 |
-
return x_next, out
|
280 |
-
|
281 |
-
@torch.no_grad()
|
282 |
-
def stochastic_encode(self, x0, t, use_original_steps=False, noise=None):
|
283 |
-
# fast, but does not allow for exact reconstruction
|
284 |
-
# t serves as an index to gather the correct alphas
|
285 |
-
if use_original_steps:
|
286 |
-
sqrt_alphas_cumprod = self.sqrt_alphas_cumprod
|
287 |
-
sqrt_one_minus_alphas_cumprod = self.sqrt_one_minus_alphas_cumprod
|
288 |
-
else:
|
289 |
-
sqrt_alphas_cumprod = torch.sqrt(self.ddim_alphas)
|
290 |
-
sqrt_one_minus_alphas_cumprod = self.ddim_sqrt_one_minus_alphas
|
291 |
-
|
292 |
-
if noise is None:
|
293 |
-
noise = torch.randn_like(x0)
|
294 |
-
return (extract_into_tensor(sqrt_alphas_cumprod, t, x0.shape) * x0 +
|
295 |
-
extract_into_tensor(sqrt_one_minus_alphas_cumprod, t, x0.shape) * noise)
|
296 |
-
|
297 |
-
@torch.no_grad()
|
298 |
-
def decode(self, x_latent, cond, t_start, unconditional_guidance_scale=1.0, unconditional_conditioning=None,
|
299 |
-
use_original_steps=False, callback=None):
|
300 |
-
|
301 |
-
timesteps = np.arange(self.ddpm_num_timesteps) if use_original_steps else self.ddim_timesteps
|
302 |
-
timesteps = timesteps[:t_start]
|
303 |
-
|
304 |
-
time_range = np.flip(timesteps)
|
305 |
-
total_steps = timesteps.shape[0]
|
306 |
-
print(f"Running DDIM Sampling with {total_steps} timesteps")
|
307 |
-
|
308 |
-
iterator = tqdm(time_range, desc='Decoding image', total=total_steps)
|
309 |
-
x_dec = x_latent
|
310 |
-
for i, step in enumerate(iterator):
|
311 |
-
index = total_steps - i - 1
|
312 |
-
ts = torch.full((x_latent.shape[0],), step, device=x_latent.device, dtype=torch.long)
|
313 |
-
x_dec, _ = self.p_sample_ddim(x_dec, cond, ts, index=index, use_original_steps=use_original_steps,
|
314 |
-
unconditional_guidance_scale=unconditional_guidance_scale,
|
315 |
-
unconditional_conditioning=unconditional_conditioning)
|
316 |
-
if callback: callback(i)
|
317 |
-
return x_dec
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
cldm/hack.py
DELETED
@@ -1,111 +0,0 @@
|
|
1 |
-
import torch
|
2 |
-
import einops
|
3 |
-
|
4 |
-
import ldm.modules.encoders.modules
|
5 |
-
import ldm.modules.attention
|
6 |
-
|
7 |
-
from transformers import logging
|
8 |
-
from ldm.modules.attention import default
|
9 |
-
|
10 |
-
|
11 |
-
def disable_verbosity():
|
12 |
-
logging.set_verbosity_error()
|
13 |
-
print('logging improved.')
|
14 |
-
return
|
15 |
-
|
16 |
-
|
17 |
-
def enable_sliced_attention():
|
18 |
-
ldm.modules.attention.CrossAttention.forward = _hacked_sliced_attentin_forward
|
19 |
-
print('Enabled sliced_attention.')
|
20 |
-
return
|
21 |
-
|
22 |
-
|
23 |
-
def hack_everything(clip_skip=0):
|
24 |
-
disable_verbosity()
|
25 |
-
ldm.modules.encoders.modules.FrozenCLIPEmbedder.forward = _hacked_clip_forward
|
26 |
-
ldm.modules.encoders.modules.FrozenCLIPEmbedder.clip_skip = clip_skip
|
27 |
-
print('Enabled clip hacks.')
|
28 |
-
return
|
29 |
-
|
30 |
-
|
31 |
-
# Written by Lvmin
|
32 |
-
def _hacked_clip_forward(self, text):
|
33 |
-
PAD = self.tokenizer.pad_token_id
|
34 |
-
EOS = self.tokenizer.eos_token_id
|
35 |
-
BOS = self.tokenizer.bos_token_id
|
36 |
-
|
37 |
-
def tokenize(t):
|
38 |
-
return self.tokenizer(t, truncation=False, add_special_tokens=False)["input_ids"]
|
39 |
-
|
40 |
-
def transformer_encode(t):
|
41 |
-
if self.clip_skip > 1:
|
42 |
-
rt = self.transformer(input_ids=t, output_hidden_states=True)
|
43 |
-
return self.transformer.text_model.final_layer_norm(rt.hidden_states[-self.clip_skip])
|
44 |
-
else:
|
45 |
-
return self.transformer(input_ids=t, output_hidden_states=False).last_hidden_state
|
46 |
-
|
47 |
-
def split(x):
|
48 |
-
return x[75 * 0: 75 * 1], x[75 * 1: 75 * 2], x[75 * 2: 75 * 3]
|
49 |
-
|
50 |
-
def pad(x, p, i):
|
51 |
-
return x[:i] if len(x) >= i else x + [p] * (i - len(x))
|
52 |
-
|
53 |
-
raw_tokens_list = tokenize(text)
|
54 |
-
tokens_list = []
|
55 |
-
|
56 |
-
for raw_tokens in raw_tokens_list:
|
57 |
-
raw_tokens_123 = split(raw_tokens)
|
58 |
-
raw_tokens_123 = [[BOS] + raw_tokens_i + [EOS] for raw_tokens_i in raw_tokens_123]
|
59 |
-
raw_tokens_123 = [pad(raw_tokens_i, PAD, 77) for raw_tokens_i in raw_tokens_123]
|
60 |
-
tokens_list.append(raw_tokens_123)
|
61 |
-
|
62 |
-
tokens_list = torch.IntTensor(tokens_list).to(self.device)
|
63 |
-
|
64 |
-
feed = einops.rearrange(tokens_list, 'b f i -> (b f) i')
|
65 |
-
y = transformer_encode(feed)
|
66 |
-
z = einops.rearrange(y, '(b f) i c -> b (f i) c', f=3)
|
67 |
-
|
68 |
-
return z
|
69 |
-
|
70 |
-
|
71 |
-
# Stolen from https://github.com/basujindal/stable-diffusion/blob/main/optimizedSD/splitAttention.py
|
72 |
-
def _hacked_sliced_attentin_forward(self, x, context=None, mask=None):
|
73 |
-
h = self.heads
|
74 |
-
|
75 |
-
q = self.to_q(x)
|
76 |
-
context = default(context, x)
|
77 |
-
k = self.to_k(context)
|
78 |
-
v = self.to_v(context)
|
79 |
-
del context, x
|
80 |
-
|
81 |
-
q, k, v = map(lambda t: einops.rearrange(t, 'b n (h d) -> (b h) n d', h=h), (q, k, v))
|
82 |
-
|
83 |
-
limit = k.shape[0]
|
84 |
-
att_step = 1
|
85 |
-
q_chunks = list(torch.tensor_split(q, limit // att_step, dim=0))
|
86 |
-
k_chunks = list(torch.tensor_split(k, limit // att_step, dim=0))
|
87 |
-
v_chunks = list(torch.tensor_split(v, limit // att_step, dim=0))
|
88 |
-
|
89 |
-
q_chunks.reverse()
|
90 |
-
k_chunks.reverse()
|
91 |
-
v_chunks.reverse()
|
92 |
-
sim = torch.zeros(q.shape[0], q.shape[1], v.shape[2], device=q.device)
|
93 |
-
del k, q, v
|
94 |
-
for i in range(0, limit, att_step):
|
95 |
-
q_buffer = q_chunks.pop()
|
96 |
-
k_buffer = k_chunks.pop()
|
97 |
-
v_buffer = v_chunks.pop()
|
98 |
-
sim_buffer = torch.einsum('b i d, b j d -> b i j', q_buffer, k_buffer) * self.scale
|
99 |
-
|
100 |
-
del k_buffer, q_buffer
|
101 |
-
# attention, what we cannot get enough of, by chunks
|
102 |
-
|
103 |
-
sim_buffer = sim_buffer.softmax(dim=-1)
|
104 |
-
|
105 |
-
sim_buffer = torch.einsum('b i j, b j d -> b i d', sim_buffer, v_buffer)
|
106 |
-
del v_buffer
|
107 |
-
sim[i:i + att_step, :, :] = sim_buffer
|
108 |
-
|
109 |
-
del sim_buffer
|
110 |
-
sim = einops.rearrange(sim, '(b h) n d -> b n (h d)', h=h)
|
111 |
-
return self.to_out(sim)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
cldm/logger.py
DELETED
@@ -1,76 +0,0 @@
|
|
1 |
-
import os
|
2 |
-
|
3 |
-
import numpy as np
|
4 |
-
import torch
|
5 |
-
import torchvision
|
6 |
-
from PIL import Image
|
7 |
-
from pytorch_lightning.callbacks import Callback
|
8 |
-
from pytorch_lightning.utilities.distributed import rank_zero_only
|
9 |
-
|
10 |
-
|
11 |
-
class ImageLogger(Callback):
|
12 |
-
def __init__(self, batch_frequency=2000, max_images=4, clamp=True, increase_log_steps=True,
|
13 |
-
rescale=True, disabled=False, log_on_batch_idx=False, log_first_step=False,
|
14 |
-
log_images_kwargs=None):
|
15 |
-
super().__init__()
|
16 |
-
self.rescale = rescale
|
17 |
-
self.batch_freq = batch_frequency
|
18 |
-
self.max_images = max_images
|
19 |
-
if not increase_log_steps:
|
20 |
-
self.log_steps = [self.batch_freq]
|
21 |
-
self.clamp = clamp
|
22 |
-
self.disabled = disabled
|
23 |
-
self.log_on_batch_idx = log_on_batch_idx
|
24 |
-
self.log_images_kwargs = log_images_kwargs if log_images_kwargs else {}
|
25 |
-
self.log_first_step = log_first_step
|
26 |
-
|
27 |
-
@rank_zero_only
|
28 |
-
def log_local(self, save_dir, split, images, global_step, current_epoch, batch_idx):
|
29 |
-
root = os.path.join(save_dir, "image_log", split)
|
30 |
-
for k in images:
|
31 |
-
grid = torchvision.utils.make_grid(images[k], nrow=4)
|
32 |
-
if self.rescale:
|
33 |
-
grid = (grid + 1.0) / 2.0 # -1,1 -> 0,1; c,h,w
|
34 |
-
grid = grid.transpose(0, 1).transpose(1, 2).squeeze(-1)
|
35 |
-
grid = grid.numpy()
|
36 |
-
grid = (grid * 255).astype(np.uint8)
|
37 |
-
filename = "{}_gs-{:06}_e-{:06}_b-{:06}.png".format(k, global_step, current_epoch, batch_idx)
|
38 |
-
path = os.path.join(root, filename)
|
39 |
-
os.makedirs(os.path.split(path)[0], exist_ok=True)
|
40 |
-
Image.fromarray(grid).save(path)
|
41 |
-
|
42 |
-
def log_img(self, pl_module, batch, batch_idx, split="train"):
|
43 |
-
check_idx = batch_idx # if self.log_on_batch_idx else pl_module.global_step
|
44 |
-
if (self.check_frequency(check_idx) and # batch_idx % self.batch_freq == 0
|
45 |
-
hasattr(pl_module, "log_images") and
|
46 |
-
callable(pl_module.log_images) and
|
47 |
-
self.max_images > 0):
|
48 |
-
logger = type(pl_module.logger)
|
49 |
-
|
50 |
-
is_train = pl_module.training
|
51 |
-
if is_train:
|
52 |
-
pl_module.eval()
|
53 |
-
|
54 |
-
with torch.no_grad():
|
55 |
-
images = pl_module.log_images(batch, split=split, **self.log_images_kwargs)
|
56 |
-
|
57 |
-
for k in images:
|
58 |
-
N = min(images[k].shape[0], self.max_images)
|
59 |
-
images[k] = images[k][:N]
|
60 |
-
if isinstance(images[k], torch.Tensor):
|
61 |
-
images[k] = images[k].detach().cpu()
|
62 |
-
if self.clamp:
|
63 |
-
images[k] = torch.clamp(images[k], -1., 1.)
|
64 |
-
|
65 |
-
self.log_local(pl_module.logger.save_dir, split, images,
|
66 |
-
pl_module.global_step, pl_module.current_epoch, batch_idx)
|
67 |
-
|
68 |
-
if is_train:
|
69 |
-
pl_module.train()
|
70 |
-
|
71 |
-
def check_frequency(self, check_idx):
|
72 |
-
return check_idx % self.batch_freq == 0
|
73 |
-
|
74 |
-
def on_train_batch_end(self, trainer, pl_module, outputs, batch, batch_idx, dataloader_idx):
|
75 |
-
if not self.disabled:
|
76 |
-
self.log_img(pl_module, batch, batch_idx, split="train")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
cldm/model.py
DELETED
@@ -1,28 +0,0 @@
|
|
1 |
-
import os
|
2 |
-
import torch
|
3 |
-
|
4 |
-
from omegaconf import OmegaConf
|
5 |
-
from ldm.util import instantiate_from_config
|
6 |
-
|
7 |
-
|
8 |
-
def get_state_dict(d):
|
9 |
-
return d.get('state_dict', d)
|
10 |
-
|
11 |
-
|
12 |
-
def load_state_dict(ckpt_path, location='cpu'):
|
13 |
-
_, extension = os.path.splitext(ckpt_path)
|
14 |
-
if extension.lower() == ".safetensors":
|
15 |
-
import safetensors.torch
|
16 |
-
state_dict = safetensors.torch.load_file(ckpt_path, device=location)
|
17 |
-
else:
|
18 |
-
state_dict = get_state_dict(torch.load(ckpt_path, map_location=torch.device(location)))
|
19 |
-
state_dict = get_state_dict(state_dict)
|
20 |
-
print(f'Loaded state_dict from [{ckpt_path}]')
|
21 |
-
return state_dict
|
22 |
-
|
23 |
-
|
24 |
-
def create_model(config_path):
|
25 |
-
config = OmegaConf.load(config_path)
|
26 |
-
model = instantiate_from_config(config.model).cpu()
|
27 |
-
print(f'Loaded model config from [{config_path}]')
|
28 |
-
return model
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|