__init__.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. import torch
  2. from torch.jit._serialization import validate_map_location
  3. import pathlib
  4. import os
  5. def _load_for_lite_interpreter(f, map_location=None):
  6. r"""
  7. Load a :class:`LiteScriptModule`
  8. saved with :func:`torch.jit._save_for_lite_interpreter`
  9. Args:
  10. f: a file-like object (has to implement read, readline, tell, and seek),
  11. or a string containing a file name
  12. map_location: a string or torch.device used to dynamically remap
  13. storages to an alternative set of devices.
  14. Returns:
  15. A :class:`LiteScriptModule` object.
  16. Example:
  17. .. testcode::
  18. import torch
  19. import io
  20. # Load LiteScriptModule from saved file path
  21. torch.jit._load_for_lite_interpreter('lite_script_module.pt')
  22. # Load LiteScriptModule from io.BytesIO object
  23. with open('lite_script_module.pt', 'rb') as f:
  24. buffer = io.BytesIO(f.read())
  25. # Load all tensors to the original device
  26. torch.jit.mobile._load_for_lite_interpreter(buffer)
  27. """
  28. if isinstance(f, str):
  29. if not os.path.exists(f):
  30. raise ValueError("The provided filename {} does not exist".format(f))
  31. if os.path.isdir(f):
  32. raise ValueError("The provided filename {} is a directory".format(f))
  33. map_location = validate_map_location(map_location)
  34. if isinstance(f, (str, pathlib.Path)):
  35. cpp_module = torch._C._load_for_lite_interpreter(f, map_location)
  36. else:
  37. cpp_module = torch._C._load_for_lite_interpreter_from_buffer(f.read(), map_location)
  38. return LiteScriptModule(cpp_module)
  39. class LiteScriptModule:
  40. def __init__(self, cpp_module):
  41. self._c = cpp_module
  42. super().__init__()
  43. def __call__(self, *input):
  44. return self._c.forward(input)
  45. def find_method(self, method_name):
  46. return self._c.find_method(method_name)
  47. def forward(self, *input):
  48. return self._c.forward(input)
  49. def run_method(self, method_name, *input):
  50. return self._c.run_method(method_name, input)
  51. def _export_operator_list(module: LiteScriptModule):
  52. r"""
  53. return a set of root operator names (with overload name) that are used by any method
  54. in this mobile module.
  55. """
  56. return torch._C._export_operator_list(module._c)
  57. def _get_model_bytecode_version(f_input) -> int:
  58. r"""
  59. Args:
  60. f_input: a file-like object (has to implement read, readline, tell, and seek),
  61. or a string containing a file name
  62. Returns:
  63. version: An integer. If the integer is -1, the version is invalid. A warning
  64. will show in the log.
  65. Example:
  66. .. testcode::
  67. from torch.jit.mobile import _get_model_bytecode_version
  68. # Get bytecode version from a saved file path
  69. version = _get_model_bytecode_version("path/to/model.ptl")
  70. """
  71. if isinstance(f_input, str):
  72. if not os.path.exists(f_input):
  73. raise ValueError(f"The provided filename {f_input} does not exist")
  74. if os.path.isdir(f_input):
  75. raise ValueError(f"The provided filename {f_input} is a directory")
  76. if (isinstance(f_input, (str, pathlib.Path))):
  77. return torch._C._get_model_bytecode_version(str(f_input))
  78. else:
  79. return torch._C._get_model_bytecode_version_from_buffer(f_input.read())
  80. def _get_mobile_model_contained_types(f_input) -> int:
  81. r"""
  82. Args:
  83. f_input: a file-like object (has to implement read, readline, tell, and seek),
  84. or a string containing a file name
  85. Returns:
  86. type_list: A set of string, like ("int", "Optional"). These are types used in bytecode.
  87. Example:
  88. .. testcode::
  89. from torch.jit.mobile import _get_mobile_model_contained_types
  90. # Get type list from a saved file path
  91. type_list = _get_mobile_model_contained_types("path/to/model.ptl")
  92. """
  93. if isinstance(f_input, str):
  94. if not os.path.exists(f_input):
  95. raise ValueError(f"The provided filename {f_input} does not exist")
  96. if os.path.isdir(f_input):
  97. raise ValueError(f"The provided filename {f_input} is a directory")
  98. if (isinstance(f_input, (str, pathlib.Path))):
  99. return torch._C._get_mobile_model_contained_types(str(f_input))
  100. else:
  101. return torch._C._get_mobile_model_contained_types_from_buffer(f_input.read())
  102. def _backport_for_mobile(f_input, f_output, to_version):
  103. r"""
  104. Args:
  105. f_input: a file-like object (has to implement read, readline, tell, and seek),
  106. or a string containing a file name
  107. f_output: path to new model destination
  108. to_version: the expected output model bytecode version
  109. Returns:
  110. success: A boolean. If backport success, return true, otherwise false
  111. """
  112. if isinstance(f_input, str):
  113. if not os.path.exists(f_input):
  114. raise ValueError(f"The provided filename {f_input} does not exist")
  115. if os.path.isdir(f_input):
  116. raise ValueError(f"The provided filename {f_input} is a directory")
  117. if ((isinstance(f_input, (str, pathlib.Path))) and (
  118. isinstance(f_output, (str, pathlib.Path)))):
  119. return torch._C._backport_for_mobile(str(f_input), str(f_output), to_version)
  120. else:
  121. return torch._C._backport_for_mobile_from_buffer(f_input.read(), str(f_output), to_version)
  122. def _backport_for_mobile_to_buffer(f_input, to_version):
  123. r"""
  124. Args:
  125. f_input: a file-like object (has to implement read, readline, tell, and seek),
  126. or a string containing a file name
  127. """
  128. if isinstance(f_input, str):
  129. if not os.path.exists(f_input):
  130. raise ValueError(f"The provided filename {f_input} does not exist")
  131. if os.path.isdir(f_input):
  132. raise ValueError(f"The provided filename {f_input} is a directory")
  133. if (isinstance(f_input, (str, pathlib.Path))):
  134. return torch._C._backport_for_mobile_to_buffer(str(f_input), to_version)
  135. else:
  136. return torch._C._backport_for_mobile_from_buffer_to_buffer(f_input.read(), to_version)
  137. def _get_model_ops_and_info(f_input):
  138. r"""
  139. A function to retrieve the root (top level) operators of a model and their corresponding
  140. compatibility info. These root operators can call other operators within them (traced ops), and
  141. a root op can call many different traced ops depending on internal code paths in the root op.
  142. These traced ops are not returned by this function. Those operators are abstracted into the
  143. runtime as an implementation detail (and the traced ops themselves can also call other operators)
  144. making retrieving them difficult and their value from this api negligible since they will differ
  145. between which runtime version the model is run on. Because of this, there is a false positive this
  146. api can't prevent in a compatibility usecase. All the root ops of a model are present in a
  147. target runtime, but not all the traced ops are which prevents a model from being able to run.
  148. Args:
  149. f_input: a file-like object (has to implement read, readline, tell, and seek),
  150. or a string containing a file name
  151. Returns:
  152. Operators and info: A Dictionary mapping strings (the qualified names of the root operators)
  153. of the model to their OperatorInfo structs.
  154. Example:
  155. .. testcode::
  156. from torch.jit.mobile import _get_model_ops_and_info
  157. # Get bytecode version from a saved file path
  158. ops_and_info = _get_model_ops_and_info("path/to/model.ptl")
  159. """
  160. if isinstance(f_input, str):
  161. if not os.path.exists(f_input):
  162. raise ValueError(f"The provided filename {f_input} does not exist")
  163. if os.path.isdir(f_input):
  164. raise ValueError(f"The provided filename {f_input} is a directory")
  165. if (isinstance(f_input, (str, pathlib.Path))):
  166. return torch._C._get_model_ops_and_info(str(f_input))
  167. else:
  168. return torch._C._get_model_ops_and_info(f_input.read())