|
| 1 | +import torch |
| 2 | +import inspect |
| 3 | +import numpy as np |
| 4 | +from .graph_compiler_backend import GraphCompilerBackend |
| 5 | + |
| 6 | +try: |
| 7 | + import tvm |
| 8 | + from tvm import relax |
| 9 | + from tvm import dlight as dl |
| 10 | + from tvm.relax.frontend.torch import dynamo_capture_subgraphs |
| 11 | +except ImportError: |
| 12 | + tvm = None |
| 13 | + relax = None |
| 14 | + from_exported_program = None |
| 15 | + |
| 16 | + |
| 17 | +class TvmCompiledModule(torch.nn.Module): |
| 18 | + def __init__(self, module, device): |
| 19 | + super().__init__() |
| 20 | + self.module = module |
| 21 | + self.counter = 0 |
| 22 | + self.tvm_input = [] |
| 23 | + self.compiled_vm = None |
| 24 | + self.dev = tvm.device(device) |
| 25 | + self.target = tvm.target.Target.from_device(self.dev) |
| 26 | + self.param_names = list(inspect.signature(module.forward).parameters.keys()) |
| 27 | + |
| 28 | + def forward(self, **kwargs): |
| 29 | + if self.counter == 0: |
| 30 | + self.compiled_vm = self.compile(self.module, **kwargs) |
| 31 | + for name in self.param_names: |
| 32 | + if name in kwargs and name != "s1": |
| 33 | + self.tvm_input.append(tvm.nd.from_dlpack(kwargs[name])) |
| 34 | + |
| 35 | + output = self.compiled_vm["subgraph_0"](*self.tvm_input) |
| 36 | + self.counter += 1 |
| 37 | + return torch.from_dlpack(output) |
| 38 | + |
| 39 | + def compile(self, module, **kwargs): |
| 40 | + with torch.no_grad(): |
| 41 | + mod = dynamo_capture_subgraphs(module, **kwargs, keep_params_as_input=True) |
| 42 | + mod, _ = relax.frontend.detach_params(mod) |
| 43 | + with self.target: |
| 44 | + mod = tvm.ir.transform.Sequential( |
| 45 | + [ |
| 46 | + relax.get_pipeline("zero"), |
| 47 | + dl.ApplyDefaultSchedule( |
| 48 | + dl.gpu.Matmul(), |
| 49 | + dl.gpu.GEMV(), |
| 50 | + dl.gpu.Reduction(), |
| 51 | + dl.gpu.GeneralReduction(), |
| 52 | + dl.gpu.Fallback(), |
| 53 | + ), |
| 54 | + ] |
| 55 | + )(mod) |
| 56 | + ex = tvm.compile(mod, target=self.target) |
| 57 | + vm = relax.VirtualMachine(ex, self.dev) |
| 58 | + return vm |
| 59 | + |
| 60 | + |
| 61 | +class TvmBackend(GraphCompilerBackend): |
| 62 | + def __call__(self, model, **kwargs): |
| 63 | + if torch.cuda.is_available(): |
| 64 | + device = "cuda" |
| 65 | + else: |
| 66 | + device = "llvm" |
| 67 | + return TvmCompiledModule(model, device=device) |
| 68 | + |
| 69 | + def synchronize(self): |
| 70 | + if torch.cuda.is_available(): |
| 71 | + torch.cuda.synchronize() |
| 72 | + |
| 73 | + def version(self): |
| 74 | + try: |
| 75 | + from importlib.metadata import version |
| 76 | + |
| 77 | + return version("tvm") |
| 78 | + except: |
| 79 | + return "unknown" |
0 commit comments