inference.py 19.2 KB
Newer Older
1 2 3
import paddle
import argparse
import numpy as np
4 5 6
import random
import os
from collections import OrderedDict
B
bitcjm 已提交
7 8 9 10
import sys
import cv2

sys.path.append(".")
11 12 13 14 15 16 17

from ppgan.utils.config import get_config
from ppgan.datasets.builder import build_dataloader
from ppgan.engine.trainer import IterLoader
from ppgan.utils.visual import save_image
from ppgan.utils.visual import tensor2img
from ppgan.utils.filesystem import makedirs
18
from ppgan.metrics import build_metric
19

20

L
lzzyzlbb 已提交
21
MODEL_CLASSES = ["pix2pix", "cyclegan", "wav2lip", "esrgan", \
K
kongdebug 已提交
22 23
                 "edvr", "fom", "stylegan2", "basicvsr", "msvsr", \
                 "singan", "swinir", "invdn",  "aotgan", "nafnet"]
24 25 26 27 28 29 30 31 32


def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--model_path",
        default=None,
        type=str,
        required=True,
33 34 35 36 37 38 39 40
        help="The path prefix of inference model to be used.",
    )
    parser.add_argument("--model_type",
                        default=None,
                        type=str,
                        required=True,
                        help="Model type selected in the list: " +
                        ", ".join(MODEL_CLASSES))
41 42 43 44
    parser.add_argument(
        "--device",
        default="gpu",
        type=str,
45
        choices=["cpu", "gpu", "xpu", "npu"],
46 47 48 49 50
        help="The device to select to train the model, is must be cpu/gpu/xpu.")
    parser.add_argument('-c',
                        '--config-file',
                        metavar="FILE",
                        help='config file path')
51 52 53 54
    parser.add_argument("--output_path",
                        type=str,
                        default="infer_output",
                        help="output_path")
55 56 57 58 59
    # config options
    parser.add_argument("-o",
                        "--opt",
                        nargs='+',
                        help="set configuration options")
60 61 62 63
    # fix random numbers by setting seed
    parser.add_argument('--seed',
                        type=int,
                        default=None,
S
simonsLiang 已提交
64
                        help='fix random numbers by setting seed\".')
L
lzzyzlbb 已提交
65
    # for tensorRT
S
simonsLiang 已提交
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
    parser.add_argument("--run_mode",
                        default="fluid",
                        type=str,
                        choices=["fluid", "trt_fp32", "trt_fp16"],
                        help="mode of running(fluid/trt_fp32/trt_fp16)")
    parser.add_argument("--trt_min_shape",
                        default=1,
                        type=int,
                        help="trt_min_shape for tensorRT")
    parser.add_argument("--trt_max_shape",
                        default=1280,
                        type=int,
                        help="trt_max_shape for tensorRT")
    parser.add_argument("--trt_opt_shape",
                        default=640,
                        type=int,
                        help="trt_opt_shape for tensorRT")
    parser.add_argument("--min_subgraph_size",
                        default=3,
                        type=int,
                        help="trt_opt_shape for tensorRT")
    parser.add_argument("--batch_size",
                        default=1,
                        type=int,
                        help="batch_size for tensorRT")
    parser.add_argument("--use_dynamic_shape",
                        dest="use_dynamic_shape",
                        action="store_true",
                        help="use_dynamic_shape for tensorRT")
    parser.add_argument("--trt_calib_mode",
                        dest="trt_calib_mode",
                        action="store_true",
                        help="trt_calib_mode for tensorRT")
99 100 101 102
    args = parser.parse_args()
    return args


S
simonsLiang 已提交
103 104 105 106 107 108 109 110 111 112
def create_predictor(model_path,
                     device="gpu",
                     run_mode='fluid',
                     batch_size=1,
                     min_subgraph_size=3,
                     use_dynamic_shape=False,
                     trt_min_shape=1,
                     trt_max_shape=1280,
                     trt_opt_shape=640,
                     trt_calib_mode=False):
113 114 115 116 117 118
    config = paddle.inference.Config(model_path + ".pdmodel",
                                     model_path + ".pdiparams")
    if device == "gpu":
        config.enable_use_gpu(100, 0)
    elif device == "cpu":
        config.disable_gpu()
