CycleGAN.py 16.2 KB
Newer Older
L
lvmengsi 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
#copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve.
#
#Licensed under the Apache License, Version 2.0 (the "License");
#you may not use this file except in compliance with the License.
#You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
#Unless required by applicable law or agreed to in writing, software
#distributed under the License is distributed on an "AS IS" BASIS,
#WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#See the License for the specific language governing permissions and
#limitations under the License.

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from network.CycleGAN_network import CycleGAN_model
from util import utility
import paddle.fluid as fluid
L
lvmengsi 已提交
21
import paddle
L
lvmengsi 已提交
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
import sys
import time

lambda_A = 10.0
lambda_B = 10.0
lambda_identity = 0.5


class GTrainer():
    def __init__(self, input_A, input_B, cfg, step_per_epoch):
        self.program = fluid.default_main_program().clone()
        with fluid.program_guard(self.program):
            model = CycleGAN_model()
            self.fake_B = model.network_G(input_A, name="GA", cfg=cfg)
            self.fake_B.persistable = True
            self.fake_A = model.network_G(input_B, name="GB", cfg=cfg)
            self.fake_A.persistable = True
            self.cyc_A = model.network_G(self.fake_B, name="GB", cfg=cfg)
            self.cyc_B = model.network_G(self.fake_A, name="GA", cfg=cfg)

            self.infer_program = self.program.clone()
            # Cycle Loss
            diff_A = fluid.layers.abs(
                fluid.layers.elementwise_sub(
                    x=input_A, y=self.cyc_A))
            diff_B = fluid.layers.abs(
                fluid.layers.elementwise_sub(
                    x=input_B, y=self.cyc_B))
            self.cyc_A_loss = fluid.layers.reduce_mean(diff_A) * lambda_A
L
lvmengsi 已提交
51
            self.cyc_A_loss.persistable = True
L
lvmengsi 已提交
52
            self.cyc_B_loss = fluid.layers.reduce_mean(diff_B) * lambda_B
L
lvmengsi 已提交
53
            self.cyc_B_loss.persistable = True
L
lvmengsi 已提交
54 55 56 57 58
            self.cyc_loss = self.cyc_A_loss + self.cyc_B_loss
            # GAN Loss D_A(G_A(A))
            self.fake_rec_A = model.network_D(self.fake_B, name="DA", cfg=cfg)
            self.G_A = fluid.layers.reduce_mean(
                fluid.layers.square(self.fake_rec_A - 1))
L
lvmengsi 已提交
59
            self.G_A.persistable = True
L
lvmengsi 已提交
60 61 62 63
            # GAN Loss D_B(G_B(B))
            self.fake_rec_B = model.network_D(self.fake_A, name="DB", cfg=cfg)
            self.G_B = fluid.layers.reduce_mean(
                fluid.layers.square(self.fake_rec_B - 1))
L
lvmengsi 已提交
64
            self.G_B.persistable = True
L
lvmengsi 已提交
65 66 67 68 69 70 71
            self.G = self.G_A + self.G_B
            # Identity Loss G_A
            self.idt_A = model.network_G(input_B, name="GA", cfg=cfg)
            self.idt_loss_A = fluid.layers.reduce_mean(
                fluid.layers.abs(
                    fluid.layers.elementwise_sub(
                        x=input_B, y=self.idt_A))) * lambda_B * lambda_identity
L
lvmengsi 已提交
72
            self.idt_loss_A.persistable = True
L
lvmengsi 已提交
73 74 75 76 77 78
            # Identity Loss G_B
            self.idt_B = model.network_G(input_A, name="GB", cfg=cfg)
            self.idt_loss_B = fluid.layers.reduce_mean(
                fluid.layers.abs(
                    fluid.layers.elementwise_sub(
                        x=input_A, y=self.idt_B))) * lambda_A * lambda_identity
L
lvmengsi 已提交
79
            self.idt_loss_B.persistable = True
L
lvmengsi 已提交
80 81 82 83 84 85 86 87 88 89 90 91

            self.idt_loss = fluid.layers.elementwise_add(self.idt_loss_A,
                                                         self.idt_loss_B)
            self.g_loss = self.cyc_loss + self.G + self.idt_loss

            vars = []
            for var in self.program.list_vars():
                if fluid.io.is_parameter(var) and (var.name.startswith("GA") or
                                                   var.name.startswith("GB")):
                    vars.append(var.name)
            self.param = vars
            lr = cfg.learning_rate
