trt-infer.py 17.2 KB
Newer Older
root's avatar
root committed
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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
import numpy as np
import tensorrt as trt
import torch
from cuda import cudart
import common as common
# import common as common
from colored import fg, stylize
import copy
import time
import json

# 随机种子
def set_random_seed(num: int):
    np.random.seed(num)
    # torch.random.manual_seed(num)

def compare_value(pre_numpy: np.array, true_numpy: np.array):
    assert pre_numpy.shape == true_numpy.shape
    diff = np.abs(pre_numpy - true_numpy).max()
    print(f"{pre_numpy[0, 0, 0, :3]} == {true_numpy[0, 0, 0, :3]}")
    if diff > 1e-5:
        print(stylize(f"diff: {diff} is_pass: failed", fg("red")))
    else:
        print(stylize(f"diff: {diff} is_pass: OK", fg("green")))
    return diff


def load_tensor_from_npy_file(file_name, dir_path):
    w_path = f"{dir_path}/{file_name}.npy"
    data = np.load(w_path)
    return torch.from_numpy(data)
    

def load_numpy_from_npy_file(file_name, dir_path):
    w_path = f"{dir_path}/{file_name}.npy"
    data = np.load(w_path)
    return data


def load_numpy_from_tensor(tensor):
    return copy.deepcopy(tensor.detach().cpu().numpy())


def get_tensor_from_numpy(data):
    return torch.from_numpy(data)


def get_data_type(trt_data_type):
    if trt.DataType.FLOAT == trt_data_type:
        return torch.float32, 4
    if trt.DataType.HALF == trt_data_type:
        return torch.float16, 2
    if trt.DataType.INT8 == trt_data_type:
        return torch.int8, 1
    if trt.DataType.INT32 == trt_data_type:
        return torch.int32, 4
    if trt.DataType.BOOL == trt_data_type:
        return torch.bool, 1
    if trt.DataType.UINT8 == trt_data_type:
        return torch.uint8, 1
    if trt.DataType.FP8 == trt_data_type:
        return torch.float8, 1
    else:
        return "unknown", 0


class trtInfer:
    def __init__(self, plan_path, batch_size=1):
        self.init_plugin()
        with open(plan_path, "rb") as f:
            buffer = f.read()
        self.engine = trt.Runtime(self.logger).deserialize_cuda_engine(buffer)
        self.nIO = self.engine.num_io_tensors
        self.ITensorName = [self.engine.get_tensor_name(i) for i in range(self.nIO)]
        self.nInput = [self.engine.get_tensor_mode(self.ITensorName[i]) for i in range(self.nIO)].count(trt.TensorIOMode.INPUT)
        self.stream = cudart.cudaStreamCreate()[1]
        self.context = self.engine.create_execution_context()
        assert self.context
        # print(f"self.ITensorName: {self.ITensorName}")
        # print(f"self.nIO: {self.nIO}")
        # print(f"self.nInput: {self.nInput}")
        # Setup I/O bindings
        self.inputs = []
        self.outputs = []
        self.allocations = []
        self.IOBindings = []
        for i in range(self.nIO):
            name = self.ITensorName[i]
            mode = self.engine.get_tensor_mode(name)
            dtype = self.engine.get_tensor_dtype(name)
            shape = self.engine.get_tensor_shape(name)
            # print(f"name: {name}, shape: {shape}, dtype: {dtype}, mode: {mode}")
            t_type, size = get_data_type(dtype)
            for s in shape:
                if s == -1:
                    s = 1
                size *= s
            # allocation = common.cuda_call(cudart.cudaMalloc(size * batch_size))
            allocation = common.cuda_call(cudart.cudaMalloc(1024))
            self.allocations.append(allocation)
            binding = {
                "index": i,
                "name": name,
                "dtype": t_type,
                "shape": list(shape),
                "allocation": allocation,
            }
            
            if trt.TensorIOMode.INPUT == mode:
                self.batch_size = shape[0]
                self.inputs.append(binding)
            else:
                self.outputs.append(binding)
        device = torch.device("cuda:0")
        self.output_buffer = []
        for shape, dtype in self.output_spec():
            self.output_buffer.append(torch.zeros(shape, dtype=dtype).float().to(device))

    def init_plugin(self):
        self.logger = trt.Logger(trt.Logger.ERROR)
        trt.init_libnvinfer_plugins(self.logger, "")
    
    def input_spec(self):
        """
        Get the specs for the input tensor of the network. Useful to prepare memory allocations.
        :return: Two items, the shape of the input tensor and its (numpy) datatype.
        """
        specs = []
        for o in self.inputs:
            specs.append((o['shape'], o['dtype']))
        return specs

    def output_spec(self):
        """
        Get the specs for the output tensors of the network. Useful to prepare memory allocations.
        :return: A list with two items per element, the shape and (numpy) datatype of each output tensor.
        """
        specs = []
        for o in self.outputs:
            specs.append((o['shape'], o['dtype']))
        return specs

    def set_Bindding(self):
        self.IOBindings = []
        self.IOBindings.extend(self.inputs)
        self.IOBindings.extend(self.outputs)
        for i, item in enumerate(self.IOBindings):
            if i < self.nInput:
                if not self.context.set_input_shape(item["name"], item["shape"]):
                    return False
            if not self.context.set_tensor_address(item["name"], item["allocation"]):
                return False
        return True

    def set_input(self, binding_buffering):
        for i, item in enumerate(binding_buffering):
            if torch.is_tensor(item):
                self.inputs[i]['shape'] = list(item.shape)
                self.inputs[i]['allocation'] = item.reshape(-1).data_ptr()
            else:
                self.inputs[i]['allocation'] = item

    def set_output(self, binding_buffering):
        for i, item in enumerate(binding_buffering):
            self.outputs[i]['shape'] = list(item.shape)
            self.outputs[i]['allocation'] = item.reshape(-1).data_ptr()

    def release(self):
        cudart.cudaStreamDestroy(self.stream)