119 120
    elif device == "npu":
        config.enable_npu()
121
    elif device == "xpu":
122
        config.enable_xpu()
123 124
    else:
        config.disable_gpu()
S
simonsLiang 已提交
125

L
lzzyzlbb 已提交
126 127 128 129 130 131
    precision_map = {
        'trt_int8': paddle.inference.Config.Precision.Int8,
        'trt_fp32': paddle.inference.Config.Precision.Float32,
        'trt_fp16': paddle.inference.Config.Precision.Half
    }
    if run_mode in precision_map.keys():
S
simonsLiang 已提交
132 133 134 135 136 137
        config.enable_tensorrt_engine(workspace_size=1 << 25,
                                      max_batch_size=batch_size,
                                      min_subgraph_size=min_subgraph_size,
                                      precision_mode=precision_map[run_mode],
                                      use_static=False,
                                      use_calib_mode=trt_calib_mode)
L
lzzyzlbb 已提交
138 139 140 141 142 143 144 145 146 147 148 149 150 151

        if use_dynamic_shape:
            min_input_shape = {
                'image': [batch_size, 3, trt_min_shape, trt_min_shape]
            }
            max_input_shape = {
                'image': [batch_size, 3, trt_max_shape, trt_max_shape]
            }
            opt_input_shape = {
                'image': [batch_size, 3, trt_opt_shape, trt_opt_shape]
            }
            config.set_trt_dynamic_shape_info(min_input_shape, max_input_shape,
                                              opt_input_shape)
            print('trt set dynamic shape done!')
152 153 154 155

    predictor = paddle.inference.create_predictor(config)
    return predictor

S
simonsLiang 已提交
156

157 158 159 160 161 162 163 164 165 166
def setup_metrics(cfg):
    metrics = OrderedDict()
    if isinstance(list(cfg.values())[0], dict):
        for metric_name, cfg_ in cfg.items():
            metrics[metric_name] = build_metric(cfg_)
    else:
        metric = build_metric(cfg)
        metrics[metric.__class__.__name__] = metric

    return metrics
167

S
simonsLiang 已提交
168

169 170
def main():
    args = parse_args()
171 172 173
    if args.seed:
        paddle.seed(args.seed)
        random.seed(args.seed)
S
simonsLiang 已提交
174
        np.random.seed(args.seed)
175
    cfg = get_config(args.config_file, args.opt)
S
simonsLiang 已提交
176 177 178 179
    predictor = create_predictor(args.model_path, args.device, args.run_mode,
                                 args.batch_size, args.min_subgraph_size,
                                 args.use_dynamic_shape, args.trt_min_shape,
                                 args.trt_max_shape, args.trt_opt_shape,
L
lzzyzlbb 已提交
180
                                 args.trt_calib_mode)
181 182 183 184
    input_handles = [
        predictor.get_input_handle(name)
        for name in predictor.get_input_names()
    ]
L
lzzyzlbb 已提交
185

186 187 188 189
    output_handle = predictor.get_output_handle(predictor.get_output_names()[0])
    test_dataloader = build_dataloader(cfg.dataset.test,
                                       is_train=False,
                                       distributed=False)
190 191 192 193 194 195 196 197

    max_eval_steps = len(test_dataloader)
    iter_loader = IterLoader(test_dataloader)
    min_max = cfg.get('min_max', None)
    if min_max is None:
        min_max = (-1., 1.)

    model_type = args.model_type
198 199 200 201 202 203 204 205 206
    makedirs(os.path.join(args.output_path, model_type))

    validate_cfg = cfg.get('validate', None)
    metrics = None
    if validate_cfg and 'metrics' in validate_cfg:
        metrics = setup_metrics(validate_cfg['metrics'])
        for metric in metrics.values():
            metric.reset()

207 208 209 210 211 212 213
    for i in range(max_eval_steps):
        data = next(iter_loader)
        if model_type == "pix2pix":
            real_A = data['B'].numpy()
            input_handles[0].copy_from_cpu(real_A)
            predictor.run()
            prediction = output_handle.copy_to_cpu()
214 215
            prediction = paddle.to_tensor(prediction)
            image_numpy = tensor2img(prediction[0], min_max)