L
lvmengsi 已提交
92 93 94 95 96 97 98 99
            if cfg.epoch <= 100:
                optimizer = fluid.optimizer.Adam(
                    learning_rate=lr, beta1=0.5, beta2=0.999, name="net_G")
            else:
                optimizer = fluid.optimizer.Adam(
                    learning_rate=fluid.layers.piecewise_decay(
                        boundaries=[99 * step_per_epoch] + [
                            x * step_per_epoch
100
                            for x in range(100, cfg.epoch - 1)
L
lvmengsi 已提交
101 102 103
                        ],
                        values=[lr] + [
                            lr * (1.0 - (x - 99.0) / 101.0)
104
                            for x in range(100, cfg.epoch)
L
lvmengsi 已提交
105 106 107 108
                        ]),
                    beta1=0.5,
                    beta2=0.999,
                    name="net_G")
L
lvmengsi 已提交
109 110 111 112 113 114 115 116 117 118 119 120 121 122
            optimizer.minimize(self.g_loss, parameter_list=vars)


class DATrainer():
    def __init__(self, input_B, fake_pool_B, cfg, step_per_epoch):
        self.program = fluid.default_main_program().clone()
        with fluid.program_guard(self.program):
            model = CycleGAN_model()
            self.rec_B = model.network_D(input_B, name="DA", cfg=cfg)
            self.fake_pool_rec_B = model.network_D(
                fake_pool_B, name="DA", cfg=cfg)
            self.d_loss_A = (fluid.layers.square(self.fake_pool_rec_B) +
                             fluid.layers.square(self.rec_B - 1)) / 2.0
            self.d_loss_A = fluid.layers.reduce_mean(self.d_loss_A)
L
lvmengsi 已提交
123
            self.d_loss_A.persistable = True
L
lvmengsi 已提交
124 125 126 127 128 129 130 131

            vars = []
            for var in self.program.list_vars():
                if fluid.io.is_parameter(var) and var.name.startswith("DA"):
                    vars.append(var.name)

            self.param = vars
            lr = cfg.learning_rate
L
lvmengsi 已提交
132 133 134 135 136 137 138 139
            if cfg.epoch <= 100:
                optimizer = fluid.optimizer.Adam(
                    learning_rate=lr, beta1=0.5, beta2=0.999, name="net_DA")
            else:
                optimizer = fluid.optimizer.Adam(
                    learning_rate=fluid.layers.piecewise_decay(
                        boundaries=[99 * step_per_epoch] + [
                            x * step_per_epoch
140
                            for x in range(100, cfg.epoch - 1)
L
lvmengsi 已提交
141 142 143
                        ],
                        values=[lr] + [
                            lr * (1.0 - (x - 99.0) / 101.0)
144
                            for x in range(100, cfg.epoch)
L
lvmengsi 已提交
145 146 147 148
                        ]),
                    beta1=0.5,
                    beta2=0.999,
                    name="net_DA")
L
lvmengsi 已提交
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163

            optimizer.minimize(self.d_loss_A, parameter_list=vars)


class DBTrainer():
    def __init__(self, input_A, fake_pool_A, cfg, step_per_epoch):
        self.program = fluid.default_main_program().clone()
        with fluid.program_guard(self.program):
            model = CycleGAN_model()
            self.rec_A = model.network_D(input_A, name="DB", cfg=cfg)
            self.fake_pool_rec_A = model.network_D(
                fake_pool_A, name="DB", cfg=cfg)
            self.d_loss_B = (fluid.layers.square(self.fake_pool_rec_A) +
                             fluid.layers.square(self.rec_A - 1)) / 2.0
            self.d_loss_B = fluid.layers.reduce_mean(self.d_loss_B)
L
lvmengsi 已提交
164
            self.d_loss_B.persistable = True
L
lvmengsi 已提交
165 166 167 168 169 170
            vars = []
            for var in self.program.list_vars():
                if fluid.io.is_parameter(var) and var.name.startswith("DB"):
                    vars.append(var.name)
            self.param = vars
            lr = 0.0002
L
lvmengsi 已提交
171 172 173 174 175 176 177 178
            if cfg.epoch <= 100:
                optimizer = fluid.optimizer.Adam(
                    learning_rate=lr, beta1=0.5, beta2=0.999, name="net_DA")
            else:
                optimizer = fluid.optimizer.Adam(
                    learning_rate=fluid.layers.piecewise_decay(
                        boundaries=[99 * step_per_epoch] + [
                            x * step_per_epoch
179
                            for x in range(100, cfg.epoch - 1)
L
lvmengsi 已提交
180 181 182
                        ],
                        values=[lr] + [
                            lr * (1.0 - (x - 99.0) / 101.0)
183
                            for x in range(100, cfg.epoch)
L
lvmengsi 已提交
184 185 186 187
                        ]),
                    beta1=0.5,
                    beta2=0.999,
                    name="net_DB")
L
lvmengsi 已提交
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
            optimizer.minimize(self.d_loss_B, parameter_list=vars)


