File size: 8,278 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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
"""TensorRT engines run on GPU buffers (Polygraphy's CUDA wrapper; no torch): a decoder's KV cache stays on the GPU
between steps, and the activations between split engines (piecewise.py) never leave it.

    from device_chain import Chain, Buffers
    step = Chain(folder, [{"engine": "gpt_step_0.engine"}, ...])        # or Chain.from_split(folder, "gpt_step")
    out = step({"token": np.array(...), "c_k0": cache_a["c_k0"], ...},  # numpy arrays are copied in, DeviceArrays used
               outputs={"n_k0": cache_b["n_k0"], ...},                   # where these outputs go (else the chain's own)
               fetch=["logits"])                                          # -> {"logits": numpy array}

A tensor a call writes must not be one it reads: a cache is read from one set of buffers and written to another, and
the two sets swap after every step (Buffers.swap). Buffers are allocated at their largest shape once; a smaller shape
reuses the allocation (DeviceArray.resize), so the steps allocate nothing.
"""
from __future__ import annotations

import json
from pathlib import Path

import numpy as np


def _cuda():
    from polygraphy import cuda
    return cuda


def device_array(shape, dtype):
    """A DeviceArray of a numpy dtype (Polygraphy's DataType: numpy dtypes there are deprecated), which also keeps
    the numpy dtype (reading DeviceArray.dtype logs a deprecation warning on every call)."""
    from polygraphy.datatype import DataType
    a = _cuda().DeviceArray(shape=tuple(shape), dtype=DataType.from_dtype(np.dtype(dtype)))
    a.np_dtype = np.dtype(dtype)
    return a


def host_dtype(a) -> np.dtype:
    return a.np_dtype


class Engine:
    """One engine on device buffers. Its execution context holds device memory for the profile's largest shapes, or,
    with shared=True, none of its own: Chain gives all its engines one scratch buffer (they run one at a time on one
    stream), the size of the largest one's."""

    def __init__(self, path, shared=False):
        import tensorrt as trt
        from trt_runner import lean_dlls
        lean_dlls()
        self.trt = trt
        runtime = trt.Runtime(trt.Logger(trt.Logger.WARNING))
        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
        if shared:
            self.context = engine.create_execution_context(trt.ExecutionContextAllocationStrategy.USER_MANAGED)
            self.scratch = engine.get_device_memory_size_for_profile_v2(0)
        else:
            self.context, self.scratch = engine.create_execution_context(), 0
        names = [engine.get_tensor_name(i) for i in range(engine.num_io_tensors)]
        self.inputs = [n for n in names if engine.get_tensor_mode(n) == trt.TensorIOMode.INPUT]
        self.outputs = [n for n in names if engine.get_tensor_mode(n) == trt.TensorIOMode.OUTPUT]
        self.dtype = {n: np.dtype(trt.nptype(engine.get_tensor_dtype(n))) for n in names}

    def enqueue(self, inputs: dict, outputs: dict, stream) -> None:
        """inputs / outputs: name -> DeviceArray. Each output is resized to its shape for these inputs."""
        c = self.context
        for n in self.inputs:
            a = inputs[n]
            c.set_input_shape(n, tuple(a.shape))
            c.set_tensor_address(n, a.ptr)
        for n in self.outputs:
            o = outputs[n]
            o.resize(tuple(c.get_tensor_shape(n)))
            c.set_tensor_address(n, o.ptr)
        if not c.execute_async_v3(stream.ptr):
            raise RuntimeError("TensorRT execution failed")

    def use_memory(self, buf) -> None:
        self.context.set_device_memory(buf.ptr, self.scratch)

    def close(self):
        self.context = self.engine = None


class Chain:
    """Engines run in order on one CUDA stream; each reads the call's inputs and earlier engines' outputs by name."""

    def __init__(self, folder, plan: list[dict], shared_memory=True):
        self.folder, self.plan, self.engines = Path(folder), plan, []
        self.pool = {}                                    # the chain's own buffers, by tensor name
        self.stream = None
        self.shared = shared_memory                       # one scratch buffer for all the engines' activations

    @classmethod
    def from_split(cls, folder, part: str):
        """<part>_split.json (the engines in order) if the part was split, else <part>.engine alone."""
        f = Path(folder) / f"{part}_split.json"
        return cls(folder, json.loads(f.read_text()) if f.exists() else [{"engine": f"{part}.engine"}])

    def load(self):
        if not self.engines:
            self.stream = _cuda().Stream()
            self.engines = [Engine(self.folder / p["engine"], self.shared) for p in self.plan]
            if self.shared:
                scratch = self.pool["scratch"] = device_array((max(1, *(e.scratch for e in self.engines)),), np.uint8)
                for e in self.engines:
                    e.use_memory(scratch)
        return self

    def buffer(self, name: str, dtype, shape=(1,)):
        """The chain's own buffer for a tensor (allocated on first use, at least one element)."""
        b = self.pool.get(name)
        if b is None:
            b = self.pool[name] = device_array(tuple(max(1, d) for d in shape) or (1,), dtype)
        return b

    def __call__(self, feeds: dict, outputs: dict | None = None, fetch=()) -> dict:
        self.load()
        outputs = outputs or {}
        env, keep = {}, []
        for n, v in feeds.items():
            if isinstance(v, np.ndarray):                 # host -> a pooled device buffer of the engine's dtype
                want = next((e.dtype[n] for e in self.engines if n in e.dtype), v.dtype)
                h = np.ascontiguousarray(v, dtype=want)
                b = self.buffer("in:" + n, want, h.shape)
                b.resize(h.shape)
                b.copy_from(h, self.stream)
                keep.append(h)                            # alive until the stream has copied it
                env[n] = b
            else:
                env[n] = v
        for e in self.engines:
            outs = {n: outputs[n] if n in outputs else self.buffer(n, e.dtype[n]) for n in e.outputs}
            e.enqueue(env, outs, self.stream)
            env.update(outs)
        res = {}
        for n in fetch:
            a = env[n]
            res[n] = np.empty(tuple(a.shape), dtype=host_dtype(a))
            a.copy_to(res[n], self.stream)
        self.stream.synchronize()
        return res

    def close(self):
        for e in self.engines:
            e.close()
        for b in self.pool.values():
            b.free()
        self.engines, self.pool = [], {}


class Buffers:
    """Two sets of device buffers for a decoder's caches, each allocated at the largest shape: step k reads set A
    and writes set B, then swap() exchanges them."""

    def __init__(self, names_in: list[str], names_out: list[str], dtype, max_shape):
        self.names_in, self.names_out = names_in, names_out
        self.a = [device_array(max_shape, dtype) for _ in names_in]
        self.b = [device_array(max_shape, dtype) for _ in names_in]

    def reads(self) -> dict:
        return dict(zip(self.names_in, self.a))

    def writes(self) -> dict:
        return dict(zip(self.names_out, self.b))

    def swap(self):
        self.a, self.b = self.b, self.a

    def reset(self, shape):
        """Set A as an empty cache of this shape (e.g. [1, 0, 256] before a prefill): no copy, no allocation."""
        for buf in self.a:
            buf.resize(tuple(shape))

    def load(self, arrays, stream=None):
        """Fill set A from host arrays (the prompt's cache)."""
        for buf, x in zip(self.a, arrays):
            x = np.ascontiguousarray(x, dtype=host_dtype(buf))
            buf.resize(x.shape)
            buf.copy_from(x, stream)

    def free(self):
        for b in self.a + self.b:
            b.free()
        self.a = self.b = []