Pix2pix_network.py 16.8 KB
Newer Older
Z
zhumanyu 已提交
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
#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 .base_network import conv2d, deconv2d, norm_layer
import paddle.fluid as fluid


class Pix2pix_model(object):
    def __init__(self):
        pass

    def network_G(self, input, name, cfg):
        if cfg.net_G == 'resnet_9block':
            net = build_generator_resnet_blocks(
                input,
                name=name + "_resnet9block",
                n_gen_res=9,
                g_base_dims=cfg.g_base_dims,
                use_dropout=cfg.dropout,
                norm_type=cfg.norm_type)
        elif cfg.net_G == 'resnet_6block':
            net = build_generator_resnet_blocks(
                input,
                name=name + "_resnet6block",
                n_gen_res=6,
                g_base_dims=cfg.g_base_dims,
                use_dropout=cfg.dropout,
                norm_type=cfg.norm_type)
        elif cfg.net_G == 'unet_128':
            net = build_generator_Unet(
                input,
                name=name + "_unet128",
                num_downsample=7,
                g_base_dims=cfg.g_base_dims,
                use_dropout=cfg.dropout,
                norm_type=cfg.norm_type)
        elif cfg.net_G == 'unet_256':
            net = build_generator_Unet(
                input,
                name=name + "_unet256",
                num_downsample=8,
                g_base_dims=cfg.g_base_dims,
                use_dropout=cfg.dropout,
                norm_type=cfg.norm_type)
        else:
            raise NotImplementedError(
                'network G: [%s] is wrong format, please check it' % cfg.net_G)
        return net

    def network_D(self, input, name, cfg):
        if cfg.net_D == 'basic':
            net = build_discriminator_Nlayers(
                input,
                name=name + '_basic',
                d_nlayers=3,
                d_base_dims=cfg.d_base_dims,
                norm_type=cfg.norm_type)
        elif cfg.net_D == 'nlayers':
            net = build_discriminator_Nlayers(
                input,
                name=name + '_nlayers',
                d_nlayers=cfg.d_nlayers,
                d_base_dims=cfg.d_base_dims,
                norm_type=cfg.norm_type)
        elif cfg.net_D == 'pixel':
            net = build_discriminator_Pixel(
                input,
                name=name + '_pixel',
                d_base_dims=cfg.d_base_dims,
                norm_type=cfg.norm_type)
        else:
            raise NotImplementedError(
                'network D: [%s] is wrong format, please check it' % cfg.net_D)
        return net


def build_resnet_block(inputres,
                       dim,
                       name="resnet",
                       use_bias=False,
                       use_dropout=False,
                       norm_type='batch_norm'):
    out_res = fluid.layers.pad2d(inputres, [1, 1, 1, 1], mode="reflect")
    out_res = conv2d(
L
lvmengsi 已提交
100 101 102 103 104
        input=out_res,
        num_filters=dim,
        filter_size=3,
        stride=1,
        stddev=0.02,
Z
zhumanyu 已提交
105 106 107 108 109 110 111 112 113 114
        name=name + "_c1",
        norm=norm_type,
        activation_fn='relu',
        use_bias=use_bias)

    if use_dropout:
        out_res = fluid.layers.dropout(out_res, dropout_prob=0.5)

    out_res = fluid.layers.pad2d(out_res, [1, 1, 1, 1], mode="reflect")
    out_res = conv2d(
L
lvmengsi 已提交
115 116 117 118 119
        input=out_res,
        num_filters=dim,
        filter_size=3,
        stride=1,
        stddev=0.02,
Z
zhumanyu 已提交
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
        name=name + "_c2",
        norm=norm_type,
        use_bias=use_bias)
    return out_res + inputres


def build_generator_resnet_blocks(inputgen,
                                  name="generator",
                                  n_gen_res=9,
                                  g_base_dims=64,
                                  use_dropout=False,
                                  norm_type='batch_norm'):
    ''' generator use resnet block'''
    '''The shape of input should be equal to the shape of output.'''
    use_bias = norm_type == 'instance_norm'
    pad_input = fluid.layers.pad2d(inputgen, [3, 3, 3, 3], mode="reflect")
    o_c1 = conv2d(
L
lvmengsi 已提交
137 138 139 140 141
        input=pad_input,
        num_filters=g_base_dims,
        filter_size=7,
        stride=1,
        stddev=0.02,
Z
zhumanyu 已提交
142 143 144 145
        name=name + "_c1",
        norm=norm_type,
        activation_fn='relu')
    o_c2 = conv2d(
L
lvmengsi 已提交
146 147 148 149 150 151
        input=o_c1,
        num_filters=g_base_dims * 2,
        filter_size=3,
        stride=2,
        stddev=0.02,
        padding=1,
Z
zhumanyu 已提交
152 153 154 155
        name=name + "_c2",
        norm=norm_type,
        activation_fn='relu')
    res_input = conv2d(
L
lvmengsi 已提交
156 157 158 159 160 161
        input=o_c2,
        num_filters=g_base_dims * 4,
        filter_size=3,
        stride=2,
        stddev=0.02,
        padding=1,
Z
zhumanyu 已提交
162 163 164
        name=name + "_c3",
        norm=norm_type,
        activation_fn='relu')
