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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# cond_imageをU-Netのforwardで渡すバージョンのControlNet-LLLite検証用実装
|
2 |
+
# ControlNet-LLLite implementation for verification with cond_image passed in U-Net's forward
|
3 |
+
|
4 |
+
import os
|
5 |
+
import re
|
6 |
+
from typing import Optional, List, Type
|
7 |
+
import torch
|
8 |
+
from library import sdxl_original_unet
|
9 |
+
from library.utils import setup_logging
|
10 |
+
setup_logging()
|
11 |
+
import logging
|
12 |
+
logger = logging.getLogger(__name__)
|
13 |
+
|
14 |
+
# input_blocksに適用するかどうか / if True, input_blocks are not applied
|
15 |
+
SKIP_INPUT_BLOCKS = False
|
16 |
+
|
17 |
+
# output_blocksに適用するかどうか / if True, output_blocks are not applied
|
18 |
+
SKIP_OUTPUT_BLOCKS = True
|
19 |
+
|
20 |
+
# conv2dに適用するかどうか / if True, conv2d are not applied
|
21 |
+
SKIP_CONV2D = False
|
22 |
+
|
23 |
+
# transformer_blocksのみに適用するかどうか。Trueの場合、ResBlockには適用されない
|
24 |
+
# if True, only transformer_blocks are applied, and ResBlocks are not applied
|
25 |
+
TRANSFORMER_ONLY = True # if True, SKIP_CONV2D is ignored because conv2d is not used in transformer_blocks
|
26 |
+
|
27 |
+
# Trueならattn1とattn2にのみ適用し、ffなどには適用しない / if True, apply only to attn1 and attn2, not to ff etc.
|
28 |
+
ATTN1_2_ONLY = True
|
29 |
+
|
30 |
+
# 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
|
31 |
+
ATTN_QKV_ONLY = True
|
32 |
+
|
33 |
+
# Trueならattn1やffなどにのみ適用し、attn2などには適用しない / if True, apply only to attn1 and ff, not to attn2
|
34 |
+
# ATTN1_2_ONLYと同時にTrueにできない / cannot be True at the same time as ATTN1_2_ONLY
|
35 |
+
ATTN1_ETC_ONLY = False # True
|
36 |
+
|
37 |
+
# transformer_blocksの最大インデックス。Noneなら全てのtransformer_blocksに適用
|
38 |
+
# max index of transformer_blocks. if None, apply to all transformer_blocks
|
39 |
+
TRANSFORMER_MAX_BLOCK_INDEX = None
|
40 |
+
|
41 |
+
ORIGINAL_LINEAR = torch.nn.Linear
|
42 |
+
ORIGINAL_CONV2D = torch.nn.Conv2d
|
43 |
+
|
44 |
+
|
45 |
+
def add_lllite_modules(module: torch.nn.Module, in_dim: int, depth, cond_emb_dim, mlp_dim) -> None:
|
46 |
+
# conditioning1はconditioning imageを embedding する。timestepごとに呼ばれない
|
47 |
+
# conditioning1 embeds conditioning image. it is not called for each timestep
|
48 |
+
modules = []
|
49 |
+
modules.append(ORIGINAL_CONV2D(3, cond_emb_dim // 2, kernel_size=4, stride=4, padding=0)) # to latent (from VAE) size
|
50 |
+
if depth == 1:
|
51 |
+
modules.append(torch.nn.ReLU(inplace=True))
|
52 |
+
modules.append(ORIGINAL_CONV2D(cond_emb_dim // 2, cond_emb_dim, kernel_size=2, stride=2, padding=0))
|
53 |
+
elif depth == 2:
|
54 |
+
modules.append(torch.nn.ReLU(inplace=True))
|
55 |
+
modules.append(ORIGINAL_CONV2D(cond_emb_dim // 2, cond_emb_dim, kernel_size=4, stride=4, padding=0))
|
56 |
+
elif depth == 3:
|
57 |
+
# kernel size 8は大きすぎるので、4にする / kernel size 8 is too large, so set it to 4
|
58 |
+
modules.append(torch.nn.ReLU(inplace=True))
|
59 |
+
modules.append(ORIGINAL_CONV2D(cond_emb_dim // 2, cond_emb_dim // 2, kernel_size=4, stride=4, padding=0))
|
60 |
+
modules.append(torch.nn.ReLU(inplace=True))
|
61 |
+
modules.append(ORIGINAL_CONV2D(cond_emb_dim // 2, cond_emb_dim, kernel_size=2, stride=2, padding=0))
|
62 |
+
|
63 |
+
module.lllite_conditioning1 = torch.nn.Sequential(*modules)
|
64 |
+
|
65 |
+
# downで入力の次元数を削減する。LoRAにヒントを得ていることにする
|
66 |
+
# midでconditioning image embeddingと入力を結合する
|
67 |
+
# upで元の次元数に戻す
|
68 |
+
# これらはtimestepごとに呼ばれる
|
69 |
+
# reduce the number of input dimensions with down. inspired by LoRA
|
70 |
+
# combine conditioning image embedding and input with mid
|
71 |
+
# restore to the original dimension with up
|
72 |
+
# these are called for each timestep
|
73 |
+
|
74 |
+
module.lllite_down = torch.nn.Sequential(
|
75 |
+
ORIGINAL_LINEAR(in_dim, mlp_dim),
|
76 |
+
torch.nn.ReLU(inplace=True),
|
77 |
+
)
|
78 |
+
module.lllite_mid = torch.nn.Sequential(
|
79 |
+
ORIGINAL_LINEAR(mlp_dim + cond_emb_dim, mlp_dim),
|
80 |
+
torch.nn.ReLU(inplace=True),
|
81 |
+
)
|
82 |
+
module.lllite_up = torch.nn.Sequential(
|
83 |
+
ORIGINAL_LINEAR(mlp_dim, in_dim),
|
84 |
+
)
|
85 |
+
|
86 |
+
# Zero-Convにする / set to Zero-Conv
|
87 |
+
torch.nn.init.zeros_(module.lllite_up[0].weight) # zero conv
|
88 |
+
|
89 |
+
|
90 |
+
class LLLiteLinear(ORIGINAL_LINEAR):
|
91 |
+
def __init__(self, in_features: int, out_features: int, **kwargs):
|
92 |
+
super().__init__(in_features, out_features, **kwargs)
|
93 |
+
self.enabled = False
|
94 |
+
|
95 |
+
def set_lllite(self, depth, cond_emb_dim, name, mlp_dim, dropout=None, multiplier=1.0):
|
96 |
+
self.enabled = True
|
97 |
+
self.lllite_name = name
|
98 |
+
self.cond_emb_dim = cond_emb_dim
|
99 |
+
self.dropout = dropout
|
100 |
+
self.multiplier = multiplier # ignored
|
101 |
+
|
102 |
+
in_dim = self.in_features
|
103 |
+
add_lllite_modules(self, in_dim, depth, cond_emb_dim, mlp_dim)
|
104 |
+
|
105 |
+
self.cond_image = None
|
106 |
+
self.cond_emb = None
|
107 |
+
|
108 |
+
def set_cond_image(self, cond_image):
|
109 |
+
self.cond_image = cond_image
|
110 |
+
self.cond_emb = None
|
111 |
+
|
112 |
+
def forward(self, x):
|
113 |
+
if not self.enabled:
|
114 |
+
return super().forward(x)
|
115 |
+
|
116 |
+
if self.cond_emb is None:
|
117 |
+
self.cond_emb = self.lllite_conditioning1(self.cond_image)
|
118 |
+
cx = self.cond_emb
|
119 |
+
|
120 |
+
# reshape / b,c,h,w -> b,h*w,c
|
121 |
+
n, c, h, w = cx.shape
|
122 |
+
cx = cx.view(n, c, h * w).permute(0, 2, 1)
|
123 |
+
|
124 |
+
cx = torch.cat([cx, self.lllite_down(x)], dim=2)
|
125 |
+
cx = self.lllite_mid(cx)
|
126 |
+
|
127 |
+
if self.dropout is not None and self.training:
|
128 |
+
cx = torch.nn.functional.dropout(cx, p=self.dropout)
|
129 |
+
|
130 |
+
cx = self.lllite_up(cx) * self.multiplier
|
131 |
+
|
132 |
+
x = super().forward(x + cx) # ここで元のモジュールを呼び出す / call the original module here
|
133 |
+
return x
|
134 |
+
|
135 |
+
|
136 |
+
class LLLiteConv2d(ORIGINAL_CONV2D):
|
137 |
+
def __init__(self, in_channels: int, out_channels: int, kernel_size, **kwargs):
|
138 |
+
super().__init__(in_channels, out_channels, kernel_size, **kwargs)
|
139 |
+
self.enabled = False
|
140 |
+
|
141 |
+
def set_lllite(self, depth, cond_emb_dim, name, mlp_dim, dropout=None, multiplier=1.0):
|
142 |
+
self.enabled = True
|
143 |
+
self.lllite_name = name
|
144 |
+
self.cond_emb_dim = cond_emb_dim
|
145 |
+
self.dropout = dropout
|
146 |
+
self.multiplier = multiplier # ignored
|
147 |
+
|
148 |
+
in_dim = self.in_channels
|
149 |
+
add_lllite_modules(self, in_dim, depth, cond_emb_dim, mlp_dim)
|
150 |
+
|
151 |
+
self.cond_image = None
|
152 |
+
self.cond_emb = None
|
153 |
+
|
154 |
+
def set_cond_image(self, cond_image):
|
155 |
+
self.cond_image = cond_image
|
156 |
+
self.cond_emb = None
|
157 |
+
|
158 |
+
def forward(self, x): # , cond_image=None):
|
159 |
+
if not self.enabled:
|
160 |
+
return super().forward(x)
|
161 |
+
|
162 |
+
if self.cond_emb is None:
|
163 |
+
self.cond_emb = self.lllite_conditioning1(self.cond_image)
|
164 |
+
cx = self.cond_emb
|
165 |
+
|
166 |
+
cx = torch.cat([cx, self.down(x)], dim=1)
|
167 |
+
cx = self.mid(cx)
|
168 |
+
|
169 |
+
if self.dropout is not None and self.training:
|
170 |
+
cx = torch.nn.functional.dropout(cx, p=self.dropout)
|
171 |
+
|
172 |
+
cx = self.up(cx) * self.multiplier
|
173 |
+
|
174 |
+
x = super().forward(x + cx) # ここで元のモジュールを呼び出す / call the original module here
|
175 |
+
return x
|
176 |
+
|
177 |
+
|
178 |
+
class SdxlUNet2DConditionModelControlNetLLLite(sdxl_original_unet.SdxlUNet2DConditionModel):
|
179 |
+
UNET_TARGET_REPLACE_MODULE = ["Transformer2DModel"]
|
180 |
+
UNET_TARGET_REPLACE_MODULE_CONV2D_3X3 = ["ResnetBlock2D", "Downsample2D", "Upsample2D"]
|
181 |
+
LLLITE_PREFIX = "lllite_unet"
|
182 |
+
|
183 |
+
def __init__(self, **kwargs):
|
184 |
+
super().__init__(**kwargs)
|
185 |
+
|
186 |
+
def apply_lllite(
|
187 |
+
self,
|
188 |
+
cond_emb_dim: int = 16,
|
189 |
+
mlp_dim: int = 16,
|
190 |
+
dropout: Optional[float] = None,
|
191 |
+
varbose: Optional[bool] = False,
|
192 |
+
multiplier: Optional[float] = 1.0,
|
193 |
+
) -> None:
|
194 |
+
def apply_to_modules(
|
195 |
+
root_module: torch.nn.Module,
|
196 |
+
target_replace_modules: List[torch.nn.Module],
|
197 |
+
) -> List[torch.nn.Module]:
|
198 |
+
prefix = "lllite_unet"
|
199 |
+
|
200 |
+
modules = []
|
201 |
+
for name, module in root_module.named_modules():
|
202 |
+
if module.__class__.__name__ in target_replace_modules:
|
203 |
+
for child_name, child_module in module.named_modules():
|
204 |
+
is_linear = child_module.__class__.__name__ == "LLLiteLinear"
|
205 |
+
is_conv2d = child_module.__class__.__name__ == "LLLiteConv2d"
|
206 |
+
|
207 |
+
if is_linear or (is_conv2d and not SKIP_CONV2D):
|
208 |
+
# block indexからdepthを計算: depthはconditioningのサイズやチャネルを計算するのに使う
|
209 |
+
# block index to depth: depth is using to calculate conditioning size and channels
|
210 |
+
block_name, index1, index2 = (name + "." + child_name).split(".")[:3]
|
211 |
+
index1 = int(index1)
|
212 |
+
if block_name == "input_blocks":
|
213 |
+
if SKIP_INPUT_BLOCKS:
|
214 |
+
continue
|
215 |
+
depth = 1 if index1 <= 2 else (2 if index1 <= 5 else 3)
|
216 |
+
elif block_name == "middle_block":
|
217 |
+
depth = 3
|
218 |
+
elif block_name == "output_blocks":
|
219 |
+
if SKIP_OUTPUT_BLOCKS:
|
220 |
+
continue
|
221 |
+
depth = 3 if index1 <= 2 else (2 if index1 <= 5 else 1)
|
222 |
+
if int(index2) >= 2:
|
223 |
+
depth -= 1
|
224 |
+
else:
|
225 |
+
raise NotImplementedError()
|
226 |
+
|
227 |
+
lllite_name = prefix + "." + name + "." + child_name
|
228 |
+
lllite_name = lllite_name.replace(".", "_")
|
229 |
+
|
230 |
+
if TRANSFORMER_MAX_BLOCK_INDEX is not None:
|
231 |
+
p = lllite_name.find("transformer_blocks")
|
232 |
+
if p >= 0:
|
233 |
+
tf_index = int(lllite_name[p:].split("_")[2])
|
234 |
+
if tf_index > TRANSFORMER_MAX_BLOCK_INDEX:
|
235 |
+
continue
|
236 |
+
|
237 |
+
# time embは適用外とする
|
238 |
+
# attn2のconditioning (CLIPからの入力) はshapeが違うので適用できない
|
239 |
+
# time emb is not applied
|
240 |
+
# attn2 conditioning (input from CLIP) cannot be applied because the shape is different
|
241 |
+
if "emb_layers" in lllite_name or (
|
242 |
+
"attn2" in lllite_name and ("to_k" in lllite_name or "to_v" in lllite_name)
|
243 |
+
):
|
244 |
+
continue
|
245 |
+
|
246 |
+
if ATTN1_2_ONLY:
|
247 |
+
if not ("attn1" in lllite_name or "attn2" in lllite_name):
|
248 |
+
continue
|
249 |
+
if ATTN_QKV_ONLY:
|
250 |
+
if "to_out" in lllite_name:
|
251 |
+
continue
|
252 |
+
|
253 |
+
if ATTN1_ETC_ONLY:
|
254 |
+
if "proj_out" in lllite_name:
|
255 |
+
pass
|
256 |
+
elif "attn1" in lllite_name and (
|
257 |
+
"to_k" in lllite_name or "to_v" in lllite_name or "to_out" in lllite_name
|
258 |
+
):
|
259 |
+
pass
|
260 |
+
elif "ff_net_2" in lllite_name:
|
261 |
+
pass
|
262 |
+
else:
|
263 |
+
continue
|
264 |
+
|
265 |
+
child_module.set_lllite(depth, cond_emb_dim, lllite_name, mlp_dim, dropout, multiplier)
|
266 |
+
modules.append(child_module)
|
267 |
+
|
268 |
+
return modules
|
269 |
+
|
270 |
+
target_modules = SdxlUNet2DConditionModelControlNetLLLite.UNET_TARGET_REPLACE_MODULE
|
271 |
+
if not TRANSFORMER_ONLY:
|
272 |
+
target_modules = target_modules + SdxlUNet2DConditionModelControlNetLLLite.UNET_TARGET_REPLACE_MODULE_CONV2D_3X3
|
273 |
+
|
274 |
+
# create module instances
|
275 |
+
self.lllite_modules = apply_to_modules(self, target_modules)
|
276 |
+
logger.info(f"enable ControlNet LLLite for U-Net: {len(self.lllite_modules)} modules.")
|
277 |
+
|
278 |
+
# def prepare_optimizer_params(self):
|
279 |
+
def prepare_params(self):
|
280 |
+
train_params = []
|
281 |
+
non_train_params = []
|
282 |
+
for name, p in self.named_parameters():
|
283 |
+
if "lllite" in name:
|
284 |
+
train_params.append(p)
|
285 |
+
else:
|
286 |
+
non_train_params.append(p)
|
287 |
+
logger.info(f"count of trainable parameters: {len(train_params)}")
|
288 |
+
logger.info(f"count of non-trainable parameters: {len(non_train_params)}")
|
289 |
+
|
290 |
+
for p in non_train_params:
|
291 |
+
p.requires_grad_(False)
|
292 |
+
|
293 |
+
# without this, an error occurs in the optimizer
|
294 |
+
# RuntimeError: element 0 of tensors does not require grad and does not have a grad_fn
|
295 |
+
non_train_params[0].requires_grad_(True)
|
296 |
+
|
297 |
+
for p in train_params:
|
298 |
+
p.requires_grad_(True)
|
299 |
+
|
300 |
+
return train_params
|
301 |
+
|
302 |
+
# def prepare_grad_etc(self):
|
303 |
+
# self.requires_grad_(True)
|
304 |
+
|
305 |
+
# def on_epoch_start(self):
|
306 |
+
# self.train()
|
307 |
+
|
308 |
+
def get_trainable_params(self):
|
309 |
+
return [p[1] for p in self.named_parameters() if "lllite" in p[0]]
|
310 |
+
|
311 |
+
def save_lllite_weights(self, file, dtype, metadata):
|
312 |
+
if metadata is not None and len(metadata) == 0:
|
313 |
+
metadata = None
|
314 |
+
|
315 |
+
org_state_dict = self.state_dict()
|
316 |
+
|
317 |
+
# copy LLLite keys from org_state_dict to state_dict with key conversion
|
318 |
+
state_dict = {}
|
319 |
+
for key in org_state_dict.keys():
|
320 |
+
# split with ".lllite"
|
321 |
+
pos = key.find(".lllite")
|
322 |
+
if pos < 0:
|
323 |
+
continue
|
324 |
+
lllite_key = SdxlUNet2DConditionModelControlNetLLLite.LLLITE_PREFIX + "." + key[:pos]
|
325 |
+
lllite_key = lllite_key.replace(".", "_") + key[pos:]
|
326 |
+
lllite_key = lllite_key.replace(".lllite_", ".")
|
327 |
+
state_dict[lllite_key] = org_state_dict[key]
|
328 |
+
|
329 |
+
if dtype is not None:
|
330 |
+
for key in list(state_dict.keys()):
|
331 |
+
v = state_dict[key]
|
332 |
+
v = v.detach().clone().to("cpu").to(dtype)
|
333 |
+
state_dict[key] = v
|
334 |
+
|
335 |
+
if os.path.splitext(file)[1] == ".safetensors":
|
336 |
+
from safetensors.torch import save_file
|
337 |
+
|
338 |
+
save_file(state_dict, file, metadata)
|
339 |
+
else:
|
340 |
+
torch.save(state_dict, file)
|
341 |
+
|
342 |
+
def load_lllite_weights(self, file, non_lllite_unet_sd=None):
|
343 |
+
r"""
|
344 |
+
LLLiteの重みを読み込まない(initされた値を使う)場合はfileにNoneを指定する。
|
345 |
+
この場合、non_lllite_unet_sdにはU-Netのstate_dictを指定する。
|
346 |
+
|
347 |
+
If you do not want to load LLLite weights (use initialized values), specify None for file.
|
348 |
+
In this case, specify the state_dict of U-Net for non_lllite_unet_sd.
|
349 |
+
"""
|
350 |
+
if not file:
|
351 |
+
state_dict = self.state_dict()
|
352 |
+
for key in non_lllite_unet_sd:
|
353 |
+
if key in state_dict:
|
354 |
+
state_dict[key] = non_lllite_unet_sd[key]
|
355 |
+
info = self.load_state_dict(state_dict, False)
|
356 |
+
return info
|
357 |
+
|
358 |
+
if os.path.splitext(file)[1] == ".safetensors":
|
359 |
+
from safetensors.torch import load_file
|
360 |
+
|
361 |
+
weights_sd = load_file(file)
|
362 |
+
else:
|
363 |
+
weights_sd = torch.load(file, map_location="cpu")
|
364 |
+
|
365 |
+
# module_name = module_name.replace("_block", "@blocks")
|
366 |
+
# module_name = module_name.replace("_layer", "@layer")
|
367 |
+
# module_name = module_name.replace("to_", "to@")
|
368 |
+
# module_name = module_name.replace("time_embed", "time@embed")
|
369 |
+
# module_name = module_name.replace("label_emb", "label@emb")
|
370 |
+
# module_name = module_name.replace("skip_connection", "skip@connection")
|
371 |
+
# module_name = module_name.replace("proj_in", "proj@in")
|
372 |
+
# module_name = module_name.replace("proj_out", "proj@out")
|
373 |
+
pattern = re.compile(r"(_block|_layer|to_|time_embed|label_emb|skip_connection|proj_in|proj_out)")
|
374 |
+
|
375 |
+
# convert to lllite with U-Net state dict
|
376 |
+
state_dict = non_lllite_unet_sd.copy() if non_lllite_unet_sd is not None else {}
|
377 |
+
for key in weights_sd.keys():
|
378 |
+
# split with "."
|
379 |
+
pos = key.find(".")
|
380 |
+
if pos < 0:
|
381 |
+
continue
|
382 |
+
|
383 |
+
module_name = key[:pos]
|
384 |
+
weight_name = key[pos + 1 :] # exclude "."
|
385 |
+
module_name = module_name.replace(SdxlUNet2DConditionModelControlNetLLLite.LLLITE_PREFIX + "_", "")
|
386 |
+
|
387 |
+
# これはうまくいかない。逆変換を考えなかった設計が悪い / this does not work well. bad design because I didn't think about inverse conversion
|
388 |
+
# module_name = module_name.replace("_", ".")
|
389 |
+
|
390 |
+
# ださいけどSDXLのU-Netの "_" を "@" に変換する / ugly but convert "_" of SDXL U-Net to "@"
|
391 |
+
matches = pattern.findall(module_name)
|
392 |
+
if matches is not None:
|
393 |
+
for m in matches:
|
394 |
+
logger.info(f"{module_name} {m}")
|
395 |
+
module_name = module_name.replace(m, m.replace("_", "@"))
|
396 |
+
module_name = module_name.replace("_", ".")
|
397 |
+
module_name = module_name.replace("@", "_")
|
398 |
+
|
399 |
+
lllite_key = module_name + ".lllite_" + weight_name
|
400 |
+
|
401 |
+
state_dict[lllite_key] = weights_sd[key]
|
402 |
+
|
403 |
+
info = self.load_state_dict(state_dict, False)
|
404 |
+
return info
|
405 |
+
|
406 |
+
def forward(self, x, timesteps=None, context=None, y=None, cond_image=None, **kwargs):
|
407 |
+
for m in self.lllite_modules:
|
408 |
+
m.set_cond_image(cond_image)
|
409 |
+
return super().forward(x, timesteps, context, y, **kwargs)
|
410 |
+
|
411 |
+
|
412 |
+
def replace_unet_linear_and_conv2d():
|
413 |
+
logger.info("replace torch.nn.Linear and torch.nn.Conv2d to LLLiteLinear and LLLiteConv2d in U-Net")
|
414 |
+
sdxl_original_unet.torch.nn.Linear = LLLiteLinear
|
415 |
+
sdxl_original_unet.torch.nn.Conv2d = LLLiteConv2d
|
416 |
+
|
417 |
+
|
418 |
+
if __name__ == "__main__":
|
419 |
+
# デバッグ用 / for debug
|
420 |
+
|
421 |
+
# sdxl_original_unet.USE_REENTRANT = False
|
422 |
+
replace_unet_linear_and_conv2d()
|
423 |
+
|
424 |
+
# test shape etc
|
425 |
+
logger.info("create unet")
|
426 |
+
unet = SdxlUNet2DConditionModelControlNetLLLite()
|
427 |
+
|
428 |
+
logger.info("enable ControlNet-LLLite")
|
429 |
+
unet.apply_lllite(32, 64, None, False, 1.0)
|
430 |
+
unet.to("cuda") # .to(torch.float16)
|
431 |
+
|
432 |
+
# from safetensors.torch import load_file
|
433 |
+
|
434 |
+
# model_sd = load_file(r"E:\Work\SD\Models\sdxl\sd_xl_base_1.0_0.9vae.safetensors")
|
435 |
+
# unet_sd = {}
|
436 |
+
|
437 |
+
# # copy U-Net keys from unet_state_dict to state_dict
|
438 |
+
# prefix = "model.diffusion_model."
|
439 |
+
# for key in model_sd.keys():
|
440 |
+
# if key.startswith(prefix):
|
441 |
+
# converted_key = key[len(prefix) :]
|
442 |
+
# unet_sd[converted_key] = model_sd[key]
|
443 |
+
|
444 |
+
# info = unet.load_lllite_weights("r:/lllite_from_unet.safetensors", unet_sd)
|
445 |
+
# logger.info(info)
|
446 |
+
|
447 |
+
# logger.info(unet)
|
448 |
+
|
449 |
+
# logger.info number of parameters
|
450 |
+
params = unet.prepare_params()
|
451 |
+
logger.info(f"number of parameters {sum(p.numel() for p in params)}")
|
452 |
+
# logger.info("type any key to continue")
|
453 |
+
# input()
|
454 |
+
|
455 |
+
unet.set_use_memory_efficient_attention(True, False)
|
456 |
+
unet.set_gradient_checkpointing(True)
|
457 |
+
unet.train() # for gradient checkpointing
|
458 |
+
|
459 |
+
# # visualize
|
460 |
+
# import torchviz
|
461 |
+
# logger.info("run visualize")
|
462 |
+
# controlnet.set_control(conditioning_image)
|
463 |
+
# output = unet(x, t, ctx, y)
|
464 |
+
# logger.info("make_dot")
|
465 |
+
# image = torchviz.make_dot(output, params=dict(controlnet.named_parameters()))
|
466 |
+
# logger.info("render")
|
467 |
+
# image.format = "svg" # "png"
|
468 |
+
# image.render("NeuralNet") # すごく時間がかかるので注意 / be careful because it takes a long time
|
469 |
+
# input()
|
470 |
+
|
471 |
+
import bitsandbytes
|
472 |
+
|
473 |
+
optimizer = bitsandbytes.adam.Adam8bit(params, 1e-3)
|
474 |
+
|
475 |
+
scaler = torch.cuda.amp.GradScaler(enabled=True)
|
476 |
+
|
477 |
+
logger.info("start training")
|
478 |
+
steps = 10
|
479 |
+
batch_size = 1
|
480 |
+
|
481 |
+
sample_param = [p for p in unet.named_parameters() if ".lllite_up." in p[0]][0]
|
482 |
+
for step in range(steps):
|
483 |
+
logger.info(f"step {step}")
|
484 |
+
|
485 |
+
conditioning_image = torch.rand(batch_size, 3, 1024, 1024).cuda() * 2.0 - 1.0
|
486 |
+
x = torch.randn(batch_size, 4, 128, 128).cuda()
|
487 |
+
t = torch.randint(low=0, high=10, size=(batch_size,)).cuda()
|
488 |
+
ctx = torch.randn(batch_size, 77, 2048).cuda()
|
489 |
+
y = torch.randn(batch_size, sdxl_original_unet.ADM_IN_CHANNELS).cuda()
|
490 |
+
|
491 |
+
with torch.cuda.amp.autocast(enabled=True, dtype=torch.bfloat16):
|
492 |
+
output = unet(x, t, ctx, y, conditioning_image)
|
493 |
+
target = torch.randn_like(output)
|
494 |
+
loss = torch.nn.functional.mse_loss(output, target)
|
495 |
+
|
496 |
+
scaler.scale(loss).backward()
|
497 |
+
scaler.step(optimizer)
|
498 |
+
scaler.update()
|
499 |
+
optimizer.zero_grad(set_to_none=True)
|
500 |
+
logger.info(sample_param)
|
501 |
+
|
502 |
+
# from safetensors.torch import save_file
|
503 |
+
|
504 |
+
# logger.info("save weights")
|
505 |
+
# unet.save_lllite_weights("r:/lllite_from_unet.safetensors", torch.float16, None)
|