hacnho commited on
Commit
310fb5f
·
verified ·
1 Parent(s): dcbf66b

Upload verify_tftrt_implicit_remote.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. verify_tftrt_implicit_remote.py +186 -0
verify_tftrt_implicit_remote.py ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import ctypes
6
+ import hashlib
7
+ import json
8
+ import shutil
9
+ import tempfile
10
+ import urllib.request
11
+ from pathlib import Path
12
+
13
+ import tensorrt as trt
14
+
15
+
16
+ BASE = "https://huggingface.co/hacnho/tensorrt-efficientnms-tftrt-implicit-bypass-poc/resolve/main"
17
+ FILES = {
18
+ "control": "control.engine",
19
+ "neg_score": "neg_score.engine",
20
+ }
21
+
22
+
23
+ def sha256_file(path: Path) -> str:
24
+ h = hashlib.sha256()
25
+ with path.open("rb") as f:
26
+ while True:
27
+ chunk = f.read(1024 * 1024)
28
+ if not chunk:
29
+ break
30
+ h.update(chunk)
31
+ return h.hexdigest()
32
+
33
+
34
+ def load_cudart():
35
+ cudart = ctypes.CDLL("libcudart.so")
36
+ cuda_malloc = cudart.cudaMalloc
37
+ cuda_malloc.argtypes = [ctypes.POINTER(ctypes.c_void_p), ctypes.c_size_t]
38
+ cuda_malloc.restype = ctypes.c_int
39
+ cuda_free = cudart.cudaFree
40
+ cuda_free.argtypes = [ctypes.c_void_p]
41
+ cuda_free.restype = ctypes.c_int
42
+ cuda_memcpy = cudart.cudaMemcpy
43
+ cuda_memcpy.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_size_t, ctypes.c_int]
44
+ cuda_memcpy.restype = ctypes.c_int
45
+ cuda_memset = cudart.cudaMemset
46
+ cuda_memset.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_size_t]
47
+ cuda_memset.restype = ctypes.c_int
48
+ return {
49
+ "malloc": cuda_malloc,
50
+ "free": cuda_free,
51
+ "memcpy": cuda_memcpy,
52
+ "memset": cuda_memset,
53
+ "h2d": 1,
54
+ "d2h": 2,
55
+ }
56
+
57
+
58
+ def upload_floats(cuda: dict, ptr: ctypes.c_void_p, values: list[float]) -> None:
59
+ arr = (ctypes.c_float * len(values))(*values)
60
+ rc = cuda["memcpy"](ptr, ctypes.cast(arr, ctypes.c_void_p), ctypes.sizeof(arr), cuda["h2d"])
61
+ if rc != 0:
62
+ raise RuntimeError(f"cudaMemcpy H2D failed rc={rc}")
63
+
64
+
65
+ def presets():
66
+ return {
67
+ "all_negative": {
68
+ "boxes": [0.0, 0.0, 1.0, 1.0] * 4,
69
+ "scores": [-0.2, -0.2, -0.2, -0.2],
70
+ },
71
+ "mixed_scores": {
72
+ "boxes": [0.0, 0.0, 1.0, 1.0] * 4,
73
+ "scores": [0.6, 0.4, 0.2, -0.1],
74
+ },
75
+ "all_zero": {
76
+ "boxes": [0.0, 0.0, 1.0, 1.0] * 4,
77
+ "scores": [0.0, 0.0, 0.0, 0.0],
78
+ },
79
+ }
80
+
81
+
82
+ def run_engine(engine_path: Path) -> dict[str, object]:
83
+ cuda = load_cudart()
84
+ logger = trt.Logger(trt.Logger.ERROR)
85
+ trt.init_libnvinfer_plugins(logger, "")
86
+ runtime = trt.Runtime(logger)
87
+ blob = engine_path.read_bytes()
88
+ engine = runtime.deserialize_cuda_engine(blob)
89
+
90
+ result: dict[str, object] = {
91
+ "engine_path": str(engine_path),
92
+ "engine_sha256": sha256_file(engine_path),
93
+ "presets": {},
94
+ }
95
+
96
+ for preset_name, preset in presets().items():
97
+ ctx = engine.create_execution_context()
98
+ ptrs: dict[str, tuple[ctypes.c_void_p, int, str]] = {}
99
+ try:
100
+ for i in range(engine.num_io_tensors):
101
+ tensor_name = engine.get_tensor_name(i)
102
+ shape = engine.get_tensor_shape(tensor_name)
103
+ count = 1
104
+ for dim in shape:
105
+ count *= dim
106
+ dtype = str(engine.get_tensor_dtype(tensor_name))
107
+ nbytes = count * 4
108
+ ptr = ctypes.c_void_p()
109
+ assert cuda["malloc"](ctypes.byref(ptr), nbytes) == 0
110
+ assert cuda["memset"](ptr, 0, nbytes) == 0
111
+ assert ctx.set_tensor_address(tensor_name, ptr.value)
112
+ ptrs[tensor_name] = (ptr, nbytes, dtype)
113
+ if tensor_name in preset:
114
+ upload_floats(cuda, ptr, preset[tensor_name])
115
+
116
+ infer = ctx.infer_shapes()
117
+ exec_ok = ctx.execute_async_v3(0)
118
+ outputs = {}
119
+ output_order = []
120
+ for i in range(engine.num_io_tensors):
121
+ tensor_name = engine.get_tensor_name(i)
122
+ if "OUTPUT" not in str(engine.get_tensor_mode(tensor_name)):
123
+ continue
124
+ output_order.append(tensor_name)
125
+ ptr, nbytes, dtype = ptrs[tensor_name]
126
+ if "INT32" in dtype:
127
+ host = (ctypes.c_int32 * min(max(nbytes // 4, 1), 16))()
128
+ rc = cuda["memcpy"](ctypes.byref(host), ptr, min(nbytes, 64), cuda["d2h"])
129
+ outputs[tensor_name] = {"copy_rc": rc, "values": list(host)}
130
+ else:
131
+ host = (ctypes.c_float * min(max(nbytes // 4, 1), 16))()
132
+ rc = cuda["memcpy"](ctypes.byref(host), ptr, min(nbytes, 64), cuda["d2h"])
133
+ outputs[tensor_name] = {"copy_rc": rc, "values": [float(x) for x in host]}
134
+
135
+ num_detections = None
136
+ score_values = []
137
+ if output_order:
138
+ first = outputs.get(output_order[0], {})
139
+ if first.get("values"):
140
+ num_detections = first["values"]
141
+ if len(output_order) >= 3:
142
+ score_values = outputs.get(output_order[2], {}).get("values", [])
143
+ result["presets"][preset_name] = {
144
+ "infer_shapes": infer,
145
+ "execute_ok": exec_ok,
146
+ "num_detections": num_detections,
147
+ "score_values": score_values,
148
+ "outputs": outputs,
149
+ }
150
+ finally:
151
+ for ptr, _, _ in ptrs.values():
152
+ if ptr.value:
153
+ cuda["free"](ptr)
154
+ return result
155
+
156
+
157
+ def main() -> int:
158
+ ap = argparse.ArgumentParser()
159
+ ap.add_argument("--local-dir", type=Path, help="reuse files from a local directory instead of downloading from HF")
160
+ args = ap.parse_args()
161
+
162
+ td = None
163
+ try:
164
+ if args.local_dir:
165
+ local = {label: args.local_dir / name for label, name in FILES.items()}
166
+ else:
167
+ td = Path(tempfile.mkdtemp(prefix="trt_efficientnms_tftrt_implicit_remote_"))
168
+ local = {}
169
+ for label, name in FILES.items():
170
+ dst = td / name
171
+ urllib.request.urlretrieve(f"{BASE}/{name}", dst)
172
+ local[label] = dst
173
+
174
+ payload = {
175
+ "control": run_engine(local["control"]),
176
+ "neg_score": run_engine(local["neg_score"]),
177
+ }
178
+ print(json.dumps(payload, indent=2, ensure_ascii=False))
179
+ finally:
180
+ if td is not None:
181
+ shutil.rmtree(td, ignore_errors=True)
182
+ return 0
183
+
184
+
185
+ if __name__ == "__main__":
186
+ raise SystemExit(main())