L
lvmengsi 已提交
165
    for i in range(n_gen_res):
Z
zhumanyu 已提交
166 167 168 169 170 171 172 173 174 175
        conv_name = name + "_r{}".format(i + 1)
        res_output = build_resnet_block(
            res_input,
            g_base_dims * 4,
            name=conv_name,
            use_bias=use_bias,
            use_dropout=use_dropout)
        res_input = res_output

    o_c4 = deconv2d(
L
lvmengsi 已提交
176 177 178 179 180 181 182
        input=res_output,
        num_filters=g_base_dims * 2,
        filter_size=3,
        stride=2,
        stddev=0.02,
        padding=[1, 1],
        outpadding=[0, 1, 0, 1],
Z
zhumanyu 已提交
183 184 185 186
        name=name + "_c4",
        norm=norm_type,
        activation_fn='relu')
    o_c5 = deconv2d(
L
lvmengsi 已提交
187 188 189 190 191 192 193
        input=o_c4,
        num_filters=g_base_dims,
        filter_size=3,
        stride=2,
        stddev=0.02,
        padding=[1, 1],
        outpadding=[0, 1, 0, 1],
Z
zhumanyu 已提交
194 195 196 197 198
        name=name + "_c5",
        norm=norm_type,
        activation_fn='relu')
    o_p2 = fluid.layers.pad2d(o_c5, [3, 3, 3, 3], mode="reflect")
    o_c6 = conv2d(
L
lvmengsi 已提交
199 200 201 202 203
        input=o_p2,
        num_filters=3,
        filter_size=7,
        stride=1,
        stddev=0.02,
Z
zhumanyu 已提交
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
        name=name + "_c6",
        activation_fn='tanh',
        use_bias=True)

    return o_c6


def Unet_block(inputunet,
               i,
               outer_dim,
               inner_dim,
               num_downsample,
               innermost=False,
               outermost=False,
               norm_type='batch_norm',
               use_bias=False,
               use_dropout=False,
               name=None):
    if outermost == True:
        downconv = conv2d(
L
lvmengsi 已提交
224 225 226 227 228 229
            input=inputunet,
            num_filters=inner_dim,
            filter_size=4,
            stride=2,
            stddev=0.02,
            padding=1,
Z
zhumanyu 已提交
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
            name=name + '_outermost_dc1',
            use_bias=True)
        i += 1
        mid_block = Unet_block(
            downconv,
            i,
            inner_dim,
            inner_dim * 2,
            num_downsample,
            norm_type=norm_type,
            use_bias=use_bias,
            use_dropout=use_dropout,
            name=name)
        uprelu = fluid.layers.relu(mid_block, name=name + '_outermost_relu')
        updeconv = deconv2d(
L
lvmengsi 已提交
245 246 247 248 249 250
            input=uprelu,
            num_filters=outer_dim,
            filter_size=4,
            stride=2,
            stddev=0.02,
            padding=1,
Z
zhumanyu 已提交
251 252 253 254 255 256 257 258
            name=name + '_outermost_uc1',
            activation_fn='tanh',
            use_bias=use_bias)
        return updeconv
    elif innermost == True:
        downrelu = fluid.layers.leaky_relu(
            inputunet, 0.2, name=name + '_innermost_leaky_relu')
        upconv = conv2d(
L
lvmengsi 已提交
259 260 261 262 263 264
            input=downrelu,
            num_filters=inner_dim,
            filter_size=4,
            stride=2,
            stddev=0.02,
            padding=1,
Z
zhumanyu 已提交
265 266 267 268
            name=name + '_innermost_dc1',
            activation_fn='relu',
            use_bias=use_bias)
        updeconv = deconv2d(
L
lvmengsi 已提交
269 270 271 272 273 274
            input=upconv,
            num_filters=outer_dim,
            filter_size=4,
            stride=2,
            stddev=0.02,
            padding=1,
Z
zhumanyu 已提交
275 276 277 278 279 280 281 282
            name=name + '_innermost_uc1',
            norm=norm_type,
            use_bias=use_bias)
        return fluid.layers.concat([inputunet, updeconv], 1)
    else:
        downrelu = fluid.layers.leaky_relu(
            inputunet, 0.2, name=name + '_leaky_relu')
        downnorm = conv2d(
L
lvmengsi 已提交
283 284 285 286 287 288
            input=downrelu,
            num_filters=inner_dim,
            filter_size=4,
            stride=2,
            stddev=0.02,
            padding=1,
Z
zhumanyu 已提交
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326
            name=name + 'dc1',
            norm=norm_type,
            use_bias=use_bias)
        i += 1
        if i < 4:
            mid_block = Unet_block(
                downnorm,
                i,
                inner_dim,
                inner_dim * 2,
                num_downsample,
                norm_type=norm_type,
                use_bias=use_bias,
                name=name + '_mid{}'.format(i))
        elif i < num_downsample - 1:
            mid_block = Unet_block(
                downnorm,
                i,
                inner_dim,
                inner_dim,
                num_downsample,
                norm_type=norm_type,
                use_bias=use_bias,
                use_dropout=use_dropout,
                name=name + '_mid{}'.format(i))
        else:
            mid_block = Unet_block(
                downnorm,
                i,
                inner_dim,
                inner_dim,
                num_downsample,
                innermost=True,
                norm_type=norm_type,
                use_bias=use_bias,
                name=name + '_innermost')
        uprelu = fluid.layers.relu(mid_block, name=name + '_relu')
        updeconv = deconv2d(
L
lvmengsi 已提交
327 328 329 330 331 332
            input=uprelu,
            num_filters=outer_dim,
            filter_size=4,
            stride=2,
            stddev=0.02,
            padding=1,
Z
zhumanyu 已提交
333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
            name=name + '_uc1',
            norm=norm_type,
            use_bias=use_bias)

        if use_dropout:
            upnorm = fluid.layers.dropout(upnorm, dropout_prob=0.5)
        return fluid.layers.concat([inputunet, updeconv], 1)


