|
| 1 | +# Copyright (c) MONAI Consortium |
| 2 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 3 | +# you may not use this file except in compliance with the License. |
| 4 | +# You may obtain a copy of the License at |
| 5 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 6 | +# Unless required by applicable law or agreed to in writing, software |
| 7 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 8 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 9 | +# See the License for the specific language governing permissions and |
| 10 | +# limitations under the License. |
| 11 | + |
| 12 | +from __future__ import annotations |
| 13 | + |
| 14 | +from typing import TYPE_CHECKING |
| 15 | + |
| 16 | +from monai.config import IgniteInfo |
| 17 | +from monai.networks import trt_compile |
| 18 | +from monai.utils import min_version, optional_import |
| 19 | + |
| 20 | +Events, _ = optional_import("ignite.engine", IgniteInfo.OPT_IMPORT_VERSION, min_version, "Events") |
| 21 | +if TYPE_CHECKING: |
| 22 | + from ignite.engine import Engine |
| 23 | +else: |
| 24 | + Engine, _ = optional_import("ignite.engine", IgniteInfo.OPT_IMPORT_VERSION, min_version, "Engine") |
| 25 | + |
| 26 | + |
| 27 | +class TrtHandler: |
| 28 | + """ |
| 29 | + TrtHandler acts as an Ignite handler to apply TRT acceleration to the model. |
| 30 | + Usage example:: |
| 31 | + handler = TrtHandler(model=model, base_path="/test/checkpoint.pt", args={"precision": "fp16"}) |
| 32 | + handler.attach(engine) |
| 33 | + engine.run() |
| 34 | + """ |
| 35 | + |
| 36 | + def __init__(self, model, base_path, args=None, submodule=None): |
| 37 | + """ |
| 38 | + Args: |
| 39 | + base_path: TRT path basename. TRT plan(s) saved to "base_path[.submodule].plan" |
| 40 | + args: passed to trt_compile(). See trt_compile() for details. |
| 41 | + submodule : Hierarchical ids of submodules to convert, e.g. 'image_decoder.decoder' |
| 42 | + """ |
| 43 | + self.model = model |
| 44 | + self.base_path = base_path |
| 45 | + self.args = args |
| 46 | + self.submodule = submodule |
| 47 | + |
| 48 | + def attach(self, engine: Engine) -> None: |
| 49 | + """ |
| 50 | + Args: |
| 51 | + engine: Ignite Engine, it can be a trainer, validator or evaluator. |
| 52 | + """ |
| 53 | + self.logger = engine.logger |
| 54 | + engine.add_event_handler(Events.STARTED, self) |
| 55 | + |
| 56 | + def __call__(self, engine: Engine) -> None: |
| 57 | + """ |
| 58 | + Args: |
| 59 | + engine: Ignite Engine, it can be a trainer, validator or evaluator. |
| 60 | + """ |
| 61 | + trt_compile(self.model, self.base_path, args=self.args, submodule=self.submodule, logger=self.logger) |
0 commit comments