S
simonsLiang 已提交
216 217 218
            save_image(
                image_numpy,
                os.path.join(args.output_path, "pix2pix/{}.png".format(i)))
219 220 221 222 223
            metric_file = os.path.join(args.output_path, "pix2pix/metric.txt")
            real_B = paddle.to_tensor(data['A'])
            for metric in metrics.values():
                metric.update(prediction, real_B)

224 225 226 227 228
        elif model_type == "cyclegan":
            real_A = data['A'].numpy()
            input_handles[0].copy_from_cpu(real_A)
            predictor.run()
            prediction = output_handle.copy_to_cpu()
229 230
            prediction = paddle.to_tensor(prediction)
            image_numpy = tensor2img(prediction[0], min_max)
S
simonsLiang 已提交
231 232 233
            save_image(
                image_numpy,
                os.path.join(args.output_path, "cyclegan/{}.png".format(i)))
234 235 236 237 238
            metric_file = os.path.join(args.output_path, "cyclegan/metric.txt")
            real_B = paddle.to_tensor(data['B'])
            for metric in metrics.values():
                metric.update(prediction, real_B)

239 240 241 242 243 244 245 246 247 248 249
        elif model_type == "wav2lip":
            indiv_mels, x = data['indiv_mels'].numpy()[0], data['x'].numpy()[0]
            x = x.transpose([1, 0, 2, 3])
            input_handles[0].copy_from_cpu(indiv_mels)
            input_handles[1].copy_from_cpu(x)
            predictor.run()
            prediction = output_handle.copy_to_cpu()
            for j in range(prediction.shape[0]):
                prediction[j] = prediction[j][::-1, :, :]
                image_numpy = paddle.to_tensor(prediction[j])
                image_numpy = tensor2img(image_numpy, (0, 1))
250 251
                save_image(image_numpy,
                           "infer_output/wav2lip/{}_{}.png".format(i, j))
252

253 254 255 256 257 258 259
        elif model_type == "esrgan":
            lq = data['lq'].numpy()
            input_handles[0].copy_from_cpu(lq)
            predictor.run()
            prediction = output_handle.copy_to_cpu()
            prediction = paddle.to_tensor(prediction[0])
            image_numpy = tensor2img(prediction, min_max)
B
Birdylx 已提交
260 261 262 263 264 265 266 267 268
            gt_numpy = tensor2img(data['gt'][0], min_max)
            save_image(
                image_numpy,
                os.path.join(args.output_path, "esrgan/{}.png".format(i)))
            metric_file = os.path.join(args.output_path, model_type,
                                       "metric.txt")
            for metric in metrics.values():
                metric.update(image_numpy, gt_numpy)
            break
269 270 271 272 273 274 275
        elif model_type == "edvr":
            lq = data['lq'].numpy()
            input_handles[0].copy_from_cpu(lq)
            predictor.run()
            prediction = output_handle.copy_to_cpu()
            prediction = paddle.to_tensor(prediction[0])
            image_numpy = tensor2img(prediction, min_max)
B
Birdylx 已提交
276 277 278 279 280 281 282 283
            gt_numpy = tensor2img(data['gt'][0, 0], min_max)
            save_image(image_numpy,
                       os.path.join(args.output_path, "edvr/{}.png".format(i)))
            metric_file = os.path.join(args.output_path, model_type,
                                       "metric.txt")
            for metric in metrics.values():
                metric.update(image_numpy, gt_numpy)
            break
284 285 286 287 288 289
        elif model_type == "stylegan2":
            noise = paddle.randn([1, 1, 512]).cpu().numpy()
            input_handles[0].copy_from_cpu(noise)
            input_handles[1].copy_from_cpu(np.array([0.7]).astype('float32'))
            predictor.run()
            prediction = output_handle.copy_to_cpu()
290 291
            prediction = paddle.to_tensor(prediction)
            image_numpy = tensor2img(prediction[0], min_max)
S
simonsLiang 已提交
292 293 294
            save_image(
                image_numpy,
                os.path.join(args.output_path, "stylegan2/{}.png".format(i)))
