|
| 1 | +import ast |
| 2 | +import logging |
| 3 | +import os |
| 4 | +from typing import List, Optional, Tuple |
| 5 | + |
| 6 | +import numpy as np |
| 7 | +import torch |
| 8 | +import torch_tensorrt as torch_trt |
| 9 | +import torchvision.models as models |
| 10 | +from torch_tensorrt.dynamo._defaults import TIMING_CACHE_PATH |
| 11 | +from torch_tensorrt.dynamo._engine_caching import BaseEngineCache |
| 12 | + |
| 13 | +_LOGGER: logging.Logger = logging.getLogger(__name__) |
| 14 | + |
| 15 | + |
| 16 | +np.random.seed(0) |
| 17 | +torch.manual_seed(0) |
| 18 | +size = (100, 3, 224, 224) |
| 19 | + |
| 20 | +model = models.resnet18(pretrained=True).eval().to("cuda") |
| 21 | +enabled_precisions = {torch.float} |
| 22 | +debug = False |
| 23 | +min_block_size = 1 |
| 24 | +use_python_runtime = False |
| 25 | + |
| 26 | + |
| 27 | +def remove_timing_cache(path=TIMING_CACHE_PATH): |
| 28 | + if os.path.exists(path): |
| 29 | + os.remove(path) |
| 30 | + |
| 31 | + |
| 32 | +def dynamo_path(iterations=3): |
| 33 | + times = [] |
| 34 | + start = torch.cuda.Event(enable_timing=True) |
| 35 | + end = torch.cuda.Event(enable_timing=True) |
| 36 | + |
| 37 | + example_inputs = (torch.randn((100, 3, 224, 224)).to("cuda"),) |
| 38 | + # Mark the dim0 of inputs as dynamic |
| 39 | + batch = torch.export.Dim("batch", min=1, max=200) |
| 40 | + exp_program = torch.export.export( |
| 41 | + model, args=example_inputs, dynamic_shapes={"x": {0: batch}} |
| 42 | + ) |
| 43 | + |
| 44 | + for i in range(iterations): |
| 45 | + inputs = [torch.rand((100 + i, 3, 224, 224)).to("cuda")] |
| 46 | + remove_timing_cache() # remove timing cache for engine caching messurement |
| 47 | + if i == 0: |
| 48 | + save_engine_cache = False |
| 49 | + load_engine_cache = False |
| 50 | + else: |
| 51 | + save_engine_cache = True |
| 52 | + load_engine_cache = True |
| 53 | + |
| 54 | + start.record() |
| 55 | + trt_gm = torch_trt.dynamo.compile( |
| 56 | + exp_program, |
| 57 | + tuple(inputs), |
| 58 | + use_python_runtime=use_python_runtime, |
| 59 | + enabled_precisions=enabled_precisions, |
| 60 | + debug=debug, |
| 61 | + min_block_size=min_block_size, |
| 62 | + make_refitable=True, |
| 63 | + save_engine_cache=save_engine_cache, |
| 64 | + load_engine_cache=load_engine_cache, |
| 65 | + engine_cache_size=1 << 30, # 1GB |
| 66 | + ) |
| 67 | + end.record() |
| 68 | + torch.cuda.synchronize() |
| 69 | + times.append(start.elapsed_time(end)) |
| 70 | + |
| 71 | + print("-----dynamo_path-----> compilation time:", times, "milliseconds") |
| 72 | + |
| 73 | + |
| 74 | +# Custom Engine Cache |
| 75 | +class MyEngineCache(BaseEngineCache): |
| 76 | + |
| 77 | + def __init__( |
| 78 | + self, |
| 79 | + engine_cache_size: int, |
| 80 | + engine_cache_dir: str, |
| 81 | + ) -> None: |
| 82 | + self.total_engine_cache_size = engine_cache_size |
| 83 | + self.available_engine_cache_size = engine_cache_size |
| 84 | + self.engine_cache_dir = engine_cache_dir |
| 85 | + |
| 86 | + def save( |
| 87 | + self, |
| 88 | + hash: str, |
| 89 | + serialized_engine: bytes, |
| 90 | + input_names: List[str], |
| 91 | + output_names: List[str], |
| 92 | + ) -> bool: |
| 93 | + path = os.path.join( |
| 94 | + self.engine_cache_dir, |
| 95 | + f"{hash}/engine--{input_names}--{output_names}.trt", |
| 96 | + ) |
| 97 | + try: |
| 98 | + os.makedirs(os.path.dirname(path), exist_ok=True) |
| 99 | + with open(path, "wb") as f: |
| 100 | + f.write(serialized_engine) |
| 101 | + except Exception as e: |
| 102 | + _LOGGER.warning(f"Failed to save the TRT engine to {path}: {e}") |
| 103 | + return False |
| 104 | + |
| 105 | + _LOGGER.info(f"A TRT engine was cached to {path}") |
| 106 | + serialized_engine_size = int(serialized_engine.nbytes) |
| 107 | + self.available_engine_cache_size -= serialized_engine_size |
| 108 | + return True |
| 109 | + |
| 110 | + def load(self, hash: str) -> Tuple[Optional[bytes], List[str], List[str]]: |
| 111 | + directory = os.path.join(self.engine_cache_dir, hash) |
| 112 | + if os.path.exists(directory): |
| 113 | + engine_list = os.listdir(directory) |
| 114 | + assert ( |
| 115 | + len(engine_list) == 1 |
| 116 | + ), f"There are more than one engine {engine_list} under {directory}." |
| 117 | + path = os.path.join(directory, engine_list[0]) |
| 118 | + input_names_str, output_names_str = ( |
| 119 | + engine_list[0].split(".trt")[0].split("--")[1:] |
| 120 | + ) |
| 121 | + input_names = ast.literal_eval(input_names_str) |
| 122 | + output_names = ast.literal_eval(output_names_str) |
| 123 | + with open(path, "rb") as f: |
| 124 | + serialized_engine = f.read() |
| 125 | + return serialized_engine, input_names, output_names |
| 126 | + else: |
| 127 | + return None, [], [] |
| 128 | + |
| 129 | + |
| 130 | +def compile_path(iterations=3): |
| 131 | + times = [] |
| 132 | + engine_cache = MyEngineCache(200 * (1 << 20), "/tmp/your_dir") |
| 133 | + start = torch.cuda.Event(enable_timing=True) |
| 134 | + end = torch.cuda.Event(enable_timing=True) |
| 135 | + |
| 136 | + for i in range(iterations): |
| 137 | + inputs = [torch.rand(size).to("cuda")] |
| 138 | + # remove timing cache and reset dynamo for engine caching messurement |
| 139 | + remove_timing_cache() |
| 140 | + torch._dynamo.reset() |
| 141 | + |
| 142 | + if i == 0: |
| 143 | + save_engine_cache = False |
| 144 | + load_engine_cache = False |
| 145 | + else: |
| 146 | + save_engine_cache = True |
| 147 | + load_engine_cache = True |
| 148 | + |
| 149 | + start.record() |
| 150 | + compiled_model = torch.compile( |
| 151 | + model, |
| 152 | + backend="tensorrt", |
| 153 | + options={ |
| 154 | + "use_python_runtime": use_python_runtime, |
| 155 | + "enabled_precisions": enabled_precisions, |
| 156 | + "debug": debug, |
| 157 | + "min_block_size": min_block_size, |
| 158 | + "make_refitable": True, |
| 159 | + "save_engine_cache": save_engine_cache, |
| 160 | + "load_engine_cache": load_engine_cache, |
| 161 | + "engine_cache_instance": engine_cache, # use custom engine cache |
| 162 | + }, |
| 163 | + ) |
| 164 | + compiled_model(*inputs) # trigger the compilation |
| 165 | + end.record() |
| 166 | + torch.cuda.synchronize() |
| 167 | + times.append(start.elapsed_time(end)) |
| 168 | + |
| 169 | + print("-----compile_path-----> compilation time:", times, "milliseconds") |
| 170 | + |
| 171 | + |
| 172 | +if __name__ == "__main__": |
| 173 | + dynamo_path() |
| 174 | + compile_path() |
0 commit comments