__init__.py 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488
  1. r"""
  2. The torch package contains data structures for multi-dimensional
  3. tensors and defines mathematical operations over these tensors.
  4. Additionally, it provides many utilities for efficient serialization of
  5. Tensors and arbitrary types, and other useful utilities.
  6. It has a CUDA counterpart, that enables you to run your tensor computations
  7. on an NVIDIA GPU with compute capability >= 3.0.
  8. """
  9. import math
  10. import os
  11. import sys
  12. import platform
  13. import textwrap
  14. import ctypes
  15. import inspect
  16. if sys.version_info < (3,):
  17. raise Exception("Python 2 has reached end-of-life and is no longer supported by PyTorch.")
  18. from ._utils import _import_dotted_name, classproperty
  19. from ._utils_internal import get_file_path, prepare_multiprocessing_environment, \
  20. USE_RTLD_GLOBAL_WITH_LIBTORCH, USE_GLOBAL_DEPS
  21. # TODO(torch_deploy) figure out how to freeze version.py in fbcode build
  22. if sys.executable == 'torch_deploy':
  23. __version__ = "torch-deploy-1.8"
  24. else:
  25. from .torch_version import __version__ as __version__
  26. from typing import Any, Callable, Dict, Optional, Set, Type, TYPE_CHECKING, Union
  27. import builtins
  28. __all__ = [
  29. 'typename', 'is_tensor', 'is_storage', 'set_default_tensor_type',
  30. 'set_default_device',
  31. 'set_rng_state', 'get_rng_state', 'manual_seed', 'initial_seed', 'seed',
  32. 'save', 'load', 'set_printoptions', 'chunk', 'split', 'stack', 'matmul',
  33. 'no_grad', 'enable_grad', 'rand', 'randn', 'inference_mode',
  34. 'DoubleStorage', 'FloatStorage', 'LongStorage', 'IntStorage',
  35. 'ShortStorage', 'CharStorage', 'ByteStorage', 'BoolStorage',
  36. 'TypedStorage', 'UntypedStorage',
  37. 'DoubleTensor', 'FloatTensor', 'LongTensor', 'IntTensor',
  38. 'ShortTensor', 'CharTensor', 'ByteTensor', 'BoolTensor', 'Tensor',
  39. 'lobpcg', 'use_deterministic_algorithms',
  40. 'are_deterministic_algorithms_enabled',
  41. 'is_deterministic_algorithms_warn_only_enabled',
  42. 'set_deterministic_debug_mode', 'get_deterministic_debug_mode',
  43. 'set_float32_matmul_precision', 'get_float32_matmul_precision',
  44. 'set_warn_always', 'is_warn_always_enabled', 'SymInt', 'SymFloat',
  45. 'SymBool', 'sym_not',
  46. 'sym_int', 'sym_float', 'sym_max', 'sym_min', 'compile', 'vmap'
  47. ]
  48. ################################################################################
  49. # Load the extension module
  50. ################################################################################
  51. if sys.platform == 'win32':
  52. pfiles_path = os.getenv('ProgramFiles', 'C:\\Program Files')
  53. py_dll_path = os.path.join(sys.exec_prefix, 'Library', 'bin')
  54. th_dll_path = os.path.join(os.path.dirname(__file__), 'lib')
  55. # When users create a virtualenv that inherits the base environment,
  56. # we will need to add the corresponding library directory into
  57. # DLL search directories. Otherwise, it will rely on `PATH` which
  58. # is dependent on user settings.
  59. if sys.exec_prefix != sys.base_exec_prefix:
  60. base_py_dll_path = os.path.join(sys.base_exec_prefix, 'Library', 'bin')
  61. else:
  62. base_py_dll_path = ''
  63. dll_paths = list(filter(os.path.exists, [th_dll_path, py_dll_path, base_py_dll_path]))
  64. if all([not os.path.exists(os.path.join(p, 'nvToolsExt64_1.dll')) for p in dll_paths]):
  65. nvtoolsext_dll_path = os.path.join(
  66. os.getenv('NVTOOLSEXT_PATH', os.path.join(pfiles_path, 'NVIDIA Corporation', 'NvToolsExt')), 'bin', 'x64')
  67. else:
  68. nvtoolsext_dll_path = ''
  69. from .version import cuda as cuda_version
  70. import glob
  71. if cuda_version and all([not glob.glob(os.path.join(p, 'cudart64*.dll')) for p in dll_paths]):
  72. cuda_version_1 = cuda_version.replace('.', '_')
  73. cuda_path_var = 'CUDA_PATH_V' + cuda_version_1
  74. default_path = os.path.join(pfiles_path, 'NVIDIA GPU Computing Toolkit', 'CUDA', 'v' + cuda_version)
  75. cuda_path = os.path.join(os.getenv(cuda_path_var, default_path), 'bin')
  76. else:
  77. cuda_path = ''
  78. dll_paths.extend(filter(os.path.exists, [nvtoolsext_dll_path, cuda_path]))
  79. kernel32 = ctypes.WinDLL('kernel32.dll', use_last_error=True)
  80. with_load_library_flags = hasattr(kernel32, 'AddDllDirectory')
  81. prev_error_mode = kernel32.SetErrorMode(0x0001)
  82. kernel32.LoadLibraryW.restype = ctypes.c_void_p
  83. if with_load_library_flags:
  84. kernel32.LoadLibraryExW.restype = ctypes.c_void_p
  85. for dll_path in dll_paths:
  86. os.add_dll_directory(dll_path)
  87. try:
  88. ctypes.CDLL('vcruntime140.dll')
  89. ctypes.CDLL('msvcp140.dll')
  90. ctypes.CDLL('vcruntime140_1.dll')
  91. except OSError:
  92. print('''Microsoft Visual C++ Redistributable is not installed, this may lead to the DLL load failure.
  93. It can be downloaded at https://aka.ms/vs/16/release/vc_redist.x64.exe''')
  94. dlls = glob.glob(os.path.join(th_dll_path, '*.dll'))
  95. path_patched = False
  96. for dll in dlls:
  97. is_loaded = False
  98. if with_load_library_flags:
  99. res = kernel32.LoadLibraryExW(dll, None, 0x00001100)
  100. last_error = ctypes.get_last_error()
  101. if res is None and last_error != 126:
  102. err = ctypes.WinError(last_error)
  103. err.strerror += f' Error loading "{dll}" or one of its dependencies.'
  104. raise err
  105. elif res is not None:
  106. is_loaded = True
  107. if not is_loaded:
  108. if not path_patched:
  109. os.environ['PATH'] = ';'.join(dll_paths + [os.environ['PATH']])
  110. path_patched = True
  111. res = kernel32.LoadLibraryW(dll)
  112. if res is None:
  113. err = ctypes.WinError(ctypes.get_last_error())
  114. err.strerror += f' Error loading "{dll}" or one of its dependencies.'
  115. raise err
  116. kernel32.SetErrorMode(prev_error_mode)
  117. def _preload_cuda_deps(lib_folder, lib_name):
  118. """Preloads cuda deps if they could not be found otherwise."""
  119. # Should only be called on Linux if default path resolution have failed
  120. assert platform.system() == 'Linux', 'Should only be called on Linux'
  121. import glob
  122. lib_path = None
  123. for path in sys.path:
  124. nvidia_path = os.path.join(path, 'nvidia')
  125. if not os.path.exists(nvidia_path):
  126. continue
  127. candidate_lib_paths = glob.glob(os.path.join(nvidia_path, lib_folder, 'lib', lib_name))
  128. if candidate_lib_paths and not lib_path:
  129. lib_path = candidate_lib_paths[0]
  130. if lib_path:
  131. break
  132. if not lib_path:
  133. raise ValueError(f"{lib_name} not found in the system path {sys.path}")
  134. ctypes.CDLL(lib_path)
  135. # See Note [Global dependencies]
  136. def _load_global_deps():
  137. if sys.executable == 'torch_deploy' or platform.system() == 'Windows':
  138. return
  139. lib_name = 'libtorch_global_deps' + ('.dylib' if platform.system() == 'Darwin' else '.so')
  140. here = os.path.abspath(__file__)
  141. lib_path = os.path.join(os.path.dirname(here), 'lib', lib_name)
  142. try:
  143. ctypes.CDLL(lib_path, mode=ctypes.RTLD_GLOBAL)
  144. except OSError as err:
  145. # Can only happen for wheel with cuda libs as PYPI deps
  146. # As PyTorch is not purelib, but nvidia-*-cu11 is
  147. cuda_libs: Dict[str, str] = {
  148. 'cublas': 'libcublas.so.*[0-9]',
  149. 'cudnn': 'libcudnn.so.*[0-9]',
  150. 'cuda_nvrtc': 'libnvrtc.so.*[0-9].*[0-9]',
  151. 'cuda_runtime': 'libcudart.so.*[0-9].*[0-9]',
  152. 'cuda_cupti': 'libcupti.so.*[0-9].*[0-9]',
  153. 'cufft': 'libcufft.so.*[0-9]',
  154. 'curand': 'libcurand.so.*[0-9]',
  155. 'cusolver': 'libcusolver.so.*[0-9]',
  156. 'cusparse': 'libcusparse.so.*[0-9]',
  157. 'nccl': 'libnccl.so.*[0-9]',
  158. 'nvtx': 'libnvToolsExt.so.*[0-9]',
  159. }
  160. is_cuda_lib_err = [lib for lib in cuda_libs.values() if(lib.split('.')[0] in err.args[0])]
  161. if not is_cuda_lib_err:
  162. raise err
  163. for lib_folder, lib_name in cuda_libs.items():
  164. _preload_cuda_deps(lib_folder, lib_name)
  165. ctypes.CDLL(lib_path, mode=ctypes.RTLD_GLOBAL)
  166. if (USE_RTLD_GLOBAL_WITH_LIBTORCH or os.getenv('TORCH_USE_RTLD_GLOBAL')) and \
  167. (sys.executable == "torch_deploy" or platform.system() != 'Windows'):
  168. # Do it the hard way. You might want to load libtorch with RTLD_GLOBAL in a
  169. # few circumstances:
  170. #
  171. # 1. You're in a build environment (e.g., fbcode) where
  172. # libtorch_global_deps is not available, but you still need
  173. # to get mkl to link in with RTLD_GLOBAL or it will just
  174. # not work.
  175. #
  176. # 2. You're trying to run PyTorch under UBSAN and you need
  177. # to ensure that only one copy of libtorch is loaded, so
  178. # vptr checks work properly
  179. #
  180. # If you're using this setting, you must verify that all the libraries
  181. # you load consistently use the same libstdc++, or you may have
  182. # mysterious segfaults.
  183. #
  184. old_flags = sys.getdlopenflags()
  185. sys.setdlopenflags(os.RTLD_GLOBAL | os.RTLD_LAZY)
  186. from torch._C import * # noqa: F403
  187. sys.setdlopenflags(old_flags)
  188. del old_flags
  189. else:
  190. # Easy way. You want this most of the time, because it will prevent
  191. # C++ symbols from libtorch clobbering C++ symbols from other
  192. # libraries, leading to mysterious segfaults.
  193. #
  194. # If building in an environment where libtorch_global_deps isn't available
  195. # like parts of fbsource, but where RTLD_GLOBAL causes segfaults, you will
  196. # want USE_RTLD_GLOBAL_WITH_LIBTORCH = False and USE_GLOBAL_DEPS = False
  197. #
  198. # See Note [Global dependencies]
  199. if USE_GLOBAL_DEPS:
  200. _load_global_deps()
  201. from torch._C import * # noqa: F403
  202. # Appease the type checker; ordinarily this binding is inserted by the
  203. # torch._C module initialization code in C
  204. if TYPE_CHECKING:
  205. import torch._C as _C
  206. class SymInt:
  207. """
  208. Like an int (including magic methods), but redirects all operations on the
  209. wrapped node. This is used in particular to symbolically record operations
  210. in the symbolic shape workflow.
  211. """
  212. def __init__(self, node):
  213. # This field MUST be named node; C++ binding code assumes that this
  214. # class has a field named node that stores SymNode
  215. self.node = node
  216. def __bool__(self):
  217. return self.node.bool_()
  218. def __int__(self):
  219. return self.node.int_()
  220. # Magic methods installed by torch.fx.experimental.symbolic_shapes
  221. def __eq__(self, other: object) -> builtins.bool:
  222. raise AssertionError("type stub not overridden")
  223. def __lt__(self, other) -> builtins.bool:
  224. raise AssertionError("type stub not overridden")
  225. def __gt__(self, other) -> builtins.bool:
  226. raise AssertionError("type stub not overridden")
  227. def __le__(self, other) -> builtins.bool:
  228. raise AssertionError("type stub not overridden")
  229. def __ge__(self, other) -> builtins.bool:
  230. raise AssertionError("type stub not overridden")
  231. def __sym_max__(self, other):
  232. raise AssertionError("type stub not overridden")
  233. def __sym_min__(self, other):
  234. raise AssertionError("type stub not overridden")
  235. def __sym_float__(self):
  236. raise AssertionError("type stub not overridden")
  237. def __repr__(self):
  238. return str(self.node)
  239. class SymFloat:
  240. """
  241. Like an float (including magic methods), but redirects all operations on the
  242. wrapped node. This is used in particular to symbolically record operations
  243. in the symbolic shape workflow.
  244. """
  245. def __init__(self, node):
  246. from torch.fx.experimental.symbolic_shapes import SymNode
  247. assert isinstance(node, SymNode)
  248. # This field MUST be named node; C++ binding code assumes that this
  249. # class has a field named node that stores SymNode
  250. self.node = node
  251. def __bool__(self):
  252. return self.node.bool_()
  253. # Magic methods installed by torch.fx.experimental.symbolic_shapes
  254. def __eq__(self, other: object) -> builtins.bool:
  255. raise AssertionError("type stub not overridden")
  256. def __lt__(self, other) -> builtins.bool:
  257. raise AssertionError("type stub not overridden")
  258. def __gt__(self, other) -> builtins.bool:
  259. raise AssertionError("type stub not overridden")
  260. def __le__(self, other) -> builtins.bool:
  261. raise AssertionError("type stub not overridden")
  262. def __ge__(self, other) -> builtins.bool:
  263. raise AssertionError("type stub not overridden")
  264. def __sym_max__(self, other):
  265. raise AssertionError("type stub not overridden")
  266. def __sym_min__(self, other):
  267. raise AssertionError("type stub not overridden")
  268. def __sym_int__(self):
  269. raise AssertionError("type stub not overridden")
  270. def __repr__(self):
  271. return self.node.str()
  272. class SymBool:
  273. """
  274. Like an bool (including magic methods), but redirects all operations on the
  275. wrapped node. This is used in particular to symbolically record operations
  276. in the symbolic shape workflow.
  277. Unlike regular bools, regular boolean operators will force extra guards instead
  278. of symbolically evaluate. Use the bitwise operators instead to handle this.
  279. """
  280. def __init__(self, node):
  281. from torch.fx.experimental.symbolic_shapes import SymNode
  282. assert isinstance(node, SymNode)
  283. # This field MUST be named node; C++ binding code assumes that this
  284. # class has a field named node that stores SymNode
  285. self.node = node
  286. def __bool__(self):
  287. return self.node.bool_()
  288. # Magic methods installed by torch.fx.experimental.symbolic_shapes
  289. def __and__(self, other) -> "SymBool":
  290. raise AssertionError("type stub not overridden")
  291. def __or__(self, other) -> "SymBool":
  292. raise AssertionError("type stub not overridden")
  293. # We very carefully define __sym_not__, and not a number of other
  294. # plausible alternatives:
  295. #
  296. # - We do not override __not__ because this is not a real magic
  297. # method; you cannot override the meaning of the not builtin in
  298. # Python. We use the name 'sym_not' to clarify that in user code you
  299. # cannot use the builtin not or operator.not_ or operator.__not__ and
  300. # hit this magic method; you must use our custom sym_not operator.
  301. #
  302. # - We do not override the __invert__ method because SymBool is
  303. # meant to be usable in situations where bool is expected. However,
  304. # bitwise negation ~a does the wrong thing with booleans (because
  305. # bool is a subclass of int, so ~1 = -2 which is not falseish.)
  306. # This would be a giant footgun, so we get around it by defining
  307. # our own operator. Note that bitwise and/or do the right thing,
  308. # so we reuse the conventional operators there for readability.
  309. #
  310. def __sym_not__(self) -> "SymBool":
  311. raise AssertionError("type stub not overridden")
  312. def __repr__(self):
  313. return self.node.str()
  314. def sym_not(a):
  315. r""" SymInt-aware utility for logical negation.
  316. Args:
  317. a (SymBool or bool): Object to negate
  318. """
  319. if hasattr(a, '__sym_not__'):
  320. return a.__sym_not__()
  321. return not a
  322. def sym_float(a):
  323. r""" SymInt-aware utility for float casting.
  324. Args:
  325. a (SymInt, SymFloat, or object): Object to cast
  326. """
  327. if isinstance(a, SymFloat):
  328. return a
  329. elif hasattr(a, '__sym_float__'):
  330. return a.__sym_float__()
  331. return py_float(a) # type: ignore[operator]
  332. def sym_int(a):
  333. r""" SymInt-aware utility for int casting.
  334. Args:
  335. a (SymInt, SymFloat, or object): Object to cast
  336. """
  337. if isinstance(a, SymInt):
  338. return a
  339. elif isinstance(a, SymFloat):
  340. return math.floor(a) if a >= 0 else math.ceil(a) # type: ignore[arg-type]
  341. return py_int(a) # type: ignore[operator]
  342. def sym_max(a, b):
  343. """ SymInt-aware utility for max()."""
  344. if isinstance(a, (SymInt, SymFloat)):
  345. return a.__sym_max__(b)
  346. elif isinstance(b, (SymInt, SymFloat)):
  347. # NB: If you actually care about preserving output type exactly
  348. # if you do something like max(0, 0.0), it is NOT sound to treat
  349. # min/max as commutative
  350. return b.__sym_max__(a)
  351. return builtins.max(a, b) # type: ignore[operator]
  352. def sym_min(a, b):
  353. """ SymInt-aware utility for max()."""
  354. if isinstance(a, (SymInt, SymFloat)):
  355. return a.__sym_min__(b)
  356. elif isinstance(b, (SymInt, SymFloat)):
  357. return b.__sym_min__(a)
  358. return builtins.min(a, b) # type: ignore[operator]
  359. # Check to see if we can load C extensions, and if not provide some guidance
  360. # on what the problem might be.
  361. try:
  362. # _initExtension is chosen (arbitrarily) as a sentinel.
  363. from torch._C import _initExtension
  364. except ImportError:
  365. import torch._C as _C_for_compiled_check
  366. # The __file__ check only works for Python 3.7 and above.
  367. if _C_for_compiled_check.__file__ is None:
  368. raise ImportError(textwrap.dedent('''
  369. Failed to load PyTorch C extensions:
  370. It appears that PyTorch has loaded the `torch/_C` folder
  371. of the PyTorch repository rather than the C extensions which
  372. are expected in the `torch._C` namespace. This can occur when
  373. using the `install` workflow. e.g.
  374. $ python setup.py install && python -c "import torch"
  375. This error can generally be solved using the `develop` workflow
  376. $ python setup.py develop && python -c "import torch" # This should succeed
  377. or by running Python from a different directory.
  378. ''').strip()) from None
  379. raise # If __file__ is not None the cause is unknown, so just re-raise.
  380. for name in dir(_C):
  381. if name[0] != '_' and not name.endswith('Base'):
  382. __all__.append(name)
  383. obj = getattr(_C, name)
  384. if (isinstance(obj, Callable) or inspect.isclass(obj)): # type: ignore[arg-type]
  385. if (obj.__module__ != 'torch'):
  386. # TODO: fix their module from C++ side
  387. if name not in ['DisableTorchFunctionSubclass', 'DisableTorchFunction', 'Generator']:
  388. obj.__module__ = 'torch'
  389. if not TYPE_CHECKING:
  390. # issue 38137 and python issue 43367. Submodules of a C extension are
  391. # non-standard, and attributes of those submodules cannot be pickled since
  392. # pickle expect to be able to import them as "from _C.sub import attr"
  393. # which fails with "_C is not a package
  394. for attr in dir(_C):
  395. candidate = getattr(_C, attr)
  396. if type(candidate) is type(_C):
  397. # submodule
  398. if f'torch._C.{attr}' not in sys.modules:
  399. sys.modules[f'torch._C.{attr}'] = candidate
  400. ################################################################################
  401. # Define basic utilities
  402. ################################################################################
  403. def typename(o):
  404. if isinstance(o, torch.Tensor):
  405. return o.type()
  406. module = ''
  407. class_name = ''
  408. if hasattr(o, '__module__') and o.__module__ != 'builtins' \
  409. and o.__module__ != '__builtin__' and o.__module__ is not None:
  410. module = o.__module__ + '.'
  411. if hasattr(o, '__qualname__'):
  412. class_name = o.__qualname__
  413. elif hasattr(o, '__name__'):
  414. class_name = o.__name__
  415. else:
  416. class_name = o.__class__.__name__
  417. return module + class_name
  418. def is_tensor(obj):
  419. r"""Returns True if `obj` is a PyTorch tensor.
  420. Note that this function is simply doing ``isinstance(obj, Tensor)``.
  421. Using that ``isinstance`` check is better for typechecking with mypy,
  422. and more explicit - so it's recommended to use that instead of
  423. ``is_tensor``.
  424. Args:
  425. obj (Object): Object to test
  426. Example::
  427. >>> x = torch.tensor([1, 2, 3])
  428. >>> torch.is_tensor(x)
  429. True
  430. """
  431. return isinstance(obj, torch.Tensor)
  432. def is_storage(obj):
  433. r"""Returns True if `obj` is a PyTorch storage object.
  434. Args:
  435. obj (Object): Object to test
  436. """
  437. return type(obj) in _storage_classes
  438. _GLOBAL_DEVICE_CONTEXT = None
  439. def set_default_device(device):
  440. """Sets the default ``torch.Tensor`` to be allocated on ``device``. This
  441. does not affect factory function calls which are called with an explicit
  442. ``device`` argument. Factory calls will be performed as if they
  443. were passed ``device`` as an argument.
  444. To only temporarily change the default device instead of setting it
  445. globally, use ``with torch.device(device):`` instead.
  446. The default device is initially ``cpu``. If you set the default tensor
  447. device to another device (e.g., ``cuda``) without a device index, tensors
  448. will be allocated on whatever the current device for the device type,
  449. even after :func:`torch.cuda.set_device` is called.
  450. .. warning::
  451. This function imposes a slight performance cost on every Python
  452. call to the torch API (not just factory functions). If this
  453. is causing problems for you, please comment on
  454. https://github.com/pytorch/pytorch/issues/92701
  455. Args:
  456. device (device or string): the device to set as default
  457. Example::
  458. >>> # xdoctest: +SKIP("requires cuda, changes global state")
  459. >>> torch.tensor([1.2, 3]).device
  460. device(type='cpu')
  461. >>> torch.set_default_device('cuda') # current device is 0
  462. >>> torch.tensor([1.2, 3]).device
  463. device(type='cuda', index=0)
  464. >>> torch.set_default_device('cuda:1')
  465. >>> torch.tensor([1.2, 3]).device
  466. device(type='cuda', index=1)
  467. """
  468. global _GLOBAL_DEVICE_CONTEXT
  469. if _GLOBAL_DEVICE_CONTEXT is not None:
  470. _GLOBAL_DEVICE_CONTEXT.__exit__(None, None, None)
  471. if device is None:
  472. _GLOBAL_DEVICE_CONTEXT = None
  473. return
  474. from torch.utils._device import DeviceContext
  475. _GLOBAL_DEVICE_CONTEXT = DeviceContext(device)
  476. _GLOBAL_DEVICE_CONTEXT.__enter__()
  477. def set_default_tensor_type(t):
  478. r"""Sets the default ``torch.Tensor`` type to floating point tensor type
  479. ``t``. This type will also be used as default floating point type for
  480. type inference in :func:`torch.tensor`.
  481. The default floating point tensor type is initially ``torch.FloatTensor``.
  482. Args:
  483. t (type or string): the floating point tensor type or its name
  484. Example::
  485. >>> # xdoctest: +SKIP("Other tests may have changed the default type. Can we reset it?")
  486. >>> torch.tensor([1.2, 3]).dtype # initial default for floating point is torch.float32
  487. torch.float32
  488. >>> torch.set_default_tensor_type(torch.DoubleTensor)
  489. >>> torch.tensor([1.2, 3]).dtype # a new floating point tensor
  490. torch.float64
  491. """
  492. if isinstance(t, str):
  493. t = _import_dotted_name(t)
  494. _C._set_default_tensor_type(t)
  495. def set_default_dtype(d):
  496. r"""
  497. Sets the default floating point dtype to :attr:`d`. Supports torch.float32
  498. and torch.float64 as inputs. Other dtypes may be accepted without complaint
  499. but are not supported and are unlikely to work as expected.
  500. When PyTorch is initialized its default floating point dtype is torch.float32,
  501. and the intent of set_default_dtype(torch.float64) is to facilitate NumPy-like
  502. type inference. The default floating point dtype is used to:
  503. 1. Implicitly determine the default complex dtype. When the default floating point
  504. type is float32 the default complex dtype is complex64, and when the default
  505. floating point type is float64 the default complex type is complex128.
  506. 2. Infer the dtype for tensors constructed using Python floats or complex Python
  507. numbers. See examples below.
  508. 3. Determine the result of type promotion between bool and integer tensors and
  509. Python floats and complex Python numbers.
  510. Args:
  511. d (:class:`torch.dtype`): the floating point dtype to make the default.
  512. Either torch.float32 or torch.float64.
  513. Example:
  514. >>> # xdoctest: +SKIP("Other tests may have changed the default type. Can we reset it?")
  515. >>> # initial default for floating point is torch.float32
  516. >>> # Python floats are interpreted as float32
  517. >>> torch.tensor([1.2, 3]).dtype
  518. torch.float32
  519. >>> # initial default for floating point is torch.complex64
  520. >>> # Complex Python numbers are interpreted as complex64
  521. >>> torch.tensor([1.2, 3j]).dtype
  522. torch.complex64
  523. >>> torch.set_default_dtype(torch.float64)
  524. >>> # Python floats are now interpreted as float64
  525. >>> torch.tensor([1.2, 3]).dtype # a new floating point tensor
  526. torch.float64
  527. >>> # Complex Python numbers are now interpreted as complex128
  528. >>> torch.tensor([1.2, 3j]).dtype # a new complex tensor
  529. torch.complex128
  530. """
  531. _C._set_default_dtype(d)
  532. def use_deterministic_algorithms(mode, *, warn_only=False):
  533. r""" Sets whether PyTorch operations must use "deterministic"
  534. algorithms. That is, algorithms which, given the same input, and when
  535. run on the same software and hardware, always produce the same output.
  536. When enabled, operations will use deterministic algorithms when available,
  537. and if only nondeterministic algorithms are available they will throw a
  538. :class:`RuntimeError` when called.
  539. .. note:: This setting alone is not always enough to make an application
  540. reproducible. Refer to :ref:`reproducibility` for more information.
  541. .. note:: :func:`torch.set_deterministic_debug_mode` offers an alternative
  542. interface for this feature.
  543. The following normally-nondeterministic operations will act
  544. deterministically when ``mode=True``:
  545. * :class:`torch.nn.Conv1d` when called on CUDA tensor
  546. * :class:`torch.nn.Conv2d` when called on CUDA tensor
  547. * :class:`torch.nn.Conv3d` when called on CUDA tensor
  548. * :class:`torch.nn.ConvTranspose1d` when called on CUDA tensor
  549. * :class:`torch.nn.ConvTranspose2d` when called on CUDA tensor
  550. * :class:`torch.nn.ConvTranspose3d` when called on CUDA tensor
  551. * :func:`torch.bmm` when called on sparse-dense CUDA tensors
  552. * :func:`torch.Tensor.__getitem__` when attempting to differentiate a CPU tensor
  553. and the index is a list of tensors
  554. * :func:`torch.Tensor.index_put` with ``accumulate=False``
  555. * :func:`torch.Tensor.index_put` with ``accumulate=True`` when called on a CPU
  556. tensor
  557. * :func:`torch.Tensor.put_` with ``accumulate=True`` when called on a CPU
  558. tensor
  559. * :func:`torch.Tensor.scatter_add_` when called on a CUDA tensor
  560. * :func:`torch.gather` when called on a CUDA tensor that requires grad
  561. * :func:`torch.index_add` when called on CUDA tensor
  562. * :func:`torch.index_select` when attempting to differentiate a CUDA tensor
  563. * :func:`torch.repeat_interleave` when attempting to differentiate a CUDA tensor
  564. * :func:`torch.Tensor.index_copy` when called on a CPU or CUDA tensor
  565. The following normally-nondeterministic operations will throw a
  566. :class:`RuntimeError` when ``mode=True``:
  567. * :class:`torch.nn.AvgPool3d` when attempting to differentiate a CUDA tensor
  568. * :class:`torch.nn.AdaptiveAvgPool2d` when attempting to differentiate a CUDA tensor
  569. * :class:`torch.nn.AdaptiveAvgPool3d` when attempting to differentiate a CUDA tensor
  570. * :class:`torch.nn.MaxPool3d` when attempting to differentiate a CUDA tensor
  571. * :class:`torch.nn.AdaptiveMaxPool2d` when attempting to differentiate a CUDA tensor
  572. * :class:`torch.nn.FractionalMaxPool2d` when attempting to differentiate a CUDA tensor
  573. * :class:`torch.nn.FractionalMaxPool3d` when attempting to differentiate a CUDA tensor
  574. * :class:`torch.nn.MaxUnpool1d`
  575. * :class:`torch.nn.MaxUnpool2d`
  576. * :class:`torch.nn.MaxUnpool3d`
  577. * :func:`torch.nn.functional.interpolate` when attempting to differentiate a CUDA tensor
  578. and one of the following modes is used:
  579. - ``linear``
  580. - ``bilinear``
  581. - ``bicubic``
  582. - ``trilinear``
  583. * :class:`torch.nn.ReflectionPad1d` when attempting to differentiate a CUDA tensor
  584. * :class:`torch.nn.ReflectionPad2d` when attempting to differentiate a CUDA tensor
  585. * :class:`torch.nn.ReflectionPad3d` when attempting to differentiate a CUDA tensor
  586. * :class:`torch.nn.ReplicationPad1d` when attempting to differentiate a CUDA tensor
  587. * :class:`torch.nn.ReplicationPad2d` when attempting to differentiate a CUDA tensor
  588. * :class:`torch.nn.ReplicationPad3d` when attempting to differentiate a CUDA tensor
  589. * :class:`torch.nn.NLLLoss` when called on a CUDA tensor
  590. * :class:`torch.nn.CTCLoss` when attempting to differentiate a CUDA tensor
  591. * :class:`torch.nn.EmbeddingBag` when attempting to differentiate a CUDA tensor when
  592. ``mode='max'``
  593. * :func:`torch.Tensor.put_` when ``accumulate=False``
  594. * :func:`torch.Tensor.put_` when ``accumulate=True`` and called on a CUDA tensor
  595. * :func:`torch.histc` when called on a CUDA tensor
  596. * :func:`torch.bincount` when called on a CUDA tensor
  597. * :func:`torch.kthvalue` with called on a CUDA tensor
  598. * :func:`torch.median` with indices output when called on a CUDA tensor
  599. * :func:`torch.nn.functional.grid_sample` when attempting to differentiate a CUDA tensor
  600. * :func:`torch.cumsum` when called on a CUDA tensor when dtype is floating point or complex
  601. A handful of CUDA operations are nondeterministic if the CUDA version is
  602. 10.2 or greater, unless the environment variable ``CUBLAS_WORKSPACE_CONFIG=:4096:8``
  603. or ``CUBLAS_WORKSPACE_CONFIG=:16:8`` is set. See the CUDA documentation for more
  604. details: `<https://docs.nvidia.com/cuda/cublas/index.html#cublasApi_reproducibility>`_
  605. If one of these environment variable configurations is not set, a :class:`RuntimeError`
  606. will be raised from these operations when called with CUDA tensors:
  607. * :func:`torch.mm`
  608. * :func:`torch.mv`
  609. * :func:`torch.bmm`
  610. Note that deterministic operations tend to have worse performance than
  611. nondeterministic operations.
  612. .. note::
  613. This flag does not detect or prevent nondeterministic behavior caused
  614. by calling an inplace operation on a tensor with an internal memory
  615. overlap or by giving such a tensor as the :attr:`out` argument for an
  616. operation. In these cases, multiple writes of different data may target
  617. a single memory location, and the order of writes is not guaranteed.
  618. Args:
  619. mode (:class:`bool`): If True, makes potentially nondeterministic
  620. operations switch to a deterministic algorithm or throw a runtime
  621. error. If False, allows nondeterministic operations.
  622. Keyword args:
  623. warn_only (:class:`bool`, optional): If True, operations that do not
  624. have a deterministic implementation will throw a warning instead of
  625. an error. Default: ``False``
  626. Example::
  627. >>> # xdoctest: +SKIP
  628. >>> torch.use_deterministic_algorithms(True)
  629. # Forward mode nondeterministic error
  630. >>> torch.randn(10, device='cuda').kthvalue(0)
  631. ...
  632. RuntimeError: kthvalue CUDA does not have a deterministic implementation...
  633. # Backward mode nondeterministic error
  634. >>> torch.nn.AvgPool3d(1)(torch.randn(3, 4, 5, 6, requires_grad=True).cuda()).sum().backward()
  635. ...
  636. RuntimeError: avg_pool3d_backward_cuda does not have a deterministic implementation...
  637. """
  638. _C._set_deterministic_algorithms(mode, warn_only=warn_only)
  639. def are_deterministic_algorithms_enabled():
  640. r"""Returns True if the global deterministic flag is turned on. Refer to
  641. :func:`torch.use_deterministic_algorithms` documentation for more details.
  642. """
  643. return _C._get_deterministic_algorithms()
  644. def is_deterministic_algorithms_warn_only_enabled():
  645. r"""Returns True if the global deterministic flag is set to warn only.
  646. Refer to :func:`torch.use_deterministic_algorithms` documentation for more
  647. details.
  648. """
  649. return _C._get_deterministic_algorithms_warn_only()
  650. def set_deterministic_debug_mode(debug_mode: Union[builtins.int, str]) -> None:
  651. r"""Sets the debug mode for deterministic operations.
  652. .. note:: This is an alternative interface for
  653. :func:`torch.use_deterministic_algorithms`. Refer to that function's
  654. documentation for details about affected operations.
  655. Args:
  656. debug_mode(str or int): If "default" or 0, don't error or warn on
  657. nondeterministic operations. If "warn" or 1, warn on
  658. nondeterministic operations. If "error" or 2, error on
  659. nondeterministic operations.
  660. """
  661. # NOTE: builtins.int is used here because int in this scope resolves
  662. # to torch.int
  663. if not isinstance(debug_mode, (builtins.int, str)):
  664. raise TypeError(f'debug_mode must be str or int, but got {type(debug_mode)}')
  665. if isinstance(debug_mode, str):
  666. if debug_mode == 'default':
  667. debug_mode = 0
  668. elif debug_mode == 'warn':
  669. debug_mode = 1
  670. elif debug_mode == 'error':
  671. debug_mode = 2
  672. else:
  673. raise RuntimeError(
  674. 'invalid value of debug_mode, expected one of `default`, '
  675. f'`warn`, `error`, but got {debug_mode}')
  676. if debug_mode == 0:
  677. _C._set_deterministic_algorithms(False)
  678. elif debug_mode == 1:
  679. _C._set_deterministic_algorithms(True, warn_only=True)
  680. elif debug_mode == 2:
  681. _C._set_deterministic_algorithms(True)
  682. else:
  683. raise RuntimeError(
  684. 'invalid value of debug_mode, expected 0, 1, or 2, '
  685. f'but got {debug_mode}')
  686. def get_deterministic_debug_mode() -> builtins.int:
  687. r"""Returns the current value of the debug mode for deterministic
  688. operations. Refer to :func:`torch.set_deterministic_debug_mode`
  689. documentation for more details.
  690. """
  691. if _C._get_deterministic_algorithms():
  692. if _C._get_deterministic_algorithms_warn_only():
  693. return 1
  694. else:
  695. return 2
  696. else:
  697. return 0
  698. def get_float32_matmul_precision() -> builtins.str:
  699. r"""Returns the current value of float32 matrix multiplication precision. Refer to
  700. :func:`torch.set_float32_matmul_precision` documentation for more details.
  701. """
  702. return _C._get_float32_matmul_precision()
  703. def set_float32_matmul_precision(precision):
  704. r"""Sets the internal precision of float32 matrix multiplications.
  705. Running float32 matrix multiplications in lower precision may significantly increase
  706. performance, and in some programs the loss of precision has a negligible impact.
  707. Supports three settings:
  708. * "highest", float32 matrix multiplications use the float32 datatype for
  709. internal computations.
  710. * "high", float32 matrix multiplications use the TensorFloat32 or bfloat16_3x
  711. datatypes for internal computations, if fast matrix multiplication algorithms
  712. using those datatypes internally are available. Otherwise float32
  713. matrix multiplications are computed as if the precision is "highest".
  714. * "medium", float32 matrix multiplications use the bfloat16 datatype for
  715. internal computations, if a fast matrix multiplication algorithm
  716. using that datatype internally is available. Otherwise float32
  717. matrix multiplications are computed as if the precision is "high".
  718. .. note::
  719. This does not change the output dtype of float32 matrix multiplications,
  720. it controls how the internal computation of the matrix multiplication is performed.
  721. .. note::
  722. This does not change the precision of convolution operations. Other flags,
  723. like `torch.backends.cudnn.allow_tf32`, may control the precision of convolution
  724. operations.
  725. .. note::
  726. This flag currently only affects one native device type: CUDA.
  727. If "high" or "medium" are set then the TensorFloat32 datatype will be used
  728. when computing float32 matrix multiplications, equivalent to setting
  729. `torch.backends.cuda.matmul.allow_tf32 = True`. When "highest" (the default)
  730. is set then the float32 datatype is used for internal computations, equivalent
  731. to setting `torch.backends.cuda.matmul.allow_tf32 = False`.
  732. Args:
  733. precision(str): can be set to "highest" (default), "high", or "medium" (see above).
  734. """
  735. _C._set_float32_matmul_precision(precision)
  736. def set_warn_always(b):
  737. r"""When this flag is False (default) then some PyTorch warnings may only
  738. appear once per process. This helps avoid excessive warning information.
  739. Setting it to True causes these warnings to always appear, which may be
  740. helpful when debugging.
  741. Args:
  742. b (:class:`bool`): If True, force warnings to always be emitted
  743. If False, set to the default behaviour
  744. """
  745. _C._set_warnAlways(b)
  746. def is_warn_always_enabled():
  747. r"""Returns True if the global warn_always flag is turned on. Refer to
  748. :func:`torch.set_warn_always` documentation for more details.
  749. """
  750. return _C._get_warnAlways()
  751. ################################################################################
  752. # Define numeric constants
  753. ################################################################################
  754. # For Python Array API (https://data-apis.org/array-api/latest/API_specification/constants.html) and
  755. # NumPy consistency (https://numpy.org/devdocs/reference/constants.html)
  756. from math import e , nan , inf , pi
  757. __all__.extend(['e', 'pi', 'nan', 'inf'])
  758. ################################################################################
  759. # Define Storage and Tensor classes
  760. ################################################################################
  761. from ._tensor import Tensor
  762. from .storage import _StorageBase, TypedStorage, _LegacyStorage, UntypedStorage, _warn_typed_storage_removal
  763. # NOTE: New <type>Storage classes should never be added. When adding a new
  764. # dtype, use torch.storage.TypedStorage directly.
  765. class ByteStorage(_LegacyStorage):
  766. @classproperty
  767. def dtype(self):
  768. _warn_typed_storage_removal()
  769. return self._dtype
  770. @classproperty
  771. def _dtype(self):
  772. return torch.uint8
  773. class DoubleStorage(_LegacyStorage):
  774. @classproperty
  775. def dtype(self):
  776. _warn_typed_storage_removal()
  777. return self._dtype
  778. @classproperty
  779. def _dtype(self):
  780. return torch.double
  781. class FloatStorage(_LegacyStorage):
  782. @classproperty
  783. def dtype(self):
  784. _warn_typed_storage_removal()
  785. return self._dtype
  786. @classproperty
  787. def _dtype(self):
  788. return torch.float
  789. class HalfStorage(_LegacyStorage):
  790. @classproperty
  791. def dtype(self):
  792. _warn_typed_storage_removal()
  793. return self._dtype
  794. @classproperty
  795. def _dtype(self):
  796. return torch.half
  797. class LongStorage(_LegacyStorage):
  798. @classproperty
  799. def dtype(self):
  800. _warn_typed_storage_removal()
  801. return self._dtype
  802. @classproperty
  803. def _dtype(self):
  804. return torch.long
  805. class IntStorage(_LegacyStorage):
  806. @classproperty
  807. def dtype(self):
  808. _warn_typed_storage_removal()
  809. return self._dtype
  810. @classproperty
  811. def _dtype(self):
  812. return torch.int
  813. class ShortStorage(_LegacyStorage):
  814. @classproperty
  815. def dtype(self):
  816. _warn_typed_storage_removal()
  817. return self._dtype
  818. @classproperty
  819. def _dtype(self):
  820. return torch.short
  821. class CharStorage(_LegacyStorage):
  822. @classproperty
  823. def dtype(self):
  824. _warn_typed_storage_removal()
  825. return self._dtype
  826. @classproperty
  827. def _dtype(self):
  828. return torch.int8
  829. class BoolStorage(_LegacyStorage):
  830. @classproperty
  831. def dtype(self):
  832. _warn_typed_storage_removal()
  833. return self._dtype
  834. @classproperty
  835. def _dtype(self):
  836. return torch.bool
  837. class BFloat16Storage(_LegacyStorage):
  838. @classproperty
  839. def dtype(self):
  840. _warn_typed_storage_removal()
  841. return self._dtype
  842. @classproperty
  843. def _dtype(self):
  844. return torch.bfloat16
  845. class ComplexDoubleStorage(_LegacyStorage):
  846. @classproperty
  847. def dtype(self):
  848. _warn_typed_storage_removal()
  849. return self._dtype
  850. @classproperty
  851. def _dtype(self):
  852. return torch.cdouble
  853. class ComplexFloatStorage(_LegacyStorage):
  854. @classproperty
  855. def dtype(self):
  856. _warn_typed_storage_removal()
  857. return self._dtype
  858. @classproperty
  859. def _dtype(self):
  860. return torch.cfloat
  861. class QUInt8Storage(_LegacyStorage):
  862. @classproperty
  863. def dtype(self):
  864. _warn_typed_storage_removal()
  865. return self._dtype
  866. @classproperty
  867. def _dtype(self):
  868. return torch.quint8
  869. class QInt8Storage(_LegacyStorage):
  870. @classproperty
  871. def dtype(self):
  872. _warn_typed_storage_removal()
  873. return self._dtype
  874. @classproperty
  875. def _dtype(self):
  876. return torch.qint8
  877. class QInt32Storage(_LegacyStorage):
  878. @classproperty
  879. def dtype(self):
  880. _warn_typed_storage_removal()
  881. return self._dtype
  882. @classproperty
  883. def _dtype(self):
  884. return torch.qint32
  885. class QUInt4x2Storage(_LegacyStorage):
  886. @classproperty
  887. def dtype(self):
  888. _warn_typed_storage_removal()
  889. return self._dtype
  890. @classproperty
  891. def _dtype(self):
  892. return torch.quint4x2
  893. class QUInt2x4Storage(_LegacyStorage):
  894. @classproperty
  895. def dtype(self):
  896. _warn_typed_storage_removal()
  897. return self._dtype
  898. @classproperty
  899. def _dtype(self):
  900. return torch.quint2x4
  901. _storage_classes = {
  902. UntypedStorage, DoubleStorage, FloatStorage, LongStorage, IntStorage,
  903. ShortStorage, CharStorage, ByteStorage, HalfStorage, BoolStorage,
  904. QUInt8Storage, QInt8Storage, QInt32Storage, BFloat16Storage,
  905. ComplexFloatStorage, ComplexDoubleStorage, QUInt4x2Storage, QUInt2x4Storage,
  906. TypedStorage
  907. }
  908. # The _tensor_classes set is initialized by the call to _C._initialize_tensor_type_bindings()
  909. _tensor_classes: Set[Type] = set()
  910. # If you edit these imports, please update torch/__init__.py.in as well
  911. from .random import set_rng_state, get_rng_state, manual_seed, initial_seed, seed
  912. from .serialization import save, load
  913. from ._tensor_str import set_printoptions
  914. ################################################################################
  915. # Initialize extension
  916. ################################################################################
  917. def manager_path():
  918. if sys.executable == 'torch_deploy' or platform.system() == 'Windows':
  919. return b""
  920. path = get_file_path('torch', 'bin', 'torch_shm_manager')
  921. prepare_multiprocessing_environment(get_file_path('torch'))
  922. if not os.path.exists(path):
  923. raise RuntimeError("Unable to find torch_shm_manager at " + path)
  924. return path.encode('utf-8')
  925. from torch.amp import autocast
  926. # Initializing the extension shadows the built-in python float / int classes;
  927. # store them for later use by SymInt / SymFloat.
  928. py_float = float
  929. py_int = int
  930. # Shared memory manager needs to know the exact location of manager executable
  931. _C._initExtension(manager_path())
  932. del manager_path
  933. # Appease the type checker: it can't deal with direct setting of globals().
  934. # Note that we will see "too many" functions when reexporting this way; there
  935. # is not a good way to fix this problem. Perhaps, try to redesign VariableFunctions
  936. # so that this import is good enough
  937. if TYPE_CHECKING:
  938. # Some type signatures pulled in from _VariableFunctions here clash with
  939. # signatures already imported. For now these clashes are ignored; see
  940. # PR #43339 for details.
  941. from torch._C._VariableFunctions import * # type: ignore[misc] # noqa: F403
  942. # Fixup segment_reduce visibility
  943. _segment_reduce = segment_reduce
  944. del segment_reduce
  945. # Ops not to be exposed in `torch` namespace,
  946. # mostly helper ops.
  947. PRIVATE_OPS = (
  948. 'unique_dim',
  949. )
  950. for name in dir(_C._VariableFunctions):
  951. if name.startswith('__') or name in PRIVATE_OPS:
  952. continue
  953. obj = getattr(_C._VariableFunctions, name)
  954. obj.__module__ = 'torch'
  955. # Hide some APIs that should not be public
  956. if name == "segment_reduce":
  957. # TODO: Once the undocumented FC window is passed, remove the line bellow
  958. globals()[name] = obj
  959. name = "_" + name
  960. globals()[name] = obj
  961. if not name.startswith("_"):
  962. __all__.append(name)
  963. ################################################################################
  964. # Import interface functions defined in Python
  965. ################################################################################
  966. # needs to be after the above ATen bindings so we can overwrite from Python side
  967. from .functional import * # noqa: F403
  968. ################################################################################
  969. # Remove unnecessary members
  970. ################################################################################
  971. del _StorageBase
  972. del _LegacyStorage
  973. ################################################################################
  974. # Define _assert
  975. ################################################################################
  976. # needs to be before the submodule imports to avoid circular dependencies
  977. def _assert(condition, message):
  978. r"""A wrapper around Python's assert which is symbolically traceable.
  979. """
  980. from .overrides import has_torch_function, handle_torch_function
  981. if type(condition) is not torch.Tensor and has_torch_function((condition,)):
  982. return handle_torch_function(_assert, (condition,), condition, message)
  983. assert condition, message
  984. ################################################################################
  985. # Import most common subpackages
  986. ################################################################################
  987. # Use the redundant form so that type checkers know that these are a part of
  988. # the public API. The "regular" import lines are there solely for the runtime
  989. # side effect of adding to the imported module's members for other users.
  990. from torch import cuda as cuda
  991. from torch import cpu as cpu
  992. from torch import autograd as autograd
  993. from torch.autograd import (
  994. no_grad as no_grad,
  995. enable_grad as enable_grad,
  996. set_grad_enabled as set_grad_enabled,
  997. inference_mode as inference_mode,
  998. )
  999. from torch import fft as fft
  1000. from torch import futures as futures
  1001. from torch import _awaits as _awaits
  1002. from torch import nested as nested
  1003. from torch import nn as nn
  1004. from torch.signal import windows as windows
  1005. from torch import optim as optim
  1006. import torch.optim._multi_tensor
  1007. from torch import multiprocessing as multiprocessing
  1008. from torch import sparse as sparse
  1009. from torch import special as special
  1010. import torch.utils.backcompat
  1011. from torch import onnx as onnx
  1012. from torch import jit as jit
  1013. from torch import linalg as linalg
  1014. from torch import hub as hub
  1015. from torch import random as random
  1016. from torch import distributions as distributions
  1017. from torch import testing as testing
  1018. import torch.backends.cuda
  1019. import torch.backends.mps
  1020. import torch.backends.cudnn
  1021. import torch.backends.mkl
  1022. import torch.backends.mkldnn
  1023. import torch.backends.openmp
  1024. import torch.backends.quantized
  1025. import torch.utils.data
  1026. from torch import __config__ as __config__
  1027. from torch import __future__ as __future__
  1028. from torch import profiler as profiler
  1029. # Quantized, sparse, AO, etc. should be last to get imported, as nothing
  1030. # is expected to depend on them.
  1031. from torch import ao as ao
  1032. # nn.quant* depends on ao -- so should be after those.
  1033. import torch.nn.quantizable
  1034. import torch.nn.quantized
  1035. import torch.nn.qat
  1036. import torch.nn.intrinsic
  1037. _C._init_names(list(torch._storage_classes))
  1038. # attach docstrings to torch and tensor functions
  1039. from . import _torch_docs, _tensor_docs, _storage_docs
  1040. del _torch_docs, _tensor_docs, _storage_docs
  1041. def compiled_with_cxx11_abi():
  1042. r"""Returns whether PyTorch was built with _GLIBCXX_USE_CXX11_ABI=1"""
  1043. return _C._GLIBCXX_USE_CXX11_ABI
  1044. # Import the ops "namespace"
  1045. from torch._ops import ops
  1046. from torch._classes import classes
  1047. # quantization depends on torch.fx
  1048. # Import quantization
  1049. from torch import quantization as quantization
  1050. # Import the quasi random sampler
  1051. from torch import quasirandom as quasirandom
  1052. # If you are seeing this, it means that this call site was not checked if
  1053. # the memory format could be preserved, and it was switched to old default
  1054. # behaviour of contiguous
  1055. legacy_contiguous_format = contiguous_format
  1056. # Register fork handler to initialize OpenMP in child processes (see gh-28389)
  1057. from torch.multiprocessing._atfork import register_after_fork
  1058. register_after_fork(torch.get_num_threads)
  1059. del register_after_fork
  1060. # Import tools that require fully imported torch (for applying
  1061. # torch.jit.script as a decorator, for instance):
  1062. from ._lobpcg import lobpcg as lobpcg
  1063. # These were previously defined in native_functions.yaml and appeared on the
  1064. # `torch` namespace, but we moved them to c10 dispatch to facilitate custom
  1065. # class usage. We add these lines here to preserve backward compatibility.
  1066. quantized_lstm = torch.ops.aten.quantized_lstm
  1067. quantized_gru = torch.ops.aten.quantized_gru
  1068. from torch.utils.dlpack import from_dlpack, to_dlpack
  1069. # Import experimental masked operations support. See
  1070. # [RFC-0016](https://github.com/pytorch/rfcs/pull/27) for more
  1071. # information.
  1072. from . import masked
  1073. # Import removed ops with error message about removal
  1074. from ._linalg_utils import ( # type: ignore[misc]
  1075. matrix_rank,
  1076. eig,
  1077. solve,
  1078. lstsq,
  1079. )
  1080. from ._linalg_utils import _symeig as symeig # type: ignore[misc]
  1081. class _TorchCompileInductorWrapper:
  1082. compiler_name = "inductor"
  1083. def __init__(self, mode, options, dynamic):
  1084. self.config = dict()
  1085. self.dynamic = dynamic
  1086. self.apply_mode(mode)
  1087. self.apply_options(options)
  1088. if dynamic:
  1089. # cudagraphs conflicts with dynamic shapes
  1090. self.config["triton.cudagraphs"] = False
  1091. assert "triton.cudagraphs" not in (
  1092. options or ()
  1093. ), "triton.cudagraphs does not support dynamic shapes"
  1094. def __eq__(self, other):
  1095. return (isinstance(other, _TorchCompileInductorWrapper) and
  1096. self.config == other.config and
  1097. self.dynamic == other.dynamic)
  1098. def apply_mode(self, mode: Optional[str]):
  1099. if mode is None or mode == "default":
  1100. pass
  1101. elif mode == "reduce-overhead":
  1102. self.apply_options({
  1103. "triton.cudagraphs": True,
  1104. "size_asserts": False,
  1105. })
  1106. elif mode == "max-autotune":
  1107. self.apply_options({
  1108. "epilogue_fusion": True,
  1109. "max_autotune": True,
  1110. "triton.cudagraphs": True,
  1111. })
  1112. else:
  1113. raise RuntimeError(
  1114. f"Unrecognized mode={mode}, should be one of: default, reduce-overhead, max-autotune"
  1115. )
  1116. def apply_options(self, options: Optional[Dict[str, Any]]):
  1117. if not options:
  1118. return
  1119. from torch._inductor import config
  1120. current_config: Dict[str, Any] = config.to_dict() # type: ignore[attr-defined]
  1121. for key, val in options.items():
  1122. attr_name = key.replace("-", "_")
  1123. if attr_name not in current_config:
  1124. raise RuntimeError(
  1125. f"Unexpected optimization option {key}, known options are {list(current_config.keys())}"
  1126. )
  1127. if type(val) is not type(current_config[attr_name]):
  1128. val_type_str = type(val).__name__
  1129. expected_type_str = type(current_config[attr_name]).__name__
  1130. raise RuntimeError(
  1131. f"Unexpected type of attr {key}, got {val_type_str} should be {expected_type_str}"
  1132. )
  1133. self.config[attr_name] = val
  1134. def __call__(self, model_, inputs_):
  1135. from torch._inductor.compile_fx import compile_fx
  1136. return compile_fx(model_, inputs_, config_patches=self.config)
  1137. def compile(model: Optional[Callable] = None, *,
  1138. fullgraph: builtins.bool = False,
  1139. dynamic: builtins.bool = False,
  1140. backend: Union[str, Callable] = "inductor",
  1141. mode: Union[str, None] = None,
  1142. options: Optional[Dict[str, Union[str, builtins.int, builtins.bool]]] = None,
  1143. disable: builtins.bool = False) -> Callable:
  1144. """
  1145. Optimizes given model/function using TorchDynamo and specified backend.
  1146. Args:
  1147. model (Callable): Module/function to optimize
  1148. fullgraph (bool): Whether it is ok to break model into several subgraphs
  1149. dynamic (bool): Use dynamic shape tracing
  1150. backend (str or Callable): backend to be used
  1151. mode (str): Can be either "default", "reduce-overhead" or "max-autotune"
  1152. options (dict): A dictionary of options to pass to the backend.
  1153. disable (bool): Turn torch.compile() into a no-op for testing
  1154. Example::
  1155. @torch.compile(options={"matmul-padding": True}, fullgraph=True)
  1156. def foo(x):
  1157. return torch.sin(x) + torch.cos(x)
  1158. """
  1159. _C._log_api_usage_once("torch.compile")
  1160. # Decorator mode
  1161. if model is None:
  1162. def fn(model: Callable):
  1163. if model is None:
  1164. raise RuntimeError("Model can't be None")
  1165. return compile(model,
  1166. fullgraph=fullgraph,
  1167. dynamic=dynamic,
  1168. backend=backend,
  1169. mode=mode,
  1170. options=options,
  1171. disable=disable)
  1172. return fn
  1173. import torch._dynamo
  1174. if mode is not None and options is not None:
  1175. raise RuntimeError("Either mode or options can be specified, but both can't be specified at the same time.")
  1176. if mode is None and options is None:
  1177. mode = "default"
  1178. if backend == "inductor":
  1179. backend = _TorchCompileInductorWrapper(mode, options, dynamic)
  1180. return torch._dynamo.optimize(backend=backend, nopython=fullgraph, dynamic=dynamic, disable=disable)(model)
  1181. def _register_device_module(device_type, module):
  1182. r"""Register an external runtime module of the specific :attr:`device_type`
  1183. supported by torch.
  1184. After the :attr:`module` is registered correctly, the user can refer
  1185. the external runtime module as part of torch with attribute torch.xxx.
  1186. """
  1187. # Make sure the device_type represent a supported device type for torch.
  1188. device_type = torch.device(device_type).type
  1189. m = sys.modules[__name__]
  1190. if hasattr(m, device_type):
  1191. raise RuntimeError("The runtime module of '{}' has already "
  1192. "been registered with '{}'".format(device_type, getattr(m, device_type)))
  1193. setattr(m, device_type, module)
  1194. torch_module_name = '.'.join([__name__, device_type])
  1195. sys.modules[torch_module_name] = module
  1196. # expose return_types
  1197. from . import return_types
  1198. from . import library
  1199. if not TYPE_CHECKING:
  1200. from . import _meta_registrations
  1201. # Enable CUDA Sanitizer
  1202. if 'TORCH_CUDA_SANITIZER' in os.environ:
  1203. import torch.cuda._sanitizer as csan
  1204. csan.enable_cuda_sanitizer()
  1205. # Populate magic methods on SymInt and SymFloat
  1206. import torch.fx.experimental.symbolic_shapes
  1207. from torch import func as func
  1208. from torch.func import vmap
  1209. # The function _sparse_coo_tensor_unsafe is removed from PyTorch
  1210. # Python API (v. 1.13), here we temporarily provide its replacement
  1211. # with a deprecation warning.
  1212. # TODO: remove the function for PyTorch v 1.15.
  1213. def _sparse_coo_tensor_unsafe(*args, **kwargs):
  1214. import warnings
  1215. warnings.warn('torch._sparse_coo_tensor_unsafe is deprecated, '
  1216. 'use torch.sparse_coo_tensor(..., check_invariants=False) instead.')
  1217. kwargs['check_invariants'] = False
  1218. return torch.sparse_coo_tensor(*args, **kwargs)