class CycleGAN(object):
    def add_special_args(self, parser):
        parser.add_argument(
            '--net_G',
            type=str,
            default="resnet_9block",
            help="Choose the CycleGAN generator's network, choose in [resnet_9block|resnet_6block|unet_128|unet_256]"
        )
        parser.add_argument(
            '--net_D',
            type=str,
            default="basic",
            help="Choose the CycleGAN discriminator's network, choose in [basic|nlayers|pixel]"
        )
        parser.add_argument(
            '--d_nlayers',
            type=int,
            default=3,
            help="only used when CycleGAN discriminator is nlayers")

        return parser

    def __init__(self,
                 cfg=None,
                 A_reader=None,
                 B_reader=None,
                 A_test_reader=None,
                 B_test_reader=None,
L
lvmengsi 已提交
219 220 221
                 batch_num=1,
                 A_id2name=None,
                 B_id2name=None):
L
lvmengsi 已提交
222 223 224 225 226 227
        self.cfg = cfg
        self.A_reader = A_reader
        self.B_reader = B_reader
        self.A_test_reader = A_test_reader
        self.B_test_reader = B_test_reader
        self.batch_num = batch_num
L
lvmengsi 已提交
228 229
        self.A_id2name = A_id2name
        self.B_id2name = B_id2name
L
lvmengsi 已提交
230 231 232 233

    def build_model(self):
        data_shape = [-1, 3, self.cfg.crop_size, self.cfg.crop_size]

234 235 236 237 238
        input_A = fluid.layers.data(
            name='input_A', shape=data_shape, dtype='float32')
        input_B = fluid.layers.data(
            name='input_B', shape=data_shape, dtype='float32')
        fake_pool_A = fluid.layers.data(
L
lvmengsi 已提交
239
            name='fake_pool_A', shape=data_shape, dtype='float32')
240
        fake_pool_B = fluid.layers.data(
L
lvmengsi 已提交
241 242
            name='fake_pool_B', shape=data_shape, dtype='float32')

L
lvmengsi 已提交
243 244 245 246 247 248 249 250 251 252 253 254
        A_py_reader = fluid.io.PyReader(
            feed_list=[input_A],
            capacity=4,
            iterable=True,
            use_double_buffer=True)

        B_py_reader = fluid.io.PyReader(
            feed_list=[input_B],
            capacity=4,
            iterable=True,
            use_double_buffer=True)

L
lvmengsi 已提交
255 256 257 258 259 260
        gen_trainer = GTrainer(input_A, input_B, self.cfg, self.batch_num)
        d_A_trainer = DATrainer(input_B, fake_pool_B, self.cfg, self.batch_num)
        d_B_trainer = DBTrainer(input_A, fake_pool_A, self.cfg, self.batch_num)

        # prepare environment
        place = fluid.CUDAPlace(0) if self.cfg.use_gpu else fluid.CPUPlace()
L
lvmengsi 已提交
261

L
lvmengsi 已提交
262 263 264 265 266 267 268 269
        A_py_reader.decorate_batch_generator(
            self.A_reader,
            places=fluid.cuda_places()
            if self.cfg.use_gpu else fluid.cpu_places())
        B_py_reader.decorate_batch_generator(
            self.B_reader,
            places=fluid.cuda_places()
            if self.cfg.use_gpu else fluid.cpu_places())
L
lvmengsi 已提交
270

L
lvmengsi 已提交
271 272 273 274 275 276 277 278 279 280 281 282 283
        exe = fluid.Executor(place)
        exe.run(fluid.default_startup_program())

        A_pool = utility.ImagePool()
        B_pool = utility.ImagePool()

        if self.cfg.init_model:
            utility.init_checkpoints(self.cfg, exe, gen_trainer, "net_G")
            utility.init_checkpoints(self.cfg, exe, d_A_trainer, "net_DA")
            utility.init_checkpoints(self.cfg, exe, d_B_trainer, "net_DB")

        ### memory optim
        build_strategy = fluid.BuildStrategy()
L
lvmengsi 已提交
284
        build_strategy.enable_inplace = True
L
lvmengsi 已提交
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302

        gen_trainer_program = fluid.CompiledProgram(
            gen_trainer.program).with_data_parallel(
                loss_name=gen_trainer.g_loss.name,
                build_strategy=build_strategy)
        d_A_trainer_program = fluid.CompiledProgram(
            d_A_trainer.program).with_data_parallel(
                loss_name=d_A_trainer.d_loss_A.name,
                build_strategy=build_strategy)
        d_B_trainer_program = fluid.CompiledProgram(
            d_B_trainer.program).with_data_parallel(
                loss_name=d_B_trainer.d_loss_B.name,
                build_strategy=build_strategy)

        t_time = 0

        for epoch_id in range(self.cfg.epoch):
            batch_id = 0