295 296 297 298
            metric_file = os.path.join(args.output_path, "stylegan2/metric.txt")
            real_img = paddle.to_tensor(data['A'])
            for metric in metrics.values():
                metric.update(prediction, real_img)
L
lzzyzlbb 已提交
299
        elif model_type in ["basicvsr", "msvsr"]:
300 301 302
            lq = data['lq'].numpy()
            input_handles[0].copy_from_cpu(lq)
            predictor.run()
L
lzzyzlbb 已提交
303
            if len(predictor.get_output_names()) > 1:
S
simonsLiang 已提交
304 305
                output_handle = predictor.get_output_handle(
                    predictor.get_output_names()[-1])
306
            prediction = output_handle.copy_to_cpu()
307 308
            prediction = paddle.to_tensor(prediction)
            _, t, _, _, _ = prediction.shape
L
lzzyzlbb 已提交
309

310 311 312 313 314
            out_img = []
            gt_img = []
            for ti in range(t):
                out_tensor = prediction[0, ti]
                gt_tensor = data['gt'][0, ti]
S
simonsLiang 已提交
315 316 317
                out_img.append(tensor2img(out_tensor, (0., 1.)))
                gt_img.append(tensor2img(gt_tensor, (0., 1.)))

318
            image_numpy = tensor2img(prediction[0], min_max)
S
simonsLiang 已提交
319 320 321
            save_image(
                image_numpy,
                os.path.join(args.output_path, model_type, "{}.png".format(i)))
322

S
simonsLiang 已提交
323 324
            metric_file = os.path.join(args.output_path, model_type,
                                       "metric.txt")
325 326
            for metric in metrics.values():
                metric.update(out_img, gt_img, is_seq=True)
B
BrilliantYuKaimin 已提交
327 328 329 330 331
        elif model_type == "singan":
            predictor.run()
            prediction = output_handle.copy_to_cpu()
            prediction = paddle.to_tensor(prediction)
            image_numpy = tensor2img(prediction, min_max)
S
simonsLiang 已提交
332 333 334
            save_image(
                image_numpy,
                os.path.join(args.output_path, "singan/{}.png".format(i)))
B
BrilliantYuKaimin 已提交
335 336 337
            metric_file = os.path.join(args.output_path, "singan/metric.txt")
            for metric in metrics.values():
                metric.update(prediction, data['A'])
Y
yangshurong 已提交
338 339 340 341 342 343 344 345 346
        elif model_type == 'gfpgan':
            input_handles[0].copy_from_cpu(data['lq'].numpy())
            predictor.run()
            prediction = output_handle.copy_to_cpu()
            prediction = paddle.to_tensor(prediction)
            image_numpy = tensor2img(prediction, min_max)
            save_image(
                image_numpy,
                os.path.join(args.output_path, "gfpgan/{}.png".format(i)))
K
kongdebug 已提交
347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403
        elif model_type == "swinir":
            lq = data[1].numpy()
            _, _, h_old, w_old = lq.shape
            window_size = 8
            tile = 128
            tile_overlap = 32
            # after feed data to model, shape of feature map is change
            h_pad = (h_old // window_size + 1) * window_size - h_old
            w_pad = (w_old // window_size + 1) * window_size - w_old
            lq = np.concatenate([lq, np.flip(lq, 2)],
                                axis=2)[:, :, :h_old + h_pad, :]
            lq = np.concatenate([lq, np.flip(lq, 3)],
                                axis=3)[:, :, :, :w_old + w_pad]
            lq = lq.astype("float32")

            b, c, h, w = lq.shape
            tile = min(tile, h, w)
            assert tile % window_size == 0, "tile size should be a multiple of window_size"
            sf = 1  # scale
            stride = tile - tile_overlap
            h_idx_list = list(range(0, h - tile, stride)) + [h - tile]
            w_idx_list = list(range(0, w - tile, stride)) + [w - tile]
            E = np.zeros([b, c, h * sf, w * sf], dtype=np.float32)
            W = np.zeros_like(E)

            for h_idx in h_idx_list:
                for w_idx in w_idx_list:
                    in_patch = lq[..., h_idx:h_idx + tile, w_idx:w_idx + tile]
                    input_handles[0].copy_from_cpu(in_patch)
                    predictor.run()
                    out_patch = output_handle.copy_to_cpu()
                    out_patch_mask = np.ones_like(out_patch)

                    E[..., h_idx * sf:(h_idx + tile) * sf,
                      w_idx * sf:(w_idx + tile) * sf] += out_patch
                    W[..., h_idx * sf:(h_idx + tile) * sf,
                      w_idx * sf:(w_idx + tile) * sf] += out_patch_mask

            output = np.true_divide(E, W)
            prediction = output[..., :h_old * sf, :w_old * sf]

            prediction = paddle.to_tensor(prediction)
            target = tensor2img(data[0], (0., 1.))
            prediction = tensor2img(prediction, (0., 1.))

            metric_file = os.path.join(args.output_path, model_type,
                                       "metric.txt")
            for metric in metrics.values():
                metric.update(prediction, target)

            lq = tensor2img(data[1], (0., 1.))

            sample_result = np.concatenate((lq, prediction, target), 1)
            sample = cv2.cvtColor(sample_result, cv2.COLOR_RGB2BGR)
            file_name = os.path.join(args.output_path, model_type,
                                     "{}.png".format(i))
            cv2.imwrite(file_name, sample)
C
CC 已提交
404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426
        elif model_type == "invdn":
            noisy = data[0].numpy()
            noise_channel = 3 * 4**(cfg.model.generator.down_num) - 3
            input_handles[0].copy_from_cpu(noisy)
            input_handles[1].copy_from_cpu(
                np.random.randn(noisy.shape[0], noise_channel, noisy.shape[2],
                                noisy.shape[3]).astype(np.float32))
            predictor.run()
            output_handles = [
                predictor.get_output_handle(name)
                for name in predictor.get_output_names()
            ]
            prediction = output_handles[0].copy_to_cpu()
            prediction = paddle.to_tensor(prediction[0])
            image_numpy = tensor2img(prediction, min_max)
            gt_numpy = tensor2img(data[1], min_max)
            save_image(image_numpy,
                       os.path.join(args.output_path, "invdn/{}.png".format(i)))
            metric_file = os.path.join(args.output_path, model_type,
                                       "metric.txt")
            for metric in metrics.values():
                metric.update(image_numpy, gt_numpy)
            break
K
kongdebug 已提交
427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448

        elif model_type == "nafnet":
            lq = data[1].numpy()
            input_handles[0].copy_from_cpu(lq)
            predictor.run()
            prediction = output_handle.copy_to_cpu()
            prediction = paddle.to_tensor(prediction)
            target = tensor2img(data[0], (0., 1.))
            prediction = tensor2img(prediction, (0., 1.))

            metric_file = os.path.join(args.output_path, model_type,
                                       "metric.txt")
            for metric in metrics.values():
                metric.update(prediction, target)

            lq = tensor2img(data[1], (0., 1.))

            sample_result = np.concatenate((lq, prediction, target), 1)
            sample = cv2.cvtColor(sample_result, cv2.COLOR_RGB2BGR)
            file_name = os.path.join(args.output_path, model_type,
                                     "{}.png".format(i))
            cv2.imwrite(file_name, sample)
F
FutureSI 已提交
449
        elif model_type == 'aotgan':
K
kongdebug 已提交
450 451
            input_data = paddle.concat((data['img'], data['mask']),
                                       axis=1).numpy()
F
FutureSI 已提交
452 453 454 455 456 457 458 459
            input_handles[0].copy_from_cpu(input_data)
            predictor.run()
            prediction = output_handle.copy_to_cpu()
            prediction = paddle.to_tensor(prediction)
            image_numpy = tensor2img(prediction, min_max)
            save_image(
                image_numpy,
                os.path.join(args.output_path, "aotgan/{}.png".format(i)))
S
simonsLiang 已提交
460

461 462 463
    if metrics:
        log_file = open(metric_file, 'a')
        for metric_name, metric in metrics.items():
S
simonsLiang 已提交
464 465
            loss_string = "Metric {}: {:.4f}".format(metric_name,
                                                     metric.accumulate())
466 467
            print(loss_string, file=log_file)
        log_file.close()
468

S
simonsLiang 已提交
469

470 471
if __name__ == '__main__':
    main()