|
| 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 TestMultiGpuSwitching(ModelTestCase): |
| 9 | + def setUp(self): |
| 10 | + if torch.cuda.device_count() < 2: |
| 11 | + self.fail("Test is not relevant for this platform since number of available CUDA devices is less than 2") |
| 12 | + |
| 13 | + trtorch.set_device(0) |
| 14 | + self.target_gpu = 1 |
| 15 | + self.input = torch.randn((1, 3, 224, 224)).to("cuda:1") |
| 16 | + self.model = self.model.to("cuda:1") |
| 17 | + self.traced_model = torch.jit.trace(self.model, [self.input]) |
| 18 | + self.scripted_model = torch.jit.script(self.model) |
| 19 | + |
| 20 | + def test_compile_traced(self): |
| 21 | + trtorch.set_device(0) |
| 22 | + compile_spec = { |
| 23 | + "input_shapes": [self.input.shape], |
| 24 | + "device": { |
| 25 | + "device_type": trtorch.DeviceType.GPU, |
| 26 | + "gpu_id": self.target_gpu, |
| 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 | + trtorch.set_device(self.target_gpu) |
| 35 | + same = (trt_mod(self.input) - self.traced_model(self.input)).abs().max() |
| 36 | + trtorch.set_device(0) |
| 37 | + self.assertTrue(same < 2e-3) |
| 38 | + |
| 39 | + def test_compile_script(self): |
| 40 | + trtorch.set_device(0) |
| 41 | + compile_spec = { |
| 42 | + "input_shapes": [self.input.shape], |
| 43 | + "device": { |
| 44 | + "device_type": trtorch.DeviceType.GPU, |
| 45 | + "gpu_id": self.target_gpu, |
| 46 | + "dla_core": 0, |
| 47 | + "allow_gpu_fallback": False, |
| 48 | + "disable_tf32": False |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + trt_mod = trtorch.compile(self.scripted_model, compile_spec) |
| 53 | + trtorch.set_device(self.target_gpu) |
| 54 | + same = (trt_mod(self.input) - self.scripted_model(self.input)).abs().max() |
| 55 | + trtorch.set_device(0) |
| 56 | + self.assertTrue(same < 2e-3) |
| 57 | + |
| 58 | +def test_suite(): |
| 59 | + suite = unittest.TestSuite() |
| 60 | + suite.addTest(TestMultiGpuSwitching.parametrize(TestMultiGpuSwitching, model=models.resnet18(pretrained=True))) |
| 61 | + |
| 62 | + return suite |
| 63 | + |
| 64 | +suite = test_suite() |
| 65 | + |
| 66 | +runner = unittest.TextTestRunner() |
| 67 | +result = runner.run(suite) |
| 68 | + |
| 69 | +exit(int(not result.wasSuccessful())) |
0 commit comments