|
| 1 | +import unittest |
| 2 | +import trtorch |
| 3 | +import torch |
| 4 | +import torchvision.models as models |
| 5 | + |
| 6 | +from model_test_case import ModelTestCase |
| 7 | + |
| 8 | +class TestCompile(MultiGpuTestCase): |
| 9 | + |
| 10 | + def setUp(self): |
| 11 | + if not torch.cuda.device_count() > 1: |
| 12 | + raise ValueError("This test case is applicable for multi-gpu configurations only") |
| 13 | + |
| 14 | + self.gpu_id = 1 |
| 15 | + # Setting it up here so that all CUDA allocations are done on correct device |
| 16 | + trtorch.set_device(self.gpu_id) |
| 17 | + self.input = torch.randn((1, 3, 224, 224)).to("cuda") |
| 18 | + self.traced_model = torch.jit.trace(self.model, [self.input]) |
| 19 | + self.scripted_model = torch.jit.script(self.model) |
| 20 | + |
| 21 | + def test_compile_traced(self): |
| 22 | + compile_spec = { |
| 23 | + "input_shapes": [self.input.shape], |
| 24 | + "device": { |
| 25 | + "device_type": trtorch.DeviceType.GPU, |
| 26 | + "gpu_id": self.gpu_id, |
| 27 | + "dla_core": 0, |
| 28 | + "allow_gpu_fallback": False, |
| 29 | + "disable_tf32": False |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + trt_mod = trtorch.compile(self.traced_model, compile_spec) |
| 34 | + same = (trt_mod(self.input) - self.traced_model(self.input)).abs().max() |
| 35 | + self.assertTrue(same < 2e-3) |
| 36 | + |
| 37 | + def test_compile_script(self): |
| 38 | + compile_spec = { |
| 39 | + "input_shapes": [self.input.shape], |
| 40 | + "device": { |
| 41 | + "device_type": trtorch.DeviceType.GPU, |
| 42 | + "gpu_id": self.gpu_id, |
| 43 | + "dla_core": 0, |
| 44 | + "allow_gpu_fallback": False, |
| 45 | + "disable_tf32": False |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + trt_mod = trtorch.compile(self.scripted_model, compile_spec) |
| 50 | + same = (trt_mod(self.input) - self.scripted_model(self.input)).abs().max() |
| 51 | + self.assertTrue(same < 2e-3) |
| 52 | + |
| 53 | + |
| 54 | + |
| 55 | +def test_suite(): |
| 56 | + suite = unittest.TestSuite() |
| 57 | + suite.addTest(TestCompile.parametrize(TestCompile, model=models.resnet18(pretrained=True))) |
| 58 | + |
| 59 | + return suite |
| 60 | + |
| 61 | +suite = test_suite() |
| 62 | + |
| 63 | +runner = unittest.TextTestRunner() |
| 64 | +result = runner.run(suite) |
| 65 | + |
| 66 | +exit(int(not result.wasSuccessful())) |
0 commit comments