Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

relocate.py 12 KB

You have to be logged in to leave a comment. Sign In
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
  1. """Helper script to package wheels and relocate binaries."""
  2. import glob
  3. import hashlib
  4. # Standard library imports
  5. import os
  6. import os.path as osp
  7. import platform
  8. import shutil
  9. import subprocess
  10. import sys
  11. import zipfile
  12. from base64 import urlsafe_b64encode
  13. # Third party imports
  14. if sys.platform == "linux":
  15. try:
  16. from auditwheel.lddtree import lddtree
  17. except ImportError:
  18. from auditwheel import lddtree
  19. ALLOWLIST = {
  20. "libgcc_s.so.1",
  21. "libstdc++.so.6",
  22. "libm.so.6",
  23. "libdl.so.2",
  24. "librt.so.1",
  25. "libc.so.6",
  26. "libnsl.so.1",
  27. "libutil.so.1",
  28. "libpthread.so.0",
  29. "libresolv.so.2",
  30. "libX11.so.6",
  31. "libXext.so.6",
  32. "libXrender.so.1",
  33. "libICE.so.6",
  34. "libSM.so.6",
  35. "libGL.so.1",
  36. "libgobject-2.0.so.0",
  37. "libgthread-2.0.so.0",
  38. "libglib-2.0.so.0",
  39. "ld-linux-x86-64.so.2",
  40. "ld-2.17.so",
  41. }
  42. WINDOWS_ALLOWLIST = {
  43. "MSVCP140.dll",
  44. "KERNEL32.dll",
  45. "VCRUNTIME140_1.dll",
  46. "VCRUNTIME140.dll",
  47. "api-ms-win-crt-heap-l1-1-0.dll",
  48. "api-ms-win-crt-runtime-l1-1-0.dll",
  49. "api-ms-win-crt-stdio-l1-1-0.dll",
  50. "api-ms-win-crt-filesystem-l1-1-0.dll",
  51. "api-ms-win-crt-string-l1-1-0.dll",
  52. "api-ms-win-crt-environment-l1-1-0.dll",
  53. "api-ms-win-crt-math-l1-1-0.dll",
  54. "api-ms-win-crt-convert-l1-1-0.dll",
  55. }
  56. HERE = osp.dirname(osp.abspath(__file__))
  57. PACKAGE_ROOT = osp.dirname(osp.dirname(HERE))
  58. PLATFORM_ARCH = platform.machine()
  59. PYTHON_VERSION = sys.version_info
  60. def rehash(path, blocksize=1 << 20):
  61. """Return (hash, length) for path using hashlib.sha256()"""
  62. h = hashlib.sha256()
  63. length = 0
  64. with open(path, "rb") as f:
  65. while block := f.read(blocksize):
  66. length += len(block)
  67. h.update(block)
  68. digest = "sha256=" + urlsafe_b64encode(h.digest()).decode("latin1").rstrip("=")
  69. # unicode/str python2 issues
  70. return (digest, str(length)) # type: ignore
  71. def unzip_file(file, dest):
  72. """Decompress zip `file` into directory `dest`."""
  73. with zipfile.ZipFile(file, "r") as zip_ref:
  74. zip_ref.extractall(dest)
  75. def is_program_installed(basename):
  76. """
  77. Return program absolute path if installed in PATH.
  78. Otherwise, return None
  79. On macOS systems, a .app is considered installed if
  80. it exists.
  81. """
  82. if sys.platform == "darwin" and basename.endswith(".app") and osp.exists(basename):
  83. return basename
  84. for path in os.environ["PATH"].split(os.pathsep):
  85. abspath = osp.join(path, basename)
  86. if osp.isfile(abspath):
  87. return abspath
  88. def find_program(basename):
  89. """
  90. Find program in PATH and return absolute path
  91. Try adding .exe or .bat to basename on Windows platforms
  92. (return None if not found)
  93. """
  94. names = [basename]
  95. if os.name == "nt":
  96. # Windows platforms
  97. extensions = (".exe", ".bat", ".cmd", ".dll")
  98. if not basename.endswith(extensions):
  99. names = [basename + ext for ext in extensions] + [basename]
  100. for name in names:
  101. path = is_program_installed(name)
  102. if path:
  103. return path
  104. def patch_new_path(library_path, new_dir):
  105. library = osp.basename(library_path)
  106. name, *rest = library.split(".")
  107. rest = ".".join(rest)
  108. hash_id = hashlib.sha256(library_path.encode("utf-8")).hexdigest()[:8]
  109. new_name = ".".join([name, hash_id, rest])
  110. return osp.join(new_dir, new_name)
  111. def find_dll_dependencies(dumpbin, binary):
  112. out = subprocess.run([dumpbin, "/dependents", binary], stdout=subprocess.PIPE)
  113. out = out.stdout.strip().decode("utf-8")
  114. start_index = out.find("dependencies:") + len("dependencies:")
  115. end_index = out.find("Summary")
  116. dlls = out[start_index:end_index].strip()
  117. dlls = dlls.split(os.linesep)
  118. dlls = [dll.strip() for dll in dlls]
  119. return dlls
  120. def relocate_elf_library(patchelf, output_dir, output_library, binary):
  121. """
  122. Relocate an ELF shared library to be packaged on a wheel.
  123. Given a shared library, find the transitive closure of its dependencies,
  124. rename and copy them into the wheel while updating their respective rpaths.
  125. """
  126. print(f"Relocating {binary}")
  127. binary_path = osp.join(output_library, binary)
  128. ld_tree = lddtree(binary_path)
  129. tree_libs = ld_tree["libs"]
  130. binary_queue = [(n, binary) for n in ld_tree["needed"]]
  131. binary_paths = {binary: binary_path}
  132. binary_dependencies = {}
  133. while binary_queue != []:
  134. library, parent = binary_queue.pop(0)
  135. library_info = tree_libs[library]
  136. print(library)
  137. if library_info["path"] is None:
  138. print(f"Omitting {library}")
  139. continue
  140. if library in ALLOWLIST:
  141. # Omit glibc/gcc/system libraries
  142. print(f"Omitting {library}")
  143. continue
  144. parent_dependencies = binary_dependencies.get(parent, [])
  145. parent_dependencies.append(library)
  146. binary_dependencies[parent] = parent_dependencies
  147. if library in binary_paths:
  148. continue
  149. binary_paths[library] = library_info["path"]
  150. binary_queue += [(n, library) for n in library_info["needed"]]
  151. print("Copying dependencies to wheel directory")
  152. new_libraries_path = osp.join(output_dir, "torchvision.libs")
  153. os.makedirs(new_libraries_path, exist_ok=True)
  154. new_names = {binary: binary_path}
  155. for library in binary_paths:
  156. if library != binary:
  157. library_path = binary_paths[library]
  158. new_library_path = patch_new_path(library_path, new_libraries_path)
  159. print(f"{library} -> {new_library_path}")
  160. shutil.copyfile(library_path, new_library_path)
  161. new_names[library] = new_library_path
  162. print("Updating dependency names by new files")
  163. for library in binary_paths:
  164. if library != binary:
  165. if library not in binary_dependencies:
  166. continue
  167. library_dependencies = binary_dependencies[library]
  168. new_library_name = new_names[library]
  169. for dep in library_dependencies:
  170. new_dep = osp.basename(new_names[dep])
  171. print(f"{library}: {dep} -> {new_dep}")
  172. subprocess.check_output(
  173. [patchelf, "--replace-needed", dep, new_dep, new_library_name], cwd=new_libraries_path
  174. )
  175. print("Updating library rpath")
  176. subprocess.check_output([patchelf, "--set-rpath", "$ORIGIN", new_library_name], cwd=new_libraries_path)
  177. subprocess.check_output([patchelf, "--print-rpath", new_library_name], cwd=new_libraries_path)
  178. print("Update library dependencies")
  179. library_dependencies = binary_dependencies[binary]
  180. for dep in library_dependencies:
  181. new_dep = osp.basename(new_names[dep])
  182. print(f"{binary}: {dep} -> {new_dep}")
  183. subprocess.check_output([patchelf, "--replace-needed", dep, new_dep, binary], cwd=output_library)
  184. print("Update library rpath")
  185. subprocess.check_output(
  186. [patchelf, "--set-rpath", "$ORIGIN:$ORIGIN/../torchvision.libs", binary_path], cwd=output_library
  187. )
  188. def relocate_dll_library(dumpbin, output_dir, output_library, binary):
  189. """
  190. Relocate a DLL/PE shared library to be packaged on a wheel.
  191. Given a shared library, find the transitive closure of its dependencies,
  192. rename and copy them into the wheel.
  193. """
  194. print(f"Relocating {binary}")
  195. binary_path = osp.join(output_library, binary)
  196. library_dlls = find_dll_dependencies(dumpbin, binary_path)
  197. binary_queue = [(dll, binary) for dll in library_dlls]
  198. binary_paths = {binary: binary_path}
  199. binary_dependencies = {}
  200. while binary_queue != []:
  201. library, parent = binary_queue.pop(0)
  202. if library in WINDOWS_ALLOWLIST or library.startswith("api-ms-win"):
  203. print(f"Omitting {library}")
  204. continue
  205. library_path = find_program(library)
  206. if library_path is None:
  207. print(f"{library} not found")
  208. continue
  209. if osp.basename(osp.dirname(library_path)) == "system32":
  210. continue
  211. print(f"{library}: {library_path}")
  212. parent_dependencies = binary_dependencies.get(parent, [])
  213. parent_dependencies.append(library)
  214. binary_dependencies[parent] = parent_dependencies
  215. if library in binary_paths:
  216. continue
  217. binary_paths[library] = library_path
  218. downstream_dlls = find_dll_dependencies(dumpbin, library_path)
  219. binary_queue += [(n, library) for n in downstream_dlls]
  220. print("Copying dependencies to wheel directory")
  221. package_dir = osp.join(output_dir, "torchvision")
  222. for library in binary_paths:
  223. if library != binary:
  224. library_path = binary_paths[library]
  225. new_library_path = osp.join(package_dir, library)
  226. print(f"{library} -> {new_library_path}")
  227. shutil.copyfile(library_path, new_library_path)
  228. def compress_wheel(output_dir, wheel, wheel_dir, wheel_name):
  229. """Create RECORD file and compress wheel distribution."""
  230. print("Update RECORD file in wheel")
  231. dist_info = glob.glob(osp.join(output_dir, "*.dist-info"))[0]
  232. record_file = osp.join(dist_info, "RECORD")
  233. with open(record_file, "w") as f:
  234. for root, _, files in os.walk(output_dir):
  235. for this_file in files:
  236. full_file = osp.join(root, this_file)
  237. rel_file = osp.relpath(full_file, output_dir)
  238. if full_file == record_file:
  239. f.write(f"{rel_file},,\n")
  240. else:
  241. digest, size = rehash(full_file)
  242. f.write(f"{rel_file},{digest},{size}\n")
  243. print("Compressing wheel")
  244. base_wheel_name = osp.join(wheel_dir, wheel_name)
  245. shutil.make_archive(base_wheel_name, "zip", output_dir)
  246. os.remove(wheel)
  247. shutil.move(f"{base_wheel_name}.zip", wheel)
  248. shutil.rmtree(output_dir)
  249. def patch_linux():
  250. # Get patchelf location
  251. patchelf = find_program("patchelf")
  252. if patchelf is None:
  253. raise FileNotFoundError("Patchelf was not found in the system, please make sure that is available on the PATH.")
  254. # Find wheel
  255. print("Finding wheels...")
  256. wheels = glob.glob(osp.join(PACKAGE_ROOT, "dist", "*.whl"))
  257. output_dir = osp.join(PACKAGE_ROOT, "dist", ".wheel-process")
  258. image_binary = "image.so"
  259. video_binary = "video_reader.so"
  260. torchvision_binaries = [image_binary, video_binary]
  261. for wheel in wheels:
  262. if osp.exists(output_dir):
  263. shutil.rmtree(output_dir)
  264. os.makedirs(output_dir)
  265. print("Unzipping wheel...")
  266. wheel_file = osp.basename(wheel)
  267. wheel_dir = osp.dirname(wheel)
  268. print(f"{wheel_file}")
  269. wheel_name, _ = osp.splitext(wheel_file)
  270. unzip_file(wheel, output_dir)
  271. print("Finding ELF dependencies...")
  272. output_library = osp.join(output_dir, "torchvision")
  273. for binary in torchvision_binaries:
  274. if osp.exists(osp.join(output_library, binary)):
  275. relocate_elf_library(patchelf, output_dir, output_library, binary)
  276. compress_wheel(output_dir, wheel, wheel_dir, wheel_name)
  277. def patch_win():
  278. # Get dumpbin location
  279. dumpbin = find_program("dumpbin")
  280. if dumpbin is None:
  281. raise FileNotFoundError("Dumpbin was not found in the system, please make sure that is available on the PATH.")
  282. # Find wheel
  283. print("Finding wheels...")
  284. wheels = glob.glob(osp.join(PACKAGE_ROOT, "dist", "*.whl"))
  285. output_dir = osp.join(PACKAGE_ROOT, "dist", ".wheel-process")
  286. image_binary = "image.pyd"
  287. video_binary = "video_reader.pyd"
  288. torchvision_binaries = [image_binary, video_binary]
  289. for wheel in wheels:
  290. if osp.exists(output_dir):
  291. shutil.rmtree(output_dir)
  292. os.makedirs(output_dir)
  293. print("Unzipping wheel...")
  294. wheel_file = osp.basename(wheel)
  295. wheel_dir = osp.dirname(wheel)
  296. print(f"{wheel_file}")
  297. wheel_name, _ = osp.splitext(wheel_file)
  298. unzip_file(wheel, output_dir)
  299. print("Finding DLL/PE dependencies...")
  300. output_library = osp.join(output_dir, "torchvision")
  301. for binary in torchvision_binaries:
  302. if osp.exists(osp.join(output_library, binary)):
  303. relocate_dll_library(dumpbin, output_dir, output_library, binary)
  304. compress_wheel(output_dir, wheel, wheel_dir, wheel_name)
  305. if __name__ == "__main__":
  306. if sys.platform == "linux":
  307. patch_linux()
  308. elif sys.platform == "win32":
  309. patch_win()
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...