File size: 4,392 Bytes
3dfb5fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
"""A minimal TensorRT engine runner: numpy in, numpy out (tensorrt-cu12 10.x and polygraphy; no torch).

    from trt_runner import Engine
    e = Engine("model.engine")
    out = e({"input": x})            # dict of output name -> numpy array
"""
from __future__ import annotations

from pathlib import Path

import numpy as np


def lean_dlls():
    """Version-compatible engines are built against and run on TensorRT's lean runtime (pip tensorrt-lean-cu12):
    put its DLL folder on the search path (Windows)."""
    import importlib.util
    import os
    spec = importlib.util.find_spec("tensorrt_lean_libs")
    if spec and spec.submodule_search_locations:
        d = list(spec.submodule_search_locations)[0]
        os.environ["PATH"] = d + os.pathsep + os.environ.get("PATH", "")
        if hasattr(os, "add_dll_directory"):
            os.add_dll_directory(d)


class Engine:
    """allocation: "static" (memory for the profiles' largest shapes, reserved once) or "runtime" (sized to each call's
    shapes: for pipelines of many engines with wide profiles, which would otherwise reserve every engine's maximum)."""

    def __init__(self, path, allocation="static"):
        lean_dlls()
        import tensorrt as trt
        from polygraphy.backend.trt import TrtRunner
        self.trt = trt
        logger = trt.Logger(trt.Logger.WARNING)
        runtime = trt.Runtime(logger)
        runtime.engine_host_code_allowed = True          # version-compatible engines carry their own lean runtime
        engine = runtime.deserialize_cuda_engine(Path(path).read_bytes())
        if engine is None:
            raise RuntimeError(f"could not load {path} (TensorRT {trt.__version__}; the engine needs TensorRT 10.x "
                               "and an RTX 30-series or newer GPU)")
        self.engine = engine
        self.runner = TrtRunner(engine, allocation_strategy=allocation)
        self.runner.activate()
        self.inputs = [engine.get_tensor_name(i) for i in range(engine.num_io_tensors)
                       if engine.get_tensor_mode(engine.get_tensor_name(i)) == trt.TensorIOMode.INPUT]

    def __call__(self, feed: dict) -> dict:
        feed = {k: np.ascontiguousarray(v) for k, v in feed.items() if k in self.inputs}
        out = self.runner.infer(feed, check_inputs=True)
        return {k: np.array(v) for k, v in out.items()}

    def close(self):
        """Release the engine's device memory and weights now (deactivating the runner alone keeps the weights on
        the GPU until the engine object is collected)."""
        runner = getattr(self, "runner", None)
        if runner is not None and runner.is_active:
            runner.deactivate()
        self.runner = self.engine = None

    def __del__(self):
        try:
            self.close()
        except Exception:
            pass


class OrtLike:
    """An engine behind onnxruntime's InferenceSession calls (run / get_inputs / get_outputs / get_providers), so a
    pipeline.py written for ONNX Runtime runs its graphs on TensorRT unchanged. Outputs come back in the order the
    ONNX graph listed them (pass `outputs`), else in the engine's order."""

    def __init__(self, path, outputs=None, allocation="static"):
        self.e = Engine(path, allocation)
        eng = self.e.engine
        names = [eng.get_tensor_name(i) for i in range(eng.num_io_tensors)]
        self.outs = list(outputs) if outputs else [n for n in names if n not in self.e.inputs]

    def get_inputs(self):
        """name, type ("tensor(float16)" etc., as onnxruntime spells it) and shape (-1 for dynamic dimensions)."""
        from types import SimpleNamespace
        eng, trt = self.e.engine, self.e.trt
        names = {trt.float16: "float16", trt.float32: "float", trt.int64: "int64", trt.int32: "int32",
                 trt.bool: "bool", trt.int8: "int8", trt.bfloat16: "bfloat16"}
        return [SimpleNamespace(name=n, type=f"tensor({names.get(eng.get_tensor_dtype(n), 'float')})",
                                shape=list(eng.get_tensor_shape(n))) for n in self.e.inputs]

    def get_outputs(self):
        from types import SimpleNamespace
        return [SimpleNamespace(name=n) for n in self.outs]

    def get_providers(self):
        return ["TensorRT"]

    def run(self, names, feed, run_options=None):
        out = self.e(feed)
        return [out[n] for n in (names or self.outs)]