class DM_TRT(trtInfer):
    def __init__(self, plan_path, bs=1):
        super().__init__(plan_path, bs)

    def __call__(self, x, timesteps, context, control, only_mid_control=False):
        device = x.device

        timesteps = timesteps.int()
        input_buffer = []
        input_buffer.append(x)
        input_buffer.append(timesteps)
        input_buffer.append(context)
        input_buffer.extend(control)

        current_batch = x.shape[0]
        output_buffer = []
        for shape, dtype in self.output_spec():
            shape[0] = current_batch
            output_buffer.append(torch.zeros(shape, dtype=dtype).float().to(device))

        self.set_input(input_buffer)  # set shape, allocate
        self.set_output(output_buffer)
        self.set_Bindding()
        self.context.execute_async_v3(self.stream)
        cudart.cudaStreamSynchronize(self.stream)
        return output_buffer[0]


class CM_TRT(trtInfer):
    def __init__(self, plan_path, bs=1):
        super().__init__(plan_path, bs)

    def __call__(self, x, hint, timesteps, context, **kwargs):
        device = x.device

        timesteps = timesteps.int()
        input_buffer = []
        input_buffer.append(x)
        input_buffer.append(hint)
        input_buffer.append(timesteps)
        input_buffer.append(context)

        # current_batch = x.shape[0]
        # output_buffer = []
        # for shape, dtype in self.output_spec():
        #     shape[0] = current_batch
        #     output_buffer.append(torch.zeros(shape, dtype=dtype).float().to(device))

        self.set_input(input_buffer)  # set shape, allocate
        # self.set_output(self.output_buffer)
        self.set_Bindding()
        self.context.execute_async_v3(self.stream)
        cudart.cudaStreamSynchronize(self.stream)

        # return output_buffer
        # return self.output_buffer
        return self.allocations[self.nInput:self.nIO]


class CM_DM_FUSE_TRT:
    def __init__(self, control_path, unet_path):
        self.control = CM_TRT(control_path)
        self.unet = DM_TRT(unet_path)

    def __call__(self, x, hint, timesteps, context, **kwargs):
        device = x.device

        timesteps = timesteps.int()
        input_buffer = []
        input_buffer.append(x)
        input_buffer.append(hint)
        input_buffer.append(timesteps)
        input_buffer.append(context)

        self.control.set_input(input_buffer)   # set shape, allocate
        # self.control.set_output(self.output_buffer)  # 使用 内部开辟好的cudaMemcpy

        input_unet_buffer = []
        input_unet_buffer.append(self.control.inputs[0]["allocation"])
        input_unet_buffer.append(self.control.inputs[2]["allocation"])
        input_unet_buffer.append(self.control.inputs[3]["allocation"])
        input_unet_buffer.extend(self.control.allocations[self.control.nInput:self.control.nIO])

        current_batch = x.shape[0]
        output_unet_buffer = []
        for shape, dtype in self.unet.output_spec():
            shape[0] = current_batch
            output_unet_buffer.append(torch.zeros(shape, dtype=dtype).float().to(device))

        self.unet.set_input(input_unet_buffer)   # set shape, allocate
        self.unet.set_output(output_unet_buffer)  # 使用 内部开辟好的cudaMemcpy
        
        self.control.set_Bindding()
        self.unet.set_Bindding()
        self.control.context.execute_async_v3(self.control.stream)
        self.unet.context.execute_async_v3(self.control.stream)
        cudart.cudaStreamSynchronize(self.control.stream)

        return output_unet_buffer[0]


