-
Notifications
You must be signed in to change notification settings - Fork 0
/
stargan.py
176 lines (147 loc) · 5.34 KB
/
stargan.py
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
import warnings
from typing import Tuple
import torch
from torch import nn
from config import cfg
from discriminator import Discriminator
from generator import Generator
from loss import DiscriminatorLoss, GeneratorLoss
from utils import permute_labels
warnings.filterwarnings("ignore")
class StarGan(nn.Module):
def __init__(
self,
height: int = 64,
width: int = 64,
n_domain: int = 5,
in_channels: int = 3,
device="cpu",
) -> None:
super(StarGan, self).__init__()
self.height = height
self.width = width
self.G = Generator(device, in_channels=in_channels + n_domain)
self.D = Discriminator(device, height, width, n_domain, in_channels)
self.generator_loss = GeneratorLoss(self.D)
self.discriminator_loss = DiscriminatorLoss(self.D)
self.optimizer_generator = torch.optim.Adam(
self.G.parameters(), lr=cfg.training.G.lr, betas=cfg.training.G.betas
)
self.optimizer_dicriminator = torch.optim.Adam(
self.D.parameters(), lr=cfg.training.D.lr, betas=cfg.training.D.betas
)
self.device = device
self.to(device)
def forward(self, x):
pass
def to(self, device):
self.D.to(device)
self.G.to(device)
def train(self):
self.G.train()
self.D.train()
def eval(self):
self.G.eval()
self.D.eval()
def concat_image_label(
self, image: torch.Tensor, label: torch.Tensor
) -> torch.Tensor:
"""
:param torch.Tensor image: size batch_size x 3 x height x width
:param torch.Tensor label: size batch_size x n_domain
:rtype: torch.Tensor
:returns: concatenated image and labels of size batch_size x (3 + n_domain) x height x width
"""
label = label[:, :, None, None].repeat(1, 1, self.height, self.width)
return torch.cat((image, label), dim=1)
def trainG(
self,
real_image: torch.Tensor,
labels_dataset: torch.Tensor,
labels_target: torch.Tensor,
) -> torch.Tensor:
"""
:param torch.Tensor real_image: real image from dataset
:param torch.Tensor labels_dataset: real domain labels to image from dataset
:param torch.Tensor labels_target: permuted real dmain labels from dataset
:rtype: torch.Tensor
:returns: Generator loss
"""
self.G.train()
self.D.eval()
fake_image = self.G(self.concat_image_label(real_image, labels_target))
reconstructed_image = self.G(
self.concat_image_label(fake_image, labels_dataset)
)
out_fake_src, out_fake_cls = self.D(fake_image)
loss = self.generator_loss(
real=real_image,
fake=fake_image,
reconstructed=reconstructed_image,
labels_target=labels_target,
output_fake_src=out_fake_src,
output_fake_cls=out_fake_cls,
)
self.optimizer_generator.zero_grad()
loss.backward()
torch.nn.utils.clip_grad_norm_(self.G.parameters(), cfg.training.G.clipping)
self.optimizer_generator.step()
return loss.item()
def trainD(
self,
real_image: torch.Tensor,
labels_dataset: torch.Tensor,
labels_target: torch.Tensor,
) -> torch.Tensor:
"""
:param torch.Tensor real_image: real image from dataset
:param torch.Tensor labels_dataset: real domain labels to image from dataset
:param torch.Tensor labels_target: permuted real dmain labels from dataset
:rtype: torch.Tensor
:returns: Discriminator loss
"""
self.G.eval()
self.D.train()
fake_image = self.G(
self.concat_image_label(real_image, labels_target).detach()
).to(self.device)
out_src_real, out_cls_real = self.D(real_image)
out_src_fake, out_cls_fake = self.D(fake_image)
loss = self.discriminator_loss(
real_image,
fake_image,
out_src_real,
out_src_fake,
out_cls_real,
labels_dataset,
)
self.optimizer_dicriminator.zero_grad()
torch.nn.utils.clip_grad_norm_(self.D.parameters(), cfg.training.D.clipping)
loss.backward()
self.optimizer_dicriminator.step()
return loss.item()
@torch.no_grad()
def generate(self, image: torch.Tensor, label: torch.Tensor) -> torch.Tensor:
"""
:param torch.Tensor image: size batch_size x 3 x height x width
:param torch.Tensor label: size batch_size x n_domain
:rtype: torch.Tensor
:returns: images of size batch_size x 3 x height x width
"""
self.eval()
images_labels = self.concat_image_label(image, label)
return self.G(images_labels)
if __name__ == "__main__":
from imageio import imsave
batch_size, channels, height, width = (4, 3, 128, 128)
n_domain = 5
real_image = torch.rand(batch_size, channels, height, width)
labels_dataset = torch.rand(batch_size, n_domain)
stargan = StarGan(
height=height, width=width, n_domain=n_domain, in_channels=channels
)
stargan.train()
# loss_gen = stargan.trainG(real_image, labels_dataset)
# print(loss_gen)
loss_dis = stargan.trainD(real_image, labels_dataset)
print(loss_dis)