Spaces:
Running
on
Zero
Running
on
Zero
Upload 9 files
#1
by
xywwww
- opened
- cldm/__pycache__/cldm.cpython-38.pyc +0 -0
- cldm/__pycache__/ddim_hacked.cpython-38.pyc +0 -0
- cldm/__pycache__/hack.cpython-38.pyc +0 -0
- cldm/__pycache__/model.cpython-38.pyc +0 -0
- cldm/cldm.py +470 -0
- cldm/ddim_hacked.py +317 -0
- cldm/hack.py +111 -0
- cldm/logger.py +76 -0
- cldm/model.py +28 -0
cldm/__pycache__/cldm.cpython-38.pyc
ADDED
Binary file (11.8 kB). View file
|
|
cldm/__pycache__/ddim_hacked.cpython-38.pyc
ADDED
Binary file (8.73 kB). View file
|
|
cldm/__pycache__/hack.cpython-38.pyc
ADDED
Binary file (3.89 kB). View file
|
|
cldm/__pycache__/model.cpython-38.pyc
ADDED
Binary file (1.09 kB). View file
|
|
cldm/cldm.py
ADDED
@@ -0,0 +1,470 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
latent_control=False,
|
79 |
+
noise_control=False
|
80 |
+
):
|
81 |
+
super().__init__()
|
82 |
+
if use_spatial_transformer:
|
83 |
+
assert context_dim is not None, 'Fool!! You forgot to include the dimension of your cross-attention conditioning...'
|
84 |
+
|
85 |
+
if context_dim is not None:
|
86 |
+
assert use_spatial_transformer, 'Fool!! You forgot to use the spatial transformer for your cross-attention conditioning...'
|
87 |
+
from omegaconf.listconfig import ListConfig
|
88 |
+
if type(context_dim) == ListConfig:
|
89 |
+
context_dim = list(context_dim)
|
90 |
+
|
91 |
+
if num_heads_upsample == -1:
|
92 |
+
num_heads_upsample = num_heads
|
93 |
+
|
94 |
+
if num_heads == -1:
|
95 |
+
assert num_head_channels != -1, 'Either num_heads or num_head_channels has to be set'
|
96 |
+
|
97 |
+
if num_head_channels == -1:
|
98 |
+
assert num_heads != -1, 'Either num_heads or num_head_channels has to be set'
|
99 |
+
|
100 |
+
self.dims = dims
|
101 |
+
self.image_size = image_size
|
102 |
+
self.in_channels = in_channels
|
103 |
+
self.model_channels = model_channels
|
104 |
+
if isinstance(num_res_blocks, int):
|
105 |
+
self.num_res_blocks = len(channel_mult) * [num_res_blocks]
|
106 |
+
else:
|
107 |
+
if len(num_res_blocks) != len(channel_mult):
|
108 |
+
raise ValueError("provide num_res_blocks either as an int (globally constant) or "
|
109 |
+
"as a list/tuple (per-level) with the same length as channel_mult")
|
110 |
+
self.num_res_blocks = num_res_blocks
|
111 |
+
if disable_self_attentions is not None:
|
112 |
+
# should be a list of booleans, indicating whether to disable self-attention in TransformerBlocks or not
|
113 |
+
assert len(disable_self_attentions) == len(channel_mult)
|
114 |
+
if num_attention_blocks is not None:
|
115 |
+
assert len(num_attention_blocks) == len(self.num_res_blocks)
|
116 |
+
assert all(map(lambda i: self.num_res_blocks[i] >= num_attention_blocks[i], range(len(num_attention_blocks))))
|
117 |
+
print(f"Constructor of UNetModel received num_attention_blocks={num_attention_blocks}. "
|
118 |
+
f"This option has LESS priority than attention_resolutions {attention_resolutions}, "
|
119 |
+
f"i.e., in cases where num_attention_blocks[i] > 0 but 2**i not in attention_resolutions, "
|
120 |
+
f"attention will still not be set.")
|
121 |
+
|
122 |
+
self.attention_resolutions = attention_resolutions
|
123 |
+
self.dropout = dropout
|
124 |
+
self.channel_mult = channel_mult
|
125 |
+
self.conv_resample = conv_resample
|
126 |
+
self.use_checkpoint = use_checkpoint
|
127 |
+
self.dtype = th.float16 if use_fp16 else th.float32
|
128 |
+
self.num_heads = num_heads
|
129 |
+
self.num_head_channels = num_head_channels
|
130 |
+
self.num_heads_upsample = num_heads_upsample
|
131 |
+
self.predict_codebook_ids = n_embed is not None
|
132 |
+
|
133 |
+
time_embed_dim = model_channels * 4
|
134 |
+
self.time_embed = nn.Sequential(
|
135 |
+
linear(model_channels, time_embed_dim),
|
136 |
+
nn.SiLU(),
|
137 |
+
linear(time_embed_dim, time_embed_dim),
|
138 |
+
)
|
139 |
+
|
140 |
+
self.input_blocks = nn.ModuleList(
|
141 |
+
[
|
142 |
+
TimestepEmbedSequential(
|
143 |
+
conv_nd(dims, in_channels, model_channels, 3, padding=1)
|
144 |
+
)
|
145 |
+
]
|
146 |
+
)
|
147 |
+
self.latent_control = latent_control
|
148 |
+
self.noise_control = noise_control
|
149 |
+
self.zero_convs = nn.ModuleList([self.make_zero_conv(model_channels)])
|
150 |
+
if self.latent_control:
|
151 |
+
self.input_hint_block = TimestepEmbedSequential(
|
152 |
+
zero_module(conv_nd(dims, hint_channels, model_channels, 3, padding=1))
|
153 |
+
)
|
154 |
+
else:
|
155 |
+
# 输入段,这一段参数都是需要训练的,要改成隐码输入,就要改变结构,这也是原设计中控制分支里面和主网络不对称的结构
|
156 |
+
# 原来的controlNet中,不管输入输出的图像是多大,control 都是 256x256
|
157 |
+
self.input_hint_block = TimestepEmbedSequential(
|
158 |
+
conv_nd(dims, hint_channels, 16, 3, padding=1),
|
159 |
+
nn.SiLU(),
|
160 |
+
conv_nd(dims, 16, 16, 3, padding=1),
|
161 |
+
nn.SiLU(),
|
162 |
+
conv_nd(dims, 16, 32, 3, padding=1, stride=2), # 256 -> 128
|
163 |
+
nn.SiLU(),
|
164 |
+
conv_nd(dims, 32, 32, 3, padding=1),
|
165 |
+
nn.SiLU(),
|
166 |
+
conv_nd(dims, 32, 96, 3, padding=1, stride=2), # 128 -> 64
|
167 |
+
nn.SiLU(),
|
168 |
+
conv_nd(dims, 96, 96, 3, padding=1),
|
169 |
+
nn.SiLU(),
|
170 |
+
conv_nd(dims, 96, 256, 3, padding=1, stride=2), # 64 -> 32
|
171 |
+
nn.SiLU(),
|
172 |
+
zero_module(conv_nd(dims, 256, model_channels, 3, padding=1))
|
173 |
+
)
|
174 |
+
|
175 |
+
self._feature_size = model_channels
|
176 |
+
input_block_chans = [model_channels]
|
177 |
+
ch = model_channels
|
178 |
+
ds = 1
|
179 |
+
for level, mult in enumerate(channel_mult):
|
180 |
+
for nr in range(self.num_res_blocks[level]):
|
181 |
+
layers = [
|
182 |
+
ResBlock(
|
183 |
+
ch,
|
184 |
+
time_embed_dim,
|
185 |
+
dropout,
|
186 |
+
out_channels=mult * model_channels,
|
187 |
+
dims=dims,
|
188 |
+
use_checkpoint=use_checkpoint,
|
189 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
190 |
+
)
|
191 |
+
]
|
192 |
+
ch = mult * model_channels
|
193 |
+
if ds in attention_resolutions:
|
194 |
+
if num_head_channels == -1:
|
195 |
+
dim_head = ch // num_heads
|
196 |
+
else:
|
197 |
+
num_heads = ch // num_head_channels
|
198 |
+
dim_head = num_head_channels
|
199 |
+
if legacy:
|
200 |
+
# num_heads = 1
|
201 |
+
dim_head = ch // num_heads if use_spatial_transformer else num_head_channels # use_spatial_transformer=True
|
202 |
+
if exists(disable_self_attentions):
|
203 |
+
disabled_sa = disable_self_attentions[level]
|
204 |
+
else:
|
205 |
+
disabled_sa = False
|
206 |
+
|
207 |
+
if not exists(num_attention_blocks) or nr < num_attention_blocks[level]:
|
208 |
+
layers.append(
|
209 |
+
AttentionBlock(
|
210 |
+
ch,
|
211 |
+
use_checkpoint=use_checkpoint,
|
212 |
+
num_heads=num_heads,
|
213 |
+
num_head_channels=dim_head,
|
214 |
+
use_new_attention_order=use_new_attention_order,
|
215 |
+
) if not use_spatial_transformer else SpatialTransformer(
|
216 |
+
ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim,
|
217 |
+
disable_self_attn=disabled_sa, use_linear=use_linear_in_transformer,
|
218 |
+
use_checkpoint=use_checkpoint
|
219 |
+
)
|
220 |
+
)
|
221 |
+
self.input_blocks.append(TimestepEmbedSequential(*layers))
|
222 |
+
self.zero_convs.append(self.make_zero_conv(ch))
|
223 |
+
self._feature_size += ch
|
224 |
+
input_block_chans.append(ch)
|
225 |
+
if level != len(channel_mult) - 1:
|
226 |
+
out_ch = ch
|
227 |
+
self.input_blocks.append(
|
228 |
+
TimestepEmbedSequential(
|
229 |
+
ResBlock(
|
230 |
+
ch,
|
231 |
+
time_embed_dim,
|
232 |
+
dropout,
|
233 |
+
out_channels=out_ch,
|
234 |
+
dims=dims,
|
235 |
+
use_checkpoint=use_checkpoint,
|
236 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
237 |
+
down=True,
|
238 |
+
)
|
239 |
+
if resblock_updown
|
240 |
+
else Downsample(
|
241 |
+
ch, conv_resample, dims=dims, out_channels=out_ch
|
242 |
+
)
|
243 |
+
)
|
244 |
+
)
|
245 |
+
ch = out_ch
|
246 |
+
input_block_chans.append(ch)
|
247 |
+
self.zero_convs.append(self.make_zero_conv(ch))
|
248 |
+
ds *= 2
|
249 |
+
self._feature_size += ch
|
250 |
+
|
251 |
+
if num_head_channels == -1:
|
252 |
+
dim_head = ch // num_heads
|
253 |
+
else:
|
254 |
+
num_heads = ch // num_head_channels
|
255 |
+
dim_head = num_head_channels
|
256 |
+
if legacy:
|
257 |
+
# num_heads = 1
|
258 |
+
dim_head = ch // num_heads if use_spatial_transformer else num_head_channels
|
259 |
+
self.middle_block = TimestepEmbedSequential(
|
260 |
+
ResBlock(
|
261 |
+
ch,
|
262 |
+
time_embed_dim,
|
263 |
+
dropout,
|
264 |
+
dims=dims,
|
265 |
+
use_checkpoint=use_checkpoint,
|
266 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
267 |
+
),
|
268 |
+
AttentionBlock(
|
269 |
+
ch,
|
270 |
+
use_checkpoint=use_checkpoint,
|
271 |
+
num_heads=num_heads,
|
272 |
+
num_head_channels=dim_head,
|
273 |
+
use_new_attention_order=use_new_attention_order,
|
274 |
+
) if not use_spatial_transformer else SpatialTransformer( # always uses a self-attn
|
275 |
+
ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim,
|
276 |
+
disable_self_attn=disable_middle_self_attn, use_linear=use_linear_in_transformer,
|
277 |
+
use_checkpoint=use_checkpoint
|
278 |
+
),
|
279 |
+
ResBlock(
|
280 |
+
ch,
|
281 |
+
time_embed_dim,
|
282 |
+
dropout,
|
283 |
+
dims=dims,
|
284 |
+
use_checkpoint=use_checkpoint,
|
285 |
+
use_scale_shift_norm=use_scale_shift_norm,
|
286 |
+
),
|
287 |
+
)
|
288 |
+
self.middle_block_out = self.make_zero_conv(ch)
|
289 |
+
self._feature_size += ch
|
290 |
+
|
291 |
+
def make_zero_conv(self, channels):
|
292 |
+
return TimestepEmbedSequential(zero_module(conv_nd(self.dims, channels, channels, 1, padding=0)))
|
293 |
+
|
294 |
+
def forward(self, x, hint, timesteps, context, **kwargs):
|
295 |
+
t_emb = timestep_embedding(timesteps, self.model_channels, repeat_only=False)
|
296 |
+
emb = self.time_embed(t_emb)
|
297 |
+
|
298 |
+
if not self.noise_control:
|
299 |
+
guided_hint = self.input_hint_block(hint, emb, context)
|
300 |
+
h = x.type(self.dtype)
|
301 |
+
else:
|
302 |
+
guided_hint = None
|
303 |
+
h = hint.type(self.dtype)
|
304 |
+
|
305 |
+
outs = []
|
306 |
+
for module, zero_conv in zip(self.input_blocks, self.zero_convs):
|
307 |
+
if guided_hint is not None:
|
308 |
+
h = module(h, emb, context)
|
309 |
+
h += guided_hint
|
310 |
+
guided_hint = None
|
311 |
+
else:
|
312 |
+
h = module(h, emb, context)
|
313 |
+
outs.append(zero_conv(h, emb, context))
|
314 |
+
|
315 |
+
h = self.middle_block(h, emb, context)
|
316 |
+
outs.append(self.middle_block_out(h, emb, context)) # 分支先预测,把所有的outs都出来
|
317 |
+
|
318 |
+
return outs
|
319 |
+
|
320 |
+
|
321 |
+
class ControlLDM(LatentDiffusion):
|
322 |
+
|
323 |
+
def __init__(self, control_stage_config, control_key, only_mid_control, *args, **kwargs):
|
324 |
+
super().__init__(*args, **kwargs)
|
325 |
+
self.control_model = instantiate_from_config(control_stage_config)
|
326 |
+
self.control_key = control_key
|
327 |
+
self.only_mid_control = only_mid_control
|
328 |
+
self.control_scales = [1.0] * 13
|
329 |
+
|
330 |
+
|
331 |
+
@torch.no_grad()
|
332 |
+
def get_input(self, batch, k, bs=None, *args, **kwargs):
|
333 |
+
x, c = super().get_input(batch, self.first_stage_key, *args, **kwargs)
|
334 |
+
control = batch[self.control_key]
|
335 |
+
if bs is not None:
|
336 |
+
control = control[:bs]
|
337 |
+
control = control.to(self.device)
|
338 |
+
control = einops.rearrange(control, 'b h w c -> b c h w')
|
339 |
+
control = control.to(memory_format=torch.contiguous_format).float()
|
340 |
+
# 之前用了一个预抽取的方法,不能兼容数据增强,所以改写
|
341 |
+
if self.control_model.latent_control:
|
342 |
+
control = (control * 2.0) - 1.0
|
343 |
+
control = self.encode_first_stage(control).mean
|
344 |
+
ctrl_loss_params = {}
|
345 |
+
if (self.l_coltrans_weight > 0 or self.l_mrcoltrans_weight > 0 or self.l_idcoltrans_weight > 0 or self.l_mridcoltrans_weight > 0) and "ctrl_mask" in batch.keys(): # 后面一个条件是为了兼容 test 和 sample 脚本
|
346 |
+
mask = batch["ctrl_mask"]
|
347 |
+
if bs is not None:
|
348 |
+
mask = mask[:bs]
|
349 |
+
mask = mask.to(self.device)
|
350 |
+
ctrl_loss_params["ctrl_mask"] = mask
|
351 |
+
tgt_rgb = batch["tgt"]
|
352 |
+
if bs is not None:
|
353 |
+
tgt_rgb = tgt_rgb[:bs]
|
354 |
+
tgt_rgb = tgt_rgb.to(self.device)
|
355 |
+
ctrl_loss_params["tgt_rgb"] = tgt_rgb
|
356 |
+
ctrl_rgb = batch["ctrl"]
|
357 |
+
if bs is not None:
|
358 |
+
ctrl_rgb = ctrl_rgb[:bs]
|
359 |
+
ctrl_rgb = ctrl_rgb.to(self.device)
|
360 |
+
ctrl_loss_params["ctrl_rgb"] = ctrl_rgb
|
361 |
+
return x, dict(c_crossattn=[c], c_concat=[control])
|
362 |
+
|
363 |
+
def apply_model(self, x_noisy, t, cond, *args, **kwargs):
|
364 |
+
assert isinstance(cond, dict)
|
365 |
+
diffusion_model = self.model.diffusion_model
|
366 |
+
|
367 |
+
cond_txt = torch.cat(cond['c_crossattn'], 1)
|
368 |
+
|
369 |
+
if cond['c_concat'] is None:
|
370 |
+
eps = diffusion_model(x=x_noisy, timesteps=t, context=cond_txt, control=None, only_mid_control=self.only_mid_control)
|
371 |
+
else:
|
372 |
+
control = self.control_model(x=x_noisy, hint=torch.cat(cond['c_concat'], 1), timesteps=t, context=cond_txt)
|
373 |
+
control = [c * scale for c, scale in zip(control, self.control_scales)]
|
374 |
+
eps = diffusion_model(x=x_noisy, timesteps=t, context=cond_txt, control=control, only_mid_control=self.only_mid_control)
|
375 |
+
|
376 |
+
return eps
|
377 |
+
|
378 |
+
@torch.no_grad()
|
379 |
+
def get_unconditional_conditioning(self, N):
|
380 |
+
return self.get_learned_conditioning([""] * N)
|
381 |
+
|
382 |
+
@torch.no_grad()
|
383 |
+
def log_images(self, batch, N=4, n_row=2, sample=False, ddim_steps=50, ddim_eta=0.0, return_keys=None,
|
384 |
+
quantize_denoised=True, inpaint=True, plot_denoise_rows=False, plot_progressive_rows=True,
|
385 |
+
plot_diffusion_rows=False, unconditional_guidance_scale=9.0, unconditional_guidance_label=None,
|
386 |
+
use_ema_scope=True,
|
387 |
+
**kwargs):
|
388 |
+
use_ddim = ddim_steps is not None
|
389 |
+
|
390 |
+
log = dict()
|
391 |
+
z, c = self.get_input(batch, self.first_stage_key, bs=N)
|
392 |
+
c_cat, c = c["c_concat"][0][:N], c["c_crossattn"][0][:N]
|
393 |
+
N = min(z.shape[0], N)
|
394 |
+
n_row = min(z.shape[0], n_row)
|
395 |
+
log["reconstruction"] = self.decode_first_stage(z)
|
396 |
+
log["control"] = c_cat * 2.0 - 1.0
|
397 |
+
log["conditioning"] = log_txt_as_img((512, 512), batch[self.cond_stage_key], size=16)
|
398 |
+
|
399 |
+
if plot_diffusion_rows:
|
400 |
+
# get diffusion row
|
401 |
+
diffusion_row = list()
|
402 |
+
z_start = z[:n_row]
|
403 |
+
for t in range(self.num_timesteps):
|
404 |
+
if t % self.log_every_t == 0 or t == self.num_timesteps - 1:
|
405 |
+
t = repeat(torch.tensor([t]), '1 -> b', b=n_row)
|
406 |
+
t = t.to(self.device).long()
|
407 |
+
noise = torch.randn_like(z_start)
|
408 |
+
z_noisy = self.q_sample(x_start=z_start, t=t, noise=noise)
|
409 |
+
diffusion_row.append(self.decode_first_stage(z_noisy))
|
410 |
+
|
411 |
+
diffusion_row = torch.stack(diffusion_row) # n_log_step, n_row, C, H, W
|
412 |
+
diffusion_grid = rearrange(diffusion_row, 'n b c h w -> b n c h w')
|
413 |
+
diffusion_grid = rearrange(diffusion_grid, 'b n c h w -> (b n) c h w')
|
414 |
+
diffusion_grid = make_grid(diffusion_grid, nrow=diffusion_row.shape[0])
|
415 |
+
log["diffusion_row"] = diffusion_grid
|
416 |
+
|
417 |
+
if sample:
|
418 |
+
# get denoise row
|
419 |
+
samples, z_denoise_row = self.sample_log(cond={"c_concat": [c_cat], "c_crossattn": [c]},
|
420 |
+
batch_size=N, ddim=use_ddim,
|
421 |
+
ddim_steps=ddim_steps, eta=ddim_eta)
|
422 |
+
x_samples = self.decode_first_stage(samples)
|
423 |
+
log["samples"] = x_samples
|
424 |
+
if plot_denoise_rows:
|
425 |
+
denoise_grid = self._get_denoise_row_from_list(z_denoise_row)
|
426 |
+
log["denoise_row"] = denoise_grid
|
427 |
+
|
428 |
+
if unconditional_guidance_scale > 1.0:
|
429 |
+
uc_cross = self.get_unconditional_conditioning(N)
|
430 |
+
uc_cat = c_cat # torch.zeros_like(c_cat)
|
431 |
+
uc_full = {"c_concat": [uc_cat], "c_crossattn": [uc_cross]}
|
432 |
+
samples_cfg, _ = self.sample_log(cond={"c_concat": [c_cat], "c_crossattn": [c]},
|
433 |
+
batch_size=N, ddim=use_ddim,
|
434 |
+
ddim_steps=ddim_steps, eta=ddim_eta,
|
435 |
+
unconditional_guidance_scale=unconditional_guidance_scale,
|
436 |
+
unconditional_conditioning=uc_full,
|
437 |
+
)
|
438 |
+
x_samples_cfg = self.decode_first_stage(samples_cfg)
|
439 |
+
log[f"samples_cfg_scale_{unconditional_guidance_scale:.2f}"] = x_samples_cfg
|
440 |
+
|
441 |
+
return log
|
442 |
+
|
443 |
+
@torch.no_grad()
|
444 |
+
def sample_log(self, cond, batch_size, ddim, ddim_steps, **kwargs):
|
445 |
+
ddim_sampler = DDIMSampler(self)
|
446 |
+
b, c, h, w = cond["c_concat"][0].shape
|
447 |
+
shape = (self.channels, h // 8, w // 8)
|
448 |
+
samples, intermediates = ddim_sampler.sample(ddim_steps, batch_size, shape, cond, verbose=False, **kwargs)
|
449 |
+
return samples, intermediates
|
450 |
+
|
451 |
+
def configure_optimizers(self):
|
452 |
+
lr = self.learning_rate
|
453 |
+
params = list(self.control_model.parameters())
|
454 |
+
if not self.sd_locked:
|
455 |
+
params += list(self.model.diffusion_model.output_blocks.parameters())
|
456 |
+
params += list(self.model.diffusion_model.out.parameters())
|
457 |
+
opt = torch.optim.AdamW(params, lr=lr)
|
458 |
+
return opt
|
459 |
+
|
460 |
+
def low_vram_shift(self, is_diffusing):
|
461 |
+
if is_diffusing:
|
462 |
+
self.model = self.model.cuda()
|
463 |
+
self.control_model = self.control_model.cuda()
|
464 |
+
self.first_stage_model = self.first_stage_model.cpu()
|
465 |
+
self.cond_stage_model = self.cond_stage_model.cpu()
|
466 |
+
else:
|
467 |
+
self.model = self.model.cpu()
|
468 |
+
self.control_model = self.control_model.cpu()
|
469 |
+
self.first_stage_model = self.first_stage_model.cuda()
|
470 |
+
self.cond_stage_model = self.cond_stage_model.cuda()
|
cldm/ddim_hacked.py
ADDED
@@ -0,0 +1,317 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
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.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
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
|