__init__.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. import torch._C
  2. from contextlib import contextmanager
  3. from typing import Iterator, Any
  4. import warnings
  5. from torch.utils import set_module
  6. # These are imported so users can access them from the `torch.jit` module
  7. from torch._jit_internal import (
  8. Final,
  9. Future,
  10. _Await,
  11. _drop,
  12. _IgnoreContextManager,
  13. _overload,
  14. _overload_method,
  15. ignore,
  16. _isinstance,
  17. is_scripting,
  18. export,
  19. unused,
  20. )
  21. from torch.jit._script import (
  22. script,
  23. Attribute,
  24. ScriptModule,
  25. script_method,
  26. RecursiveScriptClass,
  27. RecursiveScriptModule,
  28. ScriptWarning,
  29. interface,
  30. CompilationUnit,
  31. ScriptFunction,
  32. _ScriptProfile,
  33. _unwrap_optional,
  34. )
  35. from torch.jit._trace import (
  36. trace,
  37. trace_module,
  38. TracedModule,
  39. TracerWarning,
  40. TracingCheckError,
  41. is_tracing,
  42. ONNXTracedModule,
  43. TopLevelTracedModule,
  44. _unique_state_dict,
  45. _flatten,
  46. _script_if_tracing,
  47. _get_trace_graph,
  48. )
  49. from torch.jit._async import fork, wait
  50. from torch.jit._await import _awaitable, _awaitable_wait, _awaitable_nowait
  51. from torch.jit._decomposition_utils import _register_decomposition
  52. from torch.jit._serialization import (
  53. save,
  54. load,
  55. jit_module_from_flatbuffer,
  56. save_jit_module_to_flatbuffer,
  57. )
  58. from torch.jit._fuser import optimized_execution, fuser, last_executed_optimized_graph, set_fusion_strategy
  59. from torch.jit._freeze import freeze, optimize_for_inference, run_frozen_optimizations
  60. from torch.jit._ir_utils import _InsertPoint
  61. # For backwards compatibility
  62. _fork = fork
  63. _wait = wait
  64. _set_fusion_strategy = set_fusion_strategy
  65. def export_opnames(m):
  66. r"""
  67. Generates new bytecode for a Script module and returns what the op list
  68. would be for a Script Module based off the current code base. If you
  69. have a LiteScriptModule and want to get the currently present
  70. list of ops call _export_operator_list instead.
  71. """
  72. return torch._C._export_opnames(m._c)
  73. # torch.jit.Error
  74. Error = torch._C.JITException
  75. set_module(Error, "torch.jit")
  76. # This is not perfect but works in common cases
  77. Error.__name__ = "Error"
  78. Error.__qualname__ = "Error"
  79. # for use in python if using annotate
  80. def annotate(the_type, the_value):
  81. """
  82. This method is a pass-through function that returns `the_value`, used to hint TorchScript
  83. compiler the type of `the_value`. It is a no-op when running outside of TorchScript.
  84. Though TorchScript can infer correct type for most Python expressions, there are some cases where
  85. type inference can be wrong, including:
  86. - Empty containers like `[]` and `{}`, which TorchScript assumes to be container of `Tensor`
  87. - Optional types like `Optional[T]` but assigned a valid value of type `T`, TorchScript would assume
  88. it is type `T` rather than `Optional[T]`
  89. Note that `annotate()` does not help in `__init__` method of `torch.nn.Module` subclasses because it
  90. is executed in eager mode. To annotate types of `torch.nn.Module` attributes,
  91. use :meth:`~torch.jit.Annotate` instead.
  92. Example:
  93. .. testcode::
  94. import torch
  95. from typing import Dict
  96. @torch.jit.script
  97. def fn():
  98. # Telling TorchScript that this empty dictionary is a (str -> int) dictionary
  99. # instead of default dictionary type of (str -> Tensor).
  100. d = torch.jit.annotate(Dict[str, int], {})
  101. # Without `torch.jit.annotate` above, following statement would fail because of
  102. # type mismatch.
  103. d["name"] = 20
  104. .. testcleanup::
  105. del fn
  106. Args:
  107. the_type: Python type that should be passed to TorchScript compiler as type hint for `the_value`
  108. the_value: Value or expression to hint type for.
  109. Returns:
  110. `the_value` is passed back as return value.
  111. """
  112. return the_value
  113. def script_if_tracing(fn):
  114. """
  115. Compiles ``fn`` when it is first called during tracing. ``torch.jit.script``
  116. has a non-negligible start up time when it is first called due to
  117. lazy-initializations of many compiler builtins. Therefore you should not use
  118. it in library code. However, you may want to have parts of your library work
  119. in tracing even if they use control flow. In these cases, you should use
  120. ``@torch.jit.script_if_tracing`` to substitute for
  121. ``torch.jit.script``.
  122. Args:
  123. fn: A function to compile.
  124. Returns:
  125. If called during tracing, a :class:`ScriptFunction` created by `torch.jit.script` is returned.
  126. Otherwise, the original function `fn` is returned.
  127. """
  128. return _script_if_tracing(fn)
  129. # for torch.jit.isinstance
  130. def isinstance(obj, target_type):
  131. """
  132. This function provides for container type refinement in TorchScript. It can refine
  133. parameterized containers of the List, Dict, Tuple, and Optional types. E.g. ``List[str]``,
  134. ``Dict[str, List[torch.Tensor]]``, ``Optional[Tuple[int,str,int]]``. It can also
  135. refine basic types such as bools and ints that are available in TorchScript.
  136. Args:
  137. obj: object to refine the type of
  138. target_type: type to try to refine obj to
  139. Returns:
  140. ``bool``: True if obj was successfully refined to the type of target_type,
  141. False otherwise with no new type refinement
  142. Example (using ``torch.jit.isinstance`` for type refinement):
  143. .. testcode::
  144. import torch
  145. from typing import Any, Dict, List
  146. class MyModule(torch.nn.Module):
  147. def __init__(self):
  148. super().__init__()
  149. def forward(self, input: Any): # note the Any type
  150. if torch.jit.isinstance(input, List[torch.Tensor]):
  151. for t in input:
  152. y = t.clamp(0, 0.5)
  153. elif torch.jit.isinstance(input, Dict[str, str]):
  154. for val in input.values():
  155. print(val)
  156. m = torch.jit.script(MyModule())
  157. x = [torch.rand(3,3), torch.rand(4,3)]
  158. m(x)
  159. y = {"key1":"val1","key2":"val2"}
  160. m(y)
  161. """
  162. return _isinstance(obj, target_type)
  163. class strict_fusion:
  164. """
  165. This class errors if not all nodes have been fused in
  166. inference, or symbolically differentiated in training.
  167. Example:
  168. Forcing fusion of additions.
  169. .. code-block:: python
  170. @torch.jit.script
  171. def foo(x):
  172. with torch.jit.strict_fusion():
  173. return x + x + x
  174. """
  175. def __init__(self):
  176. if not torch._jit_internal.is_scripting():
  177. warnings.warn("Only works in script mode")
  178. pass
  179. def __enter__(self):
  180. pass
  181. def __exit__(self, type: Any, value: Any, tb: Any) -> None:
  182. pass
  183. # Context manager for globally hiding source ranges when printing graphs.
  184. # Note that these functions are exposed to Python as static members of the
  185. # Graph class, so mypy checks need to be skipped.
  186. @contextmanager
  187. def _hide_source_ranges() -> Iterator[None]:
  188. old_enable_source_ranges = torch._C.Graph.global_print_source_ranges # type: ignore[attr-defined]
  189. try:
  190. torch._C.Graph.set_global_print_source_ranges(False) # type: ignore[attr-defined]
  191. yield
  192. finally:
  193. torch._C.Graph.set_global_print_source_ranges(old_enable_source_ranges) # type: ignore[attr-defined]
  194. def enable_onednn_fusion(enabled: bool):
  195. """
  196. Enables or disables onednn JIT fusion based on the parameter `enabled`.
  197. """
  198. torch._C._jit_set_llga_enabled(enabled)
  199. def onednn_fusion_enabled():
  200. """
  201. Returns whether onednn JIT fusion is enabled
  202. """
  203. return torch._C._jit_llga_enabled()
  204. del Any
  205. if not torch._C._jit_init():
  206. raise RuntimeError("JIT initialization failed")