def memcpy_tensor_to_dev(data, address):
    a_size = data[0].numel() * data[0].element_size()
    for i, item in enumerate(data):
        item_address = item.reshape(-1).data_ptr()
        # batch x
        common.cuda_call(cudart.cudaMemcpy(
            address + i * a_size, item_address, a_size, cudart.cudaMemcpyKind.cudaMemcpyDeviceToDevice))


class CM_DM_BATCH_TRT:
    def __init__(self, control_path, unet_path, batch_size):
        self.control = CM_TRT(control_path, batch_size)
        self.unet = DM_TRT(unet_path, batch_size)

    # def __call__(self, x, hint, timesteps, context, **kwargs):
    #     device = x.device

    #     timesteps = timesteps.int()
    #     input_buffer = []
    #     # input_buffer.append(x)
    #     memcpy_tensor_to_dev([x,x], self.control.inputs[0]["allocation"])
    #     # input_buffer.append(hint)
    #     memcpy_tensor_to_dev(hint, self.control.inputs[1]["allocation"])
    #     # input_buffer.append(timesteps)
    #     memcpy_tensor_to_dev([timesteps, timesteps], self.control.inputs[2]["allocation"])
    #     # input_buffer.append(context)
    #     memcpy_tensor_to_dev(context, self.control.inputs[3]["allocation"])

    #     # self.control.set_input(input_buffer)   # 使用 内部开辟好的cudaMemcpy
    #     # self.control.set_output(self.output_buffer)  # 使用 内部开辟好的cudaMemcpy
    #     self.control.set_Bindding()

    #     input_unet_buffer = []
    #     input_unet_buffer.append(self.control.inputs[0]["allocation"])
    #     input_unet_buffer.append(self.control.inputs[2]["allocation"])
    #     input_unet_buffer.append(self.control.inputs[3]["allocation"])
    #     input_unet_buffer.extend(self.control.allocations[self.control.nInput:self.control.nIO])

    #     # current_batch = x.shape[0]
    #     current_batch = 2
    #     output_unet_buffer = []
    #     for shape, dtype in self.unet.output_spec():
    #         shape[0] = current_batch
    #         temp = torch.zeros(shape, dtype=dtype).float().to(device)
    #         output_unet_buffer.append(temp)

    #     self.unet.set_input(input_unet_buffer)   # set shape, allocate
    #     self.unet.set_output(output_unet_buffer)  # 使用 内部开辟好的cudaMemcpy
    #     self.unet.set_Bindding()

    #     self.control.context.execute_async_v3(self.control.stream)
    #     self.unet.context.execute_async_v3(self.control.stream)
    #     cudart.cudaStreamSynchronize(self.control.stream)

    #     model_t = output_unet_buffer[0][0]
    #     model_uncond = output_unet_buffer[0][1]
    #     model_output = model_uncond + 9 * (model_t - model_uncond)

    #     return model_output

    def __call__(self, x, hint, timesteps, context, **kwargs):
        device = x.device

        timesteps = timesteps.int()
        input_buffer = []
        input_buffer.append(x)
        # memcpy_tensor_to_dev([x,x], self.control.inputs[0]["allocation"])
        input_buffer.append(hint)
        # memcpy_tensor_to_dev(hint, self.control.inputs[1]["allocation"])
        input_buffer.append(timesteps)
        # memcpy_tensor_to_dev([timesteps, timesteps], self.control.inputs[2]["allocation"])
        input_buffer.append(context)
        # memcpy_tensor_to_dev(context, self.control.inputs[3]["allocation"])

        self.control.set_input(input_buffer)   # 使用 内部开辟好的cudaMemcpy
        # self.control.set_output(self.output_buffer)  # 使用 内部开辟好的cudaMemcpy
        self.control.set_Bindding()

        input_unet_buffer = []
        input_unet_buffer.append(self.control.inputs[0]["allocation"])
        input_unet_buffer.append(self.control.inputs[2]["allocation"])
        input_unet_buffer.append(self.control.inputs[3]["allocation"])
        input_unet_buffer.extend(self.control.allocations[self.control.nInput:self.control.nIO])

        # current_batch = x.shape[0]
        current_batch = 2
        output_unet_buffer = []
        for shape, dtype in self.unet.output_spec():
            shape[0] = current_batch
            temp = torch.zeros(shape, dtype=dtype).float().to(device)
            output_unet_buffer.append(temp)

        self.unet.set_input(input_unet_buffer)   # set shape, allocate
        self.unet.set_output(output_unet_buffer)  # 使用 内部开辟好的cudaMemcpy
        self.unet.set_Bindding()

        self.control.context.execute_async_v3(self.control.stream)
        self.unet.context.execute_async_v3(self.control.stream)
        cudart.cudaStreamSynchronize(self.control.stream)

        return output_unet_buffer[0]


class Decoder_TRT(trtInfer):
    def __init__(self, plan_path):
        super().__init__(plan_path)

    def __call__(self, z):
        device = z.device

        input_buffer = []
        input_buffer.append(z)
        current_batch = z.shape[0]
        output_buffer = []
        for shape, dtype in self.output_spec():
            shape[0] = current_batch
            output_buffer.append(torch.zeros(shape, dtype=dtype).float().to(device))

        self.set_input(input_buffer)  # set shape, allocate
        self.set_output(output_buffer)
        self.set_Bindding()
        self.context.execute_async_v3(self.stream)
        cudart.cudaStreamSynchronize(self.stream)

        return output_buffer[0]


class ClipModelOutputs:
    def __init__(self, last_hidden_state):
        self.last_hidden_state = last_hidden_state


class CL_TRT(trtInfer):
    def __init__(self, plan_path):
        super().__init__(plan_path)

    def __call__(self, input_ids, **kwargs):
        device = input_ids.device
        input_ids = input_ids.int()

        input_buffer = []
        input_buffer.append(input_ids)
        # intput_id = x.cpu().numpy()
        # common.memcpy_host_to_device(self.inputs[0]["allocation"], intput_id)

        current_batch = input_ids.shape[0]
        output_buffer = []
        for shape, dtype in self.output_spec():
            shape[0] = current_batch
            output_buffer.append(torch.zeros(shape, dtype=dtype).float().to(device))

        self.set_input(input_buffer)  # set shape, allocate
        self.set_output(output_buffer)
        self.set_Bindding()
        self.context.execute_async_v3(self.stream)
        cudart.cudaStreamSynchronize(self.stream)

        # text_embedding = np.zeros((1, 77, 768), dtype=np.float32)
        # pooler_output = np.zeros((1, 768), dtype=np.float32)
        # common.memcpy_device_to_host(text_embedding, self.outputs[0]["allocation"])
        # common.memcpy_device_to_host(pooler_output, self.outputs[1]["allocation"])
        # print(text_embedding)
        # print(pooler_output)

        return ClipModelOutputs(*output_buffer)
        # return None
        
        
class EXP_TRT(trtInfer):
    def __init__(self, plan_path, batch_size):
        super().__init__(plan_path, batch_size)

    def __call__(self, input_datas):
        self.set_input(input_datas)
        self.set_Bindding()
        self.context.execute_async_v3(self.stream)
        cudart.cudaStreamSynchronize(self.stream)
        return 0


if __name__ == "__main__":
    set_random_seed(2)
    for batch_size in [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048]:
            
        input_data_json_path = f'../new_models/model_1/dataset/input_tensor_datas_{batch_size}.json' 
        with open(input_data_json_path, 'r') as f:
            input_datas = json.load(f)
        input_datas = [value for value in input_datas.values()]
        device = torch.device("cuda:0")
        model_path = f"../new_models/model_1/trt/model-static-batch-size-{batch_size}.trt"
        dm_trt = EXP_TRT(model_path, batch_size)
        specs = dm_trt.input_spec()
        specs = [spec[-1] for spec in specs]
        input_datas = [torch.tensor(value, dtype=spec).to(device) for value, spec in zip(input_datas, specs) ]
        
        times = time.time()
        for i in range(1100):
            if i < 100:
                times = time.time()
            dm_trt(input_datas)
        print(f"*******batch_size: {batch_size} *******QPS: {1000 / (time.time() - times) * batch_size}")
        time.sleep(10)