_serialization.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  1. # mypy: allow-untyped-defs
  2. """Serialization.
  3. This module contains functionality for serializing TorchScript modules, notably:
  4. * torch.jit.save
  5. * torch.jit.load
  6. This is not intended to be imported directly; please use the exposed
  7. functionalities in `torch.jit`.
  8. """
  9. import os
  10. import sys
  11. import warnings
  12. import torch
  13. from torch._jit_internal import _get_model_id
  14. from torch._utils_internal import log_torchscript_usage
  15. from torch.jit._recursive import wrap_cpp_module
  16. from torch.serialization import validate_cuda_device
  17. def save(m, f, _extra_files=None) -> None:
  18. r"""
  19. Save an offline version of this module for use in a separate process.
  20. The saved module serializes all of the methods, submodules, parameters, and
  21. attributes of this module. It can be loaded into the C++ API using
  22. ``torch::jit::load(filename)`` or into the Python API with
  23. :func:`torch.jit.load <torch.jit.load>`.
  24. To be able to save a module, it must not make any calls to native Python
  25. functions. This means that all submodules must be subclasses of
  26. :class:`ScriptModule` as well.
  27. .. DANGER::
  28. All modules, no matter their device, are always loaded onto the CPU
  29. during loading. This is different from :func:`torch.load`'s semantics
  30. and may change in the future.
  31. Args:
  32. m: A :class:`ScriptModule` to save.
  33. f: A file-like object (has to implement write and flush) or a string
  34. containing a file name.
  35. _extra_files: Map from filename to contents which will be stored as part of `f`.
  36. .. note::
  37. torch.jit.save attempts to preserve the behavior of some operators
  38. across versions. For example, dividing two integer tensors in
  39. PyTorch 1.5 performed floor division, and if the module
  40. containing that code is saved in PyTorch 1.5 and loaded in PyTorch 1.6
  41. its division behavior will be preserved. The same module saved in
  42. PyTorch 1.6 will fail to load in PyTorch 1.5, however, since the
  43. behavior of division changed in 1.6, and 1.5 does not know how to
  44. replicate the 1.6 behavior.
  45. Example:
  46. .. testcode::
  47. import torch
  48. import io
  49. class MyModule(torch.nn.Module):
  50. def forward(self, x):
  51. return x + 10
  52. m = torch.jit.script(MyModule())
  53. # Save to file
  54. torch.jit.save(m, 'scriptmodule.pt')
  55. # This line is equivalent to the previous
  56. m.save("scriptmodule.pt")
  57. # Save to io.BytesIO buffer
  58. buffer = io.BytesIO()
  59. torch.jit.save(m, buffer)
  60. # Save with extra files
  61. extra_files = {'foo.txt': b'bar'}
  62. torch.jit.save(m, 'scriptmodule.pt', _extra_files=extra_files)
  63. """
  64. if sys.version_info >= (3, 14):
  65. warnings.warn(
  66. "`torch.jit.save` is not supported in Python 3.14+ and may break. "
  67. "Please switch to `torch.export`.",
  68. DeprecationWarning,
  69. )
  70. else:
  71. warnings.warn(
  72. "`torch.jit.save` is deprecated. Please switch to `torch.export`.",
  73. DeprecationWarning,
  74. )
  75. log_torchscript_usage("save", model_id=_get_model_id(m))
  76. if _extra_files is None:
  77. _extra_files = {}
  78. if isinstance(f, (str, os.PathLike)):
  79. m.save(f, _extra_files=_extra_files)
  80. else:
  81. ret = m.save_to_buffer(_extra_files=_extra_files)
  82. f.write(ret)
  83. def load(f, map_location=None, _extra_files=None, _restore_shapes=False):
  84. r"""
  85. Load a :class:`ScriptModule` or :class:`ScriptFunction` previously saved with :func:`torch.jit.save <torch.jit.save>`.
  86. All previously saved modules, no matter their device, are first loaded onto CPU,
  87. and then are moved to the devices they were saved from. If this fails (e.g.
  88. because the run time system doesn't have certain devices), an exception is
  89. raised.
  90. Args:
  91. f: a file-like object (has to implement read, readline, tell, and seek),
  92. or a string containing a file name
  93. map_location (string or torch.device): A simplified version of
  94. ``map_location`` in `torch.jit.save` used to dynamically remap
  95. storages to an alternative set of devices.
  96. _extra_files (dictionary of filename to content): The extra
  97. filenames given in the map would be loaded and their content
  98. would be stored in the provided map.
  99. _restore_shapes (bool): Whether or not to retrace the module on load using stored inputs
  100. Returns:
  101. A :class:`ScriptModule` object.
  102. .. warning::
  103. It is possible to construct malicious pickle data which will execute arbitrary code
  104. during func:`torch.jit.load`. Never load data that could have come from an untrusted
  105. source, or that could have been tampered with. **Only load data you trust**.
  106. Example:
  107. .. testcode::
  108. import torch
  109. import io
  110. torch.jit.load('scriptmodule.pt')
  111. # Load ScriptModule from io.BytesIO object
  112. with open('scriptmodule.pt', 'rb') as f:
  113. buffer = io.BytesIO(f.read())
  114. # Load all tensors to the original device
  115. torch.jit.load(buffer)
  116. # Load all tensors onto CPU, using a device
  117. buffer.seek(0)
  118. torch.jit.load(buffer, map_location=torch.device('cpu'))
  119. # Load all tensors onto CPU, using a string
  120. buffer.seek(0)
  121. torch.jit.load(buffer, map_location='cpu')
  122. # Load with extra files.
  123. extra_files = {'foo.txt': ''} # values will be replaced with data
  124. torch.jit.load('scriptmodule.pt', _extra_files=extra_files)
  125. print(extra_files['foo.txt'])
  126. .. testoutput::
  127. :hide:
  128. ...
  129. .. testcleanup::
  130. import os
  131. os.remove("scriptmodule.pt")
  132. """
  133. if sys.version_info >= (3, 14):
  134. warnings.warn(
  135. "`torch.jit.load` is not supported in Python 3.14+ and may break. "
  136. "Please switch to `torch.export`.",
  137. DeprecationWarning,
  138. )
  139. else:
  140. warnings.warn(
  141. "`torch.jit.load` is deprecated. Please switch to `torch.export`.",
  142. DeprecationWarning,
  143. )
  144. if isinstance(f, (str, os.PathLike)):
  145. if not os.path.exists(f):
  146. raise ValueError(f"The provided filename {f} does not exist")
  147. if os.path.isdir(f):
  148. raise ValueError(f"The provided filename {f} is a directory")
  149. map_location = validate_map_location(map_location)
  150. if _extra_files is None:
  151. _extra_files = {}
  152. cu = torch._C.CompilationUnit()
  153. if isinstance(f, (str, os.PathLike)):
  154. cpp_module = torch._C.import_ir_module(
  155. cu,
  156. os.fspath(f),
  157. map_location,
  158. _extra_files,
  159. # pyrefly: ignore [bad-argument-count]
  160. _restore_shapes,
  161. ) # type: ignore[call-arg]
  162. else:
  163. cpp_module = torch._C.import_ir_module_from_buffer(
  164. cu,
  165. f.read(),
  166. map_location,
  167. _extra_files,
  168. # pyrefly: ignore [bad-argument-count]
  169. _restore_shapes,
  170. ) # type: ignore[call-arg]
  171. # TODO: Pretty sure this approach loses ConstSequential status and such
  172. ret = wrap_cpp_module(cpp_module)
  173. log_torchscript_usage("load", model_id=_get_model_id(ret))
  174. return ret
  175. def validate_map_location(map_location=None):
  176. if isinstance(map_location, str):
  177. map_location = torch.device(map_location)
  178. elif not (map_location is None or isinstance(map_location, torch.device)):
  179. raise ValueError(
  180. "map_location should be either None, string or torch.device, "
  181. "but got type: " + str(type(map_location))
  182. )
  183. if str(map_location).startswith("cuda"):
  184. validate_cuda_device(map_location)
  185. return map_location
  186. def jit_module_from_flatbuffer(f):
  187. if isinstance(f, (str, os.PathLike)):
  188. f = os.fspath(f)
  189. return wrap_cpp_module(torch._C._load_jit_module_from_file(f))
  190. else:
  191. return wrap_cpp_module(torch._C._load_jit_module_from_bytes(f.read()))
  192. def save_jit_module_to_flatbuffer(m, f, _extra_files=None) -> None:
  193. r"""
  194. Save an offline version of this module for use in a separate process.
  195. The saved module serializes all of the methods, submodules, parameters, and
  196. attributes of this module. It can be loaded into the C++ API using
  197. ``torch::jit::load_jit_module_from_file(filename)`` or into the Python API with
  198. :func:`torch.jit.jit_module_from_flatbuffer<torch.jit.jit_module_from_flatbuffer>`.
  199. To be able to save a module, it must not make any calls to native Python
  200. functions. This means that all submodules must be subclasses of
  201. :class:`ScriptModule` as well.
  202. .. DANGER::
  203. All modules, no matter their device, are always loaded onto the CPU
  204. during loading. This is different from :func:`torch.load`'s semantics
  205. and may change in the future.
  206. Args:
  207. m: A :class:`ScriptModule` to save.
  208. f: A string for file path
  209. Example:
  210. .. testcode::
  211. import torch
  212. import io
  213. class MyModule(torch.nn.Module):
  214. def forward(self, x):
  215. return x + 10
  216. m = torch.jit.script(MyModule())
  217. # Save to file
  218. torch.jit.save_jit_module_to_flatbuffer(m, 'scriptmodule.ff')
  219. """
  220. extra_files = _extra_files
  221. if extra_files is None:
  222. extra_files = {}
  223. if isinstance(f, (str, os.PathLike)):
  224. f = os.fspath(f)
  225. torch._C._save_jit_module(m._c, f, extra_files)
  226. else:
  227. s = torch._C._save_jit_module_to_bytes(m._c, extra_files)
  228. f.write(s)
  229. def get_flatbuffer_module_info(path_or_file):
  230. r"""Get some information regarding a model file in flatbuffer format.
  231. Args:
  232. path_or_file: Either str, Path or file like object (BytesIO OK).
  233. If it's str or Path, we will read the file referenced by that
  234. path as Bytes.
  235. Returns:
  236. A dict with metadata on what that file contains, currently looks like
  237. this:
  238. {
  239. 'bytecode_version': 4, # int
  240. 'operator_version': 4, # int
  241. 'function_names': {
  242. '__torch__.___torch_mangle_0.Foo.forward'}, # set
  243. 'type_names': set(), # set
  244. 'opname_to_num_args': {'aten::linear': 3} # Dict[str, int]
  245. }
  246. """
  247. if isinstance(path_or_file, (str, os.PathLike)):
  248. with open(path_or_file, "rb") as f:
  249. all_bytes = f.read()
  250. else:
  251. all_bytes = path_or_file.read()
  252. return torch._C._get_module_info_from_flatbuffer(all_bytes)