_freeze.py 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. """
  2. Freeze Python packages.
  3. Freezing makes it possible to ship arbitrary Python modules as part of a C++
  4. library. The Python source of the module is compiled to bytecode and written
  5. to `.c` files, to be imported by Python's built-in FrozenImporter.
  6. In a normal Python installation, FrozenImporter is only used to bootstrap the
  7. initialization of the import machinery. Python's importers are defined in
  8. Python (see `_bootstrap.py` and `_bootstrap_external.py`) but need to be
  9. retrieved before any importers are available. Freezing the module bytecode
  10. resolves this circular dependency.
  11. This script will freeze the Python standard library. It produces two things:
  12. - Bytecode files: A set of `.c` that define C variables containing Python bytecode.
  13. - Main file: A `main.c` file listing all of these modules in the right form to be
  14. consumed by FrozenImporter.
  15. The library that wishes to these modules make them available to the local
  16. Python instance by extending `PyImport_FrozenModules` appropriately (see
  17. https://docs.python.org/3/c-api/import.html#c.PyImport_FrozenModules).
  18. """
  19. import argparse
  20. import functools
  21. import itertools
  22. import marshal
  23. import os
  24. from dataclasses import dataclass
  25. from pathlib import Path
  26. from typing import List
  27. import types
  28. PATH_MARKER = "<Generated by torch::deploy>"
  29. MAIN_INCLUDES = """#include <Python.h>
  30. """
  31. MAIN_PREFIX_TEMPLATE = """
  32. // Compiled standard library modules. These should be appended to the existing
  33. // `PyImport_FrozenModules` that ships with CPython.
  34. struct _frozen {}[] = {{
  35. """
  36. FAKE_PREFIX = MAIN_PREFIX_TEMPLATE.format("_PyImport_FrozenModules")
  37. MAIN_SUFFIX = """\
  38. {0, 0, 0} /* sentinel */
  39. };
  40. """
  41. # Exclude some standard library modules to:
  42. # 1. Slim down the final frozen lib.
  43. # 2. Remove functionality we don't want to support.
  44. DENY_LIST = [
  45. # Interface to unix databases
  46. "dbm",
  47. # ncurses bindings (terminal interfaces)
  48. "curses",
  49. # Tcl/Tk GUI
  50. "tkinter",
  51. "tkinter",
  52. # Tests for the standard library
  53. "test",
  54. "tests",
  55. "idle_test",
  56. "__phello__.foo.py",
  57. # importlib frozen modules. These are already baked into CPython.
  58. "_bootstrap.py",
  59. "_bootstrap_external.py",
  60. ]
  61. NUM_BYTECODE_FILES = 5
  62. def indent_msg(fn):
  63. @functools.wraps(fn)
  64. def wrapper(*args, **kwargs):
  65. args[0].indent += 1
  66. ret = fn(*args, **kwargs)
  67. args[0].indent -= 1
  68. return ret
  69. return wrapper
  70. @dataclass
  71. class FrozenModule:
  72. # The fully qualified module name, e.g. 'foo.bar.baz'
  73. module_name: str
  74. # The name of the C variable that holds the bytecode, e.g. 'M_foo__bar__baz'
  75. c_name: str
  76. # The size of the C variable. Negative if this module is a package.
  77. size: int
  78. # The frozen bytecode
  79. bytecode: bytes
  80. class Freezer:
  81. def __init__(self, verbose: bool):
  82. self.frozen_modules: List[FrozenModule] = []
  83. self.indent: int = 0
  84. self.verbose: bool = verbose
  85. def msg(self, path: Path, code: str):
  86. if not self.verbose:
  87. return
  88. # P: package dir
  89. # F: python file
  90. # S: skipped (not a package dir)
  91. # X: skipped (deny-listed)
  92. # N: skipped (not a python file)
  93. for i in range(self.indent):
  94. print(" ", end="")
  95. print(f"{code} {path}")
  96. def write_bytecode(self, install_root):
  97. """
  98. Write the `.c` files containing the frozen bytecode. Shard frozen
  99. modules evenly across the files.
  100. """
  101. bytecode_file_names = [
  102. f"bytecode_{i}.c" for i in range(NUM_BYTECODE_FILES)
  103. ]
  104. bytecode_files = [open(os.path.join(install_root, name), "w") for name in bytecode_file_names]
  105. it = itertools.cycle(bytecode_files)
  106. for m in self.frozen_modules:
  107. self.write_frozen(m, next(it))
  108. for f in bytecode_files:
  109. f.close()
  110. def write_main(self, install_root, oss, symbol_name):
  111. """
  112. Write the `main.c` file containing a table enumerating all the
  113. frozen modules.
  114. """
  115. with open(os.path.join(install_root, "main.c"), "w") as outfp:
  116. outfp.write(MAIN_INCLUDES)
  117. for m in self.frozen_modules:
  118. outfp.write(f"extern unsigned char {m.c_name}[];\n")
  119. outfp.write(MAIN_PREFIX_TEMPLATE.format(symbol_name))
  120. for m in self.frozen_modules:
  121. outfp.write(f'\t{{"{m.module_name}", {m.c_name}, {m.size}}},\n')
  122. outfp.write(MAIN_SUFFIX)
  123. if oss:
  124. outfp.write(FAKE_PREFIX)
  125. outfp.write(MAIN_SUFFIX)
  126. def write_frozen(self, m: FrozenModule, outfp):
  127. """
  128. Write a single frozen module's bytecode out to a C variable.
  129. """
  130. outfp.write(f"unsigned char {m.c_name}[] = {{")
  131. for i in range(0, len(m.bytecode), 16):
  132. outfp.write("\n\t")
  133. for c in bytes(m.bytecode[i : i + 16]):
  134. outfp.write("%d," % c)
  135. outfp.write("\n};\n")
  136. def compile_path(self, path: Path, top_package_path: Path):
  137. """Generic entry point for compiling a Path object."""
  138. if path.is_dir():
  139. self.compile_package(path, top_package_path)
  140. else:
  141. self.compile_file(path, top_package_path)
  142. @indent_msg
  143. def compile_package(self, path: Path, top_package_path: Path):
  144. """Compile all the files within a Python package dir."""
  145. assert path.is_dir()
  146. if path.name in DENY_LIST:
  147. self.msg(path, "X")
  148. return
  149. # Python packages are directories that have __init__.py in them.
  150. is_package_dir = any([child.name == "__init__.py" for child in path.iterdir()])
  151. if not is_package_dir:
  152. self.msg(path, "S")
  153. return
  154. self.msg(path, "P")
  155. # Recursively compile all children in this dir
  156. for child in path.iterdir():
  157. self.compile_path(child, top_package_path)
  158. def get_module_qualname(self, file_path: Path, top_package_path: Path) -> List[str]:
  159. # `path` looks like 'Lib/foo/bar/baz.py'
  160. # chop off 'Lib/' to get something that represents a Python module hierarchy.
  161. # e.g. 'foo/bar/baz.py', which maps to 'foo.bar.baz'
  162. normalized_path = file_path.relative_to(top_package_path.parent)
  163. if normalized_path.name == "__init__.py":
  164. # Special handling for `__init__.py`. In this case, this file
  165. # specifies that the containing directory should be treated as a package.
  166. # For 'foo/bar/baz/__init__.py':
  167. # - The module name is 'baz'
  168. module_basename = normalized_path.parent.name
  169. # - The parent is foo.bar (need to shave off the 'baz')
  170. module_parent = normalized_path.parent.parent.parts
  171. else:
  172. module_basename = normalized_path.stem
  173. module_parent = normalized_path.parent.parts
  174. return list(module_parent) + [module_basename]
  175. def compile_string(self, file_content: str) -> types.CodeType:
  176. # instead of passing in the real build time path to 'compile', we
  177. # pass in a marker instead. This prevents the build time path being
  178. # leaked to runtime. That path may not be available at runtime.
  179. # Setting the path to a mark make sure it's a hard error rather
  180. # than a flaky error when inspect module tries to retrieve python source
  181. # code during torchscripting.
  182. path_marker = PATH_MARKER
  183. return compile(file_content, path_marker, "exec")
  184. @indent_msg
  185. def compile_file(self, path: Path, top_package_path: Path):
  186. """
  187. Compile a Python source file to frozen bytecode. Append the result to
  188. `self.frozen_modules`.
  189. """
  190. assert path.is_file()
  191. if path.suffix != ".py":
  192. self.msg(path, "N")
  193. return
  194. if path.name in DENY_LIST:
  195. self.msg(path, "X")
  196. return
  197. self.msg(path, "F")
  198. module_qualname = self.get_module_qualname(path, top_package_path)
  199. module_mangled_name = "__".join(module_qualname)
  200. c_name = "M_" + module_mangled_name
  201. with open(path, "r") as src_file:
  202. co = self.compile_string(src_file.read())
  203. bytecode = marshal.dumps(co)
  204. size = len(bytecode)
  205. if path.name == '__init__.py':
  206. # Python packages are signified by negative size.
  207. size = -size
  208. self.frozen_modules.append(
  209. FrozenModule(".".join(module_qualname), c_name, size, bytecode)
  210. )
  211. if __name__ == "__main__":
  212. parser = argparse.ArgumentParser(description="Compile py source")
  213. parser.add_argument("paths", nargs="*", help="Paths to freeze.")
  214. parser.add_argument("--verbose", action="store_true", help="Print debug logs")
  215. parser.add_argument("--install-dir", "--install_dir", help="Root directory for all output files")
  216. parser.add_argument("--oss", action="store_true", help="If it's OSS build, add a fake _PyImport_FrozenModules")
  217. parser.add_argument(
  218. "--symbol-name",
  219. "--symbol_name",
  220. help="The name of the frozen module array symbol to generate",
  221. default="_PyImport_FrozenModules_torch",
  222. )
  223. args = parser.parse_args()
  224. f = Freezer(args.verbose)
  225. for p in args.paths:
  226. path = Path(p)
  227. if path.is_dir() and not Path.exists(path / '__init__.py'):
  228. # this 'top level path p' is a standard directory containing modules,
  229. # not a module itself
  230. # each 'mod' could be a dir containing __init__.py or .py file
  231. # NB: sorted to make sure this is deterministic
  232. for mod in sorted(path.glob("*")):
  233. f.compile_path(mod, mod)
  234. else:
  235. f.compile_path(path, path)
  236. f.write_bytecode(args.install_dir)
  237. f.write_main(args.install_dir, args.oss, args.symbol_name)