L
lvmengsi 已提交
303
            for data_A, data_B in zip(A_py_reader(), B_py_reader()):
L
lvmengsi 已提交
304
                s_time = time.time()
L
lvmengsi 已提交
305 306
                tensor_A, tensor_B = data_A[0]['input_A'], data_B[0]['input_B']
                ## optimize the g_A network
L
lvmengsi 已提交
307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
                g_A_loss, g_A_cyc_loss, g_A_idt_loss, g_B_loss, g_B_cyc_loss,\
                g_B_idt_loss, fake_A_tmp, fake_B_tmp = exe.run(
                    gen_trainer_program,
                    fetch_list=[
                        gen_trainer.G_A, gen_trainer.cyc_A_loss,
                        gen_trainer.idt_loss_A, gen_trainer.G_B,
                        gen_trainer.cyc_B_loss, gen_trainer.idt_loss_B,
                        gen_trainer.fake_A, gen_trainer.fake_B
                    ],
                    feed={"input_A": tensor_A,
                          "input_B": tensor_B})

                fake_pool_B = B_pool.pool_image(fake_B_tmp)
                fake_pool_A = A_pool.pool_image(fake_A_tmp)

                # optimize the d_A network
                d_A_loss = exe.run(
                    d_A_trainer_program,
                    fetch_list=[d_A_trainer.d_loss_A],
                    feed={"input_B": tensor_B,
                          "fake_pool_B": fake_pool_B})[0]

                # optimize the d_B network
                d_B_loss = exe.run(
                    d_B_trainer_program,
                    fetch_list=[d_B_trainer.d_loss_B],
                    feed={"input_A": tensor_A,
                          "fake_pool_A": fake_pool_A})[0]

                batch_time = time.time() - s_time
                t_time += batch_time
                if batch_id % self.cfg.print_freq == 0:
                    print("epoch{}: batch{}: \n\
                         d_A_loss: {}; g_A_loss: {}; g_A_cyc_loss: {}; g_A_idt_loss: {}; \n\
                         d_B_loss: {}; g_B_loss: {}; g_B_cyc_loss: {}; g_B_idt_loss: {}; \n\
342
                         Batch_time_cost: {}".format(
L
lvmengsi 已提交
343 344 345 346 347 348 349 350
                        epoch_id, batch_id, d_A_loss[0], g_A_loss[0],
                        g_A_cyc_loss[0], g_A_idt_loss[0], d_B_loss[0], g_B_loss[
                            0], g_B_cyc_loss[0], g_B_idt_loss[0], batch_time))

                sys.stdout.flush()
                batch_id += 1

            if self.cfg.run_test:
351 352 353 354
                A_image_name = fluid.layers.data(
                    name='A_image_name', shape=[1], dtype='int32')
                B_image_name = fluid.layers.data(
                    name='B_image_name', shape=[1], dtype='int32')
L
lvmengsi 已提交
355 356 357 358 359 360 361 362 363 364 365 366 367
                A_test_py_reader = fluid.io.PyReader(
                    feed_list=[input_A, A_image_name],
                    capacity=4,
                    iterable=True,
                    use_double_buffer=True)

                B_test_py_reader = fluid.io.PyReader(
                    feed_list=[input_B, B_image_name],
                    capacity=4,
                    iterable=True,
                    use_double_buffer=True)

                A_test_py_reader.decorate_batch_generator(
L
lvmengsi 已提交
368 369 370
                    self.A_test_reader,
                    places=fluid.cuda_places()
                    if self.cfg.use_gpu else fluid.cpu_places())
L
lvmengsi 已提交
371
                B_test_py_reader.decorate_batch_generator(
L
lvmengsi 已提交
372 373 374
                    self.B_test_reader,
                    places=fluid.cuda_places()
                    if self.cfg.use_gpu else fluid.cpu_places())
L
lvmengsi 已提交
375
                test_program = gen_trainer.infer_program
L
lvmengsi 已提交
376 377 378 379 380 381 382 383 384 385 386
                utility.save_test_image(
                    epoch_id,
                    self.cfg,
                    exe,
                    place,
                    test_program,
                    gen_trainer,
                    A_test_py_reader,
                    B_test_py_reader,
                    A_id2name=self.A_id2name,
                    B_id2name=self.B_id2name)
L
lvmengsi 已提交
387 388 389 390 391 392 393 394

            if self.cfg.save_checkpoints:
                utility.checkpoints(epoch_id, self.cfg, exe, gen_trainer,
                                    "net_G")
                utility.checkpoints(epoch_id, self.cfg, exe, d_A_trainer,
                                    "net_DA")
                utility.checkpoints(epoch_id, self.cfg, exe, d_B_trainer,
                                    "net_DB")