Hang Zhou commited on
Commit
9756ed1
·
verified ·
1 Parent(s): 39fac4c

Upload folder using huggingface_hub

Browse files
Files changed (5) hide show
  1. cldm/cldm.py +472 -0
  2. cldm/ddim_hacked.py +320 -0
  3. cldm/hack.py +111 -0
  4. cldm/logger.py +76 -0
  5. cldm/model.py +28 -0
cldm/cldm.py ADDED
@@ -0,0 +1,472 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import einops
2
+ import torch
3
+ import torch as th
4
+ import torch.nn as nn
5
+ import torch.nn.functional as F
6
+ from ldm.modules.diffusionmodules.util import (
7
+ conv_nd,
8
+ linear,
9
+ zero_module,
10
+ timestep_embedding,
11
+ )
12
+ from einops import rearrange, repeat
13
+ from torchvision.utils import make_grid
14
+ from ldm.modules.attention import SpatialTransformer
15
+ from ldm.modules.diffusionmodules.openaimodel import UNetModel, TimestepEmbedSequential, ResBlock, Downsample, AttentionBlock
16
+ from ldm.models.diffusion.ddpm import LatentDiffusion
17
+ from ldm.util import exists, instantiate_from_config
18
+ from ldm.models.diffusion.ddim import DDIMSampler
19
+
20
+ def scale_mask(m, target_h):
21
+ m_resized = F.interpolate(m.permute(0, 3, 1, 2).float(), size=target_h, mode='nearest')
22
+ return m_resized.permute(0, 2, 3, 1).unsqueeze(1)
23
+
24
+ class ControlledUnetModel(UNetModel):
25
+ def forward(self, x, timesteps=None, context=None, control=None, only_mid_control=False, c_mask=None, **kwargs):
26
+ hs = []
27
+
28
+ with torch.no_grad():
29
+ t_emb = timestep_embedding(timesteps, self.model_channels, repeat_only=False)
30
+ emb = self.time_embed(t_emb)
31
+ h = x.type(self.dtype)
32
+
33
+ for module in self.input_blocks:
34
+ m_emb = scale_mask(c_mask, h.shape[2:4])
35
+ h = module(h, emb, context, m_emb)
36
+ hs.append(h)
37
+
38
+ m_emb = scale_mask(c_mask, h.shape[2:4])
39
+ h = self.middle_block(h, emb, context, m_emb)
40
+
41
+ if control is not None:
42
+ h += control.pop()
43
+
44
+ for i, module in enumerate(self.output_blocks):
45
+ h = torch.cat([h, hs.pop() + (control.pop() if (control and not only_mid_control) else 0)], dim=1)
46
+ m_emb = scale_mask(c_mask, h.shape[2:4])
47
+ h = module(h, emb, context, m_emb)
48
+
49
+ return self.out(h.type(x.dtype))
50
+
51
+
52
+ class ControlNet(nn.Module):
53
+ def __init__(
54
+ self,
55
+ image_size,
56
+ in_channels,
57
+ model_channels,
58
+ hint_channels,
59
+ num_res_blocks,
60
+ attention_resolutions,
61
+ dropout=0,
62
+ channel_mult=(1, 2, 4, 8),
63
+ conv_resample=True,
64
+ dims=2,
65
+ use_checkpoint=False,
66
+ use_fp16=False,
67
+ num_heads=-1,
68
+ num_head_channels=-1,
69
+ num_heads_upsample=-1,
70
+ use_scale_shift_norm=False,
71
+ resblock_updown=False,
72
+ use_new_attention_order=False,
73
+ use_spatial_transformer=False, # custom transformer support
74
+ transformer_depth=1, # custom transformer support
75
+ context_dim=None, # custom transformer support
76
+ n_embed=None, # custom support for prediction of discrete ids into codebook of first stage vq model
77
+ legacy=True,
78
+ disable_self_attentions=None,
79
+ num_attention_blocks=None,
80
+ disable_middle_self_attn=False,
81
+ use_linear_in_transformer=False,
82
+ ):
83
+ super().__init__()
84
+ if use_spatial_transformer:
85
+ assert context_dim is not None, 'Fool!! You forgot to include the dimension of your cross-attention conditioning...'
86
+
87
+ if context_dim is not None:
88
+ assert use_spatial_transformer, 'Fool!! You forgot to use the spatial transformer for your cross-attention conditioning...'
89
+ from omegaconf.listconfig import ListConfig
90
+ if type(context_dim) == ListConfig:
91
+ context_dim = list(context_dim)
92
+
93
+ if num_heads_upsample == -1:
94
+ num_heads_upsample = num_heads
95
+
96
+ if num_heads == -1:
97
+ assert num_head_channels != -1, 'Either num_heads or num_head_channels has to be set'
98
+
99
+ if num_head_channels == -1:
100
+ assert num_heads != -1, 'Either num_heads or num_head_channels has to be set'
101
+
102
+ self.dims = dims
103
+ self.image_size = image_size
104
+ self.in_channels = in_channels
105
+ self.model_channels = model_channels
106
+ self.use_spatial_transformer = use_spatial_transformer
107
+ if isinstance(num_res_blocks, int):
108
+ self.num_res_blocks = len(channel_mult) * [num_res_blocks]
109
+ else:
110
+ if len(num_res_blocks) != len(channel_mult):
111
+ raise ValueError("provide num_res_blocks either as an int (globally constant) or "
112
+ "as a list/tuple (per-level) with the same length as channel_mult")
113
+ self.num_res_blocks = num_res_blocks
114
+ if disable_self_attentions is not None:
115
+ # should be a list of booleans, indicating whether to disable self-attention in TransformerBlocks or not
116
+ assert len(disable_self_attentions) == len(channel_mult)
117
+ if num_attention_blocks is not None:
118
+ assert len(num_attention_blocks) == len(self.num_res_blocks)
119
+ assert all(map(lambda i: self.num_res_blocks[i] >= num_attention_blocks[i], range(len(num_attention_blocks))))
120
+ print(f"Constructor of UNetModel received num_attention_blocks={num_attention_blocks}. "
121
+ f"This option has LESS priority than attention_resolutions {attention_resolutions}, "
122
+ f"i.e., in cases where num_attention_blocks[i] > 0 but 2**i not in attention_resolutions, "
123
+ f"attention will still not be set.")
124
+
125
+ self.attention_resolutions = attention_resolutions
126
+ self.dropout = dropout
127
+ self.channel_mult = channel_mult
128
+ self.conv_resample = conv_resample
129
+ self.use_checkpoint = use_checkpoint
130
+ self.dtype = th.float16 if use_fp16 else th.float32
131
+ self.num_heads = num_heads
132
+ self.num_head_channels = num_head_channels
133
+ self.num_heads_upsample = num_heads_upsample
134
+ self.predict_codebook_ids = n_embed is not None
135
+
136
+ time_embed_dim = model_channels * 4
137
+ self.time_embed = nn.Sequential(
138
+ linear(model_channels, time_embed_dim),
139
+ nn.SiLU(),
140
+ linear(time_embed_dim, time_embed_dim),
141
+ )
142
+
143
+ self.input_blocks = nn.ModuleList(
144
+ [
145
+ TimestepEmbedSequential(
146
+ conv_nd(dims, in_channels, model_channels, 3, padding=1)
147
+ )
148
+ ]
149
+ )
150
+ self.zero_convs = nn.ModuleList([self.make_zero_conv(model_channels)])
151
+
152
+ self.input_hint_block = TimestepEmbedSequential(
153
+ conv_nd(dims, hint_channels, 16, 3, padding=1),
154
+ nn.SiLU(),
155
+ conv_nd(dims, 16, 16, 3, padding=1),
156
+ nn.SiLU(),
157
+ conv_nd(dims, 16, 32, 3, padding=1, stride=2),
158
+ nn.SiLU(),
159
+ conv_nd(dims, 32, 32, 3, padding=1),
160
+ nn.SiLU(),
161
+ conv_nd(dims, 32, 96, 3, padding=1, stride=2),
162
+ nn.SiLU(),
163
+ conv_nd(dims, 96, 96, 3, padding=1),
164
+ nn.SiLU(),
165
+ conv_nd(dims, 96, 256, 3, padding=1, stride=2),
166
+ nn.SiLU(),
167
+ zero_module(conv_nd(dims, 256, model_channels, 3, padding=1))
168
+ )
169
+
170
+ self._feature_size = model_channels
171
+ input_block_chans = [model_channels]
172
+ ch = model_channels
173
+ ds = 1
174
+ for level, mult in enumerate(channel_mult):
175
+ for nr in range(self.num_res_blocks[level]):
176
+ layers = [
177
+ ResBlock(
178
+ ch,
179
+ time_embed_dim,
180
+ dropout,
181
+ out_channels=mult * model_channels,
182
+ dims=dims,
183
+ use_checkpoint=use_checkpoint,
184
+ use_scale_shift_norm=use_scale_shift_norm,
185
+ )
186
+ ]
187
+ ch = mult * model_channels
188
+ if ds in attention_resolutions:
189
+ if num_head_channels == -1:
190
+ dim_head = ch // num_heads
191
+ else:
192
+ num_heads = ch // num_head_channels
193
+ dim_head = num_head_channels
194
+ if legacy:
195
+ # num_heads = 1
196
+ dim_head = ch // num_heads if use_spatial_transformer else num_head_channels
197
+ if exists(disable_self_attentions):
198
+ disabled_sa = disable_self_attentions[level]
199
+ else:
200
+ disabled_sa = False
201
+
202
+ if not exists(num_attention_blocks) or nr < num_attention_blocks[level]:
203
+ layers.append(
204
+ AttentionBlock(
205
+ ch,
206
+ use_checkpoint=use_checkpoint,
207
+ num_heads=num_heads,
208
+ num_head_channels=dim_head,
209
+ use_new_attention_order=use_new_attention_order,
210
+ ) if not use_spatial_transformer else SpatialTransformer(
211
+ ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim,
212
+ disable_self_attn=disabled_sa, use_linear=use_linear_in_transformer,
213
+ use_checkpoint=use_checkpoint
214
+ )
215
+ )
216
+ self.input_blocks.append(TimestepEmbedSequential(*layers))
217
+ self.zero_convs.append(self.make_zero_conv(ch))
218
+ self._feature_size += ch
219
+ input_block_chans.append(ch)
220
+ if level != len(channel_mult) - 1:
221
+ out_ch = ch
222
+ self.input_blocks.append(
223
+ TimestepEmbedSequential(
224
+ ResBlock(
225
+ ch,
226
+ time_embed_dim,
227
+ dropout,
228
+ out_channels=out_ch,
229
+ dims=dims,
230
+ use_checkpoint=use_checkpoint,
231
+ use_scale_shift_norm=use_scale_shift_norm,
232
+ down=True,
233
+ )
234
+ if resblock_updown
235
+ else Downsample(
236
+ ch, conv_resample, dims=dims, out_channels=out_ch
237
+ )
238
+ )
239
+ )
240
+ ch = out_ch
241
+ input_block_chans.append(ch)
242
+ self.zero_convs.append(self.make_zero_conv(ch))
243
+ ds *= 2
244
+ self._feature_size += ch
245
+
246
+ if num_head_channels == -1:
247
+ dim_head = ch // num_heads
248
+ else:
249
+ num_heads = ch // num_head_channels
250
+ dim_head = num_head_channels
251
+ if legacy:
252
+ # num_heads = 1
253
+ dim_head = ch // num_heads if use_spatial_transformer else num_head_channels
254
+ self.middle_block = TimestepEmbedSequential(
255
+ ResBlock(
256
+ ch,
257
+ time_embed_dim,
258
+ dropout,
259
+ dims=dims,
260
+ use_checkpoint=use_checkpoint,
261
+ use_scale_shift_norm=use_scale_shift_norm,
262
+ ),
263
+ AttentionBlock(
264
+ ch,
265
+ use_checkpoint=use_checkpoint,
266
+ num_heads=num_heads,
267
+ num_head_channels=dim_head,
268
+ use_new_attention_order=use_new_attention_order,
269
+ ) if not use_spatial_transformer else SpatialTransformer( # always uses a self-attn
270
+ ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim,
271
+ disable_self_attn=disable_middle_self_attn, use_linear=use_linear_in_transformer,
272
+ use_checkpoint=use_checkpoint
273
+ ),
274
+ ResBlock(
275
+ ch,
276
+ time_embed_dim,
277
+ dropout,
278
+ dims=dims,
279
+ use_checkpoint=use_checkpoint,
280
+ use_scale_shift_norm=use_scale_shift_norm,
281
+ ),
282
+ )
283
+ self.middle_block_out = self.make_zero_conv(ch)
284
+ self._feature_size += ch
285
+
286
+ def make_zero_conv(self, channels):
287
+ return TimestepEmbedSequential(zero_module(conv_nd(self.dims, channels, channels, 1, padding=0)))
288
+
289
+ def forward(self, x, hint, timesteps, context, c_mask, **kwargs):
290
+ t_emb = timestep_embedding(timesteps, self.model_channels, repeat_only=False)
291
+ emb = self.time_embed(t_emb)
292
+
293
+ m_emb = scale_mask(c_mask, x.shape[2:4])
294
+ guided_hint = self.input_hint_block(hint, emb, context, m_emb) # only encode hint
295
+
296
+ outs = []
297
+
298
+ h = x.type(self.dtype)
299
+ for module, zero_conv in zip(self.input_blocks, self.zero_convs):
300
+ if guided_hint is not None:
301
+ # skip the first layer
302
+ h = guided_hint
303
+ guided_hint = None
304
+ else:
305
+ m_emb = scale_mask(c_mask, h.shape[2:4])
306
+ h_new = module(h, emb, context, m_emb)
307
+ h = h_new
308
+ outs.append(zero_conv(h, emb, context, m_emb))
309
+
310
+ m_emb = scale_mask(c_mask, h.shape[2:4])
311
+ h_new = self.middle_block(h, emb, context, m_emb)
312
+ m_emb = scale_mask(c_mask, h.shape[2:4])
313
+ outs.append(self.middle_block_out(h_new, emb, context, m_emb))
314
+ return outs
315
+
316
+
317
+ class ControlLDM(LatentDiffusion):
318
+
319
+ def __init__(self, control_stage_config, control_key, only_mid_control, *args, **kwargs):
320
+ super().__init__(*args, **kwargs)
321
+ self.control_model = instantiate_from_config(control_stage_config)
322
+ self.control_key = control_key
323
+ self.only_mid_control = only_mid_control
324
+ self.control_scales = [1.0] * 13
325
+
326
+ @torch.no_grad()
327
+ def get_input(self, batch, k, bs=None, *args, **kwargs):
328
+ '''
329
+ get raw inputs from dataloader:
330
+ x_orig: source image: [N, 4, 64, 64], range: [-3.0823, 2.6057]
331
+ dict(
332
+ c_pch: patch sequence: [N, 2, 257, 1024], range: [-3.7422, 4.2695]
333
+ x_back: background: [N, 512, 512, 4], range: [-1, 1]
334
+ c_mask: mask: [N, 512, 512, 2], range: [0, 1]
335
+ )
336
+ '''
337
+ x_orig, c_pch, c_mask = super().get_input(batch, self.first_stage_key, *args, **kwargs) # obtain source image and object patch
338
+ x_back = batch[self.control_key] # obtain condition image (hint)
339
+
340
+ if bs is not None:
341
+ x_back = x_back[:bs]
342
+ x_back = x_back.to(self.device)
343
+ x_back = einops.rearrange(x_back, 'b h w c -> b c h w')
344
+ x_back = x_back.to(memory_format=torch.contiguous_format).float()
345
+ self.time_steps = batch['time_steps']
346
+ return x_orig, dict(c_crossattn=[c_pch], c_concat=[x_back], c_mask=[c_mask])
347
+
348
+ def apply_model(self, x_noisy, t, cond, *args, **kwargs):
349
+ assert isinstance(cond, dict)
350
+ diffusion_model = self.model.diffusion_model
351
+
352
+ cond_txt = cond['c_crossattn'][0]['pch_code']
353
+ hint = torch.cat(cond['c_concat'], 1)
354
+ c_mask = torch.cat(cond['c_mask'], 1)
355
+ c_mask = c_mask.squeeze(1)
356
+
357
+ if cond['c_concat'] is None:
358
+ eps = diffusion_model(x=x_noisy, timesteps=t, context=cond_txt, control=None, only_mid_control=self.only_mid_control)
359
+ else:
360
+ control = self.control_model(x=x_noisy, hint=hint, timesteps=t, context=cond_txt, c_mask=c_mask)
361
+ control = [c * scale for c, scale in zip(control, self.control_scales)]
362
+ eps = diffusion_model(x=x_noisy, timesteps=t, context=cond_txt, control=control, only_mid_control=self.only_mid_control, c_mask=c_mask)
363
+ return eps
364
+
365
+ @torch.no_grad()
366
+ def get_unconditional_conditioning(self, N, obj_thr):
367
+ x = [torch.zeros((1, 3, 224, 224)).to(self.device)] * N
368
+ single_uc = self.get_learned_conditioning(x)
369
+ uc = single_uc.unsqueeze(-1).repeat(1, 1, 1, obj_thr)
370
+ return uc
371
+
372
+ @torch.no_grad()
373
+ def log_images(self, batch, N=4, n_row=2, sample=False, ddim_steps=50, ddim_eta=0.0, return_keys=None,
374
+ quantize_denoised=True, inpaint=True, plot_denoise_rows=False, plot_progressive_rows=True,
375
+ plot_diffusion_rows=False, unconditional_guidance_scale=9.0, unconditional_guidance_label=None,
376
+ use_ema_scope=True,
377
+ **kwargs):
378
+ use_ddim = ddim_steps is not None
379
+
380
+ log = dict()
381
+ z, c = self.get_input(batch, self.first_stage_key, bs=N)
382
+
383
+ c_cat, c, c_mask = c["c_concat"][0][:N], c["c_crossattn"][0], c["c_mask"][0][:N]
384
+ c = {k: v[:4] for k, v in c.items()}
385
+ N = min(z.shape[0], N)
386
+
387
+ n_row = min(z.shape[0], n_row)
388
+ log["reconstruction"] = self.decode_first_stage(z)
389
+
390
+ guide_mask = (c_cat[:, -1, :, :].unsqueeze(1) + 1) * 0.5
391
+ guide_mask = torch.cat([guide_mask, guide_mask, guide_mask], 1)
392
+ log["control"] = c_cat[:,:3,:,:]
393
+
394
+ cond_image0 = batch[self.cond_stage_key+'0'].cpu().numpy().copy()
395
+ cond_image1 = batch[self.cond_stage_key+'1'].cpu().numpy().copy()
396
+ t0 = torch.permute(torch.tensor(cond_image0), (0,3,1,2)) * 2.0 - 1.0
397
+ t1 = torch.permute(torch.tensor(cond_image1), (0,3,1,2)) * 2.0 - 1.0
398
+ log["conditioning"] = torch.cat([t0, t1], dim=0)
399
+
400
+ if plot_diffusion_rows:
401
+ # get diffusion row
402
+ diffusion_row = list()
403
+ z_start = z[:n_row]
404
+ for t in range(self.num_timesteps):
405
+ if t % self.log_every_t == 0 or t == self.num_timesteps - 1:
406
+ t = repeat(torch.tensor([t]), '1 -> b', b=n_row)
407
+ t = t.to(self.device).long()
408
+ noise = torch.randn_like(z_start)
409
+ z_noisy = self.q_sample(x_start=z_start, t=t, noise=noise)
410
+ diffusion_row.append(self.decode_first_stage(z_noisy))
411
+
412
+ diffusion_row = torch.stack(diffusion_row) # n_log_step, n_row, C, H, W
413
+ diffusion_grid = rearrange(diffusion_row, 'n b c h w -> b n c h w')
414
+ diffusion_grid = rearrange(diffusion_grid, 'b n c h w -> (b n) c h w')
415
+ diffusion_grid = make_grid(diffusion_grid, nrow=diffusion_row.shape[0])
416
+ log["diffusion_row"] = diffusion_grid
417
+
418
+ if sample:
419
+ # get denoise row
420
+ samples, z_denoise_row = self.sample_log(cond={"c_concat": [c_cat], "c_crossattn": [c], "c_mask": [c_mask]},
421
+ batch_size=N, ddim=use_ddim,
422
+ ddim_steps=ddim_steps, eta=ddim_eta)
423
+ x_samples = self.decode_first_stage(samples)
424
+ log["samples"] = x_samples
425
+ if plot_denoise_rows:
426
+ denoise_grid = self._get_denoise_row_from_list(z_denoise_row)
427
+ log["denoise_row"] = denoise_grid
428
+
429
+ if unconditional_guidance_scale > 1.0:
430
+ obj_thr = kwargs.get('obj_thr', 1)
431
+ uc_cross = self.get_unconditional_conditioning(N, obj_thr)
432
+ uc_cat = c_cat # torch.zeros_like(c_cat)
433
+ uc_full = {"c_concat": [uc_cat], "c_crossattn": [uc_cross], "c_mask": [c_mask]}
434
+ samples_cfg, _ = self.sample_log(cond={"c_concat": [c_cat], "c_crossattn": [c], "c_mask": [c_mask]},
435
+ batch_size=N, ddim=use_ddim,
436
+ ddim_steps=ddim_steps, eta=ddim_eta,
437
+ unconditional_guidance_scale=unconditional_guidance_scale,
438
+ unconditional_conditioning=uc_full,
439
+ )
440
+ x_samples_cfg = self.decode_first_stage(samples_cfg)
441
+ log[f"samples_cfg_scale_{unconditional_guidance_scale:.2f}"] = x_samples_cfg
442
+ return log
443
+
444
+ @torch.no_grad()
445
+ def sample_log(self, cond, batch_size, ddim, ddim_steps, **kwargs):
446
+ ddim_sampler = DDIMSampler(self)
447
+ b, c, h, w = cond["c_concat"][0].shape
448
+ shape = (self.channels, h // 8, w // 8)
449
+ samples, intermediates = ddim_sampler.sample(ddim_steps, batch_size, shape, cond, verbose=False, **kwargs)
450
+ return samples, intermediates
451
+
452
+ def configure_optimizers(self):
453
+ lr = self.learning_rate
454
+ params = list(self.control_model.parameters())
455
+ if not self.sd_locked:
456
+ params += list(self.model.diffusion_model.output_blocks.parameters())
457
+ params += list(self.model.diffusion_model.out.parameters())
458
+ params += list(self.cond_stage_model.projector.parameters())
459
+ opt = torch.optim.AdamW(params, lr=lr)
460
+ return opt
461
+
462
+ def low_vram_shift(self, is_diffusing):
463
+ if is_diffusing:
464
+ self.model = self.model.cuda()
465
+ self.control_model = self.control_model.cuda()
466
+ self.first_stage_model = self.first_stage_model.cpu()
467
+ self.cond_stage_model = self.cond_stage_model.cpu()
468
+ else:
469
+ self.model = self.model.cpu()
470
+ self.control_model = self.control_model.cpu()
471
+ self.first_stage_model = self.first_stage_model.cuda()
472
+ self.cond_stage_model = self.cond_stage_model.cuda()
cldm/ddim_hacked.py ADDED
@@ -0,0 +1,320 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ #x_T 1,4,64,64
133
+ if x_T is None:
134
+ img = torch.randn(shape, device=device)
135
+ else:
136
+ img = x_T
137
+
138
+ if timesteps is None:
139
+ timesteps = self.ddpm_num_timesteps if ddim_use_original_steps else self.ddim_timesteps
140
+ elif timesteps is not None and not ddim_use_original_steps:
141
+ subset_end = int(min(timesteps / self.ddim_timesteps.shape[0], 1) * self.ddim_timesteps.shape[0]) - 1
142
+ timesteps = self.ddim_timesteps[:subset_end]
143
+
144
+ intermediates = {'x_inter': [img], 'pred_x0': [img]}
145
+ time_range = reversed(range(0,timesteps)) if ddim_use_original_steps else np.flip(timesteps)
146
+ total_steps = timesteps if ddim_use_original_steps else timesteps.shape[0]
147
+ print(f"Running DDIM Sampling with {total_steps} timesteps")
148
+
149
+ iterator = tqdm(time_range, desc='DDIM Sampler', total=total_steps)
150
+
151
+ for i, step in enumerate(iterator):
152
+ index = total_steps - i - 1
153
+ ts = torch.full((b,), step, device=device, dtype=torch.long)
154
+
155
+ if mask is not None:
156
+ assert x0 is not None
157
+ img_orig = self.model.q_sample(x0, ts) # TODO: deterministic forward pass?
158
+ img = img_orig * mask + (1. - mask) * img
159
+
160
+ if ucg_schedule is not None:
161
+ assert len(ucg_schedule) == len(time_range)
162
+ unconditional_guidance_scale = ucg_schedule[i]
163
+
164
+ outs = self.p_sample_ddim(img, cond, ts, index=index, use_original_steps=ddim_use_original_steps,
165
+ quantize_denoised=quantize_denoised, temperature=temperature,
166
+ noise_dropout=noise_dropout, score_corrector=score_corrector,
167
+ corrector_kwargs=corrector_kwargs,
168
+ unconditional_guidance_scale=unconditional_guidance_scale,
169
+ unconditional_conditioning=unconditional_conditioning,
170
+ dynamic_threshold=dynamic_threshold)
171
+ img, pred_x0 = outs
172
+ if callback: callback(i)
173
+ if img_callback: img_callback(pred_x0, i)
174
+
175
+ if index % log_every_t == 0 or index == total_steps - 1:
176
+ intermediates['x_inter'].append(img)
177
+ intermediates['pred_x0'].append(pred_x0)
178
+
179
+ return img, intermediates
180
+
181
+ @torch.no_grad()
182
+ def p_sample_ddim(self, x, c, t, index, repeat_noise=False, use_original_steps=False, quantize_denoised=False,
183
+ temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None,
184
+ unconditional_guidance_scale=1., unconditional_conditioning=None,
185
+ dynamic_threshold=None):
186
+ b, *_, device = *x.shape, x.device
187
+
188
+ if unconditional_conditioning is None or unconditional_guidance_scale == 1.:
189
+ model_output = self.model.apply_model(x, t, c)
190
+ else:
191
+ model_t = self.model.apply_model(x, t, c)
192
+ # print(unconditional_conditioning)
193
+ # import pdb; pdb.set_trace()
194
+ model_uncond = self.model.apply_model(x, t, unconditional_conditioning)
195
+ model_output = model_uncond + unconditional_guidance_scale * (model_t - model_uncond)
196
+
197
+ if self.model.parameterization == "v":
198
+ e_t = self.model.predict_eps_from_z_and_v(x, t, model_output)
199
+ else:
200
+ e_t = model_output
201
+
202
+ if score_corrector is not None:
203
+ assert self.model.parameterization == "eps", 'not implemented'
204
+ e_t = score_corrector.modify_score(self.model, e_t, x, t, c, **corrector_kwargs)
205
+
206
+ alphas = self.model.alphas_cumprod if use_original_steps else self.ddim_alphas
207
+ alphas_prev = self.model.alphas_cumprod_prev if use_original_steps else self.ddim_alphas_prev
208
+ sqrt_one_minus_alphas = self.model.sqrt_one_minus_alphas_cumprod if use_original_steps else self.ddim_sqrt_one_minus_alphas
209
+ sigmas = self.model.ddim_sigmas_for_original_num_steps if use_original_steps else self.ddim_sigmas
210
+ # select parameters corresponding to the currently considered timestep
211
+ a_t = torch.full((b, 1, 1, 1), alphas[index], device=device)
212
+ a_prev = torch.full((b, 1, 1, 1), alphas_prev[index], device=device)
213
+ sigma_t = torch.full((b, 1, 1, 1), sigmas[index], device=device)
214
+ sqrt_one_minus_at = torch.full((b, 1, 1, 1), sqrt_one_minus_alphas[index],device=device)
215
+
216
+ # current prediction for x_0
217
+ if self.model.parameterization != "v":
218
+ pred_x0 = (x - sqrt_one_minus_at * e_t) / a_t.sqrt()
219
+ else:
220
+ pred_x0 = self.model.predict_start_from_z_and_v(x, t, model_output)
221
+
222
+ if quantize_denoised:
223
+ pred_x0, _, *_ = self.model.first_stage_model.quantize(pred_x0)
224
+
225
+ if dynamic_threshold is not None:
226
+ raise NotImplementedError()
227
+
228
+ # direction pointing to x_t
229
+ dir_xt = (1. - a_prev - sigma_t**2).sqrt() * e_t
230
+ noise = sigma_t * noise_like(x.shape, device, repeat_noise) * temperature
231
+ if noise_dropout > 0.:
232
+ noise = torch.nn.functional.dropout(noise, p=noise_dropout)
233
+ x_prev = a_prev.sqrt() * pred_x0 + dir_xt + noise
234
+ return x_prev, pred_x0
235
+
236
+ @torch.no_grad()
237
+ def encode(self, x0, c, t_enc, use_original_steps=False, return_intermediates=None,
238
+ unconditional_guidance_scale=1.0, unconditional_conditioning=None, callback=None):
239
+ timesteps = np.arange(self.ddpm_num_timesteps) if use_original_steps else self.ddim_timesteps
240
+ num_reference_steps = timesteps.shape[0]
241
+
242
+ assert t_enc <= num_reference_steps
243
+ num_steps = t_enc
244
+
245
+ if use_original_steps:
246
+ alphas_next = self.alphas_cumprod[:num_steps]
247
+ alphas = self.alphas_cumprod_prev[:num_steps]
248
+ else:
249
+ alphas_next = self.ddim_alphas[:num_steps]
250
+ alphas = torch.tensor(self.ddim_alphas_prev[:num_steps])
251
+
252
+ x_next = x0
253
+ intermediates = []
254
+ inter_steps = []
255
+ for i in tqdm(range(num_steps), desc='Encoding Image'):
256
+ t = torch.full((x0.shape[0],), timesteps[i], device=self.model.device, dtype=torch.long)
257
+ if unconditional_guidance_scale == 1.:
258
+ noise_pred = self.model.apply_model(x_next, t, c)
259
+ else:
260
+ assert unconditional_conditioning is not None
261
+ e_t_uncond, noise_pred = torch.chunk(
262
+ self.model.apply_model(torch.cat((x_next, x_next)), torch.cat((t, t)),
263
+ torch.cat((unconditional_conditioning, c))), 2)
264
+ noise_pred = e_t_uncond + unconditional_guidance_scale * (noise_pred - e_t_uncond)
265
+
266
+ xt_weighted = (alphas_next[i] / alphas[i]).sqrt() * x_next
267
+ weighted_noise_pred = alphas_next[i].sqrt() * (
268
+ (1 / alphas_next[i] - 1).sqrt() - (1 / alphas[i] - 1).sqrt()) * noise_pred
269
+ x_next = xt_weighted + weighted_noise_pred
270
+ if return_intermediates and i % (
271
+ num_steps // return_intermediates) == 0 and i < num_steps - 1:
272
+ intermediates.append(x_next)
273
+ inter_steps.append(i)
274
+ elif return_intermediates and i >= num_steps - 2:
275
+ intermediates.append(x_next)
276
+ inter_steps.append(i)
277
+ if callback: callback(i)
278
+
279
+ out = {'x_encoded': x_next, 'intermediate_steps': inter_steps}
280
+ if return_intermediates:
281
+ out.update({'intermediates': intermediates})
282
+ return x_next, out
283
+
284
+ @torch.no_grad()
285
+ def stochastic_encode(self, x0, t, use_original_steps=False, noise=None):
286
+ # fast, but does not allow for exact reconstruction
287
+ # t serves as an index to gather the correct alphas
288
+ if use_original_steps:
289
+ sqrt_alphas_cumprod = self.sqrt_alphas_cumprod
290
+ sqrt_one_minus_alphas_cumprod = self.sqrt_one_minus_alphas_cumprod
291
+ else:
292
+ sqrt_alphas_cumprod = torch.sqrt(self.ddim_alphas)
293
+ sqrt_one_minus_alphas_cumprod = self.ddim_sqrt_one_minus_alphas
294
+
295
+ if noise is None:
296
+ noise = torch.randn_like(x0)
297
+ return (extract_into_tensor(sqrt_alphas_cumprod, t, x0.shape) * x0 +
298
+ extract_into_tensor(sqrt_one_minus_alphas_cumprod, t, x0.shape) * noise)
299
+
300
+ @torch.no_grad()
301
+ def decode(self, x_latent, cond, t_start, unconditional_guidance_scale=1.0, unconditional_conditioning=None,
302
+ use_original_steps=False, callback=None):
303
+
304
+ timesteps = np.arange(self.ddpm_num_timesteps) if use_original_steps else self.ddim_timesteps
305
+ timesteps = timesteps[:t_start]
306
+
307
+ time_range = np.flip(timesteps)
308
+ total_steps = timesteps.shape[0]
309
+ print(f"Running DDIM Sampling with {total_steps} timesteps")
310
+
311
+ iterator = tqdm(time_range, desc='Decoding image', total=total_steps)
312
+ x_dec = x_latent
313
+ for i, step in enumerate(iterator):
314
+ index = total_steps - i - 1
315
+ ts = torch.full((x_latent.shape[0],), step, device=x_latent.device, dtype=torch.long)
316
+ x_dec, _ = self.p_sample_ddim(x_dec, cond, ts, index=index, use_original_steps=use_original_steps,
317
+ unconditional_guidance_scale=unconditional_guidance_scale,
318
+ unconditional_conditioning=unconditional_conditioning)
319
+ if callback: callback(i)
320
+ return x_dec
cldm/hack.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 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):
75
+ if not self.disabled:
76
+ self.log_img(pl_module, batch, batch_idx, split="train")
cldm/model.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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