forked from munsy0227/kohya-colab
-
Notifications
You must be signed in to change notification settings - Fork 0
/
masked_loss.patch
202 lines (180 loc) · 8.3 KB
/
masked_loss.patch
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
Subject: [PATCH] add masked loss implementation
---
Index: library/train_util.py
IDEA additional info:
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
<+>UTF-8
===================================================================
diff --git a/library/train_util.py b/library/train_util.py
--- a/library/train_util.py (revision 89c30334016a27f1d890466151a61a46d8d1545e)
+++ b/library/train_util.py (revision 39382097618845ae543443d7d2bf02c6af7343d6)
@@ -100,6 +100,8 @@
self.latents_flipped: torch.Tensor = None
self.latents_npz: str = None
self.latents_npz_flipped: str = None
+ self.mask: np.ndarray = None
+ self.mask_flipped: np.ndarray = None
class BucketManager:
@@ -697,11 +699,32 @@
random.shuffle(self.buckets_indices)
self.bucket_manager.shuffle()
+ def load_mask(self, path):
+ try:
+ p = pathlib.Path(path)
+ mask_path = os.path.join(p.parent, 'mask', p.stem + '.png')
+ mask = np.array(Image.open(mask_path))
+ if len(mask.shape) > 2 and mask.max() <= 255:
+ print(mask.shape)
+ return np.array(Image.open(mask_path).convert("L"))
+ elif len(mask.shape) == 2 and mask.max() > 255:
+ print(mask.max())
+ return mask // (((2 ** 16) - 1) // 255)
+ elif len(mask.shape) == 2 and mask.max() <= 255:
+ return mask
+ else:
+ print(f"{mask_path} has invalid mask format: Defaulting to no mask")
+ return np.ones_like(np.array(Image.open(path).convert("L"))) * 255
+ except:
+ print(f"{mask_path} not found: Defaulting to no mask")
+ return np.ones_like(np.array(Image.open(path).convert("L"))) * 255
+
def load_image(self, image_path):
image = Image.open(image_path)
- if not image.mode == "RGB":
- image = image.convert("RGB")
+ if not image.mode == "RGBA":
+ image = image.convert("RGBA")
img = np.array(image, np.uint8)
+ img[..., -1] = self.load_mask(image_path)
return img
def trim_and_resize_if_required(self, subset: BaseSubset, image, reso, resized_size):
@@ -802,31 +825,37 @@
# iterate batches
for batch in tqdm(batches, smoothing=1, total=len(batches)):
images = []
+ masks = []
for info in batch:
image = self.load_image(info.absolute_path)
image = self.trim_and_resize_if_required(subset, image, info.bucket_reso, info.resized_size)
+ mask = image[:, :, -1] / 255 # grab alpha channel
+ image = image[:, :, :3] # drop alpha channel
image = self.image_transforms(image)
images.append(image)
+ masks.append(mask)
img_tensors = torch.stack(images, dim=0)
img_tensors = img_tensors.to(device=vae.device, dtype=vae.dtype)
latents = vae.encode(img_tensors).latent_dist.sample().to("cpu")
- for info, latent in zip(batch, latents):
+ for info, latent, mask in zip(batch, latents, masks):
if cache_to_disk:
np.savez(info.latents_npz, latent.float().numpy())
else:
info.latents = latent
+ info.mask = mask
if subset.flip_aug:
img_tensors = torch.flip(img_tensors, dims=[3])
latents = vae.encode(img_tensors).latent_dist.sample().to("cpu")
- for info, latent in zip(batch, latents):
+ for info, latent, mask in zip(batch, latents, masks):
if cache_to_disk:
np.savez(info.latents_npz_flipped, latent.float().numpy())
else:
info.latents_flipped = latent
+ info.mask_flipped = mask
def get_image_size(self, image_path):
image = Image.open(image_path)
@@ -913,6 +942,7 @@
input_ids_list = []
latents_list = []
images = []
+ masks = []
for image_key in bucket[image_index : image_index + bucket_batch_size]:
image_info = self.image_data[image_key]
@@ -921,7 +951,9 @@
# image/latentsを処理する
if image_info.latents is not None: # cache_latents=Trueの場合
- latents = image_info.latents if not subset.flip_aug or random.random() < 0.5 else image_info.latents_flipped
+ rand_flip = random.random()
+ latents = image_info.latents if not subset.flip_aug or rand_flip < .5 else image_info.latents_flipped
+ mask = image_info.mask if not subset.flip_aug or rand_flip < .5 else image_info.mask_flipped
image = None
elif image_info.latents_npz is not None: # FineTuningDatasetまたはcache_latents_to_disk=Trueの場合
latents = self.load_latents_from_npz(image_info, subset.flip_aug and random.random() >= 0.5)
@@ -930,6 +962,8 @@
else:
# 画像を読み込み、必要ならcropする
img, face_cx, face_cy, face_w, face_h = self.load_image_with_face_info(subset, image_info.absolute_path)
+ mask = img[:, :, -1] / 255 # grab alpha channel
+ img = img[:, :, :3] # drop alpha channel
im_h, im_w = img.shape[0:2]
if self.enable_bucket:
@@ -960,8 +994,10 @@
latents = None
image = self.image_transforms(img) # -1.0~1.0のtorch.Tensorになる
+ mask = torch.from_numpy(mask)
images.append(image)
+ masks.append(torch.tensor(mask))
latents_list.append(latents)
caption = self.process_caption(subset, image_info.caption)
@@ -998,7 +1034,7 @@
else:
images = None
example["images"] = images
-
+ example["masks"] = torch.stack(masks) if masks[0] is not None else None
example["latents"] = torch.stack(latents_list) if latents_list[0] is not None else None
example["captions"] = captions
@@ -2388,6 +2424,8 @@
"--bucket_no_upscale", action="store_true", help="make bucket for each image without upscaling / 画像を拡大せずbucketを作成します"
)
+ parser.add_argument("--masked_loss", action="store_true", help="Enable Masked Loss from Mask File")
+
parser.add_argument(
"--token_warmup_min",
type=int,
Index: train_network.py
IDEA additional info:
Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP
<+>UTF-8
===================================================================
diff --git a/train_network.py b/train_network.py
--- a/train_network.py (revision 89c30334016a27f1d890466151a61a46d8d1545e)
+++ b/train_network.py (revision 39382097618845ae543443d7d2bf02c6af7343d6)
@@ -11,6 +11,7 @@
from tqdm import tqdm
import torch
+import torch.nn.functional
from accelerate.utils import set_seed
from diffusers import DDPMScheduler
@@ -658,6 +659,26 @@
else:
target = noise
+ if args.masked_loss and batch['masks'] is not None:
+ mask = (
+ batch['masks']
+ .to(noise_pred.device)
+ .reshape(
+ noise_pred.shape[0], 1, noise_pred.shape[2] * 8, noise_pred.shape[3] * 8
+ )
+ )
+ # resize to match noise_pred
+ mask = torch.nn.functional.interpolate(
+ mask.float(),
+ size=noise_pred.shape[-2:],
+ mode="nearest",
+ )
+
+ mask = mask / mask.mean()
+
+ noise_pred = noise_pred * mask
+ target = target * mask
+
loss = torch.nn.functional.mse_loss(noise_pred.float(), target.float(), reduction="none")
loss = loss.mean([1, 2, 3])
@@ -721,6 +742,7 @@
loss_total += current_loss
avr_loss = loss_total / len(loss_list)
logs = {"loss": avr_loss} # , "lr": lr_scheduler.get_last_lr()[0]}
+
progress_bar.set_postfix(**logs)
if args.scale_weight_norms: