__init__.py 101 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878
  1. """
  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. # mypy: allow-untyped-defs
  10. import builtins
  11. import ctypes
  12. import functools
  13. import glob
  14. import importlib
  15. import inspect
  16. import math
  17. import os
  18. import platform
  19. import sys
  20. import textwrap
  21. import threading
  22. from typing import (
  23. Any as _Any,
  24. Callable as _Callable,
  25. get_origin as _get_origin,
  26. Optional as _Optional,
  27. overload as _overload,
  28. TYPE_CHECKING,
  29. TypeVar as _TypeVar,
  30. Union as _Union,
  31. )
  32. from typing_extensions import ParamSpec as _ParamSpec, TypeIs as _TypeIs
  33. # As a bunch of torch.packages internally still have this check
  34. # we need to keep this. @todo: Remove tests that rely on this check as
  35. # they are likely stale.
  36. def _running_with_deploy() -> builtins.bool:
  37. return False
  38. from torch._utils import (
  39. _functionalize_sync as _sync,
  40. _import_dotted_name,
  41. classproperty,
  42. )
  43. from torch._utils_internal import (
  44. get_file_path,
  45. prepare_multiprocessing_environment,
  46. profiler_allow_cudagraph_cupti_lazy_reinit_cuda12,
  47. USE_GLOBAL_DEPS,
  48. USE_RTLD_GLOBAL_WITH_LIBTORCH,
  49. )
  50. from torch.torch_version import __version__ as __version__
  51. if TYPE_CHECKING:
  52. from torch.types import Device, IntLikeType
  53. __all__ = [
  54. "BoolStorage",
  55. "BoolTensor",
  56. "ByteStorage",
  57. "ByteTensor",
  58. "CharStorage",
  59. "CharTensor",
  60. "DoubleStorage",
  61. "DoubleTensor",
  62. "FloatStorage",
  63. "FloatTensor",
  64. "GradScaler",
  65. "IntStorage",
  66. "IntTensor",
  67. "LongStorage",
  68. "LongTensor",
  69. "ShortStorage",
  70. "ShortTensor",
  71. "SymBool",
  72. "SymFloat",
  73. "SymInt",
  74. "Tensor",
  75. "TypedStorage",
  76. "UntypedStorage",
  77. "are_deterministic_algorithms_enabled",
  78. "autocast",
  79. "chunk",
  80. "compile",
  81. "cond",
  82. "enable_grad",
  83. "export",
  84. "get_default_device",
  85. "get_deterministic_debug_mode",
  86. "get_device_module",
  87. "get_float32_matmul_precision",
  88. "get_rng_state",
  89. "inference_mode",
  90. "initial_seed",
  91. "is_deterministic_algorithms_warn_only_enabled",
  92. "is_storage",
  93. "is_tensor",
  94. "is_warn_always_enabled",
  95. "load",
  96. "lobpcg",
  97. "manual_seed",
  98. "matmul",
  99. "no_grad",
  100. "rand",
  101. "randn",
  102. "save",
  103. "seed",
  104. "set_default_device",
  105. "set_default_tensor_type",
  106. "set_deterministic_debug_mode",
  107. "set_float32_matmul_precision",
  108. "set_printoptions",
  109. "set_rng_state",
  110. "set_warn_always",
  111. "split",
  112. "stack",
  113. "sym_float",
  114. "sym_fresh_size",
  115. "sym_int",
  116. "sym_ite",
  117. "sym_max",
  118. "sym_min",
  119. "sym_not",
  120. "sym_sum",
  121. "typename",
  122. "unravel_index",
  123. "use_deterministic_algorithms",
  124. "vmap",
  125. ]
  126. # Please keep this list sorted
  127. assert __all__ == sorted(__all__)
  128. ################################################################################
  129. # Load the extension module
  130. ################################################################################
  131. # If PyTorch was built against the ROCm runtime wheels, then there will be
  132. # a _rocm_init module and it will define an initialize() function which can
  133. # prepare ROCm for use. See general documentation on ROCm runtime wheels:
  134. # https://github.com/ROCm/TheRock/blob/main/docs/packaging/python_packaging.md
  135. # Since this module is only ever added to the wheel if built for such a
  136. # deployment, it is always safe to attempt.
  137. try:
  138. from . import _rocm_init # type: ignore[attr-defined]
  139. except ImportError:
  140. pass
  141. else:
  142. _rocm_init.initialize()
  143. del _rocm_init
  144. if sys.platform == "win32":
  145. def _load_dll_libraries() -> None:
  146. import sysconfig
  147. from torch.version import cuda as cuda_version
  148. pfiles_path = os.getenv("ProgramFiles", r"C:\Program Files")
  149. py_dll_path = os.path.join(sys.exec_prefix, "Library", "bin")
  150. th_dll_path = os.path.join(os.path.dirname(__file__), "lib")
  151. usebase_path = os.path.join(
  152. sysconfig.get_config_var("userbase"), "Library", "bin"
  153. )
  154. py_root_bin_path = os.path.join(sys.exec_prefix, "bin")
  155. # When users create a virtualenv that inherits the base environment,
  156. # we will need to add the corresponding library directory into
  157. # DLL search directories. Otherwise, it will rely on `PATH` which
  158. # is dependent on user settings.
  159. if sys.exec_prefix != sys.base_exec_prefix:
  160. base_py_dll_path = os.path.join(sys.base_exec_prefix, "Library", "bin")
  161. else:
  162. base_py_dll_path = ""
  163. dll_paths = [
  164. p
  165. for p in (
  166. th_dll_path,
  167. py_dll_path,
  168. base_py_dll_path,
  169. usebase_path,
  170. py_root_bin_path,
  171. )
  172. if os.path.exists(p)
  173. ]
  174. if not builtins.any(
  175. os.path.exists(os.path.join(p, "nvToolsExt64_1.dll")) for p in dll_paths
  176. ):
  177. nvtoolsext_dll_path = os.path.join(
  178. os.getenv(
  179. "NVTOOLSEXT_PATH",
  180. os.path.join(pfiles_path, "NVIDIA Corporation", "NvToolsExt"),
  181. ),
  182. "bin",
  183. "x64",
  184. )
  185. else:
  186. nvtoolsext_dll_path = ""
  187. if cuda_version and builtins.all(
  188. not glob.glob(os.path.join(p, "cudart64*.dll")) for p in dll_paths
  189. ):
  190. cuda_version_1 = cuda_version.replace(".", "_")
  191. cuda_path_var = "CUDA_PATH_V" + cuda_version_1
  192. default_path = os.path.join(
  193. pfiles_path, "NVIDIA GPU Computing Toolkit", "CUDA", f"v{cuda_version}"
  194. )
  195. cuda_path = os.path.join(os.getenv(cuda_path_var, default_path), "bin")
  196. else:
  197. cuda_path = ""
  198. dll_paths.extend(
  199. p for p in (nvtoolsext_dll_path, cuda_path) if os.path.exists(p)
  200. )
  201. kernel32 = ctypes.WinDLL("kernel32.dll", use_last_error=True)
  202. with_load_library_flags = hasattr(kernel32, "AddDllDirectory")
  203. prev_error_mode = kernel32.SetErrorMode(0x0001)
  204. kernel32.LoadLibraryW.restype = ctypes.c_void_p
  205. if with_load_library_flags:
  206. kernel32.LoadLibraryExW.restype = ctypes.c_void_p
  207. for dll_path in dll_paths:
  208. os.add_dll_directory(dll_path)
  209. try:
  210. ctypes.CDLL("vcruntime140.dll")
  211. ctypes.CDLL("msvcp140.dll")
  212. if platform.machine() != "ARM64":
  213. ctypes.CDLL("vcruntime140_1.dll")
  214. except OSError:
  215. print(
  216. textwrap.dedent(
  217. """
  218. Microsoft Visual C++ Redistributable is not installed, this may lead to the DLL load failure.
  219. It can be downloaded at https://aka.ms/vs/17/release/vc_redist.x64.exe
  220. """
  221. ).strip()
  222. )
  223. dlls = glob.glob(os.path.join(th_dll_path, "*.dll"))
  224. path_patched = False
  225. for dll in dlls:
  226. is_loaded = False
  227. if with_load_library_flags:
  228. res = kernel32.LoadLibraryExW(dll, None, 0x00001100)
  229. last_error = ctypes.get_last_error()
  230. if res is None and last_error != 126:
  231. err = ctypes.WinError(last_error)
  232. err.strerror += (
  233. f' Error loading "{dll}" or one of its dependencies.'
  234. )
  235. raise err
  236. elif res is not None:
  237. is_loaded = True
  238. if not is_loaded:
  239. if not path_patched:
  240. os.environ["PATH"] = ";".join(dll_paths + [os.environ["PATH"]])
  241. path_patched = True
  242. res = kernel32.LoadLibraryW(dll)
  243. if res is None:
  244. err = ctypes.WinError(ctypes.get_last_error())
  245. err.strerror += (
  246. f' Error loading "{dll}" or one of its dependencies.'
  247. )
  248. raise err
  249. kernel32.SetErrorMode(prev_error_mode)
  250. _load_dll_libraries()
  251. del _load_dll_libraries
  252. def _get_cuda_dep_paths(path: str, lib_folder: str, lib_name: str) -> list[str]:
  253. # Libraries can either be in
  254. # path/nvidia/lib_folder/lib or
  255. # path/nvidia/cuXX/lib (since CUDA 13.0) or
  256. # path/lib_folder/lib
  257. from torch.version import cuda as cuda_version
  258. nvidia_lib_paths = glob.glob(
  259. os.path.join(path, "nvidia", lib_folder, "lib", lib_name)
  260. )
  261. if cuda_version is not None:
  262. maj_cuda_version = cuda_version.split(".")[0]
  263. nvidia_lib_paths += glob.glob(
  264. os.path.join(path, "nvidia", f"cu{maj_cuda_version}", "lib", lib_name)
  265. )
  266. lib_paths = glob.glob(os.path.join(path, lib_folder, "lib", lib_name))
  267. return nvidia_lib_paths + lib_paths
  268. def _preload_cuda_deps(lib_folder: str, lib_name: str, required: bool = True) -> None: # type: ignore[valid-type]
  269. """Preloads cuda deps if they could not be found otherwise."""
  270. # Should only be called on Linux if default path resolution have failed
  271. assert platform.system() == "Linux", "Should only be called on Linux"
  272. lib_path = None
  273. for path in sys.path:
  274. candidate_lib_paths = _get_cuda_dep_paths(path, lib_folder, lib_name)
  275. if candidate_lib_paths:
  276. lib_path = candidate_lib_paths[0]
  277. break
  278. if not lib_path and required:
  279. raise ValueError(f"{lib_name} not found in the system path {sys.path}")
  280. if lib_path:
  281. ctypes.CDLL(lib_path)
  282. # See Note [Global dependencies]
  283. def _load_global_deps() -> None:
  284. if platform.system() == "Windows":
  285. return
  286. # Determine the file extension based on the platform
  287. lib_ext = ".dylib" if platform.system() == "Darwin" else ".so"
  288. lib_name = f"libtorch_global_deps{lib_ext}"
  289. here = os.path.abspath(__file__)
  290. global_deps_lib_path = os.path.join(os.path.dirname(here), "lib", lib_name)
  291. try:
  292. ctypes.CDLL(global_deps_lib_path, mode=ctypes.RTLD_GLOBAL)
  293. # Workaround slim-wheel CUDA dependency bugs in cusparse and cudnn by preloading nvjitlink
  294. # and nvrtc. In CUDA-12.4+ cusparse depends on nvjitlink, but does not have rpath when
  295. # shipped as wheel, which results in OS picking wrong/older version of nvjitlink library
  296. # if `LD_LIBRARY_PATH` is defined, see https://github.com/pytorch/pytorch/issues/138460
  297. # Similar issue exist in cudnn that dynamically loads nvrtc, unaware of its relative path.
  298. # See https://github.com/pytorch/pytorch/issues/145580
  299. try:
  300. with open("/proc/self/maps") as f:
  301. _maps = f.read()
  302. # libtorch_global_deps.so always depends in cudart, check if its installed and loaded
  303. if "libcudart.so" not in _maps:
  304. return
  305. # If all above-mentioned conditions are met, preload nvrtc and nvjitlink
  306. _preload_cuda_deps("cuda_nvrtc", "libnvrtc.so.*[0-9]")
  307. _preload_cuda_deps("cuda_nvrtc", "libnvrtc-builtins.so.*[0-9]")
  308. _preload_cuda_deps("nvjitlink", "libnvJitLink.so.*[0-9]")
  309. except Exception:
  310. pass
  311. except OSError as err:
  312. # Can only happen for wheel with cuda libs as PYPI deps
  313. # As PyTorch is not purelib, but nvidia-*-cu12 is
  314. cuda_libs: dict[str, str] = {
  315. "cublas": "libcublas.so.*[0-9]",
  316. "cudnn": "libcudnn.so.*[0-9]",
  317. "cuda_nvrtc": "libnvrtc.so.*[0-9]",
  318. "cuda_runtime": "libcudart.so.*[0-9]",
  319. "cuda_cupti": "libcupti.so.*[0-9]",
  320. "cufft": "libcufft.so.*[0-9]",
  321. "curand": "libcurand.so.*[0-9]",
  322. "nvjitlink": "libnvJitLink.so.*[0-9]",
  323. "cusparse": "libcusparse.so.*[0-9]",
  324. "cusparselt": "libcusparseLt.so.*[0-9]",
  325. "cusolver": "libcusolver.so.*[0-9]",
  326. "nccl": "libnccl.so.*[0-9]",
  327. "nvshmem": "libnvshmem_host.so.*[0-9]",
  328. "cufile": "libcufile.so.*[0-9]",
  329. }
  330. is_cuda_lib_err = [
  331. lib for lib in cuda_libs.values() if lib.split(".")[0] in err.args[0]
  332. ]
  333. if not is_cuda_lib_err:
  334. raise err
  335. for lib_folder, lib_name in cuda_libs.items():
  336. _preload_cuda_deps(lib_folder, lib_name)
  337. # libnvToolsExt is Optional Dependency
  338. _preload_cuda_deps("nvtx", "libnvToolsExt.so.*[0-9]", required=False)
  339. ctypes.CDLL(global_deps_lib_path, mode=ctypes.RTLD_GLOBAL)
  340. if (USE_RTLD_GLOBAL_WITH_LIBTORCH or os.getenv("TORCH_USE_RTLD_GLOBAL")) and (
  341. platform.system() != "Windows"
  342. ):
  343. # Do it the hard way. You might want to load libtorch with RTLD_GLOBAL in a
  344. # few circumstances:
  345. #
  346. # 1. You're in a build environment (e.g., fbcode) where
  347. # libtorch_global_deps is not available, but you still need
  348. # to get mkl to link in with RTLD_GLOBAL or it will just
  349. # not work.
  350. #
  351. # 2. You're trying to run PyTorch under UBSAN and you need
  352. # to ensure that only one copy of libtorch is loaded, so
  353. # vptr checks work properly
  354. #
  355. # If you're using this setting, you must verify that all the libraries
  356. # you load consistently use the same libstdc++, or you may have
  357. # mysterious segfaults.
  358. #
  359. old_flags = sys.getdlopenflags()
  360. sys.setdlopenflags(os.RTLD_GLOBAL | os.RTLD_LAZY)
  361. from torch._C import * # noqa: F403
  362. sys.setdlopenflags(old_flags)
  363. del old_flags
  364. else:
  365. # Easy way. You want this most of the time, because it will prevent
  366. # C++ symbols from libtorch clobbering C++ symbols from other
  367. # libraries, leading to mysterious segfaults.
  368. #
  369. # If building in an environment where libtorch_global_deps isn't available
  370. # like parts of fbsource, but where RTLD_GLOBAL causes segfaults, you will
  371. # want USE_RTLD_GLOBAL_WITH_LIBTORCH = False and USE_GLOBAL_DEPS = False
  372. #
  373. # See Note [Global dependencies]
  374. if USE_GLOBAL_DEPS:
  375. _load_global_deps()
  376. from torch._C import * # noqa: F403
  377. class SymInt:
  378. """
  379. Like an int (including magic methods), but redirects all operations on the
  380. wrapped node. This is used in particular to symbolically record operations
  381. in the symbolic shape workflow.
  382. """
  383. def __init__(self, node):
  384. # This field MUST be named node; C++ binding code assumes that this
  385. # class has a field named node that stores SymNode
  386. self.node = node
  387. def __bool__(self):
  388. return builtins.bool(self != 0)
  389. def __int__(self):
  390. return self.node.int_()
  391. def __index__(self):
  392. return self.node.int_()
  393. # Magic methods installed by torch.fx.experimental.sym_node
  394. def __round__(self, ndigits=None):
  395. return self
  396. def __truediv__(self, other):
  397. if isinstance(other, (builtins.float, SymFloat)):
  398. return sym_float(self).__float_truediv__(other)
  399. if not isinstance(other, (builtins.int, SymInt)):
  400. return NotImplemented
  401. return self.__int_truediv__(other)
  402. def __rtruediv__(self, other):
  403. if isinstance(other, (builtins.float, SymFloat)):
  404. return sym_float(self).__rfloat_truediv__(other)
  405. if not isinstance(other, (builtins.int, SymInt)):
  406. return NotImplemented
  407. return self.__rint_truediv__(other)
  408. def __floordiv__(self, other):
  409. if isinstance(other, (builtins.float, SymFloat)):
  410. return sym_float(math.floor(sym_float(self) / other))
  411. if not isinstance(other, (builtins.int, SymInt)):
  412. return NotImplemented
  413. return self.__int_floordiv__(other)
  414. def __rfloordiv__(self, other):
  415. if isinstance(other, (builtins.float, SymFloat)):
  416. return sym_float(math.floor(other / sym_float(self)))
  417. if not isinstance(other, (builtins.int, SymInt)):
  418. return NotImplemented
  419. return self.__rint_floordiv__(other)
  420. # nb: complex is impossible to handle correctly lol, with
  421. # negative base and integral float need to diverge semantics and
  422. # just always return complex. Neener neener pretend this problem
  423. # doesn't exist
  424. def __pow__(self, other):
  425. if isinstance(other, (builtins.float, SymFloat)):
  426. return sym_float(self).__pow__(other)
  427. if not isinstance(other, (builtins.int, SymInt)):
  428. return NotImplemented
  429. # Guards! This guard is necessary because we need to know it to
  430. # determine the output type of this operation
  431. if other >= 0:
  432. return self.__pow_by_natural__(other)
  433. else:
  434. # Mercifully, when the exponent is negative, Python just promotes
  435. # to doubles and does a float pow:
  436. #
  437. # if (Py_SIZE(b) < 0 && c == NULL) {
  438. # /* if exponent is negative and there's no modulus:
  439. # return a float. This works because we know
  440. # that this calls float_pow() which converts its
  441. # arguments to double. */
  442. # Py_DECREF(a);
  443. # Py_DECREF(b);
  444. # return PyFloat_Type.tp_as_number->nb_power(v, w, x);
  445. # }
  446. return sym_float(self).__pow__(sym_float(other))
  447. def __rpow__(self, other):
  448. if isinstance(other, (builtins.float, SymFloat)):
  449. return sym_float(self).__rpow__(other)
  450. if not isinstance(other, (builtins.int, SymInt)):
  451. return NotImplemented
  452. if self >= 0: # self is exponent
  453. return self.__rpow_by_natural__(other)
  454. else:
  455. return sym_float(self).__rpow__(sym_float(other))
  456. def __eq__(self, other: object) -> builtins.bool:
  457. raise TypeError("type stub not overridden")
  458. def __lt__(self, other) -> builtins.bool:
  459. raise TypeError("type stub not overridden")
  460. def __gt__(self, other) -> builtins.bool:
  461. raise TypeError("type stub not overridden")
  462. def __le__(self, other) -> builtins.bool:
  463. raise TypeError("type stub not overridden")
  464. def __ge__(self, other) -> builtins.bool:
  465. raise TypeError("type stub not overridden")
  466. def __add__(self, other) -> "SymInt":
  467. raise TypeError("type stub not overridden")
  468. def __radd__(self, other) -> "SymInt":
  469. raise TypeError("type stub not overridden")
  470. def __rmul__(self, other) -> "SymInt":
  471. raise TypeError("type stub not overridden")
  472. def __mod__(self, other: "IntLikeType") -> "SymInt":
  473. raise TypeError("type stub not overridden")
  474. def __mul__(self, other) -> "SymInt":
  475. raise TypeError("type stub not overridden")
  476. def __pow_by_natural__(self, other) -> "SymInt":
  477. raise TypeError("type stub not overridden")
  478. def __rpow_by_natural__(self, other) -> "SymInt":
  479. raise TypeError("type stub not overridden")
  480. def __int_truediv__(self, other) -> "SymFloat":
  481. raise TypeError("type stub not overridden")
  482. def __rint_truediv__(self, other) -> "SymFloat":
  483. raise TypeError("type stub not overridden")
  484. def __int_floordiv__(self, other) -> "SymFloat":
  485. raise TypeError("type stub not overridden")
  486. def __rint_floordiv__(self, other) -> "SymFloat":
  487. raise TypeError("type stub not overridden")
  488. def __sym_max__(self, other):
  489. raise TypeError("type stub not overridden")
  490. def __sym_min__(self, other):
  491. raise TypeError("type stub not overridden")
  492. def __sym_float__(self):
  493. raise TypeError("type stub not overridden")
  494. def __neg__(self):
  495. raise TypeError("type stub not overridden")
  496. def __sub__(self, other: "IntLikeType") -> "SymInt":
  497. raise TypeError("type stub not overridden")
  498. def __rsub__(self, other: "IntLikeType") -> "SymInt":
  499. raise TypeError("type stub not overridden")
  500. def __and__(self, other) -> "SymInt":
  501. raise TypeError("type stub not overridden")
  502. def __or__(self, other) -> "SymInt":
  503. raise TypeError("type stub not overridden")
  504. def __repr__(self):
  505. return self.node._graph_repr()
  506. def _sympy_(self):
  507. return self.node.expr
  508. def __hash__(self) -> builtins.int:
  509. if self.node.is_nested_int():
  510. return hash(self.node.nested_int())
  511. else:
  512. # We could support constant SymInts as well, but not doing it for now
  513. raise TypeError("unhashable type: non-nested SymInt")
  514. # TODO: Force specialization
  515. # This can't be done because the TypeError here is load bearing
  516. # for einops
  517. # https://github.com/arogozhnikov/einops/blob/6181e1e95dc58c00a3143c1726da1c6ee0463164/einops/einops.py#L237
  518. # return hash(builtins.int(self))
  519. def as_integer_ratio(self) -> tuple["SymInt", builtins.int]:
  520. """Represent this int as an exact integer ratio"""
  521. return self, 1
  522. def bit_length(self) -> builtins.int:
  523. # TODO: A more relaxed guard is possible here, where you guard to
  524. # allow all integer quantities which would result in the same bit
  525. # length. We can also just make a dedicated Sympy function for
  526. # computing this quantity and represent it symbolically.
  527. return builtins.int(self).bit_length()
  528. def conjugate(self) -> "SymInt":
  529. return self
  530. class SymFloat:
  531. """
  532. Like a float (including magic methods), but redirects all operations on the
  533. wrapped node. This is used in particular to symbolically record operations
  534. in the symbolic shape workflow.
  535. """
  536. def __init__(self, node):
  537. # This field MUST be named node; C++ binding code assumes that this
  538. # class has a field named node that stores SymNode
  539. self.node = node
  540. def __truediv__(self, other):
  541. if not isinstance(other, (builtins.int, builtins.float, SymInt, SymFloat)):
  542. return NotImplemented
  543. return self.__float_truediv__(sym_float(other))
  544. def __rtruediv__(self, other):
  545. if not isinstance(other, (builtins.int, builtins.float, SymInt, SymFloat)):
  546. return NotImplemented
  547. return self.__rfloat_truediv__(sym_float(other))
  548. def __floordiv__(self, other):
  549. if not isinstance(other, (builtins.int, builtins.float, SymInt, SymFloat)):
  550. return NotImplemented
  551. return sym_float(math.floor(self / sym_float(other)))
  552. def __rfloordiv__(self, other):
  553. if not isinstance(other, (builtins.int, builtins.float, SymInt, SymFloat)):
  554. return NotImplemented
  555. return sym_float(math.floor(sym_float(other) / self))
  556. def __bool__(self):
  557. return self.node.bool_()
  558. def __float__(self):
  559. return self.node.guard_float("", 0)
  560. # Symbolic power does NOT work with negative base, this is to avoid
  561. # potential complex outputs
  562. def __pow__(self, other):
  563. if not isinstance(other, (builtins.int, builtins.float, SymInt, SymFloat)):
  564. return NotImplemented
  565. torch._check(self >= 0)
  566. return self.__float_pow__(other)
  567. def __rpow__(self, other):
  568. if not isinstance(other, (builtins.int, builtins.float, SymInt, SymFloat)):
  569. return NotImplemented
  570. torch._check(other >= 0)
  571. return self.__rfloat_pow__(other)
  572. # Magic methods installed by torch.fx.experimental.sym_node
  573. def __eq__(self, other: object) -> builtins.bool:
  574. raise TypeError("type stub not overridden")
  575. def __lt__(self, other) -> builtins.bool:
  576. raise TypeError("type stub not overridden")
  577. def __gt__(self, other) -> builtins.bool:
  578. raise TypeError("type stub not overridden")
  579. def __le__(self, other) -> builtins.bool:
  580. raise TypeError("type stub not overridden")
  581. def __ge__(self, other) -> builtins.bool:
  582. raise TypeError("type stub not overridden")
  583. def __float_pow__(self, other) -> "SymFloat":
  584. raise TypeError("type stub not overridden")
  585. def __rfloat_pow__(self, other) -> "SymFloat":
  586. raise TypeError("type stub not overridden")
  587. def __float_truediv__(self, other) -> "SymFloat":
  588. raise TypeError("type stub not overridden")
  589. def __rfloat_truediv__(self, other) -> "SymFloat":
  590. raise TypeError("type stub not overridden")
  591. def __trunc__(self):
  592. raise TypeError("type stub not overridden")
  593. def __sym_max__(self, other):
  594. raise TypeError("type stub not overridden")
  595. def __sym_min__(self, other):
  596. raise TypeError("type stub not overridden")
  597. def __sym_int__(self):
  598. raise TypeError("type stub not overridden")
  599. def is_integer(self):
  600. """Return True if the float is an integer."""
  601. raise TypeError("type stub not overridden")
  602. def as_integer_ratio(self) -> tuple[builtins.int, builtins.int]:
  603. """Represent this float as an exact integer ratio"""
  604. return builtins.float(self).as_integer_ratio()
  605. def __repr__(self):
  606. return self.node._graph_repr()
  607. def _sympy_(self):
  608. return self.node.expr
  609. def __hash__(self):
  610. return hash(builtins.float(self))
  611. def conjugate(self) -> "SymFloat":
  612. """Returns the complex conjugate of the float."""
  613. return self
  614. def hex(self) -> str:
  615. """Returns the hexadecimal representation of the float."""
  616. return self.node.guard_float("", 0).hex()
  617. class SymBool:
  618. """
  619. Like a bool (including magic methods), but redirects all operations on the
  620. wrapped node. This is used in particular to symbolically record operations
  621. in the symbolic shape workflow.
  622. Unlike regular bools, regular boolean operators will force extra guards instead
  623. of symbolically evaluate. Use the bitwise operators instead to handle this.
  624. """
  625. def __init__(self, node):
  626. # This field MUST be named node; C++ binding code assumes that this
  627. # class has a field named node that stores SymNode
  628. self.node = node
  629. def __bool__(self):
  630. return self.node.bool_()
  631. def __int__(self):
  632. return builtins.int(self.node.bool_())
  633. # Magic methods installed by torch.fx.experimental.sym_node
  634. def __and__(self, other) -> "SymBool":
  635. raise TypeError("type stub not overridden")
  636. def __or__(self, other) -> "SymBool":
  637. raise TypeError("type stub not overridden")
  638. # We very carefully define __sym_not__, and not a number of other
  639. # plausible alternatives:
  640. #
  641. # - We do not override __not__ because this is not a real magic
  642. # method; you cannot override the meaning of the not builtin in
  643. # Python. We use the name 'sym_not' to clarify that in user code you
  644. # cannot use the builtin not or operator.not_ or operator.__not__ and
  645. # hit this magic method; you must use our custom sym_not operator.
  646. #
  647. # - We do not override the __invert__ method because SymBool is
  648. # meant to be usable in situations where bool is expected. However,
  649. # bitwise negation ~a does the wrong thing with booleans (because
  650. # bool is a subclass of int, so ~1 = -2 which is not falseish.)
  651. # This would be a giant footgun, so we get around it by defining
  652. # our own operator. Note that bitwise and/or do the right thing,
  653. # so we reuse the conventional operators there for readability.
  654. #
  655. def __sym_not__(self) -> "SymBool":
  656. raise TypeError("type stub not overridden")
  657. def __sym_ite__(self, then_val, else_val):
  658. raise TypeError("type stub not overridden")
  659. def __eq__(self, other) -> builtins.bool:
  660. raise TypeError("type stub not overridden")
  661. def __repr__(self):
  662. return self.node._graph_repr()
  663. def _sympy_(self):
  664. return self.node.expr
  665. def __hash__(self):
  666. if self.node.is_constant():
  667. return hash(self.node.bool_())
  668. else:
  669. # Force specialization
  670. return hash(builtins.bool(self))
  671. def sym_not(a):
  672. r"""SymInt-aware utility for logical negation.
  673. Args:
  674. a (SymBool or bool): Object to negate
  675. """
  676. import sympy
  677. if overrides.has_torch_function_unary(a):
  678. return overrides.handle_torch_function(sym_not, (a,), a)
  679. if hasattr(a, "__sym_not__"):
  680. return a.__sym_not__()
  681. if isinstance(a, sympy.Basic):
  682. return ~a # type: ignore[operator]
  683. return not a
  684. def sym_float(a):
  685. r"""SymInt-aware utility for float casting.
  686. Args:
  687. a (SymInt, SymFloat, or object): Object to cast
  688. """
  689. if overrides.has_torch_function_unary(a):
  690. return overrides.handle_torch_function(sym_float, (a,), a)
  691. if isinstance(a, SymFloat):
  692. return a
  693. elif hasattr(a, "__sym_float__"):
  694. return a.__sym_float__()
  695. return builtins.float(a) # type: ignore[operator]
  696. def sym_int(a):
  697. r"""SymInt-aware utility for int casting.
  698. Args:
  699. a (SymInt, SymFloat, or object): Object to cast
  700. """
  701. if overrides.has_torch_function_unary(a):
  702. return overrides.handle_torch_function(sym_int, (a,), a)
  703. if isinstance(a, SymInt):
  704. return a
  705. elif isinstance(a, SymFloat):
  706. return math.trunc(a)
  707. return builtins.int(a) # type: ignore[operator]
  708. def sym_max(a, b):
  709. """
  710. SymInt-aware utility for max which avoids branching on a < b.
  711. Unlike builtins.max(), this only works for int/float, and it always
  712. promotes to float if any argument is float (unlike builtins.max, which
  713. will faithfully preserve the type of the input argument).
  714. """
  715. if overrides.has_torch_function((a, b)):
  716. return overrides.handle_torch_function(sym_max, (a, b), a, b)
  717. if isinstance(a, (SymInt, SymFloat)):
  718. return a.__sym_max__(b)
  719. elif isinstance(b, (SymInt, SymFloat)):
  720. # Due to promotion semantics, this is operator is commutative:
  721. # max(1, 1.0) === max(1.0, 1) === 1.0
  722. return b.__sym_max__(a)
  723. # TODO: Probably can make bool work too, just lazy
  724. all_types, float_types = __all_and_float_types()
  725. assert isinstance(a, all_types), type(a)
  726. assert isinstance(b, all_types), type(b)
  727. if isinstance(a, float_types) or isinstance(b, float_types):
  728. return builtins.float(builtins.max(a, b)) # type: ignore[call-overload]
  729. else:
  730. return builtins.max(a, b) # type: ignore[call-overload]
  731. def __all_and_float_types() -> tuple[tuple[type, ...], tuple[type, ...]]:
  732. try:
  733. import numpy as np
  734. all_types: tuple[type, ...] = (
  735. np.integer,
  736. np.floating,
  737. builtins.int,
  738. builtins.float,
  739. )
  740. float_types: tuple[type, ...] = (np.floating, builtins.float)
  741. except ModuleNotFoundError:
  742. all_types = (builtins.int, builtins.float)
  743. float_types = (builtins.float,)
  744. return all_types, float_types
  745. def sym_min(a, b):
  746. """SymInt-aware utility for min()."""
  747. if overrides.has_torch_function((a, b)):
  748. return overrides.handle_torch_function(sym_min, (a, b), a, b)
  749. if isinstance(a, (SymInt, SymFloat)):
  750. return a.__sym_min__(b)
  751. elif isinstance(b, (SymInt, SymFloat)):
  752. return b.__sym_min__(a)
  753. all_types, float_types = __all_and_float_types()
  754. assert isinstance(a, all_types), type(a)
  755. assert isinstance(b, all_types), type(b)
  756. if isinstance(a, float_types) or isinstance(b, float_types):
  757. return builtins.float(builtins.min(a, b)) # type: ignore[call-overload]
  758. else:
  759. return builtins.min(a, b) # type: ignore[call-overload]
  760. def sym_sum(args):
  761. """
  762. N-ary add which is faster to compute for long lists than iterated binary
  763. addition. Only does something special for integers.
  764. """
  765. if overrides.has_torch_function(args):
  766. return overrides.handle_torch_function(sym_sum, args, args)
  767. found = None
  768. for a in args:
  769. if not isinstance(a, (SymInt, builtins.int)):
  770. return builtins.sum(args)
  771. if isinstance(a, SymInt):
  772. found = a.node
  773. if found is None:
  774. return builtins.sum(args)
  775. from torch.fx.experimental.sym_node import to_node, wrap_node
  776. return wrap_node(found.sym_sum(tuple(to_node(found, a) for a in args)))
  777. # Drop in replacement for math.sqrt, math.sin, math.cos etc
  778. def _get_sym_math_fn(name):
  779. def fn(a):
  780. if overrides.has_torch_function_unary(a):
  781. return overrides.handle_torch_function(fn, (a,), a)
  782. if isinstance(a, SymInt):
  783. a = torch.sym_float(a)
  784. if hasattr(a, f"__sym_{name}__"):
  785. return getattr(a, f"__sym_{name}__")()
  786. return getattr(math, name)(a)
  787. return fn
  788. __fn, __name, __sym_name = None, "", ""
  789. for __name in (
  790. "sqrt",
  791. "cos",
  792. "cosh",
  793. "sin",
  794. "sinh",
  795. "tan",
  796. "tanh",
  797. "asin",
  798. "acos",
  799. "atan",
  800. "log2",
  801. ):
  802. __sym_name = f"_sym_{__name}"
  803. __fn = _get_sym_math_fn(__name)
  804. __fn.__qualname__ = __fn.__name__ = __sym_name
  805. globals()[__sym_name] = __fn
  806. del __fn, __name, __sym_name, _get_sym_math_fn
  807. # Adding temporary shortcut
  808. sym_sqrt = globals()["_sym_sqrt"]
  809. __all__.append("sym_sqrt")
  810. def sym_ite(b, t, f):
  811. """SymInt-aware utility for ternary operator (``t if b else f``.)"""
  812. if overrides.has_torch_function((b, t, f)):
  813. return overrides.handle_torch_function(sym_ite, (b, t, f), b, t, f)
  814. assert isinstance(b, (SymBool, builtins.bool)) and type(t) == type(f)
  815. if isinstance(b, SymBool):
  816. return b.__sym_ite__(t, f)
  817. return t if b else f
  818. # Create a fresh unbacked int, from an (possibly unbacked int) expression.
  819. def sym_fresh_size(expr):
  820. return torch.tensor(expr).item()
  821. # Check to see if we can load C extensions, and if not provide some guidance
  822. # on what the problem might be.
  823. try:
  824. # _initExtension is chosen (arbitrarily) as a sentinel.
  825. from torch._C import _initExtension
  826. except ImportError:
  827. import torch._C as _C_for_compiled_check
  828. # The __file__ check only works for Python 3.7 and above.
  829. if _C_for_compiled_check.__file__ is None:
  830. raise ImportError(
  831. textwrap.dedent(
  832. """
  833. Failed to load PyTorch C extensions:
  834. It appears that PyTorch has loaded the `torch/_C` folder
  835. of the PyTorch repository rather than the C extensions which
  836. are expected in the `torch._C` namespace. This can occur when
  837. using the `install` workflow. e.g.
  838. $ python -m pip install --no-build-isolation -v . && python -c "import torch"
  839. This error can generally be solved using the `develop` workflow
  840. $ python -m pip install --no-build-isolation -v -e . && python -c "import torch" # This should succeed
  841. or by running Python from a different directory.
  842. """
  843. ).strip()
  844. ) from None
  845. raise # If __file__ is not None the cause is unknown, so just re-raise.
  846. # The torch._C submodule is already loaded via `from torch._C import *` above
  847. # Make an explicit reference to the _C submodule to appease linters
  848. from torch import _C as _C
  849. __name, __obj = "", None
  850. for __name in dir(_C):
  851. if __name[0] != "_" and not __name.endswith("Base"):
  852. __all__.append(__name)
  853. __obj = getattr(_C, __name)
  854. if callable(__obj) or inspect.isclass(__obj):
  855. if __obj.__module__ != __name__: # "torch"
  856. # TODO: fix their module from C++ side
  857. if __name not in {
  858. "DisableTorchFunctionSubclass",
  859. "DisableTorchFunction",
  860. "Generator",
  861. }:
  862. __obj.__module__ = __name__ # "torch"
  863. elif __name == "TensorBase":
  864. # issue 109438 / pr 109940. Prevent TensorBase from being copied into torch.
  865. delattr(sys.modules[__name__], __name)
  866. del __name, __obj
  867. if not TYPE_CHECKING:
  868. # issue 38137 and python issue 43367. Submodules of a C extension are
  869. # non-standard, and attributes of those submodules cannot be pickled since
  870. # pickle expect to be able to import them as "from _C.sub import attr"
  871. # which fails with "_C is not a package
  872. def _import_extension_to_sys_modules(module, memo=None):
  873. if memo is None:
  874. memo = set()
  875. if module in memo:
  876. return
  877. memo.add(module)
  878. module_name = module.__name__
  879. for name in dir(module):
  880. member = getattr(module, name)
  881. member_name = getattr(member, "__name__", "")
  882. if inspect.ismodule(member) and member_name.startswith(module_name):
  883. sys.modules.setdefault(member_name, member)
  884. # Recurse for submodules (e.g., `_C._dynamo.eval_frame`)
  885. _import_extension_to_sys_modules(member, memo)
  886. _import_extension_to_sys_modules(_C)
  887. del _import_extension_to_sys_modules
  888. ################################################################################
  889. # Define basic utilities
  890. ################################################################################
  891. def typename(obj: _Any, /) -> str:
  892. """
  893. String representation of the type of an object.
  894. This function returns a fully qualified string representation of an object's type.
  895. Args:
  896. obj (object): The object whose type to represent
  897. Returns:
  898. str: the type of the object `o`
  899. Example:
  900. >>> x = torch.tensor([1, 2, 3])
  901. >>> torch.typename(x)
  902. 'torch.LongTensor'
  903. >>> torch.typename(torch.nn.Parameter)
  904. 'torch.nn.parameter.Parameter'
  905. """
  906. if isinstance(obj, torch.Tensor):
  907. return obj.type()
  908. module = getattr(obj, "__module__", "") or ""
  909. qualname = ""
  910. if hasattr(obj, "__qualname__"):
  911. qualname = obj.__qualname__
  912. elif hasattr(obj, "__name__"):
  913. qualname = obj.__name__
  914. else:
  915. module = obj.__class__.__module__ or ""
  916. qualname = obj.__class__.__qualname__
  917. if module in {"", "builtins"}:
  918. return qualname
  919. return f"{module}.{qualname}"
  920. def is_tensor(obj: _Any, /) -> _TypeIs["torch.Tensor"]:
  921. r"""Returns True if `obj` is a PyTorch tensor.
  922. Note that this function is simply doing ``isinstance(obj, Tensor)``.
  923. Using that ``isinstance`` check is better for type checking with mypy,
  924. and more explicit - so it's recommended to use that instead of
  925. ``is_tensor``.
  926. Args:
  927. obj (object): Object to test
  928. Example::
  929. >>> x = torch.tensor([1, 2, 3])
  930. >>> torch.is_tensor(x)
  931. True
  932. """
  933. return isinstance(obj, torch.Tensor)
  934. def is_storage(obj: _Any, /) -> _TypeIs[_Union["TypedStorage", "UntypedStorage"]]:
  935. r"""Returns True if `obj` is a PyTorch storage object.
  936. Args:
  937. obj (Object): Object to test
  938. """
  939. return type(obj) in _storage_classes
  940. _GLOBAL_DEVICE_CONTEXT = threading.local()
  941. def get_default_device() -> "torch.device":
  942. r"""Gets the default ``torch.Tensor`` to be allocated on ``device``"""
  943. global _GLOBAL_DEVICE_CONTEXT
  944. from torch.overrides import _get_current_function_mode_stack
  945. from torch.utils._device import DeviceContext
  946. def _get_device_with_index(device):
  947. if device.index is not None:
  948. return device
  949. else:
  950. # TODO: Call like get_device_index() method corresponding to
  951. # each device type
  952. return torch.tensor([]).device
  953. # Get device from any active DeviceContext.
  954. device_mode = next(
  955. filter(
  956. lambda mode: isinstance(mode, DeviceContext),
  957. reversed(_get_current_function_mode_stack()),
  958. ),
  959. None,
  960. )
  961. if device_mode:
  962. device = device_mode.device
  963. return _get_device_with_index(device)
  964. if hasattr(_GLOBAL_DEVICE_CONTEXT, "device_context"):
  965. device = _GLOBAL_DEVICE_CONTEXT.device_context.device
  966. return _get_device_with_index(device)
  967. else:
  968. return torch.device("cpu")
  969. def set_default_device(device: "Device") -> None:
  970. """Sets the default ``torch.Tensor`` to be allocated on ``device``. This
  971. does not affect factory function calls which are called with an explicit
  972. ``device`` argument. Factory calls will be performed as if they
  973. were passed ``device`` as an argument.
  974. To only temporarily change the default device instead of setting it
  975. globally, use ``with torch.device(device):`` instead.
  976. The default device is initially ``cpu``. If you set the default tensor
  977. device to another device (e.g., ``cuda``) without a device index, tensors
  978. will be allocated on whatever the current device for the device type,
  979. even after :func:`torch.cuda.set_device` is called.
  980. .. warning::
  981. This function imposes a slight performance cost on every Python
  982. call to the torch API (not just factory functions). If this
  983. is causing problems for you, please comment on
  984. https://github.com/pytorch/pytorch/issues/92701
  985. .. note::
  986. This doesn't affect functions that create tensors that share the same memory as the input, like:
  987. :func:`torch.from_numpy` and :func:`torch.frombuffer`
  988. Args:
  989. device (device or string): the device to set as default
  990. Example::
  991. >>> # xdoctest: +SKIP("requires cuda, changes global state")
  992. >>> torch.get_default_device()
  993. device(type='cpu')
  994. >>> torch.set_default_device('cuda') # current device is 0
  995. >>> torch.get_default_device()
  996. device(type='cuda', index=0)
  997. >>> torch.set_default_device('cuda')
  998. >>> torch.cuda.set_device('cuda:1') # current device is 1
  999. >>> torch.get_default_device()
  1000. device(type='cuda', index=1)
  1001. >>> torch.set_default_device('cuda:1')
  1002. >>> torch.get_default_device()
  1003. device(type='cuda', index=1)
  1004. """
  1005. global _GLOBAL_DEVICE_CONTEXT
  1006. if hasattr(_GLOBAL_DEVICE_CONTEXT, "device_context"):
  1007. device_context = _GLOBAL_DEVICE_CONTEXT.device_context
  1008. if device_context is not None:
  1009. device_context.__exit__(None, None, None)
  1010. if device is None:
  1011. device_context = None
  1012. else:
  1013. from torch.utils._device import DeviceContext
  1014. device_context = DeviceContext(device)
  1015. device_context.__enter__()
  1016. _GLOBAL_DEVICE_CONTEXT.device_context = device_context
  1017. def set_default_tensor_type(t: _Union[type["torch.Tensor"], str], /) -> None:
  1018. r"""
  1019. .. warning::
  1020. This function is deprecated as of PyTorch 2.1, please use :func:`torch.set_default_dtype()` and
  1021. :func:`torch.set_default_device()` as alternatives.
  1022. Sets the default ``torch.Tensor`` type to floating point tensor type
  1023. ``t``. This type will also be used as default floating point type for
  1024. type inference in :func:`torch.tensor`.
  1025. The default floating point tensor type is initially ``torch.FloatTensor``.
  1026. Args:
  1027. t (type or string): the floating point tensor type or its name
  1028. Example::
  1029. >>> # xdoctest: +SKIP("Other tests may have changed the default type. Can we reset it?")
  1030. >>> torch.tensor([1.2, 3]).dtype # initial default for floating point is torch.float32
  1031. torch.float32
  1032. >>> torch.set_default_tensor_type(torch.DoubleTensor)
  1033. >>> torch.tensor([1.2, 3]).dtype # a new floating point tensor
  1034. torch.float64
  1035. """
  1036. if isinstance(t, str):
  1037. t = _import_dotted_name(t)
  1038. _C._set_default_tensor_type(t)
  1039. def set_default_dtype(d: "torch.dtype", /) -> None:
  1040. r"""
  1041. Sets the default floating point dtype to :attr:`d`. Supports floating point dtype
  1042. as inputs. Other dtypes will cause torch to raise an exception.
  1043. When PyTorch is initialized its default floating point dtype is torch.float32,
  1044. and the intent of set_default_dtype(torch.float64) is to facilitate NumPy-like
  1045. type inference. The default floating point dtype is used to:
  1046. 1. Implicitly determine the default complex dtype. When the default floating type is float16,
  1047. the default complex dtype is complex32. For float32, the default complex dtype is complex64.
  1048. For float64, it is complex128. For bfloat16, an exception will be raised because
  1049. there is no corresponding complex type for bfloat16.
  1050. 2. Infer the dtype for tensors constructed using Python floats or complex Python
  1051. numbers. See examples below.
  1052. 3. Determine the result of type promotion between bool and integer tensors and
  1053. Python floats and complex Python numbers.
  1054. Args:
  1055. d (:class:`torch.dtype`): the floating point dtype to make the default.
  1056. Example:
  1057. >>> # xdoctest: +SKIP("Other tests may have changed the default type. Can we reset it?")
  1058. >>> # initial default for floating point is torch.float32
  1059. >>> # Python floats are interpreted as float32
  1060. >>> torch.tensor([1.2, 3]).dtype
  1061. torch.float32
  1062. >>> # initial default for floating point is torch.complex64
  1063. >>> # Complex Python numbers are interpreted as complex64
  1064. >>> torch.tensor([1.2, 3j]).dtype
  1065. torch.complex64
  1066. >>> torch.set_default_dtype(torch.float64)
  1067. >>> # Python floats are now interpreted as float64
  1068. >>> torch.tensor([1.2, 3]).dtype # a new floating point tensor
  1069. torch.float64
  1070. >>> # Complex Python numbers are now interpreted as complex128
  1071. >>> torch.tensor([1.2, 3j]).dtype # a new complex tensor
  1072. torch.complex128
  1073. >>> torch.set_default_dtype(torch.float16)
  1074. >>> # Python floats are now interpreted as float16
  1075. >>> torch.tensor([1.2, 3]).dtype # a new floating point tensor
  1076. torch.float16
  1077. >>> # Complex Python numbers are now interpreted as complex128
  1078. >>> torch.tensor([1.2, 3j]).dtype # a new complex tensor
  1079. torch.complex32
  1080. """
  1081. _C._set_default_dtype(d)
  1082. def use_deterministic_algorithms(
  1083. mode: builtins.bool,
  1084. *,
  1085. warn_only: builtins.bool = False,
  1086. ) -> None:
  1087. r"""Sets whether PyTorch operations must use "deterministic"
  1088. algorithms. That is, algorithms which, given the same input, and when
  1089. run on the same software and hardware, always produce the same output.
  1090. When enabled, operations will use deterministic algorithms when available,
  1091. and if only nondeterministic algorithms are available they will throw a
  1092. :class:`RuntimeError` when called.
  1093. .. note:: This setting alone is not always enough to make an application
  1094. reproducible. Refer to :ref:`reproducibility` for more information.
  1095. .. note:: :func:`torch.set_deterministic_debug_mode` offers an alternative
  1096. interface for this feature.
  1097. The following normally-nondeterministic operations will act
  1098. deterministically when ``mode=True``:
  1099. * :class:`torch.nn.Conv1d` when called on CUDA tensor
  1100. * :class:`torch.nn.Conv2d` when called on CUDA tensor
  1101. * :class:`torch.nn.Conv3d` when called on CUDA tensor
  1102. * :class:`torch.nn.ConvTranspose1d` when called on CUDA tensor
  1103. * :class:`torch.nn.ConvTranspose2d` when called on CUDA tensor
  1104. * :class:`torch.nn.ConvTranspose3d` when called on CUDA tensor
  1105. * :class:`torch.nn.ReplicationPad1d` when attempting to differentiate a CUDA tensor
  1106. * :class:`torch.nn.ReplicationPad2d` when attempting to differentiate a CUDA tensor
  1107. * :class:`torch.nn.ReplicationPad3d` when attempting to differentiate a CUDA tensor
  1108. * :func:`torch.bmm` when called on sparse-dense CUDA tensors
  1109. * :func:`torch.Tensor.__getitem__` when attempting to differentiate a CPU tensor
  1110. and the index is a list of tensors
  1111. * :func:`torch.Tensor.index_put` with ``accumulate=False``
  1112. * :func:`torch.Tensor.index_put` with ``accumulate=True`` when called on a CPU
  1113. tensor
  1114. * :func:`torch.Tensor.put_` with ``accumulate=True`` when called on a CPU
  1115. tensor
  1116. * :func:`torch.Tensor.scatter_add_` when called on a CUDA tensor
  1117. * :func:`torch.gather` when called on a CUDA tensor that requires grad
  1118. * :func:`torch.index_add` when called on CUDA tensor
  1119. * :func:`torch.index_select` when attempting to differentiate a CUDA tensor
  1120. * :func:`torch.repeat_interleave` when attempting to differentiate a CUDA tensor
  1121. * :func:`torch.Tensor.index_copy` when called on a CPU or CUDA tensor
  1122. * :func:`torch.Tensor.scatter` when `src` type is Tensor and called on CUDA tensor
  1123. * :func:`torch.Tensor.scatter_reduce` when ``reduce='sum'`` or ``reduce='mean'`` and called on CUDA tensor
  1124. The following normally-nondeterministic operations will throw a
  1125. :class:`RuntimeError` when ``mode=True``:
  1126. * :class:`torch.nn.AvgPool3d` when attempting to differentiate a CUDA tensor
  1127. * :class:`torch.nn.AdaptiveAvgPool2d` when attempting to differentiate a CUDA tensor
  1128. * :class:`torch.nn.AdaptiveAvgPool3d` when attempting to differentiate a CUDA tensor
  1129. * :class:`torch.nn.MaxPool3d` when attempting to differentiate a CUDA tensor
  1130. * :class:`torch.nn.AdaptiveMaxPool2d` when attempting to differentiate a CUDA tensor
  1131. * :class:`torch.nn.FractionalMaxPool2d` when attempting to differentiate a CUDA tensor
  1132. * :class:`torch.nn.FractionalMaxPool3d` when attempting to differentiate a CUDA tensor
  1133. * :class:`torch.nn.MaxUnpool1d`
  1134. * :class:`torch.nn.MaxUnpool2d`
  1135. * :class:`torch.nn.MaxUnpool3d`
  1136. * :func:`torch.nn.functional.interpolate` when attempting to differentiate a CUDA tensor
  1137. and one of the following modes is used:
  1138. - ``linear``
  1139. - ``bilinear``
  1140. - ``bicubic``
  1141. - ``trilinear``
  1142. * :class:`torch.nn.ReflectionPad1d` when attempting to differentiate a CUDA tensor
  1143. * :class:`torch.nn.ReflectionPad2d` when attempting to differentiate a CUDA tensor
  1144. * :class:`torch.nn.ReflectionPad3d` when attempting to differentiate a CUDA tensor
  1145. * :class:`torch.nn.NLLLoss` when called on a CUDA tensor
  1146. * :class:`torch.nn.CTCLoss` when attempting to differentiate a CUDA tensor
  1147. * :class:`torch.nn.EmbeddingBag` when attempting to differentiate a CUDA tensor when
  1148. ``mode='max'``
  1149. * :func:`torch.Tensor.put_` when ``accumulate=False``
  1150. * :func:`torch.Tensor.put_` when ``accumulate=True`` and called on a CUDA tensor
  1151. * :func:`torch.histc` when called on a CUDA tensor
  1152. * :func:`torch.bincount` when called on a CUDA tensor and ``weights``
  1153. tensor is given
  1154. * :func:`torch.kthvalue` with called on a CUDA tensor
  1155. * :func:`torch.median` with indices output when called on a CUDA tensor
  1156. * :func:`torch.nn.functional.grid_sample` when attempting to differentiate a CUDA tensor
  1157. * :func:`torch.cumsum` when called on a CUDA tensor when dtype is floating point or complex
  1158. * :func:`torch.Tensor.scatter_reduce` when ``reduce='prod'`` and called on CUDA tensor
  1159. * :func:`torch.Tensor.resize_` when called with a quantized tensor
  1160. In addition, several operations fill uninitialized memory when this setting
  1161. is turned on and when
  1162. :attr:`torch.utils.deterministic.fill_uninitialized_memory` is turned on.
  1163. See the documentation for that attribute for more information.
  1164. A handful of CUDA operations are nondeterministic if the CUDA version is
  1165. 10.2 or greater, unless the environment variable ``CUBLAS_WORKSPACE_CONFIG=:4096:8``
  1166. or ``CUBLAS_WORKSPACE_CONFIG=:16:8`` is set. See the CUDA documentation for more
  1167. details: `<https://docs.nvidia.com/cuda/cublas/index.html#results-reproducibility>`_
  1168. If one of these environment variable configurations is not set, a :class:`RuntimeError`
  1169. will be raised from these operations when called with CUDA tensors:
  1170. * :func:`torch.mm`
  1171. * :func:`torch.mv`
  1172. * :func:`torch.bmm`
  1173. Note that deterministic operations tend to have worse performance than
  1174. nondeterministic operations.
  1175. .. note::
  1176. This flag does not detect or prevent nondeterministic behavior caused
  1177. by calling an inplace operation on a tensor with an internal memory
  1178. overlap or by giving such a tensor as the :attr:`out` argument for an
  1179. operation. In these cases, multiple writes of different data may target
  1180. a single memory location, and the order of writes is not guaranteed.
  1181. Args:
  1182. mode (:class:`bool`): If True, makes potentially nondeterministic
  1183. operations switch to a deterministic algorithm or throw a runtime
  1184. error. If False, allows nondeterministic operations.
  1185. Keyword args:
  1186. warn_only (:class:`bool`, optional): If True, operations that do not
  1187. have a deterministic implementation will throw a warning instead of
  1188. an error. Default: ``False``
  1189. Example::
  1190. >>> # xdoctest: +SKIP
  1191. >>> torch.use_deterministic_algorithms(True)
  1192. # Forward mode nondeterministic error
  1193. >>> torch.randn(10, device='cuda').kthvalue(1)
  1194. ...
  1195. RuntimeError: kthvalue CUDA does not have a deterministic implementation...
  1196. # Backward mode nondeterministic error
  1197. >>> torch.nn.AvgPool3d(1)(torch.randn(3, 4, 5, 6, requires_grad=True).cuda()).sum().backward()
  1198. ...
  1199. RuntimeError: avg_pool3d_backward_cuda does not have a deterministic implementation...
  1200. """
  1201. _C._set_deterministic_algorithms(mode, warn_only=warn_only)
  1202. def are_deterministic_algorithms_enabled() -> builtins.bool:
  1203. r"""Returns True if the global deterministic flag is turned on. Refer to
  1204. :func:`torch.use_deterministic_algorithms` documentation for more details.
  1205. """
  1206. return _C._get_deterministic_algorithms()
  1207. def is_deterministic_algorithms_warn_only_enabled() -> builtins.bool:
  1208. r"""Returns True if the global deterministic flag is set to warn only.
  1209. Refer to :func:`torch.use_deterministic_algorithms` documentation for more
  1210. details.
  1211. """
  1212. return _C._get_deterministic_algorithms_warn_only()
  1213. def set_deterministic_debug_mode(debug_mode: _Union[builtins.int, str]) -> None:
  1214. r"""Sets the debug mode for deterministic operations.
  1215. .. note:: This is an alternative interface for
  1216. :func:`torch.use_deterministic_algorithms`. Refer to that function's
  1217. documentation for details about affected operations.
  1218. Args:
  1219. debug_mode(str or int): If "default" or 0, don't error or warn on
  1220. nondeterministic operations. If "warn" or 1, warn on
  1221. nondeterministic operations. If "error" or 2, error on
  1222. nondeterministic operations.
  1223. """
  1224. # NOTE: builtins.int is used here because int in this scope resolves
  1225. # to torch.int
  1226. if not isinstance(debug_mode, (builtins.int, str)):
  1227. raise TypeError(f"debug_mode must be str or int, but got {type(debug_mode)}")
  1228. if isinstance(debug_mode, str):
  1229. if debug_mode == "default":
  1230. debug_mode = 0
  1231. elif debug_mode == "warn":
  1232. debug_mode = 1
  1233. elif debug_mode == "error":
  1234. debug_mode = 2
  1235. else:
  1236. raise RuntimeError(
  1237. "invalid value of debug_mode, expected one of `default`, "
  1238. f"`warn`, `error`, but got {debug_mode}"
  1239. )
  1240. if debug_mode == 0:
  1241. _C._set_deterministic_algorithms(False)
  1242. elif debug_mode == 1:
  1243. _C._set_deterministic_algorithms(True, warn_only=True)
  1244. elif debug_mode == 2:
  1245. _C._set_deterministic_algorithms(True)
  1246. else:
  1247. raise RuntimeError(
  1248. f"invalid value of debug_mode, expected 0, 1, or 2, but got {debug_mode}"
  1249. )
  1250. def get_deterministic_debug_mode() -> builtins.int:
  1251. r"""Returns the current value of the debug mode for deterministic
  1252. operations. Refer to :func:`torch.set_deterministic_debug_mode`
  1253. documentation for more details.
  1254. """
  1255. if _C._get_deterministic_algorithms():
  1256. if _C._get_deterministic_algorithms_warn_only():
  1257. return 1
  1258. else:
  1259. return 2
  1260. else:
  1261. return 0
  1262. def get_float32_matmul_precision() -> str:
  1263. r"""Returns the current value of float32 matrix multiplication precision. Refer to
  1264. :func:`torch.set_float32_matmul_precision` documentation for more details.
  1265. """
  1266. return _C._get_float32_matmul_precision()
  1267. def set_float32_matmul_precision(precision: str) -> None:
  1268. r"""Sets the internal precision of float32 matrix multiplications.
  1269. Running float32 matrix multiplications in lower precision may significantly increase
  1270. performance, and in some programs the loss of precision has a negligible impact.
  1271. Supports three settings:
  1272. * "highest", float32 matrix multiplications use the float32 datatype (24 mantissa
  1273. bits with 23 bits explicitly stored) for internal computations.
  1274. * "high", float32 matrix multiplications either use the TensorFloat32 datatype (10
  1275. mantissa bits explicitly stored) or treat each float32 number as the sum of two bfloat16 numbers
  1276. (approximately 16 mantissa bits with 14 bits explicitly stored), if the appropriate fast matrix multiplication
  1277. algorithms are available. Otherwise float32 matrix multiplications are computed
  1278. as if the precision is "highest". See below for more information on the bfloat16
  1279. approach.
  1280. * "medium", float32 matrix multiplications use the bfloat16 datatype (8 mantissa
  1281. bits with 7 bits explicitly stored) for internal computations, if a fast matrix multiplication algorithm
  1282. using that datatype internally is available. Otherwise float32
  1283. matrix multiplications are computed as if the precision is "high".
  1284. When using "high" precision, float32 multiplications may use a bfloat16-based algorithm
  1285. that is more complicated than simply truncating to some smaller number mantissa bits
  1286. (e.g. 10 for TensorFloat32, 7 for bfloat16 explicitly stored). Refer to [Henry2019]_ for a complete
  1287. description of this algorithm. To briefly explain here, the first step is to realize
  1288. that we can perfectly encode a single float32 number as the sum of three bfloat16
  1289. numbers (because float32 has 23 mantissa bits while bfloat16 has 7 explicitly stored, and both have the
  1290. same number of exponent bits). This means that the product of two float32 numbers can
  1291. be exactly given by the sum of nine products of bfloat16 numbers. We can then trade
  1292. accuracy for speed by dropping some of these products. The "high" precision algorithm
  1293. specifically keeps only the three most significant products, which conveniently excludes
  1294. all of the products involving the last 8 mantissa bits of either input. This means that
  1295. we can represent our inputs as the sum of two bfloat16 numbers rather than three.
  1296. Because bfloat16 fused-multiply-add (FMA) instructions are typically >10x faster than
  1297. float32 ones, it's faster to do three multiplications and 2 additions with bfloat16
  1298. precision than it is to do a single multiplication with float32 precision.
  1299. .. [Henry2019] http://arxiv.org/abs/1904.06376
  1300. .. note::
  1301. This does not change the output dtype of float32 matrix multiplications,
  1302. it controls how the internal computation of the matrix multiplication is performed.
  1303. .. note::
  1304. This does not change the precision of convolution operations. Other flags,
  1305. like `torch.backends.cudnn.allow_tf32`, may control the precision of convolution
  1306. operations.
  1307. .. note::
  1308. This flag currently only affects one native device type: CUDA.
  1309. If "high" or "medium" are set then the TensorFloat32 datatype will be used
  1310. when computing float32 matrix multiplications, equivalent to setting
  1311. `torch.backends.cuda.matmul.allow_tf32 = True`. When "highest" (the default)
  1312. is set then the float32 datatype is used for internal computations, equivalent
  1313. to setting `torch.backends.cuda.matmul.allow_tf32 = False`.
  1314. Args:
  1315. precision(str): can be set to "highest" (default), "high", or "medium" (see above).
  1316. """
  1317. _C._set_float32_matmul_precision(precision)
  1318. def set_warn_always(b: builtins.bool, /) -> None:
  1319. r"""When this flag is False (default) then some PyTorch warnings may only
  1320. appear once per process. This helps avoid excessive warning information.
  1321. Setting it to True causes these warnings to always appear, which may be
  1322. helpful when debugging.
  1323. Args:
  1324. b (:class:`bool`): If True, force warnings to always be emitted
  1325. If False, set to the default behaviour
  1326. """
  1327. _C._set_warnAlways(b)
  1328. def is_warn_always_enabled() -> builtins.bool:
  1329. r"""Returns True if the global warn_always flag is turned on. Refer to
  1330. :func:`torch.set_warn_always` documentation for more details.
  1331. """
  1332. return _C._get_warnAlways()
  1333. ################################################################################
  1334. # Define error checking functions
  1335. ################################################################################
  1336. # These error checking functions must be kept consistent with their C++
  1337. # equivalents. Their C++ equivalents are mentioned where applicable.
  1338. def _check_with(
  1339. error_type,
  1340. cond: _Union[builtins.bool, SymBool],
  1341. message: _Callable[[], str],
  1342. ): # noqa: F811
  1343. if not isinstance(cond, (builtins.bool, SymBool)):
  1344. raise TypeError(f"cond must be a bool, but got {type(cond)}")
  1345. from torch.fx.experimental.symbolic_shapes import expect_true
  1346. if expect_true(cond):
  1347. return
  1348. # error_type must be a subclass of Exception and not subclass of Warning
  1349. assert issubclass(error_type, Exception) and not issubclass(error_type, Warning)
  1350. if message is None:
  1351. message_evaluated = (
  1352. "Expected cond to be True, but got False. (Could this error "
  1353. "message be improved? If so, please report an enhancement request "
  1354. "to PyTorch.)"
  1355. )
  1356. else:
  1357. if not callable(message):
  1358. raise TypeError("message must be a callable")
  1359. message_evaluated = str(message())
  1360. raise error_type(message_evaluated)
  1361. def _check(cond, message=None): # noqa: F811
  1362. r"""Throws error containing an optional message if the specified condition
  1363. is False.
  1364. Error type: ``RuntimeError``
  1365. C++ equivalent: ``TORCH_CHECK``
  1366. Args:
  1367. cond (:class:`bool`): If False, throw error
  1368. message (Callable, optional): Callable that returns either a string or
  1369. an object that has a ``__str__()`` method to be used as the error
  1370. message. Default: ``None``
  1371. """
  1372. _check_with(RuntimeError, cond, message)
  1373. def _check_is_size(i, message=None, *, max=None):
  1374. """Checks that a given integer is a valid size (i.e., is non-negative).
  1375. You should use this over ``_check(i >= 0)`` because it can prevent
  1376. ``GuardOnDataDependentSymNode`` exceptions by opting yourself into alternate
  1377. semantics for ``guard_size_oblivious`` tests that treat values 0 and 1
  1378. equivalently to all other values.
  1379. When max is not None, this specifies an upper bound equivalent to
  1380. ``_check(i <= max)``. This bound is also subject to alternate semantics:
  1381. in ``guard_size_oblivious`` tests, we assume that a constant max bound is
  1382. treated equivalently to all other values. Symbolic max bounds are not yet
  1383. supported.
  1384. NB: Do NOT use this in contexts where a -1 size would be valid (indicating
  1385. to infer the size from context, or if you should wrap-around or truncate).
  1386. Only use this if the only valid value is an honest to goodness size.
  1387. """
  1388. # This is responsible for the expect_true
  1389. _check(i >= 0, message)
  1390. from torch.fx.experimental.symbolic_shapes import _advise_is_size
  1391. _advise_is_size(i)
  1392. if max is not None:
  1393. _check(i <= max, message)
  1394. from torch.fx.experimental.symbolic_shapes import _advise_is_bounded
  1395. _advise_is_bounded(i, max)
  1396. def _check_index(cond, message=None): # noqa: F811
  1397. r"""Throws error containing an optional message if the specified condition
  1398. is False.
  1399. Error type: ``IndexError``
  1400. C++ equivalent: ``TORCH_CHECK_INDEX``
  1401. Args:
  1402. cond (:class:`bool`): If False, throw error
  1403. message (Callable, optional): Callable that returns either a string or
  1404. an object that has a ``__str__()`` method to be used as the error
  1405. message. Default: ``None``
  1406. """
  1407. _check_with(IndexError, cond, message)
  1408. def _check_value(cond, message=None): # noqa: F811
  1409. r"""Throws error containing an optional message if the specified condition
  1410. is False.
  1411. Error type: ``ValueError``
  1412. C++ equivalent: ``TORCH_CHECK_VALUE``
  1413. Args:
  1414. cond (:class:`bool`): If False, throw error
  1415. message (Callable, optional): Callable that returns either a string or
  1416. an object that has a ``__str__()`` method to be used as the error
  1417. message. Default: ``None``
  1418. """
  1419. _check_with(ValueError, cond, message)
  1420. def _check_type(cond, message=None): # noqa: F811
  1421. r"""Throws error containing an optional message if the specified condition
  1422. is False.
  1423. Error type: ``TypeError``
  1424. C++ equivalent: ``TORCH_CHECK_TYPE``
  1425. Args:
  1426. cond (:class:`bool`): If False, throw error
  1427. message (Callable, optional): Callable that returns either a string or
  1428. an object that has a ``__str__()`` method to be used as the error
  1429. message. Default: ``None``
  1430. """
  1431. _check_with(TypeError, cond, message)
  1432. def _check_not_implemented(cond, message=None): # noqa: F811
  1433. r"""Throws error containing an optional message if the specified condition
  1434. is False.
  1435. Error type: ``NotImplementedError``
  1436. C++ equivalent: ``TORCH_CHECK_NOT_IMPLEMENTED``
  1437. Args:
  1438. cond (:class:`bool`): If False, throw error
  1439. message (Callable, optional): Callable that returns either a string or
  1440. an object that has a ``__str__()`` method to be used as the error
  1441. message. Default: ``None``
  1442. """
  1443. _check_with(NotImplementedError, cond, message)
  1444. def _check_tensor_all_with(error_type, cond, message=None): # noqa: F811
  1445. if not is_tensor(cond):
  1446. raise TypeError(f"cond must be a tensor, but got {type(cond)}")
  1447. if not cond.dtype == torch.bool:
  1448. raise TypeError(f"cond tensor must have dtype torch.bool, but got {cond.dtype}")
  1449. _check_with(error_type, cond._is_all_true().item(), message) # type: ignore[arg-type]
  1450. # C++ equivalent: `TORCH_CHECK_TENSOR_ALL`
  1451. def _check_tensor_all(cond, message=None): # noqa: F811
  1452. r"""Throws error containing an optional message if the specified condition
  1453. is False.
  1454. Error type: ``RuntimeError``
  1455. C++ equivalent: ``TORCH_CHECK_TENSOR_ALL``
  1456. Args:
  1457. cond (:class:`torch.Tensor`): Tensor of dtype ``torch.bool``. If any
  1458. element is ``False``, throw error
  1459. message (Callable, optional): Callable that returns either a string or
  1460. an object that has a ``__str__()`` method to be used as the error
  1461. message. Default: ``None``
  1462. """
  1463. _check_tensor_all_with(RuntimeError, cond, message)
  1464. ################################################################################
  1465. # Define numeric constants
  1466. ################################################################################
  1467. # For Python Array API (https://data-apis.org/array-api/latest/API_specification/constants.html) and
  1468. # NumPy consistency (https://numpy.org/devdocs/reference/constants.html)
  1469. from math import e, inf, nan, pi
  1470. newaxis: None = None
  1471. __all__.extend(["e", "pi", "nan", "inf", "newaxis"])
  1472. ################################################################################
  1473. # Define Storage and Tensor classes
  1474. ################################################################################
  1475. from torch._tensor import Tensor # usort: skip
  1476. # needs to be after torch.Tensor is defined to avoid circular dependencies
  1477. from torch import storage as storage # usort: skip
  1478. from torch.storage import (
  1479. _LegacyStorage,
  1480. _StorageBase,
  1481. _warn_typed_storage_removal,
  1482. TypedStorage,
  1483. UntypedStorage,
  1484. )
  1485. # NOTE: New <type>Storage classes should never be added. When adding a new
  1486. # dtype, use torch.storage.TypedStorage directly.
  1487. class ByteStorage(_LegacyStorage):
  1488. @classproperty
  1489. def dtype(self):
  1490. _warn_typed_storage_removal(stacklevel=3)
  1491. return self._dtype
  1492. @classproperty
  1493. def _dtype(self):
  1494. return torch.uint8
  1495. class DoubleStorage(_LegacyStorage):
  1496. @classproperty
  1497. def dtype(self):
  1498. _warn_typed_storage_removal(stacklevel=3)
  1499. return self._dtype
  1500. @classproperty
  1501. def _dtype(self):
  1502. return torch.double
  1503. class FloatStorage(_LegacyStorage):
  1504. @classproperty
  1505. def dtype(self):
  1506. _warn_typed_storage_removal(stacklevel=3)
  1507. return self._dtype
  1508. @classproperty
  1509. def _dtype(self):
  1510. return torch.float
  1511. class HalfStorage(_LegacyStorage):
  1512. @classproperty
  1513. def dtype(self):
  1514. _warn_typed_storage_removal(stacklevel=3)
  1515. return self._dtype
  1516. @classproperty
  1517. def _dtype(self):
  1518. return torch.half
  1519. class LongStorage(_LegacyStorage):
  1520. @classproperty
  1521. def dtype(self):
  1522. _warn_typed_storage_removal(stacklevel=3)
  1523. return self._dtype
  1524. @classproperty
  1525. def _dtype(self):
  1526. return torch.long
  1527. class IntStorage(_LegacyStorage):
  1528. @classproperty
  1529. def dtype(self):
  1530. _warn_typed_storage_removal(stacklevel=3)
  1531. return self._dtype
  1532. @classproperty
  1533. def _dtype(self):
  1534. return torch.int
  1535. class ShortStorage(_LegacyStorage):
  1536. @classproperty
  1537. def dtype(self):
  1538. _warn_typed_storage_removal(stacklevel=3)
  1539. return self._dtype
  1540. @classproperty
  1541. def _dtype(self):
  1542. return torch.short
  1543. class CharStorage(_LegacyStorage):
  1544. @classproperty
  1545. def dtype(self):
  1546. _warn_typed_storage_removal(stacklevel=3)
  1547. return self._dtype
  1548. @classproperty
  1549. def _dtype(self):
  1550. return torch.int8
  1551. class BoolStorage(_LegacyStorage):
  1552. @classproperty
  1553. def dtype(self):
  1554. _warn_typed_storage_removal(stacklevel=3)
  1555. return self._dtype
  1556. @classproperty
  1557. def _dtype(self):
  1558. return torch.bool
  1559. class BFloat16Storage(_LegacyStorage):
  1560. @classproperty
  1561. def dtype(self):
  1562. _warn_typed_storage_removal(stacklevel=3)
  1563. return self._dtype
  1564. @classproperty
  1565. def _dtype(self):
  1566. return torch.bfloat16
  1567. class ComplexDoubleStorage(_LegacyStorage):
  1568. @classproperty
  1569. def dtype(self):
  1570. _warn_typed_storage_removal(stacklevel=3)
  1571. return self._dtype
  1572. @classproperty
  1573. def _dtype(self):
  1574. return torch.cdouble
  1575. class ComplexFloatStorage(_LegacyStorage):
  1576. @classproperty
  1577. def dtype(self):
  1578. _warn_typed_storage_removal(stacklevel=3)
  1579. return self._dtype
  1580. @classproperty
  1581. def _dtype(self):
  1582. return torch.cfloat
  1583. class QUInt8Storage(_LegacyStorage):
  1584. @classproperty
  1585. def dtype(self):
  1586. _warn_typed_storage_removal(stacklevel=3)
  1587. return self._dtype
  1588. @classproperty
  1589. def _dtype(self):
  1590. return torch.quint8
  1591. class QInt8Storage(_LegacyStorage):
  1592. @classproperty
  1593. def dtype(self):
  1594. _warn_typed_storage_removal(stacklevel=3)
  1595. return self._dtype
  1596. @classproperty
  1597. def _dtype(self):
  1598. return torch.qint8
  1599. class QInt32Storage(_LegacyStorage):
  1600. @classproperty
  1601. def dtype(self):
  1602. _warn_typed_storage_removal(stacklevel=3)
  1603. return self._dtype
  1604. @classproperty
  1605. def _dtype(self):
  1606. return torch.qint32
  1607. class QUInt4x2Storage(_LegacyStorage):
  1608. @classproperty
  1609. def dtype(self):
  1610. _warn_typed_storage_removal(stacklevel=3)
  1611. return self._dtype
  1612. @classproperty
  1613. def _dtype(self):
  1614. return torch.quint4x2
  1615. class QUInt2x4Storage(_LegacyStorage):
  1616. @classproperty
  1617. def dtype(self):
  1618. _warn_typed_storage_removal(stacklevel=3)
  1619. return self._dtype
  1620. @classproperty
  1621. def _dtype(self):
  1622. return torch.quint2x4
  1623. _storage_classes: set[type[_Union[TypedStorage, UntypedStorage]]] = {
  1624. UntypedStorage,
  1625. DoubleStorage,
  1626. FloatStorage,
  1627. LongStorage,
  1628. IntStorage,
  1629. ShortStorage,
  1630. CharStorage,
  1631. ByteStorage,
  1632. HalfStorage,
  1633. BoolStorage,
  1634. QUInt8Storage,
  1635. QInt8Storage,
  1636. QInt32Storage,
  1637. BFloat16Storage,
  1638. ComplexFloatStorage,
  1639. ComplexDoubleStorage,
  1640. QUInt4x2Storage,
  1641. QUInt2x4Storage,
  1642. TypedStorage,
  1643. }
  1644. # The _tensor_classes set is initialized by the call to initialize_python_bindings.
  1645. _tensor_classes: set[type["torch.Tensor"]] = set()
  1646. # If you edit these imports, please update torch/__init__.py.in as well
  1647. from torch import amp as amp, random as random, serialization as serialization
  1648. from torch._tensor_str import set_printoptions
  1649. from torch.amp import autocast, GradScaler
  1650. from torch.random import get_rng_state, initial_seed, manual_seed, seed, set_rng_state
  1651. from torch.serialization import load, save
  1652. ################################################################################
  1653. # Initialize extension
  1654. ################################################################################
  1655. # Shared memory manager needs to know the exact location of manager executable
  1656. def _manager_path():
  1657. if platform.system() == "Windows":
  1658. return b""
  1659. path = get_file_path("torch", "bin", "torch_shm_manager")
  1660. prepare_multiprocessing_environment(get_file_path("torch"))
  1661. if not os.path.exists(path):
  1662. raise RuntimeError("Unable to find torch_shm_manager at " + path)
  1663. return path.encode("utf-8")
  1664. _C._initExtension(_manager_path())
  1665. del _manager_path
  1666. # Appease the type checker: it can't deal with direct setting of globals().
  1667. # Note that we will see "too many" functions when reexporting this way; there
  1668. # is not a good way to fix this problem. Perhaps, try to redesign VariableFunctions
  1669. # so that this import is good enough
  1670. if TYPE_CHECKING:
  1671. # Some type signatures pulled in from _VariableFunctions here clash with
  1672. # signatures already imported. For now these clashes are ignored; see
  1673. # PR #43339 for details.
  1674. from torch._C._VariableFunctions import * # type: ignore[assignment, misc] # noqa: F403
  1675. # Fixup segment_reduce visibility
  1676. _segment_reduce = segment_reduce
  1677. del segment_reduce # noqa: F821
  1678. # Ops not to be exposed in `torch` namespace,
  1679. # mostly helper ops.
  1680. PRIVATE_OPS = ("unique_dim",)
  1681. __name, __obj = "", None
  1682. for __name in dir(_C._VariableFunctions):
  1683. if __name.startswith("__") or __name in PRIVATE_OPS:
  1684. continue
  1685. __obj = getattr(_C._VariableFunctions, __name)
  1686. __obj.__module__ = __name__ # "torch"
  1687. # Hide some APIs that should not be public
  1688. if __name == "segment_reduce":
  1689. # TODO: Once the undocumented FC window is passed, remove the line below
  1690. globals()[__name] = __obj
  1691. __name = "_" + __name
  1692. globals()[__name] = __obj
  1693. if not __name.startswith("_"):
  1694. __all__.append(__name)
  1695. del __name, __obj
  1696. ################################################################################
  1697. # Add torch.dtype instances to the public API
  1698. ################################################################################
  1699. import torch
  1700. __all__.extend(
  1701. name for name in dir(torch) if isinstance(getattr(torch, name), torch.dtype)
  1702. )
  1703. ################################################################################
  1704. # Import TorchDynamo's lazy APIs to avoid circular dependencies
  1705. ################################################################################
  1706. # needs to be before from torch.functional import * to avoid circular dependencies
  1707. from torch._compile import _disable_dynamo # usort: skip
  1708. ################################################################################
  1709. # Import interface functions defined in Python
  1710. ################################################################################
  1711. # needs to be after the above ATen bindings so we can overwrite from Python side
  1712. from torch import _VF as _VF, functional as functional # usort: skip
  1713. from torch.functional import * # usort: skip # noqa: F403
  1714. ################################################################################
  1715. # Remove unnecessary members
  1716. ################################################################################
  1717. del _StorageBase
  1718. del _LegacyStorage
  1719. ################################################################################
  1720. # Define _assert
  1721. ################################################################################
  1722. # needs to be before the submodule imports to avoid circular dependencies
  1723. def _assert(condition, message):
  1724. r"""A wrapper around Python's assert which is symbolically traceable."""
  1725. if type(condition) is not torch.Tensor and overrides.has_torch_function(
  1726. (condition,)
  1727. ):
  1728. return overrides.handle_torch_function(
  1729. _assert, (condition,), condition, message
  1730. )
  1731. assert condition, message
  1732. ################################################################################
  1733. # Import most common subpackages
  1734. ################################################################################
  1735. # Use the redundant form so that type checkers know that these are a part of
  1736. # the public API. The "regular" import lines are there solely for the runtime
  1737. # side effect of adding to the imported module's members for other users.
  1738. # needs to be before import torch.nn as nn to avoid circular dependencies
  1739. from torch.autograd import ( # usort: skip
  1740. enable_grad as enable_grad,
  1741. inference_mode as inference_mode,
  1742. no_grad as no_grad,
  1743. set_grad_enabled as set_grad_enabled,
  1744. )
  1745. from torch import (
  1746. __config__ as __config__,
  1747. __future__ as __future__,
  1748. _awaits as _awaits,
  1749. accelerator as accelerator,
  1750. autograd as autograd,
  1751. backends as backends,
  1752. cpu as cpu,
  1753. cuda as cuda,
  1754. distributed as distributed,
  1755. distributions as distributions,
  1756. fft as fft,
  1757. futures as futures,
  1758. hub as hub,
  1759. jit as jit,
  1760. linalg as linalg,
  1761. mps as mps,
  1762. mtia as mtia,
  1763. multiprocessing as multiprocessing,
  1764. nested as nested,
  1765. nn as nn,
  1766. optim as optim,
  1767. overrides as overrides,
  1768. profiler as profiler,
  1769. sparse as sparse,
  1770. special as special,
  1771. testing as testing,
  1772. types as types,
  1773. utils as utils,
  1774. version as version,
  1775. xpu as xpu,
  1776. )
  1777. from torch.signal import windows as windows
  1778. # Quantized, sparse, AO, etc. should be last to get imported, as nothing
  1779. # is expected to depend on them.
  1780. from torch import ao as ao # usort: skip
  1781. # nn.quant* depends on ao -- so should be after those.
  1782. import torch.nn.intrinsic
  1783. import torch.nn.qat
  1784. import torch.nn.quantizable
  1785. import torch.nn.quantized
  1786. _C._init_names(list(_storage_classes))
  1787. # attach docstrings to torch and tensor functions
  1788. from torch import _size_docs, _storage_docs, _tensor_docs, _torch_docs
  1789. del _torch_docs, _tensor_docs, _storage_docs, _size_docs
  1790. def compiled_with_cxx11_abi() -> builtins.bool:
  1791. r"""Returns whether PyTorch was built with _GLIBCXX_USE_CXX11_ABI=1"""
  1792. return True
  1793. from torch import _library as _library, _ops as _ops
  1794. # Import the ops and classes "namespace"
  1795. from torch._ops import ops as ops # usort: skip
  1796. from torch._classes import classes as classes # usort: skip
  1797. sys.modules.setdefault(f"{__name__}.ops", ops)
  1798. sys.modules.setdefault(f"{__name__}.classes", classes)
  1799. # quantization depends on torch.fx and torch.ops
  1800. # Import quantization
  1801. from torch import quantization as quantization # usort: skip
  1802. # Import the quasi random sampler
  1803. from torch import quasirandom as quasirandom # usort: skip
  1804. # If you are seeing this, it means that this call site was not checked if
  1805. # the memory format could be preserved, and it was switched to old default
  1806. # behaviour of contiguous
  1807. legacy_contiguous_format = contiguous_format # defined by _C._initExtension()
  1808. # Register fork handler to initialize OpenMP in child processes (see gh-28389)
  1809. from torch.multiprocessing._atfork import register_after_fork
  1810. register_after_fork(torch.get_num_threads)
  1811. del register_after_fork
  1812. # Import tools that require fully imported torch (for applying
  1813. # torch.jit.script as a decorator, for instance):
  1814. from torch._lobpcg import lobpcg as lobpcg
  1815. # These were previously defined in native_functions.yaml and appeared on the
  1816. # `torch` namespace, but we moved them to c10 dispatch to facilitate custom
  1817. # class usage. We add these lines here to preserve backward compatibility.
  1818. quantized_lstm = ops.aten.quantized_lstm
  1819. quantized_gru = ops.aten.quantized_gru
  1820. # Import experimental masked operations support. See
  1821. # [RFC-0016](https://github.com/pytorch/rfcs/pull/27) for more
  1822. # information.
  1823. from torch import masked as masked
  1824. # Import removed ops with error message about removal
  1825. from torch._linalg_utils import ( # type: ignore[misc]
  1826. _symeig as symeig,
  1827. eig,
  1828. lstsq,
  1829. matrix_rank,
  1830. solve,
  1831. )
  1832. from torch.utils.dlpack import from_dlpack, to_dlpack
  1833. class _TorchCompileInductorWrapper:
  1834. compiler_name = "inductor"
  1835. def __init__(self, mode, options, dynamic):
  1836. from torch._inductor.compiler_bisector import CompilerBisector
  1837. self.config: dict[str, _Any] = {}
  1838. self.dynamic = dynamic
  1839. self.apply_mode(mode)
  1840. self.apply_options(options)
  1841. self.apply_options(CompilerBisector.get_config_change("inductor"))
  1842. cuda_version = None
  1843. if hasattr(torch, "version"):
  1844. from torch.torch_version import TorchVersion
  1845. cuda_version = TorchVersion(getattr(torch.version, "cuda", "0.0"))
  1846. if self.config.get("triton.cudagraphs", False) and (
  1847. (cuda_version and cuda_version < "12.6")
  1848. or not profiler_allow_cudagraph_cupti_lazy_reinit_cuda12()
  1849. ):
  1850. os.environ["DISABLE_CUPTI_LAZY_REINIT"] = "1"
  1851. # FIXME: CUDA Graph does not work well with CUPTI teardown.
  1852. # 1) crashes on 1st lazy CUPTI re-init after teardown (CUDA 11)
  1853. # 2) crashes on 2nd non-lazy CUPTI re-init after teardown (CUDA 12)
  1854. # Workaround: turn off CUPTI teardown when using CUDA Graphs.
  1855. os.environ["TEARDOWN_CUPTI"] = "0"
  1856. def __eq__(self, other):
  1857. return (
  1858. isinstance(other, _TorchCompileInductorWrapper)
  1859. and self.config == other.config
  1860. and self.dynamic == other.dynamic
  1861. )
  1862. def apply_mode(self, mode: _Optional[str]):
  1863. if mode and mode != "default":
  1864. from torch._inductor import list_mode_options
  1865. self.apply_options(list_mode_options(mode, self.dynamic))
  1866. def apply_options(self, options: _Optional[dict[str, _Any]]):
  1867. if not options:
  1868. return
  1869. from torch._inductor import config
  1870. current_config: dict[str, _Any] = config.get_config_copy()
  1871. for key, val in options.items():
  1872. attr_name = key.replace("-", "_")
  1873. if attr_name not in current_config:
  1874. raise RuntimeError(
  1875. f"Unexpected optimization option {key}, known options are {list(current_config.keys())}"
  1876. )
  1877. attr_type = config.get_type(attr_name) # type: ignore[attr-defined]
  1878. # Subscriptable generic types don't support isinstance so skip the type
  1879. # check. There doesn't seem to be a good way of checking membership without
  1880. # 3rd party libraries.
  1881. if _get_origin(attr_type) is None:
  1882. if not isinstance(val, attr_type):
  1883. val_type_str = type(val).__name__
  1884. expected_type_str = type(current_config[attr_name]).__name__
  1885. raise RuntimeError(
  1886. f"Unexpected type of attr {key}, got {val_type_str} should be {expected_type_str}"
  1887. )
  1888. self.config[attr_name] = val
  1889. def __call__(self, model_, inputs_):
  1890. from torch._inductor.compile_fx import compile_fx
  1891. return compile_fx(model_, inputs_, config_patches=self.config)
  1892. def get_compiler_config(self):
  1893. from torch._inductor.compile_fx import get_patched_config_dict
  1894. return get_patched_config_dict(config_patches=self.config)
  1895. def reset(self):
  1896. from torch._inductor import config
  1897. if "triton.cudagraphs" in self.config or config.triton.cudagraphs:
  1898. if self.config.get("triton.cudagraphs", True):
  1899. from torch._inductor.cudagraph_trees import reset_cudagraph_trees
  1900. reset_cudagraph_trees()
  1901. class _TorchCompileWrapper:
  1902. def __init__(self, backend, mode, options, dynamic):
  1903. from torch._dynamo.backends.registry import lookup_backend
  1904. if isinstance(backend, str):
  1905. self.compiler_name = backend
  1906. elif hasattr(backend, "__name__"):
  1907. self.compiler_name = backend.__name__
  1908. else:
  1909. self.compiler_name = str(backend)
  1910. self.dynamic = dynamic
  1911. self.compiler_fn = lookup_backend(backend)
  1912. self.kwargs = {}
  1913. # only pass the args if they non-empty
  1914. if mode and mode != "default":
  1915. self.kwargs["mode"] = mode
  1916. if options:
  1917. self.kwargs["options"] = options
  1918. def __eq__(self, other):
  1919. return (
  1920. isinstance(other, _TorchCompileWrapper)
  1921. and self.compiler_fn == other.compiler_fn
  1922. and self.kwargs == other.kwargs
  1923. and self.dynamic == other.dynamic
  1924. )
  1925. def __call__(self, model_, inputs_):
  1926. return self.compiler_fn(model_, inputs_, **self.kwargs)
  1927. def reset(self):
  1928. if hasattr(self.compiler_fn, "reset"):
  1929. self.compiler_fn.reset()
  1930. _InputT = _ParamSpec("_InputT")
  1931. _RetT = _TypeVar("_RetT")
  1932. @_overload
  1933. def compile(
  1934. model: _Callable[_InputT, _RetT],
  1935. *,
  1936. fullgraph: builtins.bool = False,
  1937. dynamic: _Optional[builtins.bool] = None,
  1938. backend: _Union[str, _Callable] = "inductor",
  1939. mode: _Union[str, None] = None,
  1940. options: _Optional[
  1941. dict[str, _Union[str, builtins.int, builtins.bool, _Callable]]
  1942. ] = None,
  1943. disable: builtins.bool = False,
  1944. ) -> _Callable[_InputT, _RetT]: ...
  1945. @_overload
  1946. def compile(
  1947. model: None = None,
  1948. *,
  1949. fullgraph: builtins.bool = False,
  1950. dynamic: _Optional[builtins.bool] = None,
  1951. backend: _Union[str, _Callable] = "inductor",
  1952. mode: _Union[str, None] = None,
  1953. options: _Optional[
  1954. dict[str, _Union[str, builtins.int, builtins.bool, _Callable]]
  1955. ] = None,
  1956. disable: builtins.bool = False,
  1957. ) -> _Callable[[_Callable[_InputT, _RetT]], _Callable[_InputT, _RetT]]: ...
  1958. def compile(
  1959. model: _Optional[_Callable[_InputT, _RetT]] = None,
  1960. *,
  1961. fullgraph: builtins.bool = False,
  1962. dynamic: _Optional[builtins.bool] = None,
  1963. backend: _Union[str, _Callable] = "inductor",
  1964. mode: _Union[str, None] = None,
  1965. options: _Optional[
  1966. dict[str, _Union[str, builtins.int, builtins.bool, _Callable]]
  1967. ] = None,
  1968. disable: builtins.bool = False,
  1969. ) -> _Union[
  1970. _Callable[[_Callable[_InputT, _RetT]], _Callable[_InputT, _RetT]],
  1971. _Callable[_InputT, _RetT],
  1972. ]:
  1973. """
  1974. Optimizes given model/function using TorchDynamo and specified backend.
  1975. If you are compiling an :class:`torch.nn.Module`, you can also use :meth:`torch.nn.Module.compile`
  1976. to compile the module inplace without changing its structure.
  1977. Concretely, for every frame executed within the compiled region, we will attempt
  1978. to compile it and cache the compiled result on the code object for future
  1979. use. A single frame may be compiled multiple times if previous compiled
  1980. results are not applicable for subsequent calls (this is called a "guard
  1981. failure), you can use TORCH_LOGS=guards to debug these situations.
  1982. Multiple compiled results can be associated with a frame up to
  1983. ``torch._dynamo.config.recompile_limit``, which defaults to 8; at which
  1984. point we will fall back to eager. Note that compile caches are per
  1985. *code object*, not frame; if you dynamically create multiple copies of a
  1986. function, they will all share the same code cache.
  1987. Args:
  1988. model (Callable or None): Module/function to optimize
  1989. fullgraph (bool): If False (default), torch.compile attempts to discover compilable regions
  1990. in the function that it will optimize. If True, then we require that the entire function be
  1991. capturable into a single graph. If this is not possible (that is, if there are graph breaks),
  1992. then this will raise an error.
  1993. dynamic (bool or None): Use dynamic shape tracing. When this is True, we will up-front attempt
  1994. to generate a kernel that is as dynamic as possible to avoid recompilations when
  1995. sizes change. This may not always work as some operations/optimizations will
  1996. force specialization; use TORCH_LOGS=dynamic to debug overspecialization.
  1997. When this is False, we will NEVER generate dynamic kernels, we will always specialize.
  1998. By default (None), we automatically detect if dynamism has occurred and compile a more
  1999. dynamic kernel upon recompile.
  2000. backend (str or Callable): backend to be used
  2001. - "inductor" is the default backend, which is a good balance between performance and overhead
  2002. - Non experimental in-tree backends can be seen with `torch._dynamo.list_backends()`
  2003. - Experimental or debug in-tree backends can be seen with `torch._dynamo.list_backends(None)`
  2004. - To register an out-of-tree custom backend:
  2005. https://pytorch.org/docs/main/torch.compiler_custom_backends.html#registering-custom-backends
  2006. mode (str): Can be either "default", "reduce-overhead", "max-autotune" or "max-autotune-no-cudagraphs"
  2007. - "default" is the default mode, which is a good balance between performance and overhead
  2008. - "reduce-overhead" is a mode that reduces the overhead of python with CUDA graphs,
  2009. useful for small batches. Reduction of overhead can come at the cost of more memory
  2010. usage, as we will cache the workspace memory required for the invocation so that we
  2011. do not have to reallocate it on subsequent runs. Reduction of overhead is not guaranteed
  2012. to work; today, we only reduce overhead for CUDA only graphs which do not mutate inputs.
  2013. There are other circumstances where CUDA graphs are not applicable; use TORCH_LOG=perf_hints
  2014. to debug.
  2015. - "max-autotune" is a mode that leverages Triton or template based matrix multiplications
  2016. on supported devices and Triton based convolutions on GPU.
  2017. It enables CUDA graphs by default on GPU.
  2018. - "max-autotune-no-cudagraphs" is a mode similar to "max-autotune" but without CUDA graphs
  2019. - To see the exact configs that each mode sets you can call `torch._inductor.list_mode_options()`
  2020. options (dict): A dictionary of options to pass to the backend. Some notable ones to try out are
  2021. - `epilogue_fusion` which fuses pointwise ops into templates. Requires `max_autotune` to also be set
  2022. - `max_autotune` which will profile to pick the best matmul configuration
  2023. - `fallback_random` which is useful when debugging accuracy issues
  2024. - `shape_padding` which pads matrix shapes to better align loads on GPUs especially for tensor cores
  2025. - `triton.cudagraphs` which will reduce the overhead of python with CUDA graphs
  2026. - `trace.enabled` which is the most useful debugging flag to turn on
  2027. - `trace.graph_diagram` which will show you a picture of your graph after fusion
  2028. - `guard_filter_fn` that controls which dynamo guards are saved with compilations.
  2029. This is an unsafe feature and there is no backward compatibility guarantee provided
  2030. for dynamo guards as data types.
  2031. For stable helper functions to use, see the documentations in `torch.compiler`, for example:
  2032. - `torch.compiler.skip_guard_on_inbuilt_nn_modules_unsafe`
  2033. - `torch.compiler.skip_guard_on_all_nn_modules_unsafe`
  2034. - `torch.compiler.keep_tensor_guards_unsafe`
  2035. - For inductor you can see the full list of configs that it supports by calling `torch._inductor.list_options()`
  2036. disable (bool): Turn torch.compile() into a no-op for testing
  2037. Example::
  2038. @torch.compile(options={"triton.cudagraphs": True}, fullgraph=True)
  2039. def foo(x):
  2040. return torch.sin(x) + torch.cos(x)
  2041. """
  2042. import sysconfig
  2043. _C._log_api_usage_once("torch.compile")
  2044. if sys.version_info >= (3, 14):
  2045. raise RuntimeError("torch.compile is not supported on Python 3.14+")
  2046. elif sysconfig.get_config_var("Py_GIL_DISABLED") == 1 and sys.version_info < (
  2047. 3,
  2048. 13,
  2049. 3,
  2050. ):
  2051. raise RuntimeError(
  2052. "torch.compile is not supported on Python < 3.13.3 built with GIL disabled. "
  2053. "Please use Python 3.13.3+."
  2054. )
  2055. # Decorator mode
  2056. if model is None:
  2057. def fn(model: _Callable[_InputT, _RetT]) -> _Callable[_InputT, _RetT]:
  2058. if model is None:
  2059. raise RuntimeError("Model can't be None")
  2060. return compile(
  2061. model,
  2062. fullgraph=fullgraph,
  2063. dynamic=dynamic,
  2064. backend=backend,
  2065. mode=mode,
  2066. options=options,
  2067. disable=disable,
  2068. )
  2069. return fn
  2070. if mode is not None and options is not None:
  2071. raise RuntimeError(
  2072. "Either mode or options can be specified, but both can't be specified at the same time."
  2073. )
  2074. if mode is None and options is None:
  2075. mode = "default"
  2076. from torch._inductor.compiler_bisector import CompilerBisector
  2077. if bisect_backend := CompilerBisector.get_backend():
  2078. backend = bisect_backend
  2079. guard_filter_fn = None
  2080. if options and isinstance(options, dict):
  2081. guard_filter_fn = options.pop("guard_filter_fn", None)
  2082. if backend == "inductor":
  2083. backend = _TorchCompileInductorWrapper(mode, options, dynamic)
  2084. else:
  2085. backend = _TorchCompileWrapper(backend, mode, options, dynamic)
  2086. return torch._dynamo.optimize(
  2087. backend=backend,
  2088. nopython=fullgraph,
  2089. dynamic=dynamic,
  2090. disable=disable,
  2091. guard_filter_fn=guard_filter_fn,
  2092. )(model) # type: ignore[return-value]
  2093. def _register_device_module(device_type, module):
  2094. r"""Register an external runtime module of the specific :attr:`device_type`
  2095. supported by torch.
  2096. After the :attr:`module` is registered correctly, the user can refer
  2097. the external runtime module as part of torch with attribute torch.xxx.
  2098. """
  2099. # Make sure the device_type represent a supported device type for torch.
  2100. device_type = torch.device(device_type).type
  2101. m = sys.modules[__name__]
  2102. if hasattr(m, device_type):
  2103. raise RuntimeError(
  2104. f"The runtime module of '{device_type}' has already "
  2105. f"been registered with '{getattr(m, device_type)}'"
  2106. )
  2107. setattr(m, device_type, module)
  2108. torch_module_name = ".".join([__name__, device_type])
  2109. sys.modules[torch_module_name] = module
  2110. from torch import (
  2111. export as export,
  2112. func as func,
  2113. library as library,
  2114. return_types as return_types,
  2115. )
  2116. from torch._higher_order_ops import cond as cond, while_loop as while_loop
  2117. from torch.func import vmap as vmap
  2118. if not TYPE_CHECKING:
  2119. from torch import _meta_registrations
  2120. # Enable CUDA Sanitizer
  2121. if "TORCH_CUDA_SANITIZER" in os.environ:
  2122. import torch.cuda._sanitizer as csan
  2123. csan.enable_cuda_sanitizer()
  2124. # Populate magic methods on SymInt and SymFloat
  2125. import torch.fx.experimental.sym_node
  2126. from torch import fx as fx
  2127. # Register MPS specific decomps
  2128. torch.backends.mps._init()
  2129. from torch import compiler as compiler
  2130. class _TritonLibrary:
  2131. lib = torch.library.Library("triton", "DEF")
  2132. ops_table: dict[tuple[str, str], _Callable] = {}
  2133. @classmethod
  2134. def registerOp(cls, op_key, full_schema, op_impl, dispatch_key):
  2135. if (op_key, dispatch_key) not in cls.ops_table:
  2136. cls.lib.define(full_schema)
  2137. cls.lib.impl("triton::" + op_key, op_impl, dispatch_key)
  2138. cls.ops_table[(op_key, dispatch_key)] = op_impl
  2139. return cls.ops_table[(op_key, dispatch_key)]
  2140. # Deprecated attributes
  2141. _deprecated_attrs = {
  2142. "has_mps": torch.backends.mps.is_built,
  2143. "has_cuda": torch.backends.cuda.is_built,
  2144. "has_cudnn": torch.backends.cudnn.is_available,
  2145. "has_mkldnn": torch.backends.mkldnn.is_available,
  2146. }
  2147. if TYPE_CHECKING:
  2148. # Import the following modules during type checking to enable code intelligence features,
  2149. # such as auto-completion in tools like pylance, even when these modules are not explicitly
  2150. # imported in user code.
  2151. from torch import (
  2152. _dynamo as _dynamo,
  2153. _inductor as _inductor,
  2154. _subclasses as _subclasses,
  2155. onnx as onnx,
  2156. )
  2157. else:
  2158. _lazy_modules = {
  2159. "_dynamo",
  2160. "_inductor",
  2161. "_export",
  2162. # ONNX must be imported after _dynamo, _ops, _subclasses, fx, func and jit
  2163. "onnx",
  2164. }
  2165. def __getattr__(name):
  2166. # Deprecated attrs
  2167. replacement = _deprecated_attrs.get(name)
  2168. if replacement is not None:
  2169. import warnings
  2170. warnings.warn(
  2171. f"'{name}' is deprecated, please use '{replacement.__module__}.{replacement.__name__}()'",
  2172. stacklevel=2,
  2173. )
  2174. return replacement()
  2175. # Lazy modules
  2176. if name in _lazy_modules:
  2177. return importlib.import_module(f".{name}", __name__)
  2178. raise AttributeError(f"module '{__name__}' has no attribute '{name}'")
  2179. @functools.cache
  2180. def get_device_module(device: _Optional[_Union[torch.device, str]] = None):
  2181. """
  2182. Returns the module associated with a given device(e.g., torch.device('cuda'), "mtia:0", "xpu", ...).
  2183. If no device is given, return the module for the current accelerator or CPU if none is present.
  2184. """
  2185. if isinstance(device, torch.device):
  2186. device_module_name = device.type
  2187. elif isinstance(device, str):
  2188. device_module_name = torch.device(device).type
  2189. elif device is None:
  2190. # Using default accelerator type. If no accelerator is available, it automatically returns CPU device.
  2191. device_module_name = torch._C._get_accelerator().type
  2192. else:
  2193. raise RuntimeError(
  2194. f"Invalid value of device '{device}', expect torch.device, str, or None"
  2195. )
  2196. device_module = getattr(torch, device_module_name, None)
  2197. if device_module is None:
  2198. raise RuntimeError(
  2199. f"Device '{device_module_name}' does not have a corresponding module registered as 'torch.{device_module_name}'."
  2200. )
  2201. return device_module
  2202. def _constrain_as_size(
  2203. symbol,
  2204. min: _Optional[builtins.int] = None,
  2205. max: _Optional[builtins.int] = None,
  2206. ):
  2207. """
  2208. This indicates that a given int is size-like, and can be used in any context where a size is expected.
  2209. You will typically use this when reading out integers from Tensors, e.g., max.item() or lengths.tolist()
  2210. which then need to be used as tensor constructors. Providing these assertions to PyTorch can help resolve
  2211. GuardOnDataDependentSymNode errors upon export, since we cannot guard on unbacked SymInts.
  2212. This function has unusual semantics in some circumstances in framework
  2213. code, we will treat this int as >= 2 (when we do a size-oblivious guard).
  2214. This makes it easier to use the unbacked int in size contexts,
  2215. as we will often attempt to guard on a size being zero/one
  2216. (e.g., when computing the contiguity of a tensor, or testing if
  2217. broadcasting can occur), which will not work on unbacked SymInts.
  2218. However, if we conservatively assume that the size is not zero/one, we will
  2219. end up with a graph that will still work even if the size is zero/one.
  2220. For more details, see https://docs.google.com/document/d/1HSuTTVvYH1pTew89Rtpeu84Ht3nQEFTYhAX3Ypa_xJs/edit
  2221. ```
  2222. """
  2223. torch.sym_constrain_range_for_size(symbol, min=min, max=max)
  2224. from torch import _logging
  2225. _logging._init_logs()
  2226. def _import_device_backends():
  2227. """
  2228. Leverage the Python plugin mechanism to load out-of-the-tree device extensions.
  2229. See this RFC: https://github.com/pytorch/pytorch/issues/122468
  2230. """
  2231. from importlib.metadata import entry_points
  2232. group_name = "torch.backends"
  2233. if sys.version_info < (3, 10):
  2234. backend_extensions = entry_points().get(group_name, ())
  2235. else:
  2236. backend_extensions = entry_points(group=group_name)
  2237. for backend_extension in backend_extensions:
  2238. try:
  2239. # Load the extension
  2240. entrypoint = backend_extension.load()
  2241. # Call the entrypoint
  2242. entrypoint()
  2243. except Exception as err:
  2244. raise RuntimeError(
  2245. f"Failed to load the backend extension: {backend_extension.name}. "
  2246. f"You can disable extension auto-loading with TORCH_DEVICE_BACKEND_AUTOLOAD=0."
  2247. ) from err
  2248. def _is_device_backend_autoload_enabled() -> builtins.bool:
  2249. """
  2250. Whether autoloading out-of-the-tree device extensions is enabled.
  2251. The switch depends on the value of the environment variable
  2252. `TORCH_DEVICE_BACKEND_AUTOLOAD`.
  2253. Returns:
  2254. bool: Whether to enable autoloading the extensions. Enabled by default.
  2255. Examples:
  2256. >>> torch._is_device_backend_autoload_enabled()
  2257. True
  2258. """
  2259. # enabled by default
  2260. return os.getenv("TORCH_DEVICE_BACKEND_AUTOLOAD", "1") == "1"
  2261. def _as_tensor_fullprec(t):
  2262. """
  2263. Like torch.as_tensor, but when given Python data types it will keep
  2264. them in full precision. Used for calling convention for Dynamo.
  2265. """
  2266. ty = type(t)
  2267. if ty is builtins.float:
  2268. return torch.as_tensor(t, dtype=torch.float64)
  2269. elif ty is builtins.int:
  2270. return torch.as_tensor(t, dtype=torch.int64)
  2271. else:
  2272. return torch.as_tensor(t)
  2273. # `_import_device_backends` should be kept at the end to ensure
  2274. # all the other functions in this module that may be accessed by
  2275. # an autoloaded backend are defined
  2276. if _is_device_backend_autoload_enabled():
  2277. _import_device_backends()