def UnetSkipConnectionBlock(input,
                            i,
                            num_downs,
                            outer_nc,
                            inner_nc,
                            outermost=False,
                            innermost=False,
                            norm='batch_norm',
                            use_dropout=False,
                            name=""):
    use_bias = norm == "instance"
    if outermost:
        downconv = conv2d(
            input,
L
lvmengsi 已提交
356 357 358
            num_filters=inner_nc,
            filter_size=4,
            stride=2,
Z
zhumanyu 已提交
359 360 361 362 363 364 365 366 367 368 369 370 371 372 373
            padding=1,
            use_bias=use_bias,
            name=name + '_down_conv')
        i += 1
        ngf = inner_nc
        sub_res = UnetSkipConnectionBlock(
            downconv,
            i,
            num_downs,
            outer_nc=ngf,
            inner_nc=ngf * 2,
            norm=norm,
            name=name + '_u%d' % i)
        uprelu = fluid.layers.relu(sub_res)
        upconv = deconv2d(
L
lvmengsi 已提交
374 375 376 377
            input=uprelu,
            num_filters=outer_nc,
            filter_size=4,
            stride=2,
Z
zhumanyu 已提交
378 379 380 381 382 383 384
            padding=1,
            activation_fn='tanh',
            name=name + '_up_conv')
        return upconv
    elif innermost:
        downrelu = fluid.layers.leaky_relu(input, 0.2)
        downconv = conv2d(
L
lvmengsi 已提交
385 386 387 388
            input=downrelu,
            num_filters=inner_nc,
            filter_size=4,
            stride=2,
Z
zhumanyu 已提交
389 390 391 392 393
            padding=1,
            use_bias=use_bias,
            name=name + '_down_conv')
        uprelu = fluid.layers.relu(downconv)
        upconv = deconv2d(
L
lvmengsi 已提交
394 395 396 397
            input=uprelu,
            num_filters=outer_nc,
            filter_size=4,
            stride=2,
Z
zhumanyu 已提交
398 399 400 401 402 403 404 405
            padding=1,
            use_bias=use_bias,
            norm=norm,
            name=name + '_up_conv')
        return fluid.layers.concat([input, upconv], 1)
    else:
        downrelu = fluid.layers.leaky_relu(input, 0.2)
        downconv = conv2d(
L
lvmengsi 已提交
406 407 408 409
            input=downrelu,
            num_filters=inner_nc,
            filter_size=4,
            stride=2,
Z
zhumanyu 已提交
410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447
            padding=1,
            use_bias=use_bias,
            norm=norm,
            name=name + '_down_conv')
        i += 1
        ngf = inner_nc
        if i < 4:
            sub_res = UnetSkipConnectionBlock(
                downconv,
                i,
                num_downs,
                outer_nc=ngf,
                inner_nc=ngf * 2,
                norm=norm,
                name=name + '_u%d' % i)
        elif i < num_downs - 1:
            sub_res = UnetSkipConnectionBlock(
                downconv,
                i,
                num_downs,
                outer_nc=ngf,
                inner_nc=ngf,
                norm=norm,
                name=name + '_u%d' % i)

        else:
            sub_res = UnetSkipConnectionBlock(
                downconv,
                i,
                num_downs,
                outer_nc=ngf,
                inner_nc=ngf,
                innermost=True,
                norm=norm,
                name=name + '_u%d' % i)

        uprelu = fluid.layers.relu(sub_res)
        upconv = deconv2d(
L
lvmengsi 已提交
448 449 450 451
            input=uprelu,
            num_filters=outer_nc,
            filter_size=4,
            stride=2,
Z
zhumanyu 已提交
452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489
            padding=1,
            use_bias=use_bias,
            norm=norm,
            name=name + '_up_conv')
        out = upconv
        if use_dropout:
            out = fluid.layers.dropout(out, 0.5)
        return fluid.layers.concat([input, out], 1)


