_freeze.py 9.8 KB

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