hacnho commited on
Commit
ba209ed
·
verified ·
1 Parent(s): 038557a

Upload verify_remote_poc.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. verify_remote_poc.py +187 -0
verify_remote_poc.py ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ from __future__ import annotations
3
+
4
+ import ctypes
5
+ import hashlib
6
+ import json
7
+ import os
8
+ import shutil
9
+ import sys
10
+ import tempfile
11
+ import urllib.request
12
+ from pathlib import Path
13
+
14
+
15
+ BASE = "https://huggingface.co/hacnho/tensorrt-detectionlayer-suppression-poc/resolve/main"
16
+ FILES = {
17
+ "control": "control.engine",
18
+ "neg_keepTopK": "neg_keepTopK.engine",
19
+ }
20
+ TENSORRT_PYTHON = Path("/home/hacnho/Projects/research/targets/huntr/work/tensorrt-lab-11_1/.venv/bin/python")
21
+
22
+
23
+ def ensure_tensorrt_python() -> None:
24
+ try:
25
+ import tensorrt # noqa: F401
26
+
27
+ return
28
+ except ModuleNotFoundError:
29
+ current = Path(sys.executable)
30
+ if TENSORRT_PYTHON.exists() and current != TENSORRT_PYTHON:
31
+ os.execv(str(TENSORRT_PYTHON), [str(TENSORRT_PYTHON), __file__, *sys.argv[1:]])
32
+ raise
33
+
34
+
35
+ def sha256_file(path: Path) -> str:
36
+ h = hashlib.sha256()
37
+ with path.open("rb") as f:
38
+ while True:
39
+ chunk = f.read(1024 * 1024)
40
+ if not chunk:
41
+ break
42
+ h.update(chunk)
43
+ return h.hexdigest()
44
+
45
+
46
+ def load_cudart():
47
+ cudart = ctypes.CDLL("libcudart.so")
48
+ cuda_malloc = cudart.cudaMalloc
49
+ cuda_malloc.argtypes = [ctypes.POINTER(ctypes.c_void_p), ctypes.c_size_t]
50
+ cuda_malloc.restype = ctypes.c_int
51
+ cuda_free = cudart.cudaFree
52
+ cuda_free.argtypes = [ctypes.c_void_p]
53
+ cuda_free.restype = ctypes.c_int
54
+ cuda_memcpy = cudart.cudaMemcpy
55
+ cuda_memcpy.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_size_t, ctypes.c_int]
56
+ cuda_memcpy.restype = ctypes.c_int
57
+ cuda_memset = cudart.cudaMemset
58
+ cuda_memset.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_size_t]
59
+ cuda_memset.restype = ctypes.c_int
60
+ return {
61
+ "malloc": cuda_malloc,
62
+ "free": cuda_free,
63
+ "memcpy": cuda_memcpy,
64
+ "memset": cuda_memset,
65
+ "h2d": 1,
66
+ "d2h": 2,
67
+ }
68
+
69
+
70
+ def upload_floats(cuda: dict, ptr: ctypes.c_void_p, values: list[float]) -> None:
71
+ arr = (ctypes.c_float * len(values))(*values)
72
+ rc = cuda["memcpy"](ptr, ctypes.cast(arr, ctypes.c_void_p), ctypes.sizeof(arr), cuda["h2d"])
73
+ if rc != 0:
74
+ raise RuntimeError(f"cudaMemcpy H2D failed rc={rc}")
75
+
76
+
77
+ def presets() -> dict[str, dict[str, list[float]]]:
78
+ return {
79
+ "all_zero": {
80
+ "bbox": [0.0] * 8,
81
+ "cls": [0.0, 0.0],
82
+ "anchors": [0.0] * 4,
83
+ },
84
+ "positive_cls": {
85
+ "bbox": [0.1, 0.1, 0.2, 0.2, 0.0, 0.0, 0.0, 0.0],
86
+ "cls": [0.05, 0.95],
87
+ "anchors": [0.5, 0.5, 1.0, 1.0],
88
+ },
89
+ "neg_cls": {
90
+ "bbox": [0.1, 0.1, 0.2, 0.2, 0.0, 0.0, 0.0, 0.0],
91
+ "cls": [-0.5, -0.1],
92
+ "anchors": [0.5, 0.5, 1.0, 1.0],
93
+ },
94
+ "mixed_bbox": {
95
+ "bbox": [1.0, -1.0, 2.0, -2.0, 0.5, 0.5, -0.5, -0.5],
96
+ "cls": [0.2, 0.7],
97
+ "anchors": [0.1, 0.2, 0.3, 0.4],
98
+ },
99
+ "foreground_strong": {
100
+ "bbox": [0.2, 0.2, 0.0, 0.0, -0.2, -0.2, 0.1, 0.1],
101
+ "cls": [0.01, 0.99],
102
+ "anchors": [0.0, 0.0, 1.0, 1.0],
103
+ },
104
+ }
105
+
106
+
107
+ def run_engine(engine_path: Path) -> dict:
108
+ import tensorrt as trt
109
+
110
+ cuda = load_cudart()
111
+ logger = trt.Logger(trt.Logger.ERROR)
112
+ trt.init_libnvinfer_plugins(logger, "")
113
+ runtime = trt.Runtime(logger)
114
+ blob = engine_path.read_bytes()
115
+ engine = runtime.deserialize_cuda_engine(blob)
116
+
117
+ result = {
118
+ "engine_path": str(engine_path),
119
+ "engine_sha256": sha256_file(engine_path),
120
+ "presets": {},
121
+ }
122
+ for preset_name, preset in presets().items():
123
+ ctx = engine.create_execution_context()
124
+ ptrs: dict[str, tuple[ctypes.c_void_p, int]] = {}
125
+ try:
126
+ for i in range(engine.num_io_tensors):
127
+ tensor_name = engine.get_tensor_name(i)
128
+ shape = engine.get_tensor_shape(tensor_name)
129
+ count = 1
130
+ for dim in shape:
131
+ count *= dim
132
+ nbytes = count * 4
133
+ ptr = ctypes.c_void_p()
134
+ assert cuda["malloc"](ctypes.byref(ptr), nbytes) == 0
135
+ assert cuda["memset"](ptr, 0, nbytes) == 0
136
+ assert ctx.set_tensor_address(tensor_name, ptr.value)
137
+ ptrs[tensor_name] = (ptr, nbytes)
138
+ if tensor_name in preset:
139
+ upload_floats(cuda, ptr, preset[tensor_name])
140
+ infer = ctx.infer_shapes()
141
+ exec_ok = ctx.execute_async_v3(0)
142
+ output_name = engine.get_tensor_name(engine.num_io_tensors - 1)
143
+ _, out_nbytes = ptrs[output_name]
144
+ float_count = min(max(out_nbytes // 4, 1), 24)
145
+ host = (ctypes.c_float * float_count)()
146
+ copy_rc = cuda["memcpy"](ctypes.byref(host), ptrs[output_name][0], float_count * 4, cuda["d2h"])
147
+ result["presets"][preset_name] = {
148
+ "infer_shapes": infer,
149
+ "execute_ok": bool(exec_ok),
150
+ "output_copy_rc": copy_rc,
151
+ "output_values": [float(x) for x in host],
152
+ }
153
+ finally:
154
+ for ptr, _ in ptrs.values():
155
+ if ptr.value:
156
+ cuda["free"](ptr)
157
+ return result
158
+
159
+
160
+ def main() -> int:
161
+ ensure_tensorrt_python()
162
+ td = Path(tempfile.mkdtemp(prefix="hf_trt_detectionlayer_"))
163
+ try:
164
+ local = {}
165
+ for label, name in FILES.items():
166
+ dst = td / name
167
+ urllib.request.urlretrieve(f"{BASE}/{name}", dst)
168
+ local[label] = dst
169
+ control = run_engine(local["control"])
170
+ malicious = run_engine(local["neg_keepTopK"])
171
+ payload = {
172
+ "base": BASE,
173
+ "control": control,
174
+ "neg_keepTopK": malicious,
175
+ "semantic_suppression_observed": (
176
+ control["presets"]["positive_cls"]["output_values"] != malicious["presets"]["positive_cls"]["output_values"]
177
+ and control["presets"]["mixed_bbox"]["output_values"] != malicious["presets"]["mixed_bbox"]["output_values"]
178
+ ),
179
+ }
180
+ print(json.dumps(payload, indent=2, ensure_ascii=False))
181
+ return 0
182
+ finally:
183
+ shutil.rmtree(td, ignore_errors=True)
184
+
185
+
186
+ if __name__ == "__main__":
187
+ raise SystemExit(main())