def build_generator_Unet(input,
                         name="",
                         num_downsample=8,
                         g_base_dims=64,
                         use_dropout=False,
                         norm_type='batch_norm'):
    ''' generator use Unet'''
    i = 0
    output = UnetSkipConnectionBlock(
        input,
        i,
        num_downsample,
        3,
        g_base_dims,
        outermost=True,
        norm=norm_type,
        name=name + '_u%d' % i)

    return output


def build_discriminator_Nlayers(inputdisc,
                                name="discriminator",
                                d_nlayers=3,
                                d_base_dims=64,
                                norm_type='batch_norm'):
    use_bias = norm_type != 'batch_norm'
    dis_input = conv2d(
L
lvmengsi 已提交
490 491 492 493 494 495
        input=inputdisc,
        num_filters=d_base_dims,
        filter_size=4,
        stride=2,
        stddev=0.02,
        padding=1,
Z
zhumanyu 已提交
496 497 498 499 500
        name=name + "_c1",
        activation_fn='leaky_relu',
        relufactor=0.2,
        use_bias=True)
    d_dims = d_base_dims
L
lvmengsi 已提交
501
    for i in range(d_nlayers - 1):
Z
zhumanyu 已提交
502 503 504
        conv_name = name + "_c{}".format(i + 2)
        d_dims *= 2
        dis_output = conv2d(
L
lvmengsi 已提交
505 506 507 508 509 510
            input=dis_input,
            num_filters=d_dims,
            filter_size=4,
            stride=2,
            stddev=0.02,
            padding=1,
Z
zhumanyu 已提交
511 512 513 514 515 516 517 518
            name=conv_name,
            norm=norm_type,
            activation_fn='leaky_relu',
            relufactor=0.2,
            use_bias=use_bias)
        dis_input = dis_output
    last_dims = min(2**d_nlayers, 8)
    o_c4 = conv2d(
L
lvmengsi 已提交
519 520 521 522 523 524 525
        input=dis_output,
        num_filters=d_base_dims * last_dims,
        filter_size=4,
        stride=1,
        stddev=0.02,
        padding=1,
        name=name + "_c{}".format(d_nlayers + 1),
Z
zhumanyu 已提交
526 527 528 529 530
        norm=norm_type,
        activation_fn='leaky_relu',
        relufactor=0.2,
        use_bias=use_bias)
    o_c5 = conv2d(
L
lvmengsi 已提交
531 532 533 534 535 536 537
        input=o_c4,
        num_filters=1,
        filter_size=4,
        stride=1,
        stddev=0.02,
        padding=1,
        name=name + "_c{}".format(d_nlayers + 2),
Z
zhumanyu 已提交
538 539 540 541 542 543 544 545 546 547
        use_bias=True)
    return o_c5


def build_discriminator_Pixel(inputdisc,
                              name="discriminator",
                              d_base_dims=64,
                              norm_type='batch_norm'):
    use_bias = norm_type != 'instance_norm'
    o_c1 = conv2d(
L
lvmengsi 已提交
548 549 550 551 552
        input=inputdisc,
        num_filters=d_base_dims,
        filter_size=1,
        stride=1,
        stddev=0.02,
Z
zhumanyu 已提交
553 554 555 556 557
        name=name + '_c1',
        activation_fn='leaky_relu',
        relufactor=0.2,
        use_bias=True)
    o_c2 = conv2d(
L
lvmengsi 已提交
558 559 560 561 562
        input=o_c1,
        num_filters=d_base_dims * 2,
        filter_size=1,
        stride=1,
        stddev=0.02,
Z
zhumanyu 已提交
563 564 565 566 567
        name=name + '_c2',
        norm=norm_type,
        activation_fn='leaky_relu',
        relufactor=0.2,
        use_bias=use_bias)
L
lvmengsi 已提交
568 569 570 571 572 573 574 575
    o_c3 = conv2d(
        o_c2,
        num_filters=1,
        filter_size=1,
        stride=1,
        stddev=0.02,
        name=name + '_c3',
        use_bias=use_bias)
Z
zhumanyu 已提交
576
    return o_c3