ACCC1380 commited on
Commit
b5f7190
1 Parent(s): 7cc8356

Upload lora-scripts/sd-scripts/networks/control_net_lllite.py with huggingface_hub

Browse files
lora-scripts/sd-scripts/networks/control_net_lllite.py ADDED
@@ -0,0 +1,449 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from typing import Optional, List, Type
3
+ import torch
4
+ from library import sdxl_original_unet
5
+ from library.utils import setup_logging
6
+ setup_logging()
7
+ import logging
8
+ logger = logging.getLogger(__name__)
9
+
10
+ # input_blocksに適用するかどうか / if True, input_blocks are not applied
11
+ SKIP_INPUT_BLOCKS = False
12
+
13
+ # output_blocksに適用するかどうか / if True, output_blocks are not applied
14
+ SKIP_OUTPUT_BLOCKS = True
15
+
16
+ # conv2dに適用するかどうか / if True, conv2d are not applied
17
+ SKIP_CONV2D = False
18
+
19
+ # transformer_blocksのみに適用するかどうか。Trueの場合、ResBlockには適用されない
20
+ # if True, only transformer_blocks are applied, and ResBlocks are not applied
21
+ TRANSFORMER_ONLY = True # if True, SKIP_CONV2D is ignored because conv2d is not used in transformer_blocks
22
+
23
+ # Trueならattn1とattn2にのみ適用し、ffなどには適用しない / if True, apply only to attn1 and attn2, not to ff etc.
24
+ ATTN1_2_ONLY = True
25
+
26
+ # Trueならattn1のQKV、attn2のQにのみ適用する、ATTN1_2_ONLY指定時のみ有効 / if True, apply only to attn1 QKV and attn2 Q, only valid when ATTN1_2_ONLY is specified
27
+ ATTN_QKV_ONLY = True
28
+
29
+ # Trueならattn1やffなどにのみ適用し、attn2などには適用しない / if True, apply only to attn1 and ff, not to attn2
30
+ # ATTN1_2_ONLYと同時にTrueにできない / cannot be True at the same time as ATTN1_2_ONLY
31
+ ATTN1_ETC_ONLY = False # True
32
+
33
+ # transformer_blocksの最大インデックス。Noneなら全てのtransformer_blocksに適用
34
+ # max index of transformer_blocks. if None, apply to all transformer_blocks
35
+ TRANSFORMER_MAX_BLOCK_INDEX = None
36
+
37
+
38
+ class LLLiteModule(torch.nn.Module):
39
+ def __init__(self, depth, cond_emb_dim, name, org_module, mlp_dim, dropout=None, multiplier=1.0):
40
+ super().__init__()
41
+
42
+ self.is_conv2d = org_module.__class__.__name__ == "Conv2d"
43
+ self.lllite_name = name
44
+ self.cond_emb_dim = cond_emb_dim
45
+ self.org_module = [org_module]
46
+ self.dropout = dropout
47
+ self.multiplier = multiplier
48
+
49
+ if self.is_conv2d:
50
+ in_dim = org_module.in_channels
51
+ else:
52
+ in_dim = org_module.in_features
53
+
54
+ # conditioning1はconditioning imageを embedding する。timestepごとに呼ばれない
55
+ # conditioning1 embeds conditioning image. it is not called for each timestep
56
+ modules = []
57
+ modules.append(torch.nn.Conv2d(3, cond_emb_dim // 2, kernel_size=4, stride=4, padding=0)) # to latent (from VAE) size
58
+ if depth == 1:
59
+ modules.append(torch.nn.ReLU(inplace=True))
60
+ modules.append(torch.nn.Conv2d(cond_emb_dim // 2, cond_emb_dim, kernel_size=2, stride=2, padding=0))
61
+ elif depth == 2:
62
+ modules.append(torch.nn.ReLU(inplace=True))
63
+ modules.append(torch.nn.Conv2d(cond_emb_dim // 2, cond_emb_dim, kernel_size=4, stride=4, padding=0))
64
+ elif depth == 3:
65
+ # kernel size 8は大きすぎるので、4にする / kernel size 8 is too large, so set it to 4
66
+ modules.append(torch.nn.ReLU(inplace=True))
67
+ modules.append(torch.nn.Conv2d(cond_emb_dim // 2, cond_emb_dim // 2, kernel_size=4, stride=4, padding=0))
68
+ modules.append(torch.nn.ReLU(inplace=True))
69
+ modules.append(torch.nn.Conv2d(cond_emb_dim // 2, cond_emb_dim, kernel_size=2, stride=2, padding=0))
70
+
71
+ self.conditioning1 = torch.nn.Sequential(*modules)
72
+
73
+ # downで入力の次元数を削減する。LoRAにヒントを得ていることにする
74
+ # midでconditioning image embeddingと入力を結合する
75
+ # upで元の次元数に戻す
76
+ # これらはtimestepごとに呼ばれる
77
+ # reduce the number of input dimensions with down. inspired by LoRA
78
+ # combine conditioning image embedding and input with mid
79
+ # restore to the original dimension with up
80
+ # these are called for each timestep
81
+
82
+ if self.is_conv2d:
83
+ self.down = torch.nn.Sequential(
84
+ torch.nn.Conv2d(in_dim, mlp_dim, kernel_size=1, stride=1, padding=0),
85
+ torch.nn.ReLU(inplace=True),
86
+ )
87
+ self.mid = torch.nn.Sequential(
88
+ torch.nn.Conv2d(mlp_dim + cond_emb_dim, mlp_dim, kernel_size=1, stride=1, padding=0),
89
+ torch.nn.ReLU(inplace=True),
90
+ )
91
+ self.up = torch.nn.Sequential(
92
+ torch.nn.Conv2d(mlp_dim, in_dim, kernel_size=1, stride=1, padding=0),
93
+ )
94
+ else:
95
+ # midの前にconditioningをreshapeすること / reshape conditioning before mid
96
+ self.down = torch.nn.Sequential(
97
+ torch.nn.Linear(in_dim, mlp_dim),
98
+ torch.nn.ReLU(inplace=True),
99
+ )
100
+ self.mid = torch.nn.Sequential(
101
+ torch.nn.Linear(mlp_dim + cond_emb_dim, mlp_dim),
102
+ torch.nn.ReLU(inplace=True),
103
+ )
104
+ self.up = torch.nn.Sequential(
105
+ torch.nn.Linear(mlp_dim, in_dim),
106
+ )
107
+
108
+ # Zero-Convにする / set to Zero-Conv
109
+ torch.nn.init.zeros_(self.up[0].weight) # zero conv
110
+
111
+ self.depth = depth # 1~3
112
+ self.cond_emb = None
113
+ self.batch_cond_only = False # Trueなら推論時のcondにのみ適用する / if True, apply only to cond at inference
114
+ self.use_zeros_for_batch_uncond = False # Trueならuncondのconditioningを0にする / if True, set uncond conditioning to 0
115
+
116
+ # batch_cond_onlyとuse_zeros_for_batch_uncondはどちらも適用すると生成画像の色味がおかしくなるので実際には使えそうにない
117
+ # Controlの種類によっては使えるかも
118
+ # both batch_cond_only and use_zeros_for_batch_uncond make the color of the generated image strange, so it doesn't seem to be usable in practice
119
+ # it may be available depending on the type of Control
120
+
121
+ def set_cond_image(self, cond_image):
122
+ r"""
123
+ 中でモデルを呼び出すので必要ならwith torch.no_grad()で囲む
124
+ / call the model inside, so if necessary, surround it with torch.no_grad()
125
+ """
126
+ if cond_image is None:
127
+ self.cond_emb = None
128
+ return
129
+
130
+ # timestepごとに呼ばれないので、あらかじめ計算しておく / it is not called for each timestep, so calculate it in advance
131
+ # logger.info(f"C {self.lllite_name}, cond_image.shape={cond_image.shape}")
132
+ cx = self.conditioning1(cond_image)
133
+ if not self.is_conv2d:
134
+ # reshape / b,c,h,w -> b,h*w,c
135
+ n, c, h, w = cx.shape
136
+ cx = cx.view(n, c, h * w).permute(0, 2, 1)
137
+ self.cond_emb = cx
138
+
139
+ def set_batch_cond_only(self, cond_only, zeros):
140
+ self.batch_cond_only = cond_only
141
+ self.use_zeros_for_batch_uncond = zeros
142
+
143
+ def apply_to(self):
144
+ self.org_forward = self.org_module[0].forward
145
+ self.org_module[0].forward = self.forward
146
+
147
+ def forward(self, x):
148
+ r"""
149
+ 学習用の便利forward。元のモジュールのforwardを呼び出す
150
+ / convenient forward for training. call the forward of the original module
151
+ """
152
+ if self.multiplier == 0.0 or self.cond_emb is None:
153
+ return self.org_forward(x)
154
+
155
+ cx = self.cond_emb
156
+
157
+ if not self.batch_cond_only and x.shape[0] // 2 == cx.shape[0]: # inference only
158
+ cx = cx.repeat(2, 1, 1, 1) if self.is_conv2d else cx.repeat(2, 1, 1)
159
+ if self.use_zeros_for_batch_uncond:
160
+ cx[0::2] = 0.0 # uncond is zero
161
+ # logger.info(f"C {self.lllite_name}, x.shape={x.shape}, cx.shape={cx.shape}")
162
+
163
+ # downで入力の次元数を削減し、conditioning image embeddingと結合する
164
+ # 加算ではなくchannel方向に結合することで、うまいこと混ぜてくれることを期待している
165
+ # down reduces the number of input dimensions and combines it with conditioning image embedding
166
+ # we expect that it will mix well by combining in the channel direction instead of adding
167
+
168
+ cx = torch.cat([cx, self.down(x if not self.batch_cond_only else x[1::2])], dim=1 if self.is_conv2d else 2)
169
+ cx = self.mid(cx)
170
+
171
+ if self.dropout is not None and self.training:
172
+ cx = torch.nn.functional.dropout(cx, p=self.dropout)
173
+
174
+ cx = self.up(cx) * self.multiplier
175
+
176
+ # residual (x) を加算して元のforwardを呼び出す / add residual (x) and call the original forward
177
+ if self.batch_cond_only:
178
+ zx = torch.zeros_like(x)
179
+ zx[1::2] += cx
180
+ cx = zx
181
+
182
+ x = self.org_forward(x + cx) # ここで元のモジュールを呼び出す / call the original module here
183
+ return x
184
+
185
+
186
+ class ControlNetLLLite(torch.nn.Module):
187
+ UNET_TARGET_REPLACE_MODULE = ["Transformer2DModel"]
188
+ UNET_TARGET_REPLACE_MODULE_CONV2D_3X3 = ["ResnetBlock2D", "Downsample2D", "Upsample2D"]
189
+
190
+ def __init__(
191
+ self,
192
+ unet: sdxl_original_unet.SdxlUNet2DConditionModel,
193
+ cond_emb_dim: int = 16,
194
+ mlp_dim: int = 16,
195
+ dropout: Optional[float] = None,
196
+ varbose: Optional[bool] = False,
197
+ multiplier: Optional[float] = 1.0,
198
+ ) -> None:
199
+ super().__init__()
200
+ # self.unets = [unet]
201
+
202
+ def create_modules(
203
+ root_module: torch.nn.Module,
204
+ target_replace_modules: List[torch.nn.Module],
205
+ module_class: Type[object],
206
+ ) -> List[torch.nn.Module]:
207
+ prefix = "lllite_unet"
208
+
209
+ modules = []
210
+ for name, module in root_module.named_modules():
211
+ if module.__class__.__name__ in target_replace_modules:
212
+ for child_name, child_module in module.named_modules():
213
+ is_linear = child_module.__class__.__name__ == "Linear"
214
+ is_conv2d = child_module.__class__.__name__ == "Conv2d"
215
+
216
+ if is_linear or (is_conv2d and not SKIP_CONV2D):
217
+ # block indexからdepthを計算: depthはconditioningのサイズやチャネルを計算するのに使う
218
+ # block index to depth: depth is using to calculate conditioning size and channels
219
+ block_name, index1, index2 = (name + "." + child_name).split(".")[:3]
220
+ index1 = int(index1)
221
+ if block_name == "input_blocks":
222
+ if SKIP_INPUT_BLOCKS:
223
+ continue
224
+ depth = 1 if index1 <= 2 else (2 if index1 <= 5 else 3)
225
+ elif block_name == "middle_block":
226
+ depth = 3
227
+ elif block_name == "output_blocks":
228
+ if SKIP_OUTPUT_BLOCKS:
229
+ continue
230
+ depth = 3 if index1 <= 2 else (2 if index1 <= 5 else 1)
231
+ if int(index2) >= 2:
232
+ depth -= 1
233
+ else:
234
+ raise NotImplementedError()
235
+
236
+ lllite_name = prefix + "." + name + "." + child_name
237
+ lllite_name = lllite_name.replace(".", "_")
238
+
239
+ if TRANSFORMER_MAX_BLOCK_INDEX is not None:
240
+ p = lllite_name.find("transformer_blocks")
241
+ if p >= 0:
242
+ tf_index = int(lllite_name[p:].split("_")[2])
243
+ if tf_index > TRANSFORMER_MAX_BLOCK_INDEX:
244
+ continue
245
+
246
+ # time embは適用外とする
247
+ # attn2のconditioning (CLIPからの入力) はshapeが違うので適用できない
248
+ # time emb is not applied
249
+ # attn2 conditioning (input from CLIP) cannot be applied because the shape is different
250
+ if "emb_layers" in lllite_name or (
251
+ "attn2" in lllite_name and ("to_k" in lllite_name or "to_v" in lllite_name)
252
+ ):
253
+ continue
254
+
255
+ if ATTN1_2_ONLY:
256
+ if not ("attn1" in lllite_name or "attn2" in lllite_name):
257
+ continue
258
+ if ATTN_QKV_ONLY:
259
+ if "to_out" in lllite_name:
260
+ continue
261
+
262
+ if ATTN1_ETC_ONLY:
263
+ if "proj_out" in lllite_name:
264
+ pass
265
+ elif "attn1" in lllite_name and (
266
+ "to_k" in lllite_name or "to_v" in lllite_name or "to_out" in lllite_name
267
+ ):
268
+ pass
269
+ elif "ff_net_2" in lllite_name:
270
+ pass
271
+ else:
272
+ continue
273
+
274
+ module = module_class(
275
+ depth,
276
+ cond_emb_dim,
277
+ lllite_name,
278
+ child_module,
279
+ mlp_dim,
280
+ dropout=dropout,
281
+ multiplier=multiplier,
282
+ )
283
+ modules.append(module)
284
+ return modules
285
+
286
+ target_modules = ControlNetLLLite.UNET_TARGET_REPLACE_MODULE
287
+ if not TRANSFORMER_ONLY:
288
+ target_modules = target_modules + ControlNetLLLite.UNET_TARGET_REPLACE_MODULE_CONV2D_3X3
289
+
290
+ # create module instances
291
+ self.unet_modules: List[LLLiteModule] = create_modules(unet, target_modules, LLLiteModule)
292
+ logger.info(f"create ControlNet LLLite for U-Net: {len(self.unet_modules)} modules.")
293
+
294
+ def forward(self, x):
295
+ return x # dummy
296
+
297
+ def set_cond_image(self, cond_image):
298
+ r"""
299
+ 中でモデルを呼び出すので必要ならwith torch.no_grad()で囲む
300
+ / call the model inside, so if necessary, surround it with torch.no_grad()
301
+ """
302
+ for module in self.unet_modules:
303
+ module.set_cond_image(cond_image)
304
+
305
+ def set_batch_cond_only(self, cond_only, zeros):
306
+ for module in self.unet_modules:
307
+ module.set_batch_cond_only(cond_only, zeros)
308
+
309
+ def set_multiplier(self, multiplier):
310
+ for module in self.unet_modules:
311
+ module.multiplier = multiplier
312
+
313
+ def load_weights(self, file):
314
+ if os.path.splitext(file)[1] == ".safetensors":
315
+ from safetensors.torch import load_file
316
+
317
+ weights_sd = load_file(file)
318
+ else:
319
+ weights_sd = torch.load(file, map_location="cpu")
320
+
321
+ info = self.load_state_dict(weights_sd, False)
322
+ return info
323
+
324
+ def apply_to(self):
325
+ logger.info("applying LLLite for U-Net...")
326
+ for module in self.unet_modules:
327
+ module.apply_to()
328
+ self.add_module(module.lllite_name, module)
329
+
330
+ # マージできるかどうかを返す
331
+ def is_mergeable(self):
332
+ return False
333
+
334
+ def merge_to(self, text_encoder, unet, weights_sd, dtype, device):
335
+ raise NotImplementedError()
336
+
337
+ def enable_gradient_checkpointing(self):
338
+ # not supported
339
+ pass
340
+
341
+ def prepare_optimizer_params(self):
342
+ self.requires_grad_(True)
343
+ return self.parameters()
344
+
345
+ def prepare_grad_etc(self):
346
+ self.requires_grad_(True)
347
+
348
+ def on_epoch_start(self):
349
+ self.train()
350
+
351
+ def get_trainable_params(self):
352
+ return self.parameters()
353
+
354
+ def save_weights(self, file, dtype, metadata):
355
+ if metadata is not None and len(metadata) == 0:
356
+ metadata = None
357
+
358
+ state_dict = self.state_dict()
359
+
360
+ if dtype is not None:
361
+ for key in list(state_dict.keys()):
362
+ v = state_dict[key]
363
+ v = v.detach().clone().to("cpu").to(dtype)
364
+ state_dict[key] = v
365
+
366
+ if os.path.splitext(file)[1] == ".safetensors":
367
+ from safetensors.torch import save_file
368
+
369
+ save_file(state_dict, file, metadata)
370
+ else:
371
+ torch.save(state_dict, file)
372
+
373
+
374
+ if __name__ == "__main__":
375
+ # デバッグ用 / for debug
376
+
377
+ # sdxl_original_unet.USE_REENTRANT = False
378
+
379
+ # test shape etc
380
+ logger.info("create unet")
381
+ unet = sdxl_original_unet.SdxlUNet2DConditionModel()
382
+ unet.to("cuda").to(torch.float16)
383
+
384
+ logger.info("create ControlNet-LLLite")
385
+ control_net = ControlNetLLLite(unet, 32, 64)
386
+ control_net.apply_to()
387
+ control_net.to("cuda")
388
+
389
+ logger.info(control_net)
390
+
391
+ # logger.info number of parameters
392
+ logger.info(f"number of parameters {sum(p.numel() for p in control_net.parameters() if p.requires_grad)}")
393
+
394
+ input()
395
+
396
+ unet.set_use_memory_efficient_attention(True, False)
397
+ unet.set_gradient_checkpointing(True)
398
+ unet.train() # for gradient checkpointing
399
+
400
+ control_net.train()
401
+
402
+ # # visualize
403
+ # import torchviz
404
+ # logger.info("run visualize")
405
+ # controlnet.set_control(conditioning_image)
406
+ # output = unet(x, t, ctx, y)
407
+ # logger.info("make_dot")
408
+ # image = torchviz.make_dot(output, params=dict(controlnet.named_parameters()))
409
+ # logger.info("render")
410
+ # image.format = "svg" # "png"
411
+ # image.render("NeuralNet") # すごく時間がかかるので注意 / be careful because it takes a long time
412
+ # input()
413
+
414
+ import bitsandbytes
415
+
416
+ optimizer = bitsandbytes.adam.Adam8bit(control_net.prepare_optimizer_params(), 1e-3)
417
+
418
+ scaler = torch.cuda.amp.GradScaler(enabled=True)
419
+
420
+ logger.info("start training")
421
+ steps = 10
422
+
423
+ sample_param = [p for p in control_net.named_parameters() if "up" in p[0]][0]
424
+ for step in range(steps):
425
+ logger.info(f"step {step}")
426
+
427
+ batch_size = 1
428
+ conditioning_image = torch.rand(batch_size, 3, 1024, 1024).cuda() * 2.0 - 1.0
429
+ x = torch.randn(batch_size, 4, 128, 128).cuda()
430
+ t = torch.randint(low=0, high=10, size=(batch_size,)).cuda()
431
+ ctx = torch.randn(batch_size, 77, 2048).cuda()
432
+ y = torch.randn(batch_size, sdxl_original_unet.ADM_IN_CHANNELS).cuda()
433
+
434
+ with torch.cuda.amp.autocast(enabled=True):
435
+ control_net.set_cond_image(conditioning_image)
436
+
437
+ output = unet(x, t, ctx, y)
438
+ target = torch.randn_like(output)
439
+ loss = torch.nn.functional.mse_loss(output, target)
440
+
441
+ scaler.scale(loss).backward()
442
+ scaler.step(optimizer)
443
+ scaler.update()
444
+ optimizer.zero_grad(set_to_none=True)
445
+ logger.info(f"{sample_param}")
446
+
447
+ # from safetensors.torch import save_file
448
+
449
+ # save_file(control_net.state_dict(), "logs/control_net.safetensors")