forked from TejasBob/TensorRT-5_Inference_Engine_Python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
infer_lenet.py
70 lines (39 loc) · 1.67 KB
/
infer_lenet.py
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
import tensorflow as tf
import numpy as np
import tensorrt as trt
import pycuda.driver as cuda
import pycuda.autoinit
MNIST_DATASETS = tf.contrib.learn.datasets.load_dataset("mnist")
img, label = MNIST_DATASETS.test.next_batch(1)
img = img[0]
img = img.astype(np.float32)
label = label[0]
model_file = "model_data/mnist.uff"
TRT_LOGGER = trt.Logger(trt.Logger.WARNING)
builder = trt.Builder(TRT_LOGGER)
network = builder.create_network()
with trt.UffParser() as parser:
parser.register_input("Placeholder", (1, 28, 28))
parser.register_output("fc2/Softmax")
parser.parse(model_file, network)
builder.max_batch_size = 1
builder.max_workspace_size = 1 << 10
# h_input = cuda.pagelocked_empty(engine.get_binding_shape(0).volume(), dtype=np.float32)
# h_output = cuda.pagelocked_empty(engine.get_binding_shape(1).volume(), dtype=np.float32)
# d_input = cuda.mem_alloc(h_input.nbytes)
# d_output = cuda.mem_alloc(h_output.nbytes)
with builder.build_cuda_engine(network) as engine:
output = np.empty(10, dtype = np.float32)
# Alocate device memory
d_input = cuda.mem_alloc(1 * img.nbytes)
d_output = cuda.mem_alloc(1 * output.nbytes)
bindings=[int(d_input), int(d_output)]
stream = cuda.Stream()
with engine.create_execution_context() as context:
cuda.memcpy_htod_async(d_input, img, stream)
context.execute_async(bindings = bindings, stream_handle=stream.handle)
cuda.memcpy_dtoh_async(output, d_output, stream)
stream.synchronize()
print("true label : ", label)
print(np.argmax(output))
print(output)