#******************************************************************************
# Copyright (c) 2021 Advanced Micro Devices, Inc. All rights reserved.
#
#Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
#1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
#2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
#3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
#THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#*******************************************************************************

# This script can be used to benchmark CNN models with Pytorch + ZenDNN
import sys
import torch, time, argparse
import torchvision.models as models

def get_model(model_name, batch_size, use_trained=True):
    model = models.__dict__[model_name](pretrained=use_trained).eval()
    desc_strs = [model_name]
    desc_strs.append("bs" + str(batch_size))

    # Prepare model
    model = torch.jit.script(model)
    try:
        model = torch.jit.optimize_for_inference(model)
    except:
        try:
            model = torch.jit.freeze(model)
        except:
            print("Unable to freeze the model", flush=True)
            return model, "_".join(desc_strs)
        print("model is frozen but not optimized ", flush=True)
    return model, "_".join(desc_strs)

def benchmark_inference(mod, inp, desc, warmup_cnt, iterations):
    batch_size = inp.shape[0]

    # Warm up
    start = time.time()
    for i in range(warmup_cnt):
        out = mod(inp)
    end = time.time()
    Warmup_dur = (end-start)/warmup_cnt

    # Final runs
    start = time.time()
    for i in range(iterations):
        out = mod(inp)
    end = time.time()
    inference_dur = (end-start)/iterations

    print("*" * 80, flush=True)
    print("*" + desc.center(78) + "*", flush=True)
    print("*" * 80, flush=True)
    desc += ":"
    print(desc.ljust(30) + "Warm up time".rjust(15) + ": {0:7.6f}s".format(Warmup_dur)+"QPS".rjust(10)+ ": {0:7.6f}".format(batch_size/Warmup_dur), flush=True)
    print(desc.ljust(30) + "Inference time".rjust(15) + ": {0:7.6f}s".format(inference_dur)+"QPS".rjust(10)+ ": {0:7.6f}".format(batch_size/inference_dur), flush=True)
    return


if __name__ == "__main__":

    #Input Dimensions (C, H, W)
    arch_list = ['inception_v3', 'alexnet', 'vgg11', 'googlenet', 
                 'resnet50', 'resnet152', 'squeezenet1_0', 'mobilenet_v2', 'densenet121', 'mobilenet_v2', 'shufflenet_v2_x1_0']
    # Benchmark Settings
    parser = argparse.ArgumentParser(description='PyTorch Convnet Benchmark')

    parser.add_argument('--arch',  action='store', default='resnet50',
            help='model name (default is ResNet50) can be specified as any of these models : ' + ', '.join(arch_list))
    parser.add_argument('--batch_size', action='store', default=1, type=int,
                        help="batch size is 1 (default)")
    parser.add_argument('--warmups', action='store', default=5, type=int,
                        help="warmups are 5 (default)")
    parser.add_argument('--iterations', action='store', default=10, type=int,
                        help="iterations are 10 (default)")

    args = parser.parse_args()
    if not args.arch in arch_list:
       print("unsupported model is specified")
       sys.exit

    if args.arch == "inception_v3":
        c, h, w = [3, 299, 299]
    else:
        c, h, w = [3, 224, 224]
    # Random Input
    inp = torch.randn(args.batch_size, c, h, w)

    # Generate Model
    model, desc = get_model(model_name = args.arch, batch_size = args.batch_size)

    # Execute the Benchmark
    benchmark_inference(model, inp, desc, warmup_cnt = args.warmups, iterations = args.iterations)
