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A/blob/main/loralib/layers.py
|
4 |
+
# https://github.com/cloneofsimo/lora/blob/master/lora_diffusion/lora.py
|
5 |
+
|
6 |
+
# temporary implementation of LoRA-FA: https://arxiv.org/abs/2308.03303
|
7 |
+
# need to be refactored and merged to lora.py
|
8 |
+
|
9 |
+
import math
|
10 |
+
import os
|
11 |
+
from typing import Dict, List, Optional, Tuple, Type, Union
|
12 |
+
from diffusers import AutoencoderKL
|
13 |
+
from transformers import CLIPTextModel
|
14 |
+
import numpy as np
|
15 |
+
import torch
|
16 |
+
import re
|
17 |
+
from library.utils import setup_logging
|
18 |
+
setup_logging()
|
19 |
+
import logging
|
20 |
+
logger = logging.getLogger(__name__)
|
21 |
+
|
22 |
+
RE_UPDOWN = re.compile(r"(up|down)_blocks_(\d+)_(resnets|upsamplers|downsamplers|attentions)_(\d+)_")
|
23 |
+
|
24 |
+
|
25 |
+
class LoRAModule(torch.nn.Module):
|
26 |
+
"""
|
27 |
+
replaces forward method of the original Linear, instead of replacing the original Linear module.
|
28 |
+
"""
|
29 |
+
|
30 |
+
def __init__(
|
31 |
+
self,
|
32 |
+
lora_name,
|
33 |
+
org_module: torch.nn.Module,
|
34 |
+
multiplier=1.0,
|
35 |
+
lora_dim=4,
|
36 |
+
alpha=1,
|
37 |
+
dropout=None,
|
38 |
+
rank_dropout=None,
|
39 |
+
module_dropout=None,
|
40 |
+
):
|
41 |
+
"""if alpha == 0 or None, alpha is rank (no scaling)."""
|
42 |
+
super().__init__()
|
43 |
+
self.lora_name = lora_name
|
44 |
+
|
45 |
+
if org_module.__class__.__name__ == "Conv2d":
|
46 |
+
in_dim = org_module.in_channels
|
47 |
+
out_dim = org_module.out_channels
|
48 |
+
else:
|
49 |
+
in_dim = org_module.in_features
|
50 |
+
out_dim = org_module.out_features
|
51 |
+
|
52 |
+
# if limit_rank:
|
53 |
+
# self.lora_dim = min(lora_dim, in_dim, out_dim)
|
54 |
+
# if self.lora_dim != lora_dim:
|
55 |
+
# logger.info(f"{lora_name} dim (rank) is changed to: {self.lora_dim}")
|
56 |
+
# else:
|
57 |
+
self.lora_dim = lora_dim
|
58 |
+
|
59 |
+
if org_module.__class__.__name__ == "Conv2d":
|
60 |
+
kernel_size = org_module.kernel_size
|
61 |
+
stride = org_module.stride
|
62 |
+
padding = org_module.padding
|
63 |
+
self.lora_down = torch.nn.Conv2d(in_dim, self.lora_dim, kernel_size, stride, padding, bias=False)
|
64 |
+
self.lora_up = torch.nn.Conv2d(self.lora_dim, out_dim, (1, 1), (1, 1), bias=False)
|
65 |
+
else:
|
66 |
+
self.lora_down = torch.nn.Linear(in_dim, self.lora_dim, bias=False)
|
67 |
+
self.lora_up = torch.nn.Linear(self.lora_dim, out_dim, bias=False)
|
68 |
+
|
69 |
+
if type(alpha) == torch.Tensor:
|
70 |
+
alpha = alpha.detach().float().numpy() # without casting, bf16 causes error
|
71 |
+
alpha = self.lora_dim if alpha is None or alpha == 0 else alpha
|
72 |
+
self.scale = alpha / self.lora_dim
|
73 |
+
self.register_buffer("alpha", torch.tensor(alpha)) # 定数として扱える
|
74 |
+
|
75 |
+
# # same as microsoft's
|
76 |
+
# torch.nn.init.kaiming_uniform_(self.lora_down.weight, a=math.sqrt(5))
|
77 |
+
|
78 |
+
# according to the paper, initialize LoRA-A (down) as normal distribution
|
79 |
+
torch.nn.init.normal_(self.lora_down.weight, std=math.sqrt(2.0 / (in_dim + self.lora_dim)))
|
80 |
+
|
81 |
+
torch.nn.init.zeros_(self.lora_up.weight)
|
82 |
+
|
83 |
+
self.multiplier = multiplier
|
84 |
+
self.org_module = org_module # remove in applying
|
85 |
+
self.dropout = dropout
|
86 |
+
self.rank_dropout = rank_dropout
|
87 |
+
self.module_dropout = module_dropout
|
88 |
+
|
89 |
+
def get_trainable_params(self):
|
90 |
+
params = self.named_parameters()
|
91 |
+
trainable_params = []
|
92 |
+
for param in params:
|
93 |
+
if param[0] == "lora_up.weight": # up only
|
94 |
+
trainable_params.append(param[1])
|
95 |
+
return trainable_params
|
96 |
+
|
97 |
+
def requires_grad_(self, requires_grad: bool = True):
|
98 |
+
self.lora_up.requires_grad_(requires_grad)
|
99 |
+
self.lora_down.requires_grad_(False)
|
100 |
+
return self
|
101 |
+
|
102 |
+
def apply_to(self):
|
103 |
+
self.org_forward = self.org_module.forward
|
104 |
+
self.org_module.forward = self.forward
|
105 |
+
del self.org_module
|
106 |
+
|
107 |
+
def forward(self, x):
|
108 |
+
org_forwarded = self.org_forward(x)
|
109 |
+
|
110 |
+
# module dropout
|
111 |
+
if self.module_dropout is not None and self.training:
|
112 |
+
if torch.rand(1) < self.module_dropout:
|
113 |
+
return org_forwarded
|
114 |
+
|
115 |
+
lx = self.lora_down(x)
|
116 |
+
|
117 |
+
# normal dropout
|
118 |
+
if self.dropout is not None and self.training:
|
119 |
+
lx = torch.nn.functional.dropout(lx, p=self.dropout)
|
120 |
+
|
121 |
+
# rank dropout
|
122 |
+
if self.rank_dropout is not None and self.training:
|
123 |
+
mask = torch.rand((lx.size(0), self.lora_dim), device=lx.device) > self.rank_dropout
|
124 |
+
if len(lx.size()) == 3:
|
125 |
+
mask = mask.unsqueeze(1) # for Text Encoder
|
126 |
+
elif len(lx.size()) == 4:
|
127 |
+
mask = mask.unsqueeze(-1).unsqueeze(-1) # for Conv2d
|
128 |
+
lx = lx * mask
|
129 |
+
|
130 |
+
# scaling for rank dropout: treat as if the rank is changed
|
131 |
+
# maskから計算することも考えられるが、augmentation的な効果を期待してrank_dropoutを用いる
|
132 |
+
scale = self.scale * (1.0 / (1.0 - self.rank_dropout)) # redundant for readability
|
133 |
+
else:
|
134 |
+
scale = self.scale
|
135 |
+
|
136 |
+
lx = self.lora_up(lx)
|
137 |
+
|
138 |
+
return org_forwarded + lx * self.multiplier * scale
|
139 |
+
|
140 |
+
|
141 |
+
class LoRAInfModule(LoRAModule):
|
142 |
+
def __init__(
|
143 |
+
self,
|
144 |
+
lora_name,
|
145 |
+
org_module: torch.nn.Module,
|
146 |
+
multiplier=1.0,
|
147 |
+
lora_dim=4,
|
148 |
+
alpha=1,
|
149 |
+
**kwargs,
|
150 |
+
):
|
151 |
+
# no dropout for inference
|
152 |
+
super().__init__(lora_name, org_module, multiplier, lora_dim, alpha)
|
153 |
+
|
154 |
+
self.org_module_ref = [org_module] # 後から参照できるように
|
155 |
+
self.enabled = True
|
156 |
+
|
157 |
+
# check regional or not by lora_name
|
158 |
+
self.text_encoder = False
|
159 |
+
if lora_name.startswith("lora_te_"):
|
160 |
+
self.regional = False
|
161 |
+
self.use_sub_prompt = True
|
162 |
+
self.text_encoder = True
|
163 |
+
elif "attn2_to_k" in lora_name or "attn2_to_v" in lora_name:
|
164 |
+
self.regional = False
|
165 |
+
self.use_sub_prompt = True
|
166 |
+
elif "time_emb" in lora_name:
|
167 |
+
self.regional = False
|
168 |
+
self.use_sub_prompt = False
|
169 |
+
else:
|
170 |
+
self.regional = True
|
171 |
+
self.use_sub_prompt = False
|
172 |
+
|
173 |
+
self.network: LoRANetwork = None
|
174 |
+
|
175 |
+
def set_network(self, network):
|
176 |
+
self.network = network
|
177 |
+
|
178 |
+
# freezeしてマージする
|
179 |
+
def merge_to(self, sd, dtype, device):
|
180 |
+
# get up/down weight
|
181 |
+
up_weight = sd["lora_up.weight"].to(torch.float).to(device)
|
182 |
+
down_weight = sd["lora_down.weight"].to(torch.float).to(device)
|
183 |
+
|
184 |
+
# extract weight from org_module
|
185 |
+
org_sd = self.org_module.state_dict()
|
186 |
+
weight = org_sd["weight"].to(torch.float)
|
187 |
+
|
188 |
+
# merge weight
|
189 |
+
if len(weight.size()) == 2:
|
190 |
+
# linear
|
191 |
+
weight = weight + self.multiplier * (up_weight @ down_weight) * self.scale
|
192 |
+
elif down_weight.size()[2:4] == (1, 1):
|
193 |
+
# conv2d 1x1
|
194 |
+
weight = (
|
195 |
+
weight
|
196 |
+
+ self.multiplier
|
197 |
+
* (up_weight.squeeze(3).squeeze(2) @ down_weight.squeeze(3).squeeze(2)).unsqueeze(2).unsqueeze(3)
|
198 |
+
* self.scale
|
199 |
+
)
|
200 |
+
else:
|
201 |
+
# conv2d 3x3
|
202 |
+
conved = torch.nn.functional.conv2d(down_weight.permute(1, 0, 2, 3), up_weight).permute(1, 0, 2, 3)
|
203 |
+
# logger.info(conved.size(), weight.size(), module.stride, module.padding)
|
204 |
+
weight = weight + self.multiplier * conved * self.scale
|
205 |
+
|
206 |
+
# set weight to org_module
|
207 |
+
org_sd["weight"] = weight.to(dtype)
|
208 |
+
self.org_module.load_state_dict(org_sd)
|
209 |
+
|
210 |
+
# 復元できるマージのため、このモジュールのweightを返す
|
211 |
+
def get_weight(self, multiplier=None):
|
212 |
+
if multiplier is None:
|
213 |
+
multiplier = self.multiplier
|
214 |
+
|
215 |
+
# get up/down weight from module
|
216 |
+
up_weight = self.lora_up.weight.to(torch.float)
|
217 |
+
down_weight = self.lora_down.weight.to(torch.float)
|
218 |
+
|
219 |
+
# pre-calculated weight
|
220 |
+
if len(down_weight.size()) == 2:
|
221 |
+
# linear
|
222 |
+
weight = self.multiplier * (up_weight @ down_weight) * self.scale
|
223 |
+
elif down_weight.size()[2:4] == (1, 1):
|
224 |
+
# conv2d 1x1
|
225 |
+
weight = (
|
226 |
+
self.multiplier
|
227 |
+
* (up_weight.squeeze(3).squeeze(2) @ down_weight.squeeze(3).squeeze(2)).unsqueeze(2).unsqueeze(3)
|
228 |
+
* self.scale
|
229 |
+
)
|
230 |
+
else:
|
231 |
+
# conv2d 3x3
|
232 |
+
conved = torch.nn.functional.conv2d(down_weight.permute(1, 0, 2, 3), up_weight).permute(1, 0, 2, 3)
|
233 |
+
weight = self.multiplier * conved * self.scale
|
234 |
+
|
235 |
+
return weight
|
236 |
+
|
237 |
+
def set_region(self, region):
|
238 |
+
self.region = region
|
239 |
+
self.region_mask = None
|
240 |
+
|
241 |
+
def default_forward(self, x):
|
242 |
+
# logger.info("default_forward", self.lora_name, x.size())
|
243 |
+
return self.org_forward(x) + self.lora_up(self.lora_down(x)) * self.multiplier * self.scale
|
244 |
+
|
245 |
+
def forward(self, x):
|
246 |
+
if not self.enabled:
|
247 |
+
return self.org_forward(x)
|
248 |
+
|
249 |
+
if self.network is None or self.network.sub_prompt_index is None:
|
250 |
+
return self.default_forward(x)
|
251 |
+
if not self.regional and not self.use_sub_prompt:
|
252 |
+
return self.default_forward(x)
|
253 |
+
|
254 |
+
if self.regional:
|
255 |
+
return self.regional_forward(x)
|
256 |
+
else:
|
257 |
+
return self.sub_prompt_forward(x)
|
258 |
+
|
259 |
+
def get_mask_for_x(self, x):
|
260 |
+
# calculate size from shape of x
|
261 |
+
if len(x.size()) == 4:
|
262 |
+
h, w = x.size()[2:4]
|
263 |
+
area = h * w
|
264 |
+
else:
|
265 |
+
area = x.size()[1]
|
266 |
+
|
267 |
+
mask = self.network.mask_dic[area]
|
268 |
+
if mask is None:
|
269 |
+
raise ValueError(f"mask is None for resolution {area}")
|
270 |
+
if len(x.size()) != 4:
|
271 |
+
mask = torch.reshape(mask, (1, -1, 1))
|
272 |
+
return mask
|
273 |
+
|
274 |
+
def regional_forward(self, x):
|
275 |
+
if "attn2_to_out" in self.lora_name:
|
276 |
+
return self.to_out_forward(x)
|
277 |
+
|
278 |
+
if self.network.mask_dic is None: # sub_prompt_index >= 3
|
279 |
+
return self.default_forward(x)
|
280 |
+
|
281 |
+
# apply mask for LoRA result
|
282 |
+
lx = self.lora_up(self.lora_down(x)) * self.multiplier * self.scale
|
283 |
+
mask = self.get_mask_for_x(lx)
|
284 |
+
# logger.info("regional", self.lora_name, self.network.sub_prompt_index, lx.size(), mask.size())
|
285 |
+
lx = lx * mask
|
286 |
+
|
287 |
+
x = self.org_forward(x)
|
288 |
+
x = x + lx
|
289 |
+
|
290 |
+
if "attn2_to_q" in self.lora_name and self.network.is_last_network:
|
291 |
+
x = self.postp_to_q(x)
|
292 |
+
|
293 |
+
return x
|
294 |
+
|
295 |
+
def postp_to_q(self, x):
|
296 |
+
# repeat x to num_sub_prompts
|
297 |
+
has_real_uncond = x.size()[0] // self.network.batch_size == 3
|
298 |
+
qc = self.network.batch_size # uncond
|
299 |
+
qc += self.network.batch_size * self.network.num_sub_prompts # cond
|
300 |
+
if has_real_uncond:
|
301 |
+
qc += self.network.batch_size # real_uncond
|
302 |
+
|
303 |
+
query = torch.zeros((qc, x.size()[1], x.size()[2]), device=x.device, dtype=x.dtype)
|
304 |
+
query[: self.network.batch_size] = x[: self.network.batch_size]
|
305 |
+
|
306 |
+
for i in range(self.network.batch_size):
|
307 |
+
qi = self.network.batch_size + i * self.network.num_sub_prompts
|
308 |
+
query[qi : qi + self.network.num_sub_prompts] = x[self.network.batch_size + i]
|
309 |
+
|
310 |
+
if has_real_uncond:
|
311 |
+
query[-self.network.batch_size :] = x[-self.network.batch_size :]
|
312 |
+
|
313 |
+
# logger.info("postp_to_q", self.lora_name, x.size(), query.size(), self.network.num_sub_prompts)
|
314 |
+
return query
|
315 |
+
|
316 |
+
def sub_prompt_forward(self, x):
|
317 |
+
if x.size()[0] == self.network.batch_size: # if uncond in text_encoder, do not apply LoRA
|
318 |
+
return self.org_forward(x)
|
319 |
+
|
320 |
+
emb_idx = self.network.sub_prompt_index
|
321 |
+
if not self.text_encoder:
|
322 |
+
emb_idx += self.network.batch_size
|
323 |
+
|
324 |
+
# apply sub prompt of X
|
325 |
+
lx = x[emb_idx :: self.network.num_sub_prompts]
|
326 |
+
lx = self.lora_up(self.lora_down(lx)) * self.multiplier * self.scale
|
327 |
+
|
328 |
+
# logger.info("sub_prompt_forward", self.lora_name, x.size(), lx.size(), emb_idx)
|
329 |
+
|
330 |
+
x = self.org_forward(x)
|
331 |
+
x[emb_idx :: self.network.num_sub_prompts] += lx
|
332 |
+
|
333 |
+
return x
|
334 |
+
|
335 |
+
def to_out_forward(self, x):
|
336 |
+
# logger.info("to_out_forward", self.lora_name, x.size(), self.network.is_last_network)
|
337 |
+
|
338 |
+
if self.network.is_last_network:
|
339 |
+
masks = [None] * self.network.num_sub_prompts
|
340 |
+
self.network.shared[self.lora_name] = (None, masks)
|
341 |
+
else:
|
342 |
+
lx, masks = self.network.shared[self.lora_name]
|
343 |
+
|
344 |
+
# call own LoRA
|
345 |
+
x1 = x[self.network.batch_size + self.network.sub_prompt_index :: self.network.num_sub_prompts]
|
346 |
+
lx1 = self.lora_up(self.lora_down(x1)) * self.multiplier * self.scale
|
347 |
+
|
348 |
+
if self.network.is_last_network:
|
349 |
+
lx = torch.zeros(
|
350 |
+
(self.network.num_sub_prompts * self.network.batch_size, *lx1.size()[1:]), device=lx1.device, dtype=lx1.dtype
|
351 |
+
)
|
352 |
+
self.network.shared[self.lora_name] = (lx, masks)
|
353 |
+
|
354 |
+
# logger.info("to_out_forward", lx.size(), lx1.size(), self.network.sub_prompt_index, self.network.num_sub_prompts)
|
355 |
+
lx[self.network.sub_prompt_index :: self.network.num_sub_prompts] += lx1
|
356 |
+
masks[self.network.sub_prompt_index] = self.get_mask_for_x(lx1)
|
357 |
+
|
358 |
+
# if not last network, return x and masks
|
359 |
+
x = self.org_forward(x)
|
360 |
+
if not self.network.is_last_network:
|
361 |
+
return x
|
362 |
+
|
363 |
+
lx, masks = self.network.shared.pop(self.lora_name)
|
364 |
+
|
365 |
+
# if last network, combine separated x with mask weighted sum
|
366 |
+
has_real_uncond = x.size()[0] // self.network.batch_size == self.network.num_sub_prompts + 2
|
367 |
+
|
368 |
+
out = torch.zeros((self.network.batch_size * (3 if has_real_uncond else 2), *x.size()[1:]), device=x.device, dtype=x.dtype)
|
369 |
+
out[: self.network.batch_size] = x[: self.network.batch_size] # uncond
|
370 |
+
if has_real_uncond:
|
371 |
+
out[-self.network.batch_size :] = x[-self.network.batch_size :] # real_uncond
|
372 |
+
|
373 |
+
# logger.info("to_out_forward", self.lora_name, self.network.sub_prompt_index, self.network.num_sub_prompts)
|
374 |
+
# for i in range(len(masks)):
|
375 |
+
# if masks[i] is None:
|
376 |
+
# masks[i] = torch.zeros_like(masks[-1])
|
377 |
+
|
378 |
+
mask = torch.cat(masks)
|
379 |
+
mask_sum = torch.sum(mask, dim=0) + 1e-4
|
380 |
+
for i in range(self.network.batch_size):
|
381 |
+
# 1枚の画像ごとに処理する
|
382 |
+
lx1 = lx[i * self.network.num_sub_prompts : (i + 1) * self.network.num_sub_prompts]
|
383 |
+
lx1 = lx1 * mask
|
384 |
+
lx1 = torch.sum(lx1, dim=0)
|
385 |
+
|
386 |
+
xi = self.network.batch_size + i * self.network.num_sub_prompts
|
387 |
+
x1 = x[xi : xi + self.network.num_sub_prompts]
|
388 |
+
x1 = x1 * mask
|
389 |
+
x1 = torch.sum(x1, dim=0)
|
390 |
+
x1 = x1 / mask_sum
|
391 |
+
|
392 |
+
x1 = x1 + lx1
|
393 |
+
out[self.network.batch_size + i] = x1
|
394 |
+
|
395 |
+
# logger.info("to_out_forward", x.size(), out.size(), has_real_uncond)
|
396 |
+
return out
|
397 |
+
|
398 |
+
|
399 |
+
def parse_block_lr_kwargs(nw_kwargs):
|
400 |
+
down_lr_weight = nw_kwargs.get("down_lr_weight", None)
|
401 |
+
mid_lr_weight = nw_kwargs.get("mid_lr_weight", None)
|
402 |
+
up_lr_weight = nw_kwargs.get("up_lr_weight", None)
|
403 |
+
|
404 |
+
# 以上のいずれにも設定がない場合は無効としてNoneを返す
|
405 |
+
if down_lr_weight is None and mid_lr_weight is None and up_lr_weight is None:
|
406 |
+
return None, None, None
|
407 |
+
|
408 |
+
# extract learning rate weight for each block
|
409 |
+
if down_lr_weight is not None:
|
410 |
+
# if some parameters are not set, use zero
|
411 |
+
if "," in down_lr_weight:
|
412 |
+
down_lr_weight = [(float(s) if s else 0.0) for s in down_lr_weight.split(",")]
|
413 |
+
|
414 |
+
if mid_lr_weight is not None:
|
415 |
+
mid_lr_weight = float(mid_lr_weight)
|
416 |
+
|
417 |
+
if up_lr_weight is not None:
|
418 |
+
if "," in up_lr_weight:
|
419 |
+
up_lr_weight = [(float(s) if s else 0.0) for s in up_lr_weight.split(",")]
|
420 |
+
|
421 |
+
down_lr_weight, mid_lr_weight, up_lr_weight = get_block_lr_weight(
|
422 |
+
down_lr_weight, mid_lr_weight, up_lr_weight, float(nw_kwargs.get("block_lr_zero_threshold", 0.0))
|
423 |
+
)
|
424 |
+
|
425 |
+
return down_lr_weight, mid_lr_weight, up_lr_weight
|
426 |
+
|
427 |
+
|
428 |
+
def create_network(
|
429 |
+
multiplier: float,
|
430 |
+
network_dim: Optional[int],
|
431 |
+
network_alpha: Optional[float],
|
432 |
+
vae: AutoencoderKL,
|
433 |
+
text_encoder: Union[CLIPTextModel, List[CLIPTextModel]],
|
434 |
+
unet,
|
435 |
+
neuron_dropout: Optional[float] = None,
|
436 |
+
**kwargs,
|
437 |
+
):
|
438 |
+
if network_dim is None:
|
439 |
+
network_dim = 4 # default
|
440 |
+
if network_alpha is None:
|
441 |
+
network_alpha = 1.0
|
442 |
+
|
443 |
+
# extract dim/alpha for conv2d, and block dim
|
444 |
+
conv_dim = kwargs.get("conv_dim", None)
|
445 |
+
conv_alpha = kwargs.get("conv_alpha", None)
|
446 |
+
if conv_dim is not None:
|
447 |
+
conv_dim = int(conv_dim)
|
448 |
+
if conv_alpha is None:
|
449 |
+
conv_alpha = 1.0
|
450 |
+
else:
|
451 |
+
conv_alpha = float(conv_alpha)
|
452 |
+
|
453 |
+
# block dim/alpha/lr
|
454 |
+
block_dims = kwargs.get("block_dims", None)
|
455 |
+
down_lr_weight, mid_lr_weight, up_lr_weight = parse_block_lr_kwargs(kwargs)
|
456 |
+
|
457 |
+
# 以上のいずれかに指定があればblockごとのdim(rank)を有効にする
|
458 |
+
if block_dims is not None or down_lr_weight is not None or mid_lr_weight is not None or up_lr_weight is not None:
|
459 |
+
block_alphas = kwargs.get("block_alphas", None)
|
460 |
+
conv_block_dims = kwargs.get("conv_block_dims", None)
|
461 |
+
conv_block_alphas = kwargs.get("conv_block_alphas", None)
|
462 |
+
|
463 |
+
block_dims, block_alphas, conv_block_dims, conv_block_alphas = get_block_dims_and_alphas(
|
464 |
+
block_dims, block_alphas, network_dim, network_alpha, conv_block_dims, conv_block_alphas, conv_dim, conv_alpha
|
465 |
+
)
|
466 |
+
|
467 |
+
# remove block dim/alpha without learning rate
|
468 |
+
block_dims, block_alphas, conv_block_dims, conv_block_alphas = remove_block_dims_and_alphas(
|
469 |
+
block_dims, block_alphas, conv_block_dims, conv_block_alphas, down_lr_weight, mid_lr_weight, up_lr_weight
|
470 |
+
)
|
471 |
+
|
472 |
+
else:
|
473 |
+
block_alphas = None
|
474 |
+
conv_block_dims = None
|
475 |
+
conv_block_alphas = None
|
476 |
+
|
477 |
+
# rank/module dropout
|
478 |
+
rank_dropout = kwargs.get("rank_dropout", None)
|
479 |
+
if rank_dropout is not None:
|
480 |
+
rank_dropout = float(rank_dropout)
|
481 |
+
module_dropout = kwargs.get("module_dropout", None)
|
482 |
+
if module_dropout is not None:
|
483 |
+
module_dropout = float(module_dropout)
|
484 |
+
|
485 |
+
# すごく引数が多いな ( ^ω^)・・・
|
486 |
+
network = LoRANetwork(
|
487 |
+
text_encoder,
|
488 |
+
unet,
|
489 |
+
multiplier=multiplier,
|
490 |
+
lora_dim=network_dim,
|
491 |
+
alpha=network_alpha,
|
492 |
+
dropout=neuron_dropout,
|
493 |
+
rank_dropout=rank_dropout,
|
494 |
+
module_dropout=module_dropout,
|
495 |
+
conv_lora_dim=conv_dim,
|
496 |
+
conv_alpha=conv_alpha,
|
497 |
+
block_dims=block_dims,
|
498 |
+
block_alphas=block_alphas,
|
499 |
+
conv_block_dims=conv_block_dims,
|
500 |
+
conv_block_alphas=conv_block_alphas,
|
501 |
+
varbose=True,
|
502 |
+
)
|
503 |
+
|
504 |
+
if up_lr_weight is not None or mid_lr_weight is not None or down_lr_weight is not None:
|
505 |
+
network.set_block_lr_weight(up_lr_weight, mid_lr_weight, down_lr_weight)
|
506 |
+
|
507 |
+
return network
|
508 |
+
|
509 |
+
|
510 |
+
# このメソッドは外部から呼び出される可能性を考慮しておく
|
511 |
+
# network_dim, network_alpha にはデフォルト値が入っている。
|
512 |
+
# block_dims, block_alphas は両方ともNoneまたは両方とも値が入っている
|
513 |
+
# conv_dim, conv_alpha は両方ともNoneまたは両方とも値が入っている
|
514 |
+
def get_block_dims_and_alphas(
|
515 |
+
block_dims, block_alphas, network_dim, network_alpha, conv_block_dims, conv_block_alphas, conv_dim, conv_alpha
|
516 |
+
):
|
517 |
+
num_total_blocks = LoRANetwork.NUM_OF_BLOCKS * 2 + 1
|
518 |
+
|
519 |
+
def parse_ints(s):
|
520 |
+
return [int(i) for i in s.split(",")]
|
521 |
+
|
522 |
+
def parse_floats(s):
|
523 |
+
return [float(i) for i in s.split(",")]
|
524 |
+
|
525 |
+
# block_dimsとblock_alphasをパースする。必ず値が入る
|
526 |
+
if block_dims is not None:
|
527 |
+
block_dims = parse_ints(block_dims)
|
528 |
+
assert (
|
529 |
+
len(block_dims) == num_total_blocks
|
530 |
+
), f"block_dims must have {num_total_blocks} elements / block_dimsは{num_total_blocks}個指定してください"
|
531 |
+
else:
|
532 |
+
logger.warning(f"block_dims is not specified. all dims are set to {network_dim} / block_dimsが指定されていません。すべてのdimは{network_dim}になります")
|
533 |
+
block_dims = [network_dim] * num_total_blocks
|
534 |
+
|
535 |
+
if block_alphas is not None:
|
536 |
+
block_alphas = parse_floats(block_alphas)
|
537 |
+
assert (
|
538 |
+
len(block_alphas) == num_total_blocks
|
539 |
+
), f"block_alphas must have {num_total_blocks} elements / block_alphasは{num_total_blocks}個指定してください"
|
540 |
+
else:
|
541 |
+
logger.warning(
|
542 |
+
f"block_alphas is not specified. all alphas are set to {network_alpha} / block_alphasが指定されていません。すべてのalphaは{network_alpha}になります"
|
543 |
+
)
|
544 |
+
block_alphas = [network_alpha] * num_total_blocks
|
545 |
+
|
546 |
+
# conv_block_dimsとconv_block_alphasを、指定がある場合のみパースする。指定がなければconv_dimとconv_alphaを使う
|
547 |
+
if conv_block_dims is not None:
|
548 |
+
conv_block_dims = parse_ints(conv_block_dims)
|
549 |
+
assert (
|
550 |
+
len(conv_block_dims) == num_total_blocks
|
551 |
+
), f"conv_block_dims must have {num_total_blocks} elements / conv_block_dimsは{num_total_blocks}個指定してください"
|
552 |
+
|
553 |
+
if conv_block_alphas is not None:
|
554 |
+
conv_block_alphas = parse_floats(conv_block_alphas)
|
555 |
+
assert (
|
556 |
+
len(conv_block_alphas) == num_total_blocks
|
557 |
+
), f"conv_block_alphas must have {num_total_blocks} elements / conv_block_alphasは{num_total_blocks}個指定してください"
|
558 |
+
else:
|
559 |
+
if conv_alpha is None:
|
560 |
+
conv_alpha = 1.0
|
561 |
+
logger.warning(
|
562 |
+
f"conv_block_alphas is not specified. all alphas are set to {conv_alpha} / conv_block_alphasが指定されていません。すべてのalphaは{conv_alpha}になります"
|
563 |
+
)
|
564 |
+
conv_block_alphas = [conv_alpha] * num_total_blocks
|
565 |
+
else:
|
566 |
+
if conv_dim is not None:
|
567 |
+
logger.warning(
|
568 |
+
f"conv_dim/alpha for all blocks are set to {conv_dim} and {conv_alpha} / すべてのブロックのconv_dimとalphaは{conv_dim}および{conv_alpha}になります"
|
569 |
+
)
|
570 |
+
conv_block_dims = [conv_dim] * num_total_blocks
|
571 |
+
conv_block_alphas = [conv_alpha] * num_total_blocks
|
572 |
+
else:
|
573 |
+
conv_block_dims = None
|
574 |
+
conv_block_alphas = None
|
575 |
+
|
576 |
+
return block_dims, block_alphas, conv_block_dims, conv_block_alphas
|
577 |
+
|
578 |
+
|
579 |
+
# 層別学習率用に層ごとの学習率に対する倍率を定義する、外部から呼び出される可能性を考慮しておく
|
580 |
+
def get_block_lr_weight(
|
581 |
+
down_lr_weight, mid_lr_weight, up_lr_weight, zero_threshold
|
582 |
+
) -> Tuple[List[float], List[float], List[float]]:
|
583 |
+
# パラメータ未指定時は何もせず、今までと同じ動作とする
|
584 |
+
if up_lr_weight is None and mid_lr_weight is None and down_lr_weight is None:
|
585 |
+
return None, None, None
|
586 |
+
|
587 |
+
max_len = LoRANetwork.NUM_OF_BLOCKS # フルモデル相当でのup,downの層の数
|
588 |
+
|
589 |
+
def get_list(name_with_suffix) -> List[float]:
|
590 |
+
import math
|
591 |
+
|
592 |
+
tokens = name_with_suffix.split("+")
|
593 |
+
name = tokens[0]
|
594 |
+
base_lr = float(tokens[1]) if len(tokens) > 1 else 0.0
|
595 |
+
|
596 |
+
if name == "cosine":
|
597 |
+
return [math.sin(math.pi * (i / (max_len - 1)) / 2) + base_lr for i in reversed(range(max_len))]
|
598 |
+
elif name == "sine":
|
599 |
+
return [math.sin(math.pi * (i / (max_len - 1)) / 2) + base_lr for i in range(max_len)]
|
600 |
+
elif name == "linear":
|
601 |
+
return [i / (max_len - 1) + base_lr for i in range(max_len)]
|
602 |
+
elif name == "reverse_linear":
|
603 |
+
return [i / (max_len - 1) + base_lr for i in reversed(range(max_len))]
|
604 |
+
elif name == "zeros":
|
605 |
+
return [0.0 + base_lr] * max_len
|
606 |
+
else:
|
607 |
+
logger.error(
|
608 |
+
"Unknown lr_weight argument %s is used. Valid arguments: / 不明なlr_weightの引数 %s が使われました。有効な引数:\n\tcosine, sine, linear, reverse_linear, zeros"
|
609 |
+
% (name)
|
610 |
+
)
|
611 |
+
return None
|
612 |
+
|
613 |
+
if type(down_lr_weight) == str:
|
614 |
+
down_lr_weight = get_list(down_lr_weight)
|
615 |
+
if type(up_lr_weight) == str:
|
616 |
+
up_lr_weight = get_list(up_lr_weight)
|
617 |
+
|
618 |
+
if (up_lr_weight != None and len(up_lr_weight) > max_len) or (down_lr_weight != None and len(down_lr_weight) > max_len):
|
619 |
+
logger.warning("down_weight or up_weight is too long. Parameters after %d-th are ignored." % max_len)
|
620 |
+
logger.warning("down_weightもしくはup_weightが長すぎます。%d個目以降のパラメータは無視されます。" % max_len)
|
621 |
+
up_lr_weight = up_lr_weight[:max_len]
|
622 |
+
down_lr_weight = down_lr_weight[:max_len]
|
623 |
+
|
624 |
+
if (up_lr_weight != None and len(up_lr_weight) < max_len) or (down_lr_weight != None and len(down_lr_weight) < max_len):
|
625 |
+
logger.warning("down_weight or up_weight is too short. Parameters after %d-th are filled with 1." % max_len)
|
626 |
+
logger.warning("down_weightもしくはup_weightが短すぎます。%d個目までの不足したパラメータは1で補われます。" % max_len)
|
627 |
+
|
628 |
+
if down_lr_weight != None and len(down_lr_weight) < max_len:
|
629 |
+
down_lr_weight = down_lr_weight + [1.0] * (max_len - len(down_lr_weight))
|
630 |
+
if up_lr_weight != None and len(up_lr_weight) < max_len:
|
631 |
+
up_lr_weight = up_lr_weight + [1.0] * (max_len - len(up_lr_weight))
|
632 |
+
|
633 |
+
if (up_lr_weight != None) or (mid_lr_weight != None) or (down_lr_weight != None):
|
634 |
+
logger.info("apply block learning rate / 階層別学習率を適用します。")
|
635 |
+
if down_lr_weight != None:
|
636 |
+
down_lr_weight = [w if w > zero_threshold else 0 for w in down_lr_weight]
|
637 |
+
logger.info(f"down_lr_weight (shallower -> deeper, 浅い層->深い層): {down_lr_weight}")
|
638 |
+
else:
|
639 |
+
logger.info("down_lr_weight: all 1.0, すべて1.0")
|
640 |
+
|
641 |
+
if mid_lr_weight != None:
|
642 |
+
mid_lr_weight = mid_lr_weight if mid_lr_weight > zero_threshold else 0
|
643 |
+
logger.info(f"mid_lr_weight: {mid_lr_weight}")
|
644 |
+
else:
|
645 |
+
logger.info("mid_lr_weight: 1.0")
|
646 |
+
|
647 |
+
if up_lr_weight != None:
|
648 |
+
up_lr_weight = [w if w > zero_threshold else 0 for w in up_lr_weight]
|
649 |
+
logger.info(f"up_lr_weight (deeper -> shallower, 深い層->浅い層): {up_lr_weight}")
|
650 |
+
else:
|
651 |
+
logger.info("up_lr_weight: all 1.0, すべて1.0")
|
652 |
+
|
653 |
+
return down_lr_weight, mid_lr_weight, up_lr_weight
|
654 |
+
|
655 |
+
|
656 |
+
# lr_weightが0のblockをblock_dimsから除外する、外部から呼び出す可能性を考慮しておく
|
657 |
+
def remove_block_dims_and_alphas(
|
658 |
+
block_dims, block_alphas, conv_block_dims, conv_block_alphas, down_lr_weight, mid_lr_weight, up_lr_weight
|
659 |
+
):
|
660 |
+
# set 0 to block dim without learning rate to remove the block
|
661 |
+
if down_lr_weight != None:
|
662 |
+
for i, lr in enumerate(down_lr_weight):
|
663 |
+
if lr == 0:
|
664 |
+
block_dims[i] = 0
|
665 |
+
if conv_block_dims is not None:
|
666 |
+
conv_block_dims[i] = 0
|
667 |
+
if mid_lr_weight != None:
|
668 |
+
if mid_lr_weight == 0:
|
669 |
+
block_dims[LoRANetwork.NUM_OF_BLOCKS] = 0
|
670 |
+
if conv_block_dims is not None:
|
671 |
+
conv_block_dims[LoRANetwork.NUM_OF_BLOCKS] = 0
|
672 |
+
if up_lr_weight != None:
|
673 |
+
for i, lr in enumerate(up_lr_weight):
|
674 |
+
if lr == 0:
|
675 |
+
block_dims[LoRANetwork.NUM_OF_BLOCKS + 1 + i] = 0
|
676 |
+
if conv_block_dims is not None:
|
677 |
+
conv_block_dims[LoRANetwork.NUM_OF_BLOCKS + 1 + i] = 0
|
678 |
+
|
679 |
+
return block_dims, block_alphas, conv_block_dims, conv_block_alphas
|
680 |
+
|
681 |
+
|
682 |
+
# 外部から呼び出す可能性を考慮しておく
|
683 |
+
def get_block_index(lora_name: str) -> int:
|
684 |
+
block_idx = -1 # invalid lora name
|
685 |
+
|
686 |
+
m = RE_UPDOWN.search(lora_name)
|
687 |
+
if m:
|
688 |
+
g = m.groups()
|
689 |
+
i = int(g[1])
|
690 |
+
j = int(g[3])
|
691 |
+
if g[2] == "resnets":
|
692 |
+
idx = 3 * i + j
|
693 |
+
elif g[2] == "attentions":
|
694 |
+
idx = 3 * i + j
|
695 |
+
elif g[2] == "upsamplers" or g[2] == "downsamplers":
|
696 |
+
idx = 3 * i + 2
|
697 |
+
|
698 |
+
if g[0] == "down":
|
699 |
+
block_idx = 1 + idx # 0に該当するLoRAは存在しない
|
700 |
+
elif g[0] == "up":
|
701 |
+
block_idx = LoRANetwork.NUM_OF_BLOCKS + 1 + idx
|
702 |
+
|
703 |
+
elif "mid_block_" in lora_name:
|
704 |
+
block_idx = LoRANetwork.NUM_OF_BLOCKS # idx=12
|
705 |
+
|
706 |
+
return block_idx
|
707 |
+
|
708 |
+
|
709 |
+
# Create network from weights for inference, weights are not loaded here (because can be merged)
|
710 |
+
def create_network_from_weights(multiplier, file, vae, text_encoder, unet, weights_sd=None, for_inference=False, **kwargs):
|
711 |
+
if weights_sd is None:
|
712 |
+
if os.path.splitext(file)[1] == ".safetensors":
|
713 |
+
from safetensors.torch import load_file, safe_open
|
714 |
+
|
715 |
+
weights_sd = load_file(file)
|
716 |
+
else:
|
717 |
+
weights_sd = torch.load(file, map_location="cpu")
|
718 |
+
|
719 |
+
# get dim/alpha mapping
|
720 |
+
modules_dim = {}
|
721 |
+
modules_alpha = {}
|
722 |
+
for key, value in weights_sd.items():
|
723 |
+
if "." not in key:
|
724 |
+
continue
|
725 |
+
|
726 |
+
lora_name = key.split(".")[0]
|
727 |
+
if "alpha" in key:
|
728 |
+
modules_alpha[lora_name] = value
|
729 |
+
elif "lora_down" in key:
|
730 |
+
dim = value.size()[0]
|
731 |
+
modules_dim[lora_name] = dim
|
732 |
+
# logger.info(lora_name, value.size(), dim)
|
733 |
+
|
734 |
+
# support old LoRA without alpha
|
735 |
+
for key in modules_dim.keys():
|
736 |
+
if key not in modules_alpha:
|
737 |
+
modules_alpha[key] = modules_dim[key]
|
738 |
+
|
739 |
+
module_class = LoRAInfModule if for_inference else LoRAModule
|
740 |
+
|
741 |
+
network = LoRANetwork(
|
742 |
+
text_encoder, unet, multiplier=multiplier, modules_dim=modules_dim, modules_alpha=modules_alpha, module_class=module_class
|
743 |
+
)
|
744 |
+
|
745 |
+
# block lr
|
746 |
+
down_lr_weight, mid_lr_weight, up_lr_weight = parse_block_lr_kwargs(kwargs)
|
747 |
+
if up_lr_weight is not None or mid_lr_weight is not None or down_lr_weight is not None:
|
748 |
+
network.set_block_lr_weight(up_lr_weight, mid_lr_weight, down_lr_weight)
|
749 |
+
|
750 |
+
return network, weights_sd
|
751 |
+
|
752 |
+
|
753 |
+
class LoRANetwork(torch.nn.Module):
|
754 |
+
NUM_OF_BLOCKS = 12 # フルモデル相当でのup,downの層の数
|
755 |
+
|
756 |
+
UNET_TARGET_REPLACE_MODULE = ["Transformer2DModel"]
|
757 |
+
UNET_TARGET_REPLACE_MODULE_CONV2D_3X3 = ["ResnetBlock2D", "Downsample2D", "Upsample2D"]
|
758 |
+
TEXT_ENCODER_TARGET_REPLACE_MODULE = ["CLIPAttention", "CLIPMLP"]
|
759 |
+
LORA_PREFIX_UNET = "lora_unet"
|
760 |
+
LORA_PREFIX_TEXT_ENCODER = "lora_te"
|
761 |
+
|
762 |
+
# SDXL: must starts with LORA_PREFIX_TEXT_ENCODER
|
763 |
+
LORA_PREFIX_TEXT_ENCODER1 = "lora_te1"
|
764 |
+
LORA_PREFIX_TEXT_ENCODER2 = "lora_te2"
|
765 |
+
|
766 |
+
def __init__(
|
767 |
+
self,
|
768 |
+
text_encoder: Union[List[CLIPTextModel], CLIPTextModel],
|
769 |
+
unet,
|
770 |
+
multiplier: float = 1.0,
|
771 |
+
lora_dim: int = 4,
|
772 |
+
alpha: float = 1,
|
773 |
+
dropout: Optional[float] = None,
|
774 |
+
rank_dropout: Optional[float] = None,
|
775 |
+
module_dropout: Optional[float] = None,
|
776 |
+
conv_lora_dim: Optional[int] = None,
|
777 |
+
conv_alpha: Optional[float] = None,
|
778 |
+
block_dims: Optional[List[int]] = None,
|
779 |
+
block_alphas: Optional[List[float]] = None,
|
780 |
+
conv_block_dims: Optional[List[int]] = None,
|
781 |
+
conv_block_alphas: Optional[List[float]] = None,
|
782 |
+
modules_dim: Optional[Dict[str, int]] = None,
|
783 |
+
modules_alpha: Optional[Dict[str, int]] = None,
|
784 |
+
module_class: Type[object] = LoRAModule,
|
785 |
+
varbose: Optional[bool] = False,
|
786 |
+
) -> None:
|
787 |
+
"""
|
788 |
+
LoRA network: すごく引数が多いが、パターンは以下の通り
|
789 |
+
1. lora_dimとalphaを指定
|
790 |
+
2. lora_dim、alpha、conv_lora_dim、conv_alphaを指定
|
791 |
+
3. block_dimsとblock_alphasを指定 : Conv2d3x3には適用しない
|
792 |
+
4. block_dims、block_alphas、conv_block_dims、conv_block_alphasを指定 : Conv2d3x3にも適用する
|
793 |
+
5. modules_dimとmodules_alphaを指定 (推論用)
|
794 |
+
"""
|
795 |
+
super().__init__()
|
796 |
+
self.multiplier = multiplier
|
797 |
+
|
798 |
+
self.lora_dim = lora_dim
|
799 |
+
self.alpha = alpha
|
800 |
+
self.conv_lora_dim = conv_lora_dim
|
801 |
+
self.conv_alpha = conv_alpha
|
802 |
+
self.dropout = dropout
|
803 |
+
self.rank_dropout = rank_dropout
|
804 |
+
self.module_dropout = module_dropout
|
805 |
+
|
806 |
+
if modules_dim is not None:
|
807 |
+
logger.info(f"create LoRA network from weights")
|
808 |
+
elif block_dims is not None:
|
809 |
+
logger.info(f"create LoRA network from block_dims")
|
810 |
+
logger.info(f"neuron dropout: p={self.dropout}, rank dropout: p={self.rank_dropout}, module dropout: p={self.module_dropout}")
|
811 |
+
logger.info(f"block_dims: {block_dims}")
|
812 |
+
logger.info(f"block_alphas: {block_alphas}")
|
813 |
+
if conv_block_dims is not None:
|
814 |
+
logger.info(f"conv_block_dims: {conv_block_dims}")
|
815 |
+
logger.info(f"conv_block_alphas: {conv_block_alphas}")
|
816 |
+
else:
|
817 |
+
logger.info(f"create LoRA network. base dim (rank): {lora_dim}, alpha: {alpha}")
|
818 |
+
logger.info(f"neuron dropout: p={self.dropout}, rank dropout: p={self.rank_dropout}, module dropout: p={self.module_dropout}")
|
819 |
+
if self.conv_lora_dim is not None:
|
820 |
+
logger.info(f"apply LoRA to Conv2d with kernel size (3,3). dim (rank): {self.conv_lora_dim}, alpha: {self.conv_alpha}")
|
821 |
+
|
822 |
+
# create module instances
|
823 |
+
def create_modules(
|
824 |
+
is_unet: bool,
|
825 |
+
text_encoder_idx: Optional[int], # None, 1, 2
|
826 |
+
root_module: torch.nn.Module,
|
827 |
+
target_replace_modules: List[torch.nn.Module],
|
828 |
+
) -> List[LoRAModule]:
|
829 |
+
prefix = (
|
830 |
+
self.LORA_PREFIX_UNET
|
831 |
+
if is_unet
|
832 |
+
else (
|
833 |
+
self.LORA_PREFIX_TEXT_ENCODER
|
834 |
+
if text_encoder_idx is None
|
835 |
+
else (self.LORA_PREFIX_TEXT_ENCODER1 if text_encoder_idx == 1 else self.LORA_PREFIX_TEXT_ENCODER2)
|
836 |
+
)
|
837 |
+
)
|
838 |
+
loras = []
|
839 |
+
skipped = []
|
840 |
+
for name, module in root_module.named_modules():
|
841 |
+
if module.__class__.__name__ in target_replace_modules:
|
842 |
+
for child_name, child_module in module.named_modules():
|
843 |
+
is_linear = child_module.__class__.__name__ == "Linear"
|
844 |
+
is_conv2d = child_module.__class__.__name__ == "Conv2d"
|
845 |
+
is_conv2d_1x1 = is_conv2d and child_module.kernel_size == (1, 1)
|
846 |
+
|
847 |
+
if is_linear or is_conv2d:
|
848 |
+
lora_name = prefix + "." + name + "." + child_name
|
849 |
+
lora_name = lora_name.replace(".", "_")
|
850 |
+
|
851 |
+
dim = None
|
852 |
+
alpha = None
|
853 |
+
|
854 |
+
if modules_dim is not None:
|
855 |
+
# モジュール指定あり
|
856 |
+
if lora_name in modules_dim:
|
857 |
+
dim = modules_dim[lora_name]
|
858 |
+
alpha = modules_alpha[lora_name]
|
859 |
+
elif is_unet and block_dims is not None:
|
860 |
+
# U-Netでblock_dims指定あり
|
861 |
+
block_idx = get_block_index(lora_name)
|
862 |
+
if is_linear or is_conv2d_1x1:
|
863 |
+
dim = block_dims[block_idx]
|
864 |
+
alpha = block_alphas[block_idx]
|
865 |
+
elif conv_block_dims is not None:
|
866 |
+
dim = conv_block_dims[block_idx]
|
867 |
+
alpha = conv_block_alphas[block_idx]
|
868 |
+
else:
|
869 |
+
# 通常、すべて対象とする
|
870 |
+
if is_linear or is_conv2d_1x1:
|
871 |
+
dim = self.lora_dim
|
872 |
+
alpha = self.alpha
|
873 |
+
elif self.conv_lora_dim is not None:
|
874 |
+
dim = self.conv_lora_dim
|
875 |
+
alpha = self.conv_alpha
|
876 |
+
|
877 |
+
if dim is None or dim == 0:
|
878 |
+
# skipした情報を出力
|
879 |
+
if is_linear or is_conv2d_1x1 or (self.conv_lora_dim is not None or conv_block_dims is not None):
|
880 |
+
skipped.append(lora_name)
|
881 |
+
continue
|
882 |
+
|
883 |
+
lora = module_class(
|
884 |
+
lora_name,
|
885 |
+
child_module,
|
886 |
+
self.multiplier,
|
887 |
+
dim,
|
888 |
+
alpha,
|
889 |
+
dropout=dropout,
|
890 |
+
rank_dropout=rank_dropout,
|
891 |
+
module_dropout=module_dropout,
|
892 |
+
)
|
893 |
+
loras.append(lora)
|
894 |
+
return loras, skipped
|
895 |
+
|
896 |
+
text_encoders = text_encoder if type(text_encoder) == list else [text_encoder]
|
897 |
+
|
898 |
+
# create LoRA for text encoder
|
899 |
+
# 毎回すべてのモジュールを作るのは無駄なので要検討
|
900 |
+
self.text_encoder_loras = []
|
901 |
+
skipped_te = []
|
902 |
+
for i, text_encoder in enumerate(text_encoders):
|
903 |
+
if len(text_encoders) > 1:
|
904 |
+
index = i + 1
|
905 |
+
logger.info(f"create LoRA for Text Encoder {index}:")
|
906 |
+
else:
|
907 |
+
index = None
|
908 |
+
logger.info(f"create LoRA for Text Encoder:")
|
909 |
+
|
910 |
+
text_encoder_loras, skipped = create_modules(False, index, text_encoder, LoRANetwork.TEXT_ENCODER_TARGET_REPLACE_MODULE)
|
911 |
+
self.text_encoder_loras.extend(text_encoder_loras)
|
912 |
+
skipped_te += skipped
|
913 |
+
logger.info(f"create LoRA for Text Encoder: {len(self.text_encoder_loras)} modules.")
|
914 |
+
|
915 |
+
# extend U-Net target modules if conv2d 3x3 is enabled, or load from weights
|
916 |
+
target_modules = LoRANetwork.UNET_TARGET_REPLACE_MODULE
|
917 |
+
if modules_dim is not None or self.conv_lora_dim is not None or conv_block_dims is not None:
|
918 |
+
target_modules += LoRANetwork.UNET_TARGET_REPLACE_MODULE_CONV2D_3X3
|
919 |
+
|
920 |
+
self.unet_loras, skipped_un = create_modules(True, None, unet, target_modules)
|
921 |
+
logger.info(f"create LoRA for U-Net: {len(self.unet_loras)} modules.")
|
922 |
+
|
923 |
+
skipped = skipped_te + skipped_un
|
924 |
+
if varbose and len(skipped) > 0:
|
925 |
+
logger.warning(
|
926 |
+
f"because block_lr_weight is 0 or dim (rank) is 0, {len(skipped)} LoRA modules are skipped / block_lr_weightまたはdim (rank)が0の為、次の{len(skipped)}個のLoRAモジュールはスキップされます:"
|
927 |
+
)
|
928 |
+
for name in skipped:
|
929 |
+
logger.info(f"\t{name}")
|
930 |
+
|
931 |
+
self.up_lr_weight: List[float] = None
|
932 |
+
self.down_lr_weight: List[float] = None
|
933 |
+
self.mid_lr_weight: float = None
|
934 |
+
self.block_lr = False
|
935 |
+
|
936 |
+
# assertion
|
937 |
+
names = set()
|
938 |
+
for lora in self.text_encoder_loras + self.unet_loras:
|
939 |
+
assert lora.lora_name not in names, f"duplicated lora name: {lora.lora_name}"
|
940 |
+
names.add(lora.lora_name)
|
941 |
+
|
942 |
+
def set_multiplier(self, multiplier):
|
943 |
+
self.multiplier = multiplier
|
944 |
+
for lora in self.text_encoder_loras + self.unet_loras:
|
945 |
+
lora.multiplier = self.multiplier
|
946 |
+
|
947 |
+
def load_weights(self, file):
|
948 |
+
if os.path.splitext(file)[1] == ".safetensors":
|
949 |
+
from safetensors.torch import load_file
|
950 |
+
|
951 |
+
weights_sd = load_file(file)
|
952 |
+
else:
|
953 |
+
weights_sd = torch.load(file, map_location="cpu")
|
954 |
+
|
955 |
+
info = self.load_state_dict(weights_sd, False)
|
956 |
+
return info
|
957 |
+
|
958 |
+
def apply_to(self, text_encoder, unet, apply_text_encoder=True, apply_unet=True):
|
959 |
+
if apply_text_encoder:
|
960 |
+
logger.info("enable LoRA for text encoder")
|
961 |
+
else:
|
962 |
+
self.text_encoder_loras = []
|
963 |
+
|
964 |
+
if apply_unet:
|
965 |
+
logger.info("enable LoRA for U-Net")
|
966 |
+
else:
|
967 |
+
self.unet_loras = []
|
968 |
+
|
969 |
+
for lora in self.text_encoder_loras + self.unet_loras:
|
970 |
+
lora.apply_to()
|
971 |
+
self.add_module(lora.lora_name, lora)
|
972 |
+
|
973 |
+
# マージできるかどうかを返す
|
974 |
+
def is_mergeable(self):
|
975 |
+
return True
|
976 |
+
|
977 |
+
# TODO refactor to common function with apply_to
|
978 |
+
def merge_to(self, text_encoder, unet, weights_sd, dtype, device):
|
979 |
+
apply_text_encoder = apply_unet = False
|
980 |
+
for key in weights_sd.keys():
|
981 |
+
if key.startswith(LoRANetwork.LORA_PREFIX_TEXT_ENCODER):
|
982 |
+
apply_text_encoder = True
|
983 |
+
elif key.startswith(LoRANetwork.LORA_PREFIX_UNET):
|
984 |
+
apply_unet = True
|
985 |
+
|
986 |
+
if apply_text_encoder:
|
987 |
+
logger.info("enable LoRA for text encoder")
|
988 |
+
else:
|
989 |
+
self.text_encoder_loras = []
|
990 |
+
|
991 |
+
if apply_unet:
|
992 |
+
logger.info("enable LoRA for U-Net")
|
993 |
+
else:
|
994 |
+
self.unet_loras = []
|
995 |
+
|
996 |
+
for lora in self.text_encoder_loras + self.unet_loras:
|
997 |
+
sd_for_lora = {}
|
998 |
+
for key in weights_sd.keys():
|
999 |
+
if key.startswith(lora.lora_name):
|
1000 |
+
sd_for_lora[key[len(lora.lora_name) + 1 :]] = weights_sd[key]
|
1001 |
+
lora.merge_to(sd_for_lora, dtype, device)
|
1002 |
+
|
1003 |
+
logger.info(f"weights are merged")
|
1004 |
+
|
1005 |
+
# 層別学習率用に層ごとの学習率に対する倍率を定義する 引数の順番が逆だがとりあえず気にしない
|
1006 |
+
def set_block_lr_weight(
|
1007 |
+
self,
|
1008 |
+
up_lr_weight: List[float] = None,
|
1009 |
+
mid_lr_weight: float = None,
|
1010 |
+
down_lr_weight: List[float] = None,
|
1011 |
+
):
|
1012 |
+
self.block_lr = True
|
1013 |
+
self.down_lr_weight = down_lr_weight
|
1014 |
+
self.mid_lr_weight = mid_lr_weight
|
1015 |
+
self.up_lr_weight = up_lr_weight
|
1016 |
+
|
1017 |
+
def get_lr_weight(self, lora: LoRAModule) -> float:
|
1018 |
+
lr_weight = 1.0
|
1019 |
+
block_idx = get_block_index(lora.lora_name)
|
1020 |
+
if block_idx < 0:
|
1021 |
+
return lr_weight
|
1022 |
+
|
1023 |
+
if block_idx < LoRANetwork.NUM_OF_BLOCKS:
|
1024 |
+
if self.down_lr_weight != None:
|
1025 |
+
lr_weight = self.down_lr_weight[block_idx]
|
1026 |
+
elif block_idx == LoRANetwork.NUM_OF_BLOCKS:
|
1027 |
+
if self.mid_lr_weight != None:
|
1028 |
+
lr_weight = self.mid_lr_weight
|
1029 |
+
elif block_idx > LoRANetwork.NUM_OF_BLOCKS:
|
1030 |
+
if self.up_lr_weight != None:
|
1031 |
+
lr_weight = self.up_lr_weight[block_idx - LoRANetwork.NUM_OF_BLOCKS - 1]
|
1032 |
+
|
1033 |
+
return lr_weight
|
1034 |
+
|
1035 |
+
# 二つのText Encoderに別々の学習率を設定できるようにするといいかも
|
1036 |
+
def prepare_optimizer_params(self, text_encoder_lr, unet_lr, default_lr):
|
1037 |
+
self.requires_grad_(True)
|
1038 |
+
all_params = []
|
1039 |
+
|
1040 |
+
def enumerate_params(loras: List[LoRAModule]):
|
1041 |
+
params = []
|
1042 |
+
for lora in loras:
|
1043 |
+
# params.extend(lora.parameters())
|
1044 |
+
params.extend(lora.get_trainable_params())
|
1045 |
+
return params
|
1046 |
+
|
1047 |
+
if self.text_encoder_loras:
|
1048 |
+
param_data = {"params": enumerate_params(self.text_encoder_loras)}
|
1049 |
+
if text_encoder_lr is not None:
|
1050 |
+
param_data["lr"] = text_encoder_lr
|
1051 |
+
all_params.append(param_data)
|
1052 |
+
|
1053 |
+
if self.unet_loras:
|
1054 |
+
if self.block_lr:
|
1055 |
+
# 学習率のグラフをblockごとにしたいので、blockごとにloraを分類
|
1056 |
+
block_idx_to_lora = {}
|
1057 |
+
for lora in self.unet_loras:
|
1058 |
+
idx = get_block_index(lora.lora_name)
|
1059 |
+
if idx not in block_idx_to_lora:
|
1060 |
+
block_idx_to_lora[idx] = []
|
1061 |
+
block_idx_to_lora[idx].append(lora)
|
1062 |
+
|
1063 |
+
# blockごとにパラメータを設定する
|
1064 |
+
for idx, block_loras in block_idx_to_lora.items():
|
1065 |
+
param_data = {"params": enumerate_params(block_loras)}
|
1066 |
+
|
1067 |
+
if unet_lr is not None:
|
1068 |
+
param_data["lr"] = unet_lr * self.get_lr_weight(block_loras[0])
|
1069 |
+
elif default_lr is not None:
|
1070 |
+
param_data["lr"] = default_lr * self.get_lr_weight(block_loras[0])
|
1071 |
+
if ("lr" in param_data) and (param_data["lr"] == 0):
|
1072 |
+
continue
|
1073 |
+
all_params.append(param_data)
|
1074 |
+
|
1075 |
+
else:
|
1076 |
+
param_data = {"params": enumerate_params(self.unet_loras)}
|
1077 |
+
if unet_lr is not None:
|
1078 |
+
param_data["lr"] = unet_lr
|
1079 |
+
all_params.append(param_data)
|
1080 |
+
|
1081 |
+
return all_params
|
1082 |
+
|
1083 |
+
def enable_gradient_checkpointing(self):
|
1084 |
+
# not supported
|
1085 |
+
pass
|
1086 |
+
|
1087 |
+
def prepare_grad_etc(self, text_encoder, unet):
|
1088 |
+
self.requires_grad_(True)
|
1089 |
+
|
1090 |
+
def on_epoch_start(self, text_encoder, unet):
|
1091 |
+
self.train()
|
1092 |
+
|
1093 |
+
def get_trainable_params(self):
|
1094 |
+
return self.parameters()
|
1095 |
+
|
1096 |
+
def save_weights(self, file, dtype, metadata):
|
1097 |
+
if metadata is not None and len(metadata) == 0:
|
1098 |
+
metadata = None
|
1099 |
+
|
1100 |
+
state_dict = self.state_dict()
|
1101 |
+
|
1102 |
+
if dtype is not None:
|
1103 |
+
for key in list(state_dict.keys()):
|
1104 |
+
v = state_dict[key]
|
1105 |
+
v = v.detach().clone().to("cpu").to(dtype)
|
1106 |
+
state_dict[key] = v
|
1107 |
+
|
1108 |
+
if os.path.splitext(file)[1] == ".safetensors":
|
1109 |
+
from safetensors.torch import save_file
|
1110 |
+
from library import train_util
|
1111 |
+
|
1112 |
+
# Precalculate model hashes to save time on indexing
|
1113 |
+
if metadata is None:
|
1114 |
+
metadata = {}
|
1115 |
+
model_hash, legacy_hash = train_util.precalculate_safetensors_hashes(state_dict, metadata)
|
1116 |
+
metadata["sshs_model_hash"] = model_hash
|
1117 |
+
metadata["sshs_legacy_hash"] = legacy_hash
|
1118 |
+
|
1119 |
+
save_file(state_dict, file, metadata)
|
1120 |
+
else:
|
1121 |
+
torch.save(state_dict, file)
|
1122 |
+
|
1123 |
+
# mask is a tensor with values from 0 to 1
|
1124 |
+
def set_region(self, sub_prompt_index, is_last_network, mask):
|
1125 |
+
if mask.max() == 0:
|
1126 |
+
mask = torch.ones_like(mask)
|
1127 |
+
|
1128 |
+
self.mask = mask
|
1129 |
+
self.sub_prompt_index = sub_prompt_index
|
1130 |
+
self.is_last_network = is_last_network
|
1131 |
+
|
1132 |
+
for lora in self.text_encoder_loras + self.unet_loras:
|
1133 |
+
lora.set_network(self)
|
1134 |
+
|
1135 |
+
def set_current_generation(self, batch_size, num_sub_prompts, width, height, shared):
|
1136 |
+
self.batch_size = batch_size
|
1137 |
+
self.num_sub_prompts = num_sub_prompts
|
1138 |
+
self.current_size = (height, width)
|
1139 |
+
self.shared = shared
|
1140 |
+
|
1141 |
+
# create masks
|
1142 |
+
mask = self.mask
|
1143 |
+
mask_dic = {}
|
1144 |
+
mask = mask.unsqueeze(0).unsqueeze(1) # b(1),c(1),h,w
|
1145 |
+
ref_weight = self.text_encoder_loras[0].lora_down.weight if self.text_encoder_loras else self.unet_loras[0].lora_down.weight
|
1146 |
+
dtype = ref_weight.dtype
|
1147 |
+
device = ref_weight.device
|
1148 |
+
|
1149 |
+
def resize_add(mh, mw):
|
1150 |
+
# logger.info(mh, mw, mh * mw)
|
1151 |
+
m = torch.nn.functional.interpolate(mask, (mh, mw), mode="bilinear") # doesn't work in bf16
|
1152 |
+
m = m.to(device, dtype=dtype)
|
1153 |
+
mask_dic[mh * mw] = m
|
1154 |
+
|
1155 |
+
h = height // 8
|
1156 |
+
w = width // 8
|
1157 |
+
for _ in range(4):
|
1158 |
+
resize_add(h, w)
|
1159 |
+
if h % 2 == 1 or w % 2 == 1: # add extra shape if h/w is not divisible by 2
|
1160 |
+
resize_add(h + h % 2, w + w % 2)
|
1161 |
+
h = (h + 1) // 2
|
1162 |
+
w = (w + 1) // 2
|
1163 |
+
|
1164 |
+
self.mask_dic = mask_dic
|
1165 |
+
|
1166 |
+
def backup_weights(self):
|
1167 |
+
# 重みのバックアップを行う
|
1168 |
+
loras: List[LoRAInfModule] = self.text_encoder_loras + self.unet_loras
|
1169 |
+
for lora in loras:
|
1170 |
+
org_module = lora.org_module_ref[0]
|
1171 |
+
if not hasattr(org_module, "_lora_org_weight"):
|
1172 |
+
sd = org_module.state_dict()
|
1173 |
+
org_module._lora_org_weight = sd["weight"].detach().clone()
|
1174 |
+
org_module._lora_restored = True
|
1175 |
+
|
1176 |
+
def restore_weights(self):
|
1177 |
+
# 重みのリストアを行う
|
1178 |
+
loras: List[LoRAInfModule] = self.text_encoder_loras + self.unet_loras
|
1179 |
+
for lora in loras:
|
1180 |
+
org_module = lora.org_module_ref[0]
|
1181 |
+
if not org_module._lora_restored:
|
1182 |
+
sd = org_module.state_dict()
|
1183 |
+
sd["weight"] = org_module._lora_org_weight
|
1184 |
+
org_module.load_state_dict(sd)
|
1185 |
+
org_module._lora_restored = True
|
1186 |
+
|
1187 |
+
def pre_calculation(self):
|
1188 |
+
# 事前計算を行う
|
1189 |
+
loras: List[LoRAInfModule] = self.text_encoder_loras + self.unet_loras
|
1190 |
+
for lora in loras:
|
1191 |
+
org_module = lora.org_module_ref[0]
|
1192 |
+
sd = org_module.state_dict()
|
1193 |
+
|
1194 |
+
org_weight = sd["weight"]
|
1195 |
+
lora_weight = lora.get_weight().to(org_weight.device, dtype=org_weight.dtype)
|
1196 |
+
sd["weight"] = org_weight + lora_weight
|
1197 |
+
assert sd["weight"].shape == org_weight.shape
|
1198 |
+
org_module.load_state_dict(sd)
|
1199 |
+
|
1200 |
+
org_module._lora_restored = False
|
1201 |
+
lora.enabled = False
|
1202 |
+
|
1203 |
+
def apply_max_norm_regularization(self, max_norm_value, device):
|
1204 |
+
downkeys = []
|
1205 |
+
upkeys = []
|
1206 |
+
alphakeys = []
|
1207 |
+
norms = []
|
1208 |
+
keys_scaled = 0
|
1209 |
+
|
1210 |
+
state_dict = self.state_dict()
|
1211 |
+
for key in state_dict.keys():
|
1212 |
+
if "lora_down" in key and "weight" in key:
|
1213 |
+
downkeys.append(key)
|
1214 |
+
upkeys.append(key.replace("lora_down", "lora_up"))
|
1215 |
+
alphakeys.append(key.replace("lora_down.weight", "alpha"))
|
1216 |
+
|
1217 |
+
for i in range(len(downkeys)):
|
1218 |
+
down = state_dict[downkeys[i]].to(device)
|
1219 |
+
up = state_dict[upkeys[i]].to(device)
|
1220 |
+
alpha = state_dict[alphakeys[i]].to(device)
|
1221 |
+
dim = down.shape[0]
|
1222 |
+
scale = alpha / dim
|
1223 |
+
|
1224 |
+
if up.shape[2:] == (1, 1) and down.shape[2:] == (1, 1):
|
1225 |
+
updown = (up.squeeze(2).squeeze(2) @ down.squeeze(2).squeeze(2)).unsqueeze(2).unsqueeze(3)
|
1226 |
+
elif up.shape[2:] == (3, 3) or down.shape[2:] == (3, 3):
|
1227 |
+
updown = torch.nn.functional.conv2d(down.permute(1, 0, 2, 3), up).permute(1, 0, 2, 3)
|
1228 |
+
else:
|
1229 |
+
updown = up @ down
|
1230 |
+
|
1231 |
+
updown *= scale
|
1232 |
+
|
1233 |
+
norm = updown.norm().clamp(min=max_norm_value / 2)
|
1234 |
+
desired = torch.clamp(norm, max=max_norm_value)
|
1235 |
+
ratio = desired.cpu() / norm.cpu()
|
1236 |
+
sqrt_ratio = ratio**0.5
|
1237 |
+
if ratio != 1:
|
1238 |
+
keys_scaled += 1
|
1239 |
+
state_dict[upkeys[i]] *= sqrt_ratio
|
1240 |
+
state_dict[downkeys[i]] *= sqrt_ratio
|
1241 |
+
scalednorm = updown.norm() * ratio
|
1242 |
+
norms.append(scalednorm.item())
|
1243 |
+
|
1244 |
+
return keys_scaled, sum(norms) / len(norms), max(norms)
|