__init__.py 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690
  1. from __future__ import annotations
  2. from typing import Any, Union, Sequence, Optional, Tuple, List, Callable, Type, overload, cast
  3. from enum import Enum
  4. from functools import reduce, cmp_to_key
  5. import operator
  6. import weakref
  7. import torch
  8. from torch import sym_float, sym_int, sym_max
  9. try:
  10. from nvfuser._C import DataType # type: ignore[import]
  11. _torch_dtype_to_nvfuser_dtype_map = {
  12. torch.cdouble: DataType.ComplexDouble,
  13. torch.cfloat: DataType.ComplexFloat,
  14. torch.double: DataType.Double,
  15. torch.float: DataType.Float,
  16. torch.half: DataType.Half,
  17. torch.bfloat16: DataType.BFloat16,
  18. torch.long: DataType.Int,
  19. torch.int: DataType.Int32,
  20. torch.uint8: DataType.Int32,
  21. torch.bool: DataType.Bool,
  22. # Python scalars
  23. complex: DataType.ComplexDouble,
  24. float: DataType.Double,
  25. int: DataType.Int,
  26. bool: DataType.Bool,
  27. }
  28. except ImportError:
  29. _torch_dtype_to_nvfuser_dtype_map = {}
  30. def getnvFuserDtype(dtype: Union[torch.dtype, NumberTypeType]):
  31. """
  32. Translates from torch.dtype to nvFuser's DataType enum
  33. """
  34. return _torch_dtype_to_nvfuser_dtype_map[dtype]
  35. ShapeType = Union[torch.Size, List[int], Tuple[int, ...]]
  36. StrideType = Union[List[int], Tuple[int, ...]]
  37. DimsType = Union[int, List[int], Tuple[int, ...]]
  38. DimsSequenceType = Union[List[int], Tuple[int, ...]]
  39. # TODO: Type[torch.SymInt], Type[torch.SymFloat]
  40. NumberTypeType = Union[Type[bool], Type[int], Type[float], Type[complex]]
  41. # TODO: This needs a lot more type annotations
  42. # NumberType = Union[bool, int, float, complex, torch.SymInt, torch.SymFloat]
  43. NumberType = Union[bool, int, float, complex]
  44. Number = (bool, int, float, complex, torch.SymInt, torch.SymFloat)
  45. # I don't call it Integral because numbers.Integral includes bool, but IntLike
  46. # does not
  47. Dim = int
  48. IntLike = (int, torch.SymInt)
  49. FloatLike = (float, torch.SymFloat)
  50. IntWithoutSymInt = int
  51. FloatWithoutSymFloat = float
  52. DeviceLikeType = Union[str, torch.device]
  53. Tensor = torch.Tensor
  54. torch_function_passthrough = {
  55. torch.Tensor.dim,
  56. torch.Tensor.ndim.__get__, # type: ignore[attr-defined]
  57. torch.Tensor.numel,
  58. torch.Tensor.size,
  59. torch.Tensor.storage_offset,
  60. torch.Tensor.stride,
  61. torch.Tensor.dtype.__get__, # type: ignore[attr-defined]
  62. torch.Tensor.is_sparse.__get__, # type: ignore[attr-defined]
  63. torch.Tensor.shape.__get__, # type: ignore[attr-defined]
  64. torch.Tensor.device.__get__, # type: ignore[attr-defined]
  65. torch.Tensor.requires_grad.__get__, # type: ignore[attr-defined]
  66. torch.Tensor.layout.__get__, # type: ignore[attr-defined]
  67. # For TorchRefsMode only
  68. torch.Tensor.__format__,
  69. torch.Tensor.__repr__,
  70. torch.Tensor.requires_grad.__get__, # type: ignore[attr-defined]
  71. }
  72. TensorLikeType = torch.Tensor
  73. TensorLike = torch.Tensor
  74. TensorSequenceType = Union[List[TensorLikeType], Tuple[TensorLikeType, ...]]
  75. TensorOrNumberLikeType = Union[TensorLikeType, NumberType]
  76. def same_shape(a: ShapeType, b: ShapeType) -> bool:
  77. if len(a) != len(b):
  78. return False
  79. for x, y in zip(a, b):
  80. if x != y:
  81. return False
  82. return True
  83. # TODO: look at using torch.testing.assert_close instead with an option
  84. # to just compare metadata
  85. def compare_tensor_meta(a: TensorLikeType, b: TensorLikeType, check_strides=False):
  86. """
  87. Checks that two tensor likes have the same shape,
  88. dtype and device.
  89. In the future this will validate additional metadata, like
  90. strides.
  91. """
  92. assert isinstance(a, TensorLike)
  93. assert isinstance(b, TensorLike)
  94. if not same_shape(a.shape, b.shape):
  95. msg = "Shapes {0} and {1} are not equal!".format(a.shape, b.shape)
  96. raise AssertionError(msg)
  97. if a.dtype != b.dtype:
  98. msg = "Dtypes {0} and {1} are not equal!".format(a.dtype, b.dtype)
  99. raise AssertionError(msg)
  100. if a.device != b.device:
  101. # Handles special cuda:0 vs cuda case
  102. # TODO: we should review why this happens and see about fixing it
  103. if (str(a.device) == "cuda:0" or str(a.device) == "cuda") and (
  104. str(b.device) == "cuda:0" or str(b.device) == "cuda"
  105. ):
  106. pass
  107. else:
  108. msg = "Devices {0} and {1} are not equal!".format(a.device, b.device)
  109. raise AssertionError(msg)
  110. # Stride checking is currently disabled, see https://github.com/pytorch/pytorch/issues/78050
  111. if check_strides:
  112. same_strides, idx = check_significant_strides(a, b)
  113. if not same_strides:
  114. msg = (
  115. "Stride mismatch! Strides are {0} and {1} (mismatched at {2})!".format(
  116. a.stride(), b.stride(), idx
  117. )
  118. )
  119. raise RuntimeError(msg)
  120. if a.storage_offset() != b.storage_offset():
  121. msg = (
  122. "Storage offset mismatch! Storage offsets are {0} and {1}!".format(
  123. a.storage_offset(), b.storage_offset()
  124. )
  125. )
  126. raise RuntimeError(msg)
  127. def _check_strides_helper(
  128. a: TensorLikeType, b: TensorLikeType, *, only_cuda=True, significant_only=True
  129. ) -> Tuple[bool, Optional[int]]:
  130. # NOTE: only on CUDA because CPU elementwise strides are incorrect in PyTorch
  131. # See https://github.com/pytorch/pytorch/issues/77553
  132. # Only compares strides that are "meaningful" -- strides for dimensions with length > 1
  133. # and for tensors with more than one element
  134. if (not only_cuda or a.device.type == "cuda" or b.device.type == "cuda") and a.numel() > 0:
  135. for idx in range(a.ndim):
  136. check = not significant_only or a.shape[idx] > 1
  137. if a.stride()[idx] != b.stride()[idx] and check:
  138. return False, idx
  139. return True, None
  140. def check_significant_strides(
  141. a: TensorLikeType, b: TensorLikeType, *, only_cuda=True
  142. ) -> Tuple[bool, Optional[int]]:
  143. return _check_strides_helper(a, b, only_cuda=only_cuda, significant_only=True)
  144. def check_all_strides(
  145. a: TensorLikeType, b: TensorLikeType, *, only_cuda=True
  146. ) -> Tuple[bool, Optional[int]]:
  147. return _check_strides_helper(a, b, only_cuda=only_cuda, significant_only=False)
  148. # This function is equivalent to compute_contiguous() from TensorImpl.cpp
  149. def is_contiguous(a: TensorLikeType) -> bool:
  150. """
  151. Tests whether a tensor is contiguous or not.
  152. Tensors are contiguous when they have no elements,
  153. one element, or when they have "nested" strides.
  154. """
  155. if a.numel() < 2:
  156. return True
  157. expected_stride = 1
  158. for x, y in reversed(tuple(zip(a.shape, a.stride()))):
  159. # Skips checking strides when a dimension has length 1
  160. if x == 1:
  161. continue
  162. if y != expected_stride:
  163. return False
  164. expected_stride = expected_stride * x
  165. return True
  166. # This function is equivalent to compute_channels_last_contiguous_2d() in TensorImpl.cpp
  167. def is_channels_last_contiguous_2d(a: Tensor) -> bool:
  168. # NHWC or not channels last 2D contiguous
  169. if a.ndim != 4:
  170. return False
  171. expected_stride = 1
  172. for idx in (1, 3, 2, 0):
  173. length = a.shape[idx]
  174. if length == 1:
  175. continue
  176. stride = a.stride()[idx]
  177. if stride != expected_stride:
  178. return False
  179. expected_stride *= length
  180. return True
  181. def is_channels_last_contiguous_3d(a: Tensor) -> bool:
  182. # NDHWC or not channels last 3D contiguous
  183. if a.ndim != 5:
  184. return False
  185. expected_stride = 1
  186. for idx in (1, 4, 3, 2, 0):
  187. length = a.shape[idx]
  188. if length == 1:
  189. continue
  190. stride = a.stride()[idx]
  191. if stride != expected_stride:
  192. return False
  193. expected_stride *= length
  194. return True
  195. _memory_formats = {
  196. torch.contiguous_format,
  197. torch.preserve_format,
  198. torch.channels_last,
  199. torch.channels_last_3d,
  200. }
  201. def validate_memory_format(memory_format: torch.memory_format):
  202. check(
  203. memory_format in _memory_formats,
  204. lambda: f"Received unknown memory format {memory_format}!",
  205. )
  206. def is_contiguous_for_memory_format( # type: ignore[return]
  207. a: Tensor, *, memory_format: torch.memory_format
  208. ) -> bool:
  209. validate_memory_format(memory_format)
  210. if memory_format == torch.contiguous_format:
  211. return is_contiguous(a)
  212. if memory_format == torch.channels_last:
  213. return is_channels_last_contiguous_2d(a)
  214. if memory_format == torch.channels_last_3d:
  215. return is_channels_last_contiguous_3d(a)
  216. check(
  217. False,
  218. lambda: f"is_contiguous received unsupported memory format {memory_format}",
  219. )
  220. # NOTE: that tensors with no elements and channels last is ???
  221. def is_channels_last_contiguous(a: Tensor) -> bool:
  222. """
  223. True when a tensor is channels-last contiguous.
  224. This requires that:
  225. - the tensor is conceptually either 4 (NHWC) or 5 (NDHWC) dimensions
  226. - if we name the tensor's dimensions NCHW or NCDHW, then the strides are such that the
  227. stride of the 'C' dimension (Cs) is 1 and the strides corresponding to
  228. each dimension (Xs) can be ordered Cs <= Ws <= Hs <= (Ds) <= Ns and are
  229. "nested" -- so Ws = Cs * Cl, where Cl is the length of the 'C' dimension,
  230. for example.
  231. """
  232. return is_channels_last_contiguous_2d(a) or is_channels_last_contiguous_3d(a)
  233. def is_non_overlapping_and_dense(a: Tensor) -> bool:
  234. """
  235. True when a tensor is non-overlapping and dense.
  236. A tensor is non-overlapping and dense when there exists a permutation of
  237. its dimensions that is contiguous.
  238. """
  239. if a.is_sparse:
  240. return False
  241. # Short-circuits if the tensor is already contiguous or channels-last contiguous
  242. if is_contiguous(a) or is_channels_last_contiguous(a):
  243. return True
  244. # The following is equivalent to compute_non_overlapping_and_dense in TensorImpl.cpp
  245. # Short-circuits for tensors of rank one, which are
  246. # non-overlapping and "dense" if their stride is one
  247. if a.ndim == 1:
  248. return a.stride()[0] == 1
  249. # Checks that there exists a permutation of the strides s.t. the tensor would be contiguous
  250. # Sorts (length, stride) pairs by stride
  251. lengths_and_strides = sorted(
  252. zip(a.shape, a.stride()), key=operator.itemgetter(1)
  253. )
  254. expected_stride = 1
  255. for length, stride in lengths_and_strides:
  256. if length == 1:
  257. continue
  258. if stride != expected_stride:
  259. return False
  260. expected_stride *= length
  261. return True
  262. # NOTE: Based on the implementation in TensorIterator.cpp, but note that
  263. # the note [Computing output strides] is incorrect, because it
  264. # says that strides will be preserved even if they are not
  265. # "non overlapping and dense", but this is incorrect. The
  266. # output of elementwise operations are always given
  267. # non overlapping and dense strides.
  268. # This is also INCORRECT because it does not model TensorIterator's
  269. # short-circuit, which can cause different strides.
  270. def compute_elementwise_output_strides(*tensors) -> Tuple[int, ...]:
  271. """
  272. Computes the output strides for elementwise operations.
  273. """
  274. if len(tensors) == 0:
  275. msg = "Can't compute elementwise output strides for zero tensors!"
  276. raise ValueError(msg)
  277. check_same_shape(*tensors, allow_cpu_scalar_tensors=True)
  278. # Filters the tensors to actual tensors
  279. tensors = tuple(
  280. a for a in tensors if isinstance(a, TensorLike) and not is_cpu_scalar_tensor(a)
  281. )
  282. # Short-circuits for CPU scalar case
  283. if len(tensors) == 0:
  284. return ()
  285. # Short-circuits for shapes with zero or one dimensions
  286. # TODO: are these necessary?
  287. ndim = tensors[0].ndim
  288. if ndim == 0:
  289. return ()
  290. if ndim == 1:
  291. return (1,)
  292. shape = tensors[0].shape
  293. def should_swap(idx_a, idx_b):
  294. for tensor in tensors:
  295. stride_a = tensor.stride()[idx_a]
  296. stride_b = tensor.stride()[idx_b]
  297. if stride_a == 0 or stride_b == 0:
  298. continue
  299. if stride_a < stride_b:
  300. return -1
  301. if stride_a > stride_b:
  302. return 1
  303. # stride_a == stride_b
  304. if shape[idx_a] > shape[idx_b]:
  305. return 1
  306. # Note: this case is hit if all strides are zero,
  307. # or all strides are equal and all dimensions have the same length
  308. return 0
  309. perm = list(reversed(range(ndim)))
  310. # insertion sort with support for ambiguous comparisons
  311. for i in range(1, ndim):
  312. dim1 = i
  313. for dim0 in reversed(range(i)):
  314. comparison = should_swap(perm[dim0], perm[dim1])
  315. if comparison > 0:
  316. perm[dim0], perm[dim1] = perm[dim1], perm[dim0]
  317. dim1 = dim0
  318. elif comparison < 0:
  319. break
  320. permuted_shape = [-1] * ndim
  321. for idx, x in enumerate(reversed(perm)):
  322. permuted_shape[idx] = shape[x]
  323. new_strides = make_contiguous_strides_for(permuted_shape)
  324. permuted_strides = [-1] * ndim
  325. for idx, x in enumerate(reversed(perm)):
  326. permuted_strides[x] = new_strides[idx]
  327. return tuple(permuted_strides)
  328. #
  329. # Common helper functions
  330. #
  331. def validate_dim_length(length: int):
  332. """
  333. Validates that an object represents a valid
  334. dimension length.
  335. """
  336. assert length >= 0
  337. def validate_shape(shape: ShapeType):
  338. """
  339. Validates that a sequence represents a valid shape.
  340. """
  341. assert isinstance(shape, Sequence)
  342. for l in shape:
  343. validate_dim_length(l)
  344. def validate_strides(strides: StrideType):
  345. """
  346. Verifies the object specifies valid strides.
  347. """
  348. assert isinstance(strides, Sequence)
  349. for stride in strides:
  350. assert stride >= 0
  351. def validate_idx(rank: int, idx: int):
  352. """
  353. Validates that idx is a valid index for the given shape.
  354. Assumes the index is already canonicalized.
  355. """
  356. assert isinstance(idx, Dim)
  357. assert isinstance(rank, Dim)
  358. assert idx >= 0 and idx < rank or idx == 0
  359. def validate_dimension_indices(rank: int, indices: DimsSequenceType):
  360. for idx in indices:
  361. validate_idx(rank, idx)
  362. def validate_exclusive_idx(rank: int, ex_idx: int):
  363. """
  364. Validates that ex_idx is a valid exclusive index
  365. for the given shape.
  366. """
  367. assert isinstance(ex_idx, Dim)
  368. assert isinstance(rank, Dim)
  369. assert ex_idx > 0 and ex_idx <= rank
  370. # "Wraps" a dim (up to one time) for the given rank, allowing dims to be
  371. # specified using negative indices. If `wrap_scalar` is true then scalar
  372. # tensors of rank 0 will allow dimensions in the range [-1, 0]. Otherwise,
  373. # idx should be in the range [-rank, rank-1].
  374. def canonicalize_dim(rank: int, idx: int, wrap_scalar: bool = True) -> int:
  375. if rank < 0:
  376. msg = f"Rank cannot be negative but got {rank}"
  377. raise IndexError(msg)
  378. if rank == 0:
  379. if not wrap_scalar:
  380. msg = f"Dimension specified as {idx} but tensor has no dimensions"
  381. raise IndexError(msg)
  382. rank = 1
  383. if idx >= 0 and idx < rank:
  384. return idx
  385. if idx < 0:
  386. _idx = idx + rank
  387. else:
  388. _idx = idx
  389. if _idx < 0 or _idx >= rank:
  390. # Same error message as in aten/src/ATen/WrapDimUtils.h:49
  391. msg = "Dimension out of range (expected to be in range of [{0}, {1}], but got {2})".format(
  392. -rank, rank - 1, idx
  393. )
  394. raise IndexError(msg)
  395. return _idx
  396. # Takes a dimension or sequence of dimensions and "wraps" them,
  397. # mapping negative offsets to positive ones
  398. @overload
  399. def canonicalize_dims(rank: int, indices: Sequence[int], wrap_scalar: bool = True) -> Tuple[int, ...]:
  400. pass
  401. @overload
  402. def canonicalize_dims(rank: int, indices: int, wrap_scalar: bool = True) -> int:
  403. pass
  404. def canonicalize_dims(rank, indices, wrap_scalar=True):
  405. if isinstance(indices, Dim):
  406. return canonicalize_dim(rank, indices, wrap_scalar)
  407. return tuple(canonicalize_dim(rank, x, wrap_scalar) for x in indices)
  408. def is_valid_permutation(rank: int, perm: DimsSequenceType) -> bool:
  409. """
  410. Validates that perm is a permutation of length rank.
  411. """
  412. if not isinstance(perm, Sequence):
  413. return False
  414. if not (tuple(sorted(perm)) == tuple(range(0, rank))):
  415. return False
  416. return True
  417. def is_same_shape(a: Sequence, b: Sequence) -> bool:
  418. """
  419. Compares two shapes a and b, returning True if they are the same
  420. (their ranks and corresponding lengths match) and False otherwise.
  421. """
  422. return tuple(a) == tuple(b)
  423. def is_cpu_scalar_tensor(a: Any) -> bool:
  424. return isinstance(a, TensorLike) and a.ndim == 0 and a.device.type == "cpu"
  425. def check_same_device(*args, allow_cpu_scalar_tensors):
  426. """
  427. Checks that all Tensors in args have the same device.
  428. Raises a RuntimeError when:
  429. - args contains an object whose type is not Tensor or Number
  430. - two Tensor objects in args have different devices, unless one is a CPU scalar tensor and allow_cpu_scalar_tensors is True
  431. """
  432. # Short-circuits if all (one or fewer) arguments are trivially on the same device
  433. if len(args) <= 1:
  434. return
  435. # Note: cannot initialize device to the first arg's device (it may not have one)
  436. device = None
  437. for arg in args:
  438. if isinstance(arg, Number):
  439. continue
  440. elif isinstance(arg, TensorLike):
  441. if allow_cpu_scalar_tensors and is_cpu_scalar_tensor(arg):
  442. continue
  443. if device is None:
  444. device = arg.device
  445. if device != arg.device:
  446. msg = (
  447. "Tensor on device "
  448. + str(arg.device)
  449. + " is not on the expected device "
  450. + str(device)
  451. + "!"
  452. )
  453. raise RuntimeError(msg)
  454. else:
  455. msg = (
  456. "Unexpected type when checking for same device, " + str(type(arg)) + "!"
  457. )
  458. raise RuntimeError(msg)
  459. def canonicalize_device(device: DeviceLikeType) -> torch.device:
  460. if isinstance(device, torch.device):
  461. return device
  462. assert isinstance(device, str)
  463. return torch.device(device)
  464. # Asserts if any of the following are true:
  465. # - a non-scalar or non-Tensor is given
  466. # - the shape of any tensors is distinct
  467. def check_same_shape(*args, allow_cpu_scalar_tensors: bool):
  468. """
  469. Checks that all Tensors in args have the same shape.
  470. Raises a RuntimeError when:
  471. - args contains an object whose type is not Tensor or Number
  472. - two Tensor objects in args have different devices
  473. """
  474. shape = None
  475. for arg in args:
  476. if isinstance(arg, Number):
  477. continue
  478. elif isinstance(arg, TensorLike):
  479. if allow_cpu_scalar_tensors and is_cpu_scalar_tensor(arg):
  480. continue
  481. if shape is None:
  482. shape = arg.shape
  483. if not is_same_shape(shape, arg.shape):
  484. msg = "Shape {0} is not the expected shape {1}!".format(
  485. arg.shape, shape
  486. )
  487. raise RuntimeError(msg)
  488. else:
  489. msg = (
  490. "Unexpected type when checking for same shape, " + str(type(arg)) + "!"
  491. )
  492. raise RuntimeError(msg)
  493. # Acquires a common shape, if it exists, from one or more tensor arguments,
  494. # filtering number arguments
  495. def extract_shape(*args, allow_cpu_scalar_tensors: bool) -> Optional[ShapeType]:
  496. shape = None
  497. scalar_shape = None
  498. for arg in args:
  499. if isinstance(arg, Number):
  500. continue
  501. elif isinstance(arg, TensorLike):
  502. if allow_cpu_scalar_tensors and is_cpu_scalar_tensor(arg):
  503. scalar_shape = arg.shape
  504. continue
  505. if shape is None:
  506. shape = arg.shape
  507. if not is_same_shape(shape, arg.shape):
  508. return None
  509. else:
  510. return None
  511. return shape if shape is not None else scalar_shape
  512. # Extracts dimensions that might be passed either as a list/tuple or as varargs.
  513. # A typical case is Tensor.permute .
  514. def extract_dims_from_varargs(dims: Union[DimsSequenceType, Tuple[DimsSequenceType, ...]]) -> DimsSequenceType:
  515. if dims and isinstance(dims[0], Sequence):
  516. assert len(dims) == 1
  517. dims = cast(Tuple[DimsSequenceType], dims)
  518. return dims[0]
  519. else:
  520. return cast(DimsSequenceType, dims)
  521. def extract_shape_from_varargs(
  522. shape: Union[ShapeType, Tuple[ShapeType]],
  523. validate=True,
  524. ) -> Tuple[int, ...]:
  525. """
  526. Returns a shape from varargs.
  527. In PyTorch, operations that accept shapes often accept them as varargs, like
  528. foo(*shape). However a user can pass the shape as a sequence of integers,
  529. like this:
  530. foo(1, 2, 3)
  531. or as a sequence of integers
  532. foo((1, 2, 3))
  533. In the first case shape will be a tuple of integers, and in the second case it's a tuple
  534. containing a tuple of integers. This validates those inputs and canonicalizes them
  535. to a tuple of integers.
  536. """
  537. # Handles tuple unwrapping
  538. if len(shape) == 1 and isinstance(shape[0], Sequence):
  539. shape = shape[0]
  540. if validate:
  541. validate_shape(shape) # type: ignore[arg-type]
  542. return shape # type: ignore[return-value]
  543. def infer_size(shape: ShapeType, numel: int) -> Tuple[int, ...]:
  544. """
  545. Infers the size of a dim with size -1, if it exists.
  546. Also checks that new shape is compatible with the number of elements.
  547. """
  548. dim = None
  549. newsize = 1
  550. for i, d in enumerate(shape):
  551. if d == -1:
  552. check(dim is None, lambda: "only one dimension can be inferred")
  553. dim = i
  554. elif d >= 0:
  555. newsize *= d
  556. else:
  557. check(False, lambda: f"invalid shape dimension {d}")
  558. check(
  559. numel == newsize or (dim is not None and newsize > 0 and numel % newsize == 0),
  560. lambda: f"shape '{list(shape)}' is invalid for input of size {numel}",
  561. )
  562. if dim is not None:
  563. # Convert to list to produce a compatible error message with core
  564. # PyTorch, which prints sequences in square brackets.
  565. shape = list(shape)
  566. check(
  567. newsize != 0,
  568. lambda: (f"cannot reshape tensor of 0 elements into shape {shape} because the "
  569. f"unspecified dimension size -1 can be any value and is ambiguous"),
  570. )
  571. shape[dim] = numel // newsize
  572. return tuple(shape)
  573. _integer_dtypes = (torch.uint8, torch.int8, torch.int16, torch.int32, torch.int64)
  574. _low_precision_dtypes = (torch.float16, torch.bfloat16, torch.complex32)
  575. _float_dtypes = (torch.float16, torch.bfloat16, torch.float32, torch.float64)
  576. _complex_dtypes = (torch.complex32, torch.complex64, torch.complex128)
  577. def is_boolean_dtype(dtype: torch.dtype) -> bool:
  578. assert isinstance(dtype, torch.dtype)
  579. return dtype is torch.bool
  580. def is_integer_dtype(dtype: torch.dtype) -> bool:
  581. assert isinstance(dtype, torch.dtype)
  582. return dtype in _integer_dtypes
  583. def is_low_precision_dtype(dtype: torch.dtype) -> bool:
  584. assert isinstance(dtype, torch.dtype)
  585. return dtype in _low_precision_dtypes
  586. def is_float_dtype(dtype: torch.dtype) -> bool:
  587. assert isinstance(dtype, torch.dtype)
  588. return dtype in _float_dtypes
  589. def is_complex_dtype(dtype: torch.dtype) -> bool:
  590. assert isinstance(dtype, torch.dtype)
  591. return dtype in _complex_dtypes
  592. def is_grad_dtype(dtype: torch.dtype) -> bool:
  593. """
  594. Checks if the dtype can require a gradient.
  595. """
  596. return is_float_dtype(dtype) or is_complex_dtype(dtype)
  597. _complex_to_real_dtype_map = {
  598. torch.complex128: torch.float64,
  599. torch.complex64: torch.float32,
  600. torch.complex32: torch.float16,
  601. }
  602. _real_to_complex_dtype_map = {
  603. torch.float16: torch.complex32,
  604. torch.bfloat16: torch.complex64,
  605. torch.float32: torch.complex64,
  606. torch.float64: torch.complex128,
  607. }
  608. def corresponding_real_dtype(dtype: torch.dtype) -> torch.dtype:
  609. return _complex_to_real_dtype_map[dtype]
  610. def corresponding_complex_dtype(dtype: torch.dtype) -> torch.dtype:
  611. return _real_to_complex_dtype_map[dtype]
  612. def dtype_to_type(dtype: torch.dtype) -> type:
  613. """
  614. Computes the corresponding Python type (AKA "type kind") for the
  615. given dtype.
  616. """
  617. assert isinstance(dtype, torch.dtype)
  618. if dtype is torch.bool:
  619. return bool
  620. if dtype in _integer_dtypes:
  621. return int
  622. if dtype in _float_dtypes:
  623. return float
  624. if dtype in _complex_dtypes:
  625. return complex
  626. raise ValueError("Invalid dtype!")
  627. def dtype_to_type_ctor(dtype: torch.dtype) -> Callable[[NumberType], NumberType]:
  628. """
  629. Computes the corresponding Python type constructor for the
  630. given dtype.
  631. """
  632. assert isinstance(dtype, torch.dtype)
  633. if dtype is torch.bool:
  634. return lambda x: bool(x)
  635. if dtype in _integer_dtypes:
  636. return sym_int
  637. if dtype in _float_dtypes:
  638. return sym_float
  639. if dtype in _complex_dtypes:
  640. # TODO: type error here is real, replace with sym_complex
  641. return lambda x: complex(x) # type: ignore[arg-type]
  642. raise ValueError("Invalid dtype!")
  643. def type_to_dtype(typ: type) -> torch.dtype:
  644. """
  645. Computes the corresponding dtype for a Number type.
  646. """
  647. assert isinstance(typ, type)
  648. if typ is bool:
  649. return torch.bool
  650. if typ in [int, torch.SymInt]:
  651. return torch.long
  652. if typ in [float, torch.SymFloat]:
  653. return torch.get_default_dtype()
  654. # TODO: sym_complex_float?
  655. if typ is complex:
  656. return corresponding_complex_dtype(torch.get_default_dtype())
  657. raise ValueError("Invalid type!")
  658. def get_dtype(x: Union[torch.Tensor, NumberType]):
  659. if isinstance(x, torch.Tensor):
  660. return x.dtype
  661. else:
  662. return type_to_dtype(type(x))
  663. _ordered_types = (bool, int, float, complex)
  664. def check_fp_or_complex(
  665. dtype: torch.dtype, fn_name: str, allow_low_precision_dtypes: bool = True
  666. ):
  667. """
  668. Checks whether the input is floating point or complex.
  669. If allow_low_precision_dtypes is True, it allows having float16, bfloat16, and complex32
  670. """
  671. check(
  672. is_float_dtype(dtype) or is_complex_dtype(dtype),
  673. lambda: f"{fn_name}: Expected a floating point or complex tensor as input. Got {dtype}",
  674. )
  675. check(
  676. allow_low_precision_dtypes or not is_low_precision_dtype(dtype),
  677. lambda: f"{fn_name}: Half precision dtypes not supported. Got {dtype}",
  678. )
  679. def check_is_matrix(A: TensorLikeType, f_name: str, arg_name: str = "A"):
  680. check(
  681. len(A.shape) >= 2,
  682. lambda: f"{f_name}: The input tensor {arg_name} must have at least 2 dimensions.",
  683. )
  684. def get_higher_type(a: type, b: type) -> type:
  685. """
  686. Returns the higher of the two given Number types.
  687. The types are ordered bool -> int -> float -> complex.
  688. """
  689. # Type checking
  690. assert a in _ordered_types
  691. assert b in _ordered_types
  692. if a is b:
  693. return a
  694. for typ in _ordered_types:
  695. if a is typ:
  696. return b
  697. if b is typ:
  698. return a
  699. raise ValueError("Unknown Python scalar type!")
  700. # Returns the higher of two torch datatypes a and b or, if the two
  701. # are not ordered relative to each other, the next
  702. # higher datatype
  703. def get_higher_dtype(
  704. a: Optional[Union[torch.dtype, TensorLikeType, NumberType]],
  705. b: Optional[Union[torch.dtype, TensorLikeType, NumberType]],
  706. ) -> Optional[torch.dtype]:
  707. """
  708. Computes the "lowest" datatype that is weakly
  709. "higher" than both a and b.
  710. """
  711. # Type checking
  712. assert a is None or isinstance(a, (torch.dtype, TensorLike, Number))
  713. assert b is None or isinstance(b, (torch.dtype, TensorLike, Number))
  714. def _extract_dtype(
  715. x: Optional[Union[torch.dtype, TensorLikeType, NumberType]]
  716. ) -> Optional[torch.dtype]:
  717. if x is None:
  718. return None
  719. if isinstance(x, torch.dtype):
  720. return x
  721. if isinstance(x, TensorLike):
  722. return x.dtype
  723. if isinstance(x, Number):
  724. return type_to_dtype(type(x))
  725. raise RuntimeError("Unexpected type given to _extract_dtype!")
  726. a, b = _extract_dtype(a), _extract_dtype(b)
  727. if a is b:
  728. return a
  729. if a is None:
  730. return b
  731. if b is None:
  732. return a
  733. ordered_datatypes = (
  734. (torch.bool,),
  735. (torch.uint8, torch.int8),
  736. (torch.int16,),
  737. (torch.int32,),
  738. (torch.int64,),
  739. (torch.float16, torch.bfloat16),
  740. (torch.float32,),
  741. (torch.float64,),
  742. (torch.complex32,),
  743. (torch.complex64,),
  744. (torch.complex128,),
  745. )
  746. for idx, dtypes in enumerate(ordered_datatypes):
  747. if a in dtypes and b in dtypes:
  748. return ordered_datatypes[idx + 1][0]
  749. if a in dtypes:
  750. return b
  751. if b in dtypes:
  752. return a
  753. raise RuntimeError("Unexpected termination!")
  754. def check_pin_memory(pin_memory: bool):
  755. check(not pin_memory, lambda: "PrimTorch does not support pinned memory", NotImplementedError)
  756. def check_layout(layout: torch.layout):
  757. check(layout == torch.strided, lambda: f"PrimTorch doesn't support layout={layout}", NotImplementedError)
  758. # TODO: maybe unify with can_cast_to?
  759. def is_weakly_lesser_type(a: type, b: type) -> bool:
  760. """
  761. Compares two types, a and b, returning True if a is weakly "less" than b.
  762. The comparison is determined by the following type ordering: bool, int, float, complex.
  763. """
  764. ordered_types = (
  765. bool,
  766. int,
  767. float,
  768. complex,
  769. )
  770. assert a in ordered_types
  771. assert b in ordered_types
  772. for typ in ordered_types:
  773. if a == typ:
  774. return True
  775. if b == typ:
  776. return False
  777. raise RuntimeError("Unexpected termination!")
  778. def can_safe_cast_to(*, cast_to: torch.dtype, cast_from: torch.dtype) -> bool:
  779. for fn in (is_complex_dtype, is_float_dtype, is_integer_dtype, is_boolean_dtype):
  780. if fn(cast_to):
  781. return True
  782. if fn(cast_from):
  783. return False
  784. raise ValueError("Received unknown dtypes {0}, {1}!".format(cast_to, cast_from))
  785. def check_same_dtype(*args):
  786. """
  787. Checks that all Tensors in args have the same device and that all Numbers have the
  788. same corresponding Python type.
  789. Raises a RuntimeError when:
  790. - args contains an object whose type is not Tensor or Number
  791. - two Tensors objects in args have different dtypes
  792. - two Number objects in args have different types
  793. - there are Tensors and Numbers in args, and one of those Tensors corresponding
  794. Python types is different from the type of one of those Numbers
  795. """
  796. full_dtype = None
  797. scalar_type = None
  798. for arg in args:
  799. if isinstance(arg, Number):
  800. # Scalar type checking is disabled (and may be removed in the future)
  801. continue
  802. # if scalar_type is None:
  803. # scalar_type = type(arg)
  804. # if scalar_type is not type(arg):
  805. # msg = (
  806. # "Scalar of type "
  807. # + str(type(arg))
  808. # + " is not the expected type of "
  809. # + str(scalar_type)
  810. # + "!"
  811. # )
  812. # raise RuntimeError(msg)
  813. elif isinstance(arg, TensorLike):
  814. if full_dtype is None:
  815. full_dtype = arg.dtype
  816. if scalar_type is None:
  817. scalar_type = dtype_to_type(arg.dtype)
  818. if full_dtype is not arg.dtype:
  819. msg = (
  820. "Tensor with dtype "
  821. + str(arg.dtype)
  822. + " is not the expected dtype of "
  823. + str(full_dtype)
  824. + "!"
  825. )
  826. raise RuntimeError(msg)
  827. arg_type = dtype_to_type(arg.dtype)
  828. if arg_type is not scalar_type:
  829. msg = (
  830. "Tensor with corresponding Python type "
  831. + str(arg_type)
  832. + " is not the expected type of "
  833. + str(scalar_type)
  834. + "!"
  835. )
  836. raise RuntimeError(msg)
  837. else:
  838. msg = (
  839. "Unexpected type when checking for same dtype, " + str(type(arg)) + "!"
  840. )
  841. raise RuntimeError(msg)
  842. # Maps datatypes to their computation types for elementwise operations
  843. _computation_dtype_map = {
  844. torch.bfloat16: torch.float32,
  845. torch.float16: torch.float32,
  846. torch.complex32: torch.complex64,
  847. }
  848. def get_computation_dtype(dtype: torch.dtype) -> torch.dtype:
  849. return _computation_dtype_map.get(dtype, dtype)
  850. _cpu_acc_type_map = {
  851. torch.bfloat16: torch.float64,
  852. torch.float16: torch.float64,
  853. torch.float32: torch.float64,
  854. torch.complex32: torch.complex128,
  855. torch.complex64: torch.complex128,
  856. }
  857. def get_acc_type(dtype: torch.dtype, device: torch.device) -> torch.dtype:
  858. # Equivalent to at::toAccumulateType, prefer computation_dtype where possible
  859. if device.type == "cpu":
  860. return _cpu_acc_type_map.get(dtype, dtype)
  861. else:
  862. return get_computation_dtype(dtype)
  863. class ELEMENTWISE_TYPE_PROMOTION_KIND(Enum):
  864. DEFAULT = (0,)
  865. NO_OPMATH = (1,)
  866. INT_TO_FLOAT = (2,)
  867. ALWAYS_BOOL = (3,)
  868. COMPLEX_TO_FLOAT = (4,)
  869. BOOL_TO_LONG = (5,)
  870. class REDUCTION_OUTPUT_TYPE_KIND(Enum):
  871. SAME = (0,)
  872. COMPLEX_TO_FLOAT = (1,) # for complex types outputs corresponding real type
  873. KEEP_PROMOTED_TYPE = (2,) # keep output in opmath type, needed for mean
  874. ALWAYS_BOOL = (3,)
  875. # Describes the return type of the primitive:
  876. #
  877. # - NEW, a new tensor is created
  878. # - VIEW, a view of an input tensor is returned
  879. # - INPLACE, one or more input tensors is modified
  880. #
  881. # these descriptors are mututally exclusive and exhaustive.
  882. class RETURN_TYPE(Enum):
  883. NEW = (0,)
  884. VIEW = (1,)
  885. INPLACE = (2,)
  886. # TODO: when NumberType contains the sym types, can simplify this
  887. def number_type(x: Union[NumberType, torch.SymInt, torch.SymFloat]) -> Type:
  888. if isinstance(x, torch.SymInt):
  889. return int
  890. elif isinstance(x, torch.SymFloat):
  891. return float
  892. else:
  893. return type(x)
  894. # TODO: document type promotion kinds
  895. def elementwise_dtypes(
  896. *_args,
  897. type_promotion_kind: ELEMENTWISE_TYPE_PROMOTION_KIND,
  898. ) -> Tuple[torch.dtype, torch.dtype]:
  899. """
  900. Computes the computation and result dtypes for elementwise type promotion
  901. on the given arguments and with the given elementwise type promotion kind.
  902. Note that not all inputs to an elementwise operation necessarily participate in type promotion.
  903. For example, the "alpha" parameter of torch.add does not participate in type promotion,
  904. although it may be cast to the Python type corresponding to the computation dtype that
  905. the type promotion algorithm determines.
  906. Default elementwise type promotion, which all other type promotion kinds tweak (see below),
  907. first decides which of four ordered types to use:
  908. bool -> integer -> floating point -> complex
  909. The selected type is the "lowest" type in the above list such that all number arguments
  910. have a weakly "lower" type and all tensor arguments have a weakly lower corresponding
  911. type for their dtype.
  912. Once the type is determined, the particular result dtype is found. The dtypes are
  913. partially ordered as follows:
  914. bool -> uint8, int8 -> int16 -> int32 -> int64 ->
  915. float16, bfloat16 -> float32 -> float64 -> complex32 -> complex64 -> complex128
  916. The result dtype is selected by:
  917. - if no tensor's dtype has the same corresponding type as the one selected,
  918. then the result dtype is the (default) dtype corresponding to the selected type
  919. (for example, 1.5 + an integer tensor has a result dtype of the default floating point dtype)
  920. - if the result type is complex then the dtype is:
  921. - the default complex dtype if there are no floating point or complex tensors
  922. - if there are floating point or complex tensors with one or more dimensions, then
  923. the complex dtype corresponding to the highest corresponding complex dtype among those tensors
  924. (for example, double + cfloat -> cdouble)
  925. - if there are only floating point or complex tensors with zero dimensions, then
  926. the complex dtype corresponding to the highest corresponding complex dtype among those tensors
  927. - if the first two cases do not apply, the result dtype is the highest dtype among
  928. all tensors with one or more dimensions of the output type, and if there are no such
  929. tensors then it's the highest dtype among all tensors with zero dimensions of the output type
  930. (for example, long + half -> half, even if the half tensor has zero dimensions)
  931. The "corresponding complex dtypes" are:
  932. float16 -> complex32
  933. bfloat16 -> complex64
  934. float32 -> complex64
  935. float64 -> complex128
  936. complex32 -> complex32
  937. complex64 -> complex64
  938. complex128 -> complex128
  939. The DEFAULT type promotion kind computes per above, and then uses the result dtype to pick a computation
  940. dtype by mapping low precision floating point and complex dtypes as follows:
  941. float16 -> float32
  942. bfloat16 -> float32
  943. complex32 -> complex64
  944. This is referred to as "op math", and the NO_OPMATH type promotion kind disables this mapping, making the
  945. computation dtype the same as the result dtype when it's selected. NO_OPMATH is appropriate for kernels
  946. which perform no mathematical operations on their tensors (see below for examples).
  947. The INT_TO_FLOAT type promotion kind maps boolean and integer maps result dtypes to the default floating point dtype,
  948. and computation dtypes to the appropriate op math dtype.
  949. The COMPLEX_TO_FLOAT type promotion kind maps complex result dtypes to the corresponding float dtype, following this
  950. mapping:
  951. complex32 -> float16
  952. complex64 -> float32
  953. complex128 -> float64
  954. Note that COMPLEX_TO_FLOAT derives the computation dtype as the DEFAULT setting does.
  955. The BOOL_TO_LONG type promotion kind maps boolean computation and result dtypes to long.
  956. The ALWAYS_BOOL type promotion kind always sets the result dtype to bool.
  957. Example operators for each type promotion option:
  958. DEFAULT : add
  959. NO_OPMATH : where, nextafter, cat
  960. INT_TO_FLOAT : sin
  961. COMPLEX_TO_FLOAT : abs
  962. BOOL_TO_LONG : pow
  963. ALWAYS_BOOL : eq
  964. """
  965. args = tuple(x for x in _args if x is not None)
  966. highest_type: type = bool
  967. for x in args:
  968. if not isinstance(x, (Number, TensorLike)):
  969. msg = (
  970. "Unexpected type {0} when computing elementwise type promotion!".format(
  971. str(type(x))
  972. )
  973. )
  974. raise ValueError(msg)
  975. if isinstance(x, Number):
  976. highest_type = get_higher_type(highest_type, number_type(x))
  977. else:
  978. # x is a TensorLike
  979. highest_type = get_higher_type(highest_type, dtype_to_type(x.dtype))
  980. result_dtype = None
  981. def _find_highest_dtype_filtered(
  982. args, filter, *, float_as_complex=False
  983. ) -> Optional[torch.dtype]:
  984. zero_dim_tensor_dtype = None
  985. one_plus_dim_tensor_dtype = None
  986. for x in args:
  987. if isinstance(x, TensorLike) and filter(x.dtype):
  988. _dtype = x.dtype
  989. if float_as_complex and is_float_dtype(_dtype):
  990. _dtype = corresponding_complex_dtype(_dtype)
  991. if x.ndim == 0:
  992. zero_dim_tensor_dtype = get_higher_dtype(
  993. zero_dim_tensor_dtype, _dtype
  994. )
  995. else:
  996. # x.ndim > 0
  997. one_plus_dim_tensor_dtype = get_higher_dtype(
  998. one_plus_dim_tensor_dtype, _dtype
  999. )
  1000. # Prefers dtype of tensors with one or more dimensions
  1001. if one_plus_dim_tensor_dtype is not None:
  1002. return one_plus_dim_tensor_dtype
  1003. return zero_dim_tensor_dtype
  1004. if highest_type is float:
  1005. result_dtype = _find_highest_dtype_filtered(args, is_float_dtype)
  1006. result_dtype = (
  1007. torch.get_default_dtype() if result_dtype is None else result_dtype
  1008. )
  1009. elif highest_type is complex:
  1010. result_dtype = _find_highest_dtype_filtered(
  1011. args,
  1012. lambda x: is_float_dtype(x) or is_complex_dtype(x),
  1013. float_as_complex=True,
  1014. )
  1015. if result_dtype is None:
  1016. result_dtype = corresponding_complex_dtype(torch.get_default_dtype())
  1017. elif highest_type is int:
  1018. result_dtype = _find_highest_dtype_filtered(args, is_integer_dtype)
  1019. result_dtype = torch.long if result_dtype is None else result_dtype
  1020. else:
  1021. # highest_type is bool
  1022. result_dtype = torch.bool
  1023. if type_promotion_kind is ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT:
  1024. return get_computation_dtype(result_dtype), result_dtype
  1025. elif type_promotion_kind is ELEMENTWISE_TYPE_PROMOTION_KIND.NO_OPMATH:
  1026. return result_dtype, result_dtype
  1027. elif type_promotion_kind is ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT:
  1028. if is_integer_dtype(result_dtype) or is_boolean_dtype(result_dtype):
  1029. result_dtype = torch.get_default_dtype()
  1030. return get_computation_dtype(result_dtype), result_dtype
  1031. elif type_promotion_kind is ELEMENTWISE_TYPE_PROMOTION_KIND.COMPLEX_TO_FLOAT:
  1032. # NOTE: computation can still occur in a complex dtype
  1033. computation_dtype = get_computation_dtype(result_dtype)
  1034. if is_complex_dtype(result_dtype):
  1035. result_dtype = corresponding_real_dtype(result_dtype)
  1036. return computation_dtype, result_dtype
  1037. elif type_promotion_kind is ELEMENTWISE_TYPE_PROMOTION_KIND.BOOL_TO_LONG:
  1038. if is_boolean_dtype(result_dtype):
  1039. return torch.long, torch.long
  1040. return get_computation_dtype(result_dtype), result_dtype
  1041. elif type_promotion_kind is ELEMENTWISE_TYPE_PROMOTION_KIND.ALWAYS_BOOL:
  1042. return get_computation_dtype(result_dtype), torch.bool
  1043. else:
  1044. raise ValueError(
  1045. "Unknown type promotion kind {0}".format(str(type_promotion_kind))
  1046. )
  1047. def reduction_dtypes(
  1048. arg,
  1049. output_dtype_kind: REDUCTION_OUTPUT_TYPE_KIND,
  1050. dtype: Optional[torch.dtype] = None,
  1051. ) -> Tuple[torch.dtype, Optional[torch.dtype]]:
  1052. # even though some reductions, like amin or amax, don't strictly require type promotion,
  1053. # all the math ops (including comparisons) are still defined only for a computation type,
  1054. # so promotion will still happen. We are doing it explicitly here
  1055. inp_dtype = dtype if dtype is not None else arg.dtype
  1056. computation_dtype = get_computation_dtype(inp_dtype)
  1057. if (
  1058. output_dtype_kind == REDUCTION_OUTPUT_TYPE_KIND.SAME
  1059. or output_dtype_kind == REDUCTION_OUTPUT_TYPE_KIND.COMPLEX_TO_FLOAT
  1060. ):
  1061. result_dtype = dtype if dtype else arg.dtype
  1062. if (
  1063. output_dtype_kind == REDUCTION_OUTPUT_TYPE_KIND.COMPLEX_TO_FLOAT
  1064. and is_complex_dtype(result_dtype)
  1065. ):
  1066. result_dtype = corresponding_real_dtype(result_dtype)
  1067. elif output_dtype_kind == REDUCTION_OUTPUT_TYPE_KIND.KEEP_PROMOTED_TYPE:
  1068. result_dtype = None
  1069. else: # ALWAYS_BOOL
  1070. result_dtype = torch.bool
  1071. return computation_dtype, result_dtype
  1072. # This function's logic is borrowed from the following functions defined in C++:
  1073. # batched_matrix_contiguous_strides and contiguous_strides
  1074. def make_contiguous_strides_for(
  1075. shape: ShapeType, row_major: bool = True
  1076. ) -> Tuple[int, ...]:
  1077. """
  1078. Returns the strides of a contiguous tensor if row_major
  1079. If row_major=True, it returns the strides of a contiguous batch of Fortran-contiguous matrices
  1080. This is often used when calling external libraries like BLAS/LAPACK/cuSolver...
  1081. """
  1082. # contiguous_strides from c10/util/strides.h
  1083. validate_shape(shape)
  1084. if not shape:
  1085. return ()
  1086. multiplier = 1
  1087. strides = []
  1088. for l in reversed(shape):
  1089. strides.append(multiplier)
  1090. multiplier *= sym_max(l, 1)
  1091. result = tuple(reversed(strides))
  1092. # batched_matrix_contiguous_strides from aten/src/ATen/native/LinearAlgebraUtils.h
  1093. if row_major:
  1094. return result
  1095. else:
  1096. if len(shape) < 2:
  1097. return result
  1098. return result[:-2] + (1, max(shape[-2], 1))
  1099. def make_channels_last_2d_strides_for(shape: ShapeType) -> Tuple[int, ...]:
  1100. # TODO: maybe inform the user of channels_last_3d if rank of the tensor is 5?
  1101. check(
  1102. len(shape) == 4,
  1103. lambda: "Only tensors of rank 4 can use the channels_last memory format",
  1104. )
  1105. multiplier = 1
  1106. strides = [0] * 4
  1107. for idx in (1, -1, -2, 0):
  1108. # NOTE: intentionally divergence from make_contiguous_strides_for
  1109. # This is consistent with eager
  1110. strides[idx] = multiplier
  1111. multiplier *= shape[idx]
  1112. return tuple(strides)
  1113. def make_channels_last_3d_strides_for(shape: ShapeType) -> Tuple[int, ...]:
  1114. check(
  1115. len(shape) == 5,
  1116. lambda: "Only tensors of rank 5 can use the channels_last_3d memory format",
  1117. )
  1118. multiplier = 1
  1119. strides = [0] * 5
  1120. for idx in (1, -1, -2, -3, 0):
  1121. # NOTE: intentionally divergence from make_contiguous_strides_for
  1122. # This is consistent with eager
  1123. strides[idx] = multiplier
  1124. multiplier *= shape[idx]
  1125. return tuple(strides)
  1126. def make_channels_last_strides_for(shape: ShapeType) -> Tuple[int, ...]:
  1127. ndim = len(shape) if isinstance(shape, Sequence) else 1
  1128. if ndim == 4:
  1129. return make_channels_last_2d_strides_for(shape)
  1130. elif ndim == 5:
  1131. return make_channels_last_3d_strides_for(shape)
  1132. else:
  1133. raise RuntimeError(
  1134. f"no channels last format strides exist in {ndim} dimensions"
  1135. )
  1136. def compute_reduction_output_shape(
  1137. shape: ShapeType, dimensions: Sequence
  1138. ) -> Tuple[int, ...]:
  1139. for idx in dimensions:
  1140. validate_idx(len(shape), idx)
  1141. new_shape = []
  1142. for idx in range(len(shape)):
  1143. if idx in dimensions:
  1144. continue
  1145. new_shape.append(shape[idx])
  1146. return tuple(new_shape)
  1147. def validate_no_repeating_dims(dims: Sequence):
  1148. if len(dims) != len(set(dims)):
  1149. raise RuntimeError("duplicate value in the list of dims")
  1150. def reduction_dims(shape: ShapeType, dims: Optional[Sequence]) -> Tuple[int, ...]:
  1151. if dims is None:
  1152. return tuple(range(len(shape)))
  1153. dims = tuple(canonicalize_dim(len(shape), idx) for idx in dims)
  1154. validate_no_repeating_dims(dims)
  1155. return dims
  1156. def set_correction(
  1157. unbiased: Optional[bool] = None,
  1158. correction: Optional[int] = None,
  1159. ):
  1160. if correction is not None and unbiased is not None:
  1161. raise RuntimeError("cannot specify both correction and unbiased arguments")
  1162. elif correction is None and unbiased is None:
  1163. correction = 1
  1164. elif correction is None and unbiased is not None:
  1165. correction = 0 if unbiased is False else 1
  1166. # NB: we don't actually support symint here, but it's harmless to accept
  1167. if not isinstance(correction, IntLike):
  1168. raise ValueError("correction argument should be integer")
  1169. if correction < 0:
  1170. raise ValueError("correction argument should be non-negative")
  1171. return correction
  1172. def compute_required_storage_length(
  1173. shape: ShapeType, strides: StrideType, storage_offset: int
  1174. ) -> int:
  1175. """Computes the minimum storage size to hold the given tensor geometry.
  1176. Example
  1177. =======
  1178. This is the size of a newly allocated tensor's storage, in units of elements
  1179. >>> t = torch.empty((10, 20))
  1180. >>> compute_required_storage_length(t.shape, t.stride(), t.storage_offset())
  1181. 200
  1182. >>> # xdoctest: +SKIP(failing)
  1183. >>> t2 = torch.empty_strided((1, 2, 3), (5, 7, 11))
  1184. >>> size = compute_required_storage_length(t2.shape, t2.stride(), t2.storage_offset())
  1185. >>> size == t.storage().size()
  1186. True
  1187. A valid tensor may have a larger storage size, but never smaller
  1188. >>> slice = torch.empty(100)[20:40]
  1189. >>> slice.storage().size()
  1190. 100
  1191. >>> compute_required_storage_length(slice.shape, slice.stride(), slice.storage_offset())
  1192. 40
  1193. """
  1194. # Short-circuits if the shape has no elements
  1195. if reduce(operator.mul, shape, 1) == 0:
  1196. return 0
  1197. max_offset = sum((x - 1) * y for x, y in zip(shape, strides))
  1198. # +1 to account for the first element which offsets are taken from
  1199. return 1 + storage_offset + max_offset
  1200. def check_in_bounds_for_storage(
  1201. a: torch.TypedStorage, shape: ShapeType, strides: StrideType, storage_offset: int
  1202. ):
  1203. """
  1204. Determines if the given shape, strides, and offset are valid for the given storage.
  1205. """
  1206. required_length = compute_required_storage_length(shape, strides, storage_offset)
  1207. if a.size() < required_length:
  1208. msg = (
  1209. "Can't view a storage of size {0} with an offset of {1}, shape of {2}, and strides of {3}, "
  1210. "which requires a storage of size {4}".format(
  1211. a.size(), storage_offset, str(shape), str(strides), required_length
  1212. )
  1213. )
  1214. raise ValueError(msg)
  1215. def check(
  1216. b: bool, s: Callable[[], str], exc_type: Type[Exception] = RuntimeError
  1217. ) -> None:
  1218. """
  1219. Helper function for raising an error_type (default: RuntimeError) if a boolean condition fails.
  1220. Error message is a callable producing a string (to avoid wasting time
  1221. string formatting in non-error case, and also to make it easier for torchdynamo
  1222. to trace.)
  1223. """
  1224. if not b:
  1225. raise exc_type(s())
  1226. # This combines is_channels_last_strides_2d and is_channels_last_strides_3d in
  1227. # c10/core/MemoryFormat.h into one function
  1228. def are_strides_like_channels_last(
  1229. shape: Sequence[int], strides: Sequence[int]
  1230. ) -> bool:
  1231. ndim = len(shape)
  1232. if ndim == 4:
  1233. # Check for channels_last_2d
  1234. dim_order = [1, 3, 2, 0]
  1235. elif ndim == 5:
  1236. # Check for channels_last_3d
  1237. dim_order = [1, 4, 3, 2, 0]
  1238. else:
  1239. return False
  1240. if strides[1] == 0:
  1241. return False
  1242. min = 0
  1243. for d in dim_order:
  1244. if shape[d] == 0:
  1245. return False
  1246. if strides[d] < min:
  1247. return False
  1248. if d == 0 and min == strides[1]:
  1249. return False
  1250. min = strides[d]
  1251. if strides[d] > 1:
  1252. min *= shape[d]
  1253. return True
  1254. def suggest_memory_format(x: TensorLikeType) -> torch.memory_format:
  1255. if x.layout != torch.strided:
  1256. return torch.contiguous_format
  1257. if are_strides_like_channels_last(x.shape, x.stride()):
  1258. return torch.channels_last if x.ndim == 4 else torch.channels_last_3d
  1259. return torch.contiguous_format
  1260. def prod(xs: Sequence[NumberType]) -> NumberType:
  1261. """Product of elements in input sequence. Returns 1 for empty sequence"""
  1262. return reduce(operator.mul, xs, 1)
  1263. def is_expandable_to(shape: ShapeType, desired: ShapeType) -> bool:
  1264. """Checks if a shape can be expanded to another shape.
  1265. This is equivalent to checking if the two shapes are broadcastable.
  1266. """
  1267. # This is a Python implementation of
  1268. # aten/src/ATen/ExpandUtils.h:is_expandable_to
  1269. if len(shape) > len(desired):
  1270. return False
  1271. for i in range(len(shape)):
  1272. if shape[-i - 1] != desired[-i - 1] and shape[-i - 1] != 1:
  1273. return False
  1274. return True
  1275. def mask_tensor(mask: TensorLikeType, t: TensorLikeType):
  1276. """
  1277. Similar to torch.where(mask, t, 0) but if t is boolean,
  1278. result is also boolean and not promoted to int.
  1279. """
  1280. # torch.where(mask, t, False) is equivalent
  1281. # but feels hacky and might break in the future
  1282. if t.dtype is torch.bool:
  1283. return mask.logical_and(t)
  1284. else:
  1285. return torch.where(mask, t, 0)
  1286. def get_aten_op(fn: Callable, name: str):
  1287. """
  1288. Given the __module__ of reference and its name, it returns
  1289. (our best guess of) the ATen name of the associated operation
  1290. Note: In ATen, the __name__ of a function within a module often
  1291. starts by the module name. E.g. linalg_eigh, or special_zeta
  1292. """
  1293. module = fn.__module__
  1294. prefix = "torch._refs"
  1295. assert(module.startswith(prefix))
  1296. module = module[len(prefix):]
  1297. # We want to go from .special / .nn.functional
  1298. # to special and special_ / nn_functional_
  1299. if module:
  1300. module = module[1:]
  1301. module = module.replace(".", "_")
  1302. module = module + "_"
  1303. return getattr(torch._ops.ops.aten, f"{module}{name}")
  1304. def dtype_or_default(dtype: Optional[torch.dtype]) -> torch.dtype:
  1305. return dtype if dtype is not None else torch.get_default_dtype()
  1306. def device_or_default(device: Optional[torch.device]) -> torch.device:
  1307. return device if device is not None else torch.device("cpu")
  1308. def layout_or_default(layout: Optional[torch.layout]) -> torch.layout:
  1309. return layout if layout is not None else torch.strided
  1310. def clone_preserve_strides(x):
  1311. needed_size = compute_required_storage_length(
  1312. x.size(), x.stride(), x.storage_offset()
  1313. )
  1314. # Our eager implementations for *_scatter ops are all primitives w.r.t autograd,
  1315. # so these as_strided() calls are not seen by autograd.
  1316. # We need to mimic this behavior in our ref/prim implementations.
  1317. # TODO: a better way to handle this would be with a new op, "_unsafe_as_strided"
  1318. # We should revisit this when we add a compositional as_strided op,
  1319. # and also as part of https://github.com/pytorch/pytorch/issues/90507
  1320. try:
  1321. old = torch._C._dispatch_tls_is_dispatch_key_excluded(torch._C.DispatchKey.ADInplaceOrView)
  1322. torch._C._dispatch_tls_set_dispatch_key_excluded(torch._C.DispatchKey.ADInplaceOrView, True)
  1323. buffer = torch.as_strided(x, (needed_size,), (1,), 0).clone()
  1324. return torch.as_strided(buffer, x.size(), x.stride(), x.storage_offset())
  1325. finally:
  1326. torch._C._dispatch_tls_set_dispatch_key_excluded(torch._C.DispatchKey.ADInplaceOrView, old)