masahi commented on a change in pull request #4497: [WIP] [Relay] Add a PyTorch to Relay Parser URL: https://github.com/apache/incubator-tvm/pull/4497#discussion_r370911023
########## File path: tests/python/frontend/pytorch/test_forward.py ########## @@ -0,0 +1,732 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. +# pylint: disable=import-self, invalid-name, unused-argument +"""Unit tests for various models and operators""" +from time import time +import os +import sys +from tempfile import TemporaryDirectory +from scipy.stats import t as tdistr +import numpy as np +import torch +import tvm +import torchvision +import single_op + + +from tvm import relay +from tvm.contrib import graph_runtime +#from tvm.relay.testing.config import ctx_list + +sys.setrecursionlimit(10000) + +TARGET = 'llvm' +CTX = tvm.cpu() +EXT_ACCEL = None + +model_names = [] +baseline_latencies_map = {} +compiled_latencies_map = {} +speedups_map = {} + +test_repeats = 1 + +def _vectorize(ten): + return ten.reshape(-1) + +def atol(tru, est): + def _atol_elt(tru, est): + return abs(tru - est) + tru = _vectorize(tru) + est = _vectorize(est) + return max([_atol_elt(x, y) for x, y in zip(tru, est)]) + +def rtol(tru, est): + def _rtol_elt(tru, est): + return abs(tru - est) / min(abs(tru), abs(est)) + tru = _vectorize(tru) + est = _vectorize(est) + return max([_rtol_elt(x, y) for x, y in zip(tru, est)]) + +def assert_shapes_match(tru, est): + if tru.shape != est.shape: + msg = "Output shapes {} and {} don't match" + raise AssertionError(msg.format(tru.shape, est.shape)) + +def load_single_op(model_name, input_type=None): + """Given a model name, returns a single-operator model in eval + mode as well as an example input.""" + input_shape = [1, 3, 224, 224] + if input_type is None or input_type == 'float32': + model = getattr(single_op, model_name)().float().eval() + input_data = torch.rand(input_shape).float() + elif input_type == 'float64': + model = getattr(single_op, model_name)().double().eval() + #input_data = torch.rand(input_shape).double() + #input_data = torch.from_numpy(np.random.random_sample((1, 3, 224, 224))).double() + temp = np.random.random_sample((1, 3, 224, 224)) + input_data = torch.from_numpy(temp) + elif input_type == 'float16': + model = getattr(single_op, model_name)().float().eval() + input_data = torch.rand(input_shape) + elif input_type == 'int32': + model = getattr(single_op, model_name)().eval() + input_data = torch.randint(0, 10, input_shape).int() + elif input_type == 'int16': + model = getattr(single_op, model_name)().eval() + input_data = torch.randint(0, 10, input_shape).short() + elif input_type == 'int8': + model = getattr(single_op, model_name)().eval() + input_data = torch.randint(0, 10, input_shape).char() + elif input_type == 'uint8': + model = getattr(single_op, model_name)().eval() + input_data = torch.randint(0, 10, input_shape).byte() + return model, input_data + +def load_torchvision(model_name, input_type=None): + """Given a model name, returns a Torchvision model in eval mode as well + as an example input.""" + + if model_name.startswith('inception'): + height = width = 299 + mean = [0.5, 0.5, 0.5] + std = [0.5, 0.5, 0.5] + else: + height = width = 224 + mean = [0.485, 0.456, 0.406] + std = [0.229, 0.224, 0.225] + input_shape = [1, 3, height, width] + + model = getattr(torchvision.models, model_name)(pretrained=True) + #model = model.float().eval() + + if input_type is None or input_type == 'float32': + model = model.float().eval() + input_data = torch.randn(input_shape).float() + elif input_type == 'float64': + model = model.double().eval() + input_data = torch.randn(input_shape).double() + + for channel in range(3): + input_data[:, channel] -= mean[channel] + input_data[:, channel] /= std[channel] + + return model, input_data + +def load_pretrainedmodels(model_name): + """Given a model name, returns a pretrainedmodels.pytorch model in eval + mode as well as an example input.""" + import pretrainedmodels # https://github.com/Cadene/pretrained-models.pytorch + model = getattr(pretrainedmodels, model_name)().float().eval() + input_shape = [1, *model.input_size] + input_data = torch.rand(input_shape).float() * 256 + for channel in range(3): + input_data[:, channel] -= model.mean[channel] + input_data[:, channel] /= model.std[channel] + return model, input_data + +def load_model(model_name, input_type=None): + """Given a model name, returns a model as well as an example input.""" + if hasattr(single_op, model_name): + return load_single_op(model_name, input_type) + if hasattr(torchvision.models, model_name): + return load_torchvision(model_name) + try: + if hasattr(pretrainedmodels, model_name): + return load_pretrainedmodels(model_name) + except ModuleNotFoundError: + raise ModuleNotFoundError('Please install pretrainedmodels.pytorch') + raise RuntimeError('Model not supported') + + +def confidence_interval(mean, stdev, count, alpha=.01): + """Returns the lower and upper bounds of the confidence interval of a random + variable. Confidence is 1 - alpha (default confidence is 99%).""" + stdval = tdistr.ppf(1 - alpha / 2, count - 1) + lower, upper = mean + np.array([-1, 1]) * stdval * stdev / np.sqrt(count) + return lower, upper + +def measure_latency(model, input_shapes, output_shapes, thresh, dryruns=40): + """Compute the latency of the given model""" + latencies = [] + count = 0 + while True: + if isinstance(model, torch.nn.Module): + input_data = [torch.rand(shape).float() for shape in input_shapes] + if torch.cuda.is_available(): + input_data = list(map(lambda x: x.cuda(), input_data)) + model = model.cuda() + t_start = time() + model(*input_data) + t_end = time() + latencies.append(t_end - t_start) + else: + input_data = {} + for i, shape in enumerate(input_shapes): + name = 'input' + str(i) + arr = np.random.random(shape).astype('float32') + input_data[name] = tvm.nd.array(arr) + t_start = time() + model.set_input(**input_data) + model.run() + for i, shape in enumerate(output_shapes): + arr = np.zeros(shape).astype('float32') + model.get_output(i, tvm.nd.array(arr)) + t_end = time() + count += 1 + if count < dryruns: + continue + latencies.append(t_end - t_start) + mean = np.mean(latencies) + stdev = np.std(latencies) + sample_size = len(latencies) + if sample_size > dryruns: + lower, upper = confidence_interval(mean, stdev, sample_size) + est = (upper + lower) / 2 + err = (upper - lower) / 2 + if err < thresh: + return est + +def verify_model(model_name, input_type=None): + """Assert that the output of a compiled model matches with that of its + baseline.""" + + print(model_name) + + baseline_model, baseline_input = load_model(model_name, input_type) + if torch.cuda.is_available(): + baseline_model = baseline_model.cuda() + baseline_input = baseline_input.cuda() + baseline_outputs = baseline_model(baseline_input) + dtype = input_type + if input_type is None or input_type == 'float32': + baseline_model = baseline_model.float() + baseline_input = baseline_input.float() + baseline_outputs = baseline_outputs.float() + if isinstance(baseline_outputs, tuple): + baseline_outputs = tuple(out.detach().cpu().numpy() for out in baseline_outputs) + else: + baseline_outputs = (baseline_outputs.detach().float().cpu().numpy(),) Review comment: remove detach() same for all detach below ---------------------------------------------------------------- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. For queries about this service, please contact Infrastructure at: us...@infra.apache.org With regards, Apache Git Services