from __future__ import annotations import functools import itertools import math import operator import sys from functools import reduce from typing import Any, cast as typing_cast, TYPE_CHECKING, TypeVar from typing_extensions import ParamSpec import torch import torch._custom_op import torch._logging import torch._prims_common as utils from torch._C._functorch import ( _unwrap_for_grad, _wrap_for_grad, is_functorch_wrapped_tensor, TransformType, ) from torch._dispatch.python import no_python_dispatcher from torch._functorch.pyfunctorch import retrieve_current_functorch_interpreter from torch._functorch.utils import enable_single_level_autograd_function from torch._ops import OpOverload from torch._prims_common import ( canonicalize_dim, elementwise_dtypes, ELEMENTWISE_TYPE_PROMOTION_KIND, is_boolean_dtype, is_contiguous, is_contiguous_for_memory_format_or_false, is_contiguous_or_false, is_float_dtype, is_integer_dtype, make_contiguous_strides_for, ShapeType, ) from torch._subclasses.fake_tensor import ( DataDependentOutputException, DynamicOutputShapeException, FakeTensor, in_kernel_invocation_manager, is_fake_tensor, run_fallback_kernel, UnsupportedOperatorException, ) from torch.fx.operator_schemas import _normalize_function_or_error from torch.utils._stats import count_label if TYPE_CHECKING: from collections.abc import Callable, Sequence from torch._subclasses.fake_tensor import FakeTensorMode from torch.types import IntLikeType FakeTensorLike = FakeTensor | torch.Tensor _P = ParamSpec("_P") _R = TypeVar("_R") _T = TypeVar("_T") pytree = torch.utils._pytree __all__ = [ "op_implementations_checks", "get_fast_op_impls", "stride_incorrect_op", "has_meta", ] # pyrefly: ignore [implicit-any] op_implementations_dict = {} # pyrefly: ignore [implicit-any] op_implementations_checks = [] aten = torch._ops.ops.aten _MKLDNN_DISPATCH_KEYS = torch._C.DispatchKeySet( torch._C._dispatch_key_parse("MkldnnCPU") ) _MKLDNN_DTYPES = { torch.float32, torch.bfloat16, torch.float16, torch.uint8, torch.int8, } _MKLDNN_TO_DENSE_DTYPES = _MKLDNN_DTYPES | {torch.float8_e4m3fn} _MKLDNN_DTYPE_CHANGE_RESTRICTED_DTYPES = { torch.uint8, torch.int8, torch.float8_e4m3fn, } _TO_DENSE_SPARSE_LAYOUTS = frozenset( { torch.sparse_coo, torch.sparse_csr, torch.sparse_csc, torch.sparse_bsr, torch.sparse_bsc, } ) _PYTHON_TLS_SNAPSHOT_KEYSET = torch._C.DispatchKeySet( torch._C.DispatchKey.PythonTLSSnapshot ) def ordered_set(*items: _T) -> dict[_T, bool]: return dict.fromkeys(items, True) # This function indicates if the backend device # supports non-contiguous tensors def is_noncontiguous_supported(device: torch.device) -> bool: return device.type != "hpu" def _same_device_or_unspecified_index(a: torch.device, b: torch.device) -> bool: if a.type != b.type: return False return a.index is None or b.index is None or a.index == b.index _like_tensor_constructors = ordered_set( aten.empty_like.default, aten.empty_like.out, aten.full_like.default, aten.full_like.out, aten.ones_like.default, aten.ones_like.out, aten.rand_like.default, aten.rand_like.generator, aten.rand_like.out, aten.rand_like.generator_out, aten.randn_like.default, aten.randn_like.generator, aten.randn_like.out, aten.randn_like.generator_out, aten.randint_like.default, aten.randint_like.generator, aten.randint_like.Tensor, aten.randint_like.Tensor_generator, aten.randint_like.Tensor_out, aten.randint_like.Tensor_generator_out, aten.randint_like.out, aten.randint_like.generator_out, aten.randint_like.low_dtype, aten.randint_like.low_generator_dtype, aten.randint_like.low_dtype_out, aten.randint_like.low_generator_dtype_out, aten.zeros_like.default, aten.zeros_like.out, aten.new_empty.default, aten.new_empty.out, aten.new_empty_strided.default, aten.new_empty_strided.out, aten.new_full.default, aten.new_full.out, aten.new_zeros.default, aten.new_zeros.out, aten.new_ones.default, aten.new_ones.out, ) _device_not_kwarg_ops = ordered_set( aten._resize_output_.default, aten._nested_tensor_from_tensor_list.default, aten._nested_tensor_from_tensor_list.out, aten.pin_memory.default, aten.to.device, aten.to.prim_Device, aten.is_pinned.default, aten._pin_memory.default, aten._pin_memory.out, aten._resize_output.default, aten._resize_output.out, ) # this op is never actually used _non_kwarg_device_constructors = (aten._list_to_tensor,) def contains_tensor_types(type_: Any) -> bool: tensor_type = torch._C.TensorType.get() return type_.isSubtypeOf(tensor_type) or any( contains_tensor_types(e) for e in type_.containedTypes() ) @functools.cache def _is_tensor_constructor(func: OpOverload) -> bool: if not isinstance(func, OpOverload): raise AssertionError(f"func must be an OpOverload, got {type(func)}") schema = func._schema if any(contains_tensor_types(arg.type) for arg in schema.arguments): return False # TODO: no real reason to restrict multiple outputs return ( len(schema.returns) == 1 and schema.returns[0].type is torch._C.TensorType.get() ) @functools.cache def _has_device_arg(func: OpOverload) -> bool: device_type = torch._C.DeviceObjType.get() optional_device_type = torch._C.OptionalType(device_type) return any( arg.name == "device" and ( arg.type.isSubtypeOf(device_type) or arg.type.isSubtypeOf(optional_device_type) ) for arg in func._schema.arguments ) def register_op_impl( run_impl_check: Callable[[OpOverload], bool] | OpOverload | list[OpOverload] | tuple[OpOverload, ...], ) -> Callable[[Callable[_P, _R]], Callable[_P, _R]]: def impl_decorator(op_impl: Callable[_P, _R]) -> Callable[_P, _R]: if isinstance(run_impl_check, OpOverload): if run_impl_check in op_implementations_dict: raise AssertionError(f"duplicate registration: {run_impl_check}") op_implementations_dict[run_impl_check] = op_impl schema = run_impl_check._schema torch._C._fake_dispatch_register_op_impl(schema.name, schema.overload_name) elif isinstance(run_impl_check, (list, tuple)): for op in run_impl_check: register_op_impl(op)(op_impl) else: if not callable(run_impl_check): raise AssertionError( f"run_impl_check must be callable, got {type(run_impl_check)}" ) op_implementations_checks.append((run_impl_check, op_impl)) return op_impl return impl_decorator def _is_op_registered_to_fake_rule(op: OpOverload) -> bool: return op in op_implementations_dict def _deregister_op_impl(op: OpOverload) -> None: if op in op_implementations_dict: op_implementations_dict.pop(op, None) torch._C._fake_dispatch_deregister_op_impl( op._schema.name, op._schema.overload_name ) for check, impl in op_implementations_checks: if check is op: op_implementations_checks.remove((check, impl)) break @register_op_impl(op_implementations_dict.__contains__) def dispatch_to_op_implementations_dict( fake_mode: FakeTensorMode, func: OpOverload, *args: Any, **kwargs: Any ) -> Any: return op_implementations_dict[func](fake_mode, func, *args, **kwargs) @register_op_impl(_is_tensor_constructor) @register_op_impl([*_like_tensor_constructors]) def constructors( fake_mode: FakeTensorMode, func: OpOverload, *args: Any, **kwargs: Any ) -> FakeTensor: if func in _non_kwarg_device_constructors: raise AssertionError( f"func must not be in _non_kwarg_device_constructors, got {func}" ) _, new_kwargs = _normalize_function_or_error( func, args=args, kwargs=kwargs, normalize_to_only_use_kwargs=True ) if func in _like_tensor_constructors: default_device = new_kwargs["input"].device # TODO: file issue args = (new_kwargs.pop("input"),) else: # cpu is default device if none is specified default_device = torch.device("cpu") args = () has_device_arg = _has_device_arg(func) out_device = new_kwargs.pop("device", None) if has_device_arg else None out_device = out_device if out_device is not None else default_device if has_device_arg: new_kwargs["device"] = torch.device("meta") # _like constructors have fake tensor inputs (maybe this causes the non-like # to fail? hmmm) with in_kernel_invocation_manager(fake_mode): r = func(*args, **new_kwargs) if r.device.type == "meta": return fake_mode.fake_tensor_converter.from_meta_and_device( fake_mode, r, out_device ) return fake_mode.fake_tensor_converter.from_real_tensor(fake_mode, r) @register_op_impl(aten.is_pinned.default) def non_kwarg_is_pinned( fake_mode: FakeTensorMode, func: OpOverload, *args: Any, **kwargs: Any ) -> bool: _, new_kwargs = _normalize_function_or_error( func, args, kwargs, normalize_to_only_use_kwargs=True ) inp = new_kwargs.pop("input") # we'll ignore device argument because it is deprecated and not # actually used by is_pinned. with in_kernel_invocation_manager(fake_mode): r = func(inp) return r # Legacy profiler ops return Tensors but don't follow tensor constructor patterns # They take string arguments and should not have device/dtype parameters added @register_op_impl(torch.ops.profiler._record_function_enter.default) def _record_function_enter( fake_mode: FakeTensorMode, func: OpOverload, name: str, args: object | None = None ) -> FakeTensor: # Call the real implementation to get a real handle tensor with in_kernel_invocation_manager(fake_mode): real_handle = func(name, args) # Create a meta tensor with the same properties as the real handle meta_handle = torch.empty_like(real_handle, device="meta") # Wrap it as a FakeTensor return FakeTensor(fake_mode, meta_handle, torch.device("cpu")) @register_op_impl(torch.ops.profiler._record_function_exit.default) def _record_function_exit( fake_mode: FakeTensorMode, func: OpOverload, handle: Any ) -> None: # Exit doesn't return anything and doesn't need to do anything for fake tensors # Just return None (the actual return type is void) pass @register_op_impl(torch.ops.profiler._record_function_enter_new.default) def _record_function_enter_new( fake_mode: FakeTensorMode, func: OpOverload, name: str, args: object | None = None ) -> Any: # Call the real implementation - returns a custom class, not a tensor # Just pass through without wrapping with in_kernel_invocation_manager(fake_mode): return func(name, args) @register_op_impl(aten.to.prim_Device) @register_op_impl(aten.to.device) def non_kwarg_to( fake_mode: FakeTensorMode, func: OpOverload, *args: Any, **kwargs: Any ) -> FakeTensor: _, new_kwargs = _normalize_function_or_error( func, args, kwargs, normalize_to_only_use_kwargs=True ) input_device = new_kwargs["device"] out_device = input_device if input_device else new_kwargs["input"].device new_kwargs["device"] = torch.device("meta") inp = new_kwargs.pop("input") with in_kernel_invocation_manager(fake_mode): r = func(inp, **new_kwargs) # TODO: I think this does the wrong thing if r is inp return fake_mode.fake_tensor_converter.from_meta_and_device( fake_mode, r, out_device ) def stride_incorrect_op(op: OpOverload) -> bool: return False # These operators have meta implementations with incorrect strides @register_op_impl(stride_incorrect_op) def workaround_stride_incorrect_op( fake_mode: FakeTensorMode, func: OpOverload, *args: Any, **kwargs: Any ) -> FakeTensor: # This is a workaround for meta implementations with incorrect strides def is_symbolic(x: object) -> bool: if is_fake_tensor(x): return x._has_symbolic_sizes_strides if isinstance(x, (torch.SymInt, torch.SymFloat, torch.SymBool)): return True return False # For static shapes, we can fall back to eager for the real strides if fake_mode.allow_fallback_kernels: require_dynamic = any( is_symbolic(x) for x in itertools.chain(args, kwargs.values()) ) if not require_dynamic: flat_args, args_spec = pytree.tree_flatten((args, kwargs)) return run_fallback_kernel( fake_mode, func, flat_args, args_spec, # TODO: refactor to lambda so we don't instantiate extra errors before # calling RuntimeError("Cannot run fallback kernel for stride_incorrect_op"), ) raise UnsupportedOperatorException(func) # Don't default to default device handling, # since the device of `the_template` is ignored @register_op_impl(aten.resize_as_.default) def resize_as_( fake_mode: FakeTensorMode, func: OpOverload, *args: Any, **kwargs: Any ) -> FakeTensor: with in_kernel_invocation_manager(fake_mode): return func(*args, **kwargs) @register_op_impl(aten._sparse_coo_tensor_with_dims_and_tensors.default) def _sparse_coo_tensor_with_dims_and_tensors( fake_mode: FakeTensorMode, func: OpOverload, *args: Any, **kwargs: Any ) -> FakeTensor: return constructors(fake_mode, func, *args, **kwargs) def _spdiags_static_offsets(offsets: FakeTensorLike) -> list[int] | None: constant = getattr(offsets, "constant", None) if constant is None: constant = getattr(offsets, "real_tensor", None) if is_fake_tensor(constant): return None if constant is None or constant.device.type != "cpu": return None return [int(offset) for offset in constant.reshape(-1).tolist()] def _spdiags_nnz(offsets: list[int], rows: int, cols: int, diag_cols: int) -> int: nnz = 0 pos_offset_limit = min(cols, diag_cols) for offset in offsets: if offset <= 0: nnz_per_diag = min(offset + rows, diag_cols) else: nnz_per_diag = pos_offset_limit - offset torch._check( nnz_per_diag >= 0, lambda: f"Trying to create tensor with negative dimension {nnz_per_diag}", ) nnz += nnz_per_diag return nnz def _spdiags_max_nnz_per_diag(rows: int, cols: int, diag_cols: int) -> int: non_positive_offset_max = min(rows, diag_cols) positive_offset_max = max(min(cols, diag_cols) - 1, 0) return max(non_positive_offset_max, positive_offset_max, 0) def _spdiags_dynamic_size( fake_mode: FakeTensorMode, func: OpOverload, *, max_size: int | None, ) -> torch.SymInt: if ( fake_mode.shape_env is None or not fake_mode.shape_env.allow_dynamic_output_shape_ops ): raise DynamicOutputShapeException(func) nnz = fake_mode.shape_env.create_unbacked_symint() from torch.fx.experimental.symbolic_shapes import _constrain_range_for_size _constrain_range_for_size(nnz, min=0, max=max_size) return nnz def _spdiags_is_static_int(value: object) -> bool: return isinstance(value, int) and not isinstance(value, bool) @register_op_impl(aten._spdiags.default) def _spdiags( fake_mode: FakeTensorMode, func: OpOverload, diagonals: FakeTensorLike, offsets: FakeTensorLike, shape: Sequence[int], layout: torch.layout | None = None, ) -> FakeTensor: diagonals_dim = diagonals.dim() torch._check(diagonals_dim in (1, 2), lambda: "Diagonals must be vector or matrix") torch._check(len(shape) == 2, lambda: "Output shape must be 2d") offsets_dim = offsets.dim() torch._check(offsets_dim in (0, 1), lambda: "Offsets must be scalar or vector") n_diags = 1 if diagonals_dim == 1 else diagonals.size(0) n_offsets = 1 if offsets_dim == 0 else offsets.size(0) torch._check( n_diags == n_offsets, lambda: f"Number of diagonals ({n_diags}) does not match the number of offsets ({n_offsets})", ) if layout is not None: torch._check( layout in (torch.sparse_coo, torch.sparse_csc, torch.sparse_csr), lambda: f"Only output layouts (Sparse, SparseCsc, SparseCsr) are supported, got {layout}", ) torch._check( offsets.dtype == torch.long, lambda: f"Offset Tensor must have dtype Long but got {offsets.dtype}", ) torch._check( diagonals.device.type == "cpu" and offsets.device.type == "cpu", lambda: "_spdiags is only implemented for CPU tensors", ) rows, cols = shape diag_cols = diagonals.size(0) if diagonals_dim == 1 else diagonals.size(1) static_sizes = all( _spdiags_is_static_int(value) for value in (rows, cols, diag_cols, n_offsets) ) static_offsets = _spdiags_static_offsets(offsets) if static_offsets is not None: torch._check( len(static_offsets) == len(set(static_offsets)), lambda: "Offset tensor contains duplicate values", ) out_layout = layout if layout is not None else torch.sparse_coo if static_sizes and (rows == 0 or cols == 0): nnz = 0 elif static_offsets is not None and static_sizes: nnz = _spdiags_nnz(static_offsets, rows, cols, diag_cols) # type: ignore[arg-type] elif static_sizes and n_offsets == 0: nnz = 0 else: max_nnz = ( n_offsets * _spdiags_max_nnz_per_diag(rows, cols, diag_cols) if static_sizes else None ) nnz = _spdiags_dynamic_size(fake_mode, func, max_size=max_nnz) # type: ignore[arg-type] with in_kernel_invocation_manager(fake_mode): values = torch.empty((nnz,), dtype=diagonals.dtype, device="meta") with torch.sparse.check_sparse_tensor_invariants(False): if out_layout == torch.sparse_coo: indices = torch.empty((2, nnz), dtype=torch.long, device="meta") is_coalesced = nnz <= 1 if isinstance(nnz, int) else False out = torch.ops.aten._sparse_coo_tensor_unsafe.default( indices, values, shape, device=torch.device("meta"), is_coalesced=is_coalesced, ) elif out_layout == torch.sparse_csr: crow_indices = torch.empty((rows + 1,), dtype=torch.long, device="meta") col_indices = torch.empty((nnz,), dtype=torch.long, device="meta") out = torch.ops.aten._sparse_compressed_tensor_unsafe.default( crow_indices, col_indices, values, shape, layout=out_layout, device=torch.device("meta"), ) else: ccol_indices = torch.empty((cols + 1,), dtype=torch.long, device="meta") row_indices = torch.empty((nnz,), dtype=torch.long, device="meta") out = torch.ops.aten._sparse_compressed_tensor_unsafe.default( ccol_indices, row_indices, values, shape, layout=out_layout, device=torch.device("meta"), ) return fake_mode.fake_tensor_converter.from_meta_and_device( fake_mode, out, diagonals.device ) @register_op_impl(aten._to_dense.default) def _to_dense( fake_mode: FakeTensorMode, func: OpOverload, self: FakeTensor, dtype: torch.dtype | None = None, masked_grad: bool | None = None, ) -> FakeTensor: maybe_mkldnn_out = maybe_to_dense_mkldnn(fake_mode, self, dtype, masked_grad) if maybe_mkldnn_out is not NotImplemented: return typing_cast(FakeTensor, maybe_mkldnn_out) if self.layout is torch.sparse_coo: if dtype is not None: raise RuntimeError("dtype argument is not supported by sparse_to_dense") with in_kernel_invocation_manager(fake_mode): out = torch.empty( tuple(self.shape), dtype=self.dtype, device="meta", ) return FakeTensor(fake_mode, out, self.fake_device) with in_kernel_invocation_manager(fake_mode): out = func(self, dtype=dtype, masked_grad=masked_grad) return fake_mode.fake_tensor_converter.from_meta_and_device( fake_mode, out, self.fake_device ) # index.Tensor data-dependent in only some conditions @register_op_impl( lambda func: torch.Tag.dynamic_output_shape in func.tags and func not in [aten.index.Tensor, aten.nonzero.default, aten.repeat_interleave.Tensor] ) def dyn_shape( fake_mode: FakeTensorMode, func: OpOverload, *args: Any, **kwargs: Any ) -> None: raise DynamicOutputShapeException(func) def _unique( fake_mode: FakeTensorMode, func: OpOverload, arg: FakeTensor, dim: int | None, sorted: bool = True, return_inverse: bool = False, return_counts: bool = False, *, unique_consecutive: bool = False, ) -> tuple[FakeTensor, FakeTensor, FakeTensor]: if ( fake_mode.shape_env is None or not fake_mode.shape_env.allow_dynamic_output_shape_ops ): # Without symints/symfloats, cannot handle this raise DynamicOutputShapeException(func) nnz = arg.unique_consecutive_memo if unique_consecutive else arg.unique_memo # Do not use a memo for unique_dim if dim is not None or nnz is None: # Avoid importing sympy at a module level from torch.fx.experimental.symbolic_shapes import ( _constrain_range_for_size, has_free_symbols, ) if not has_free_symbols(arg.numel()) and arg.numel() == 0: # If numel is zero, then the output size must be zero. # In this case, we must not allocate an unbacked SymInt, # because if we do, it will immediately get refined to # zero, but this will be inconsistent with size oblivious # tests (which will continue to claim that the unbacked # symint cannot equal zero). We could also unconditionally # allocate an unbacked SymInt and not refine its range, # but this seems more precise. nnz = 0 else: nnz = fake_mode.shape_env.create_unbacked_symint() maxval = sys.maxsize - 1 numel = arg.numel() if dim is None else arg.size(dim) if not has_free_symbols(numel): maxval = int(numel) _constrain_range_for_size(nnz, max=maxval) if dim is None: if unique_consecutive: arg.unique_consecutive_memo = nnz # pyrefly: ignore[bad-assignment] else: arg.unique_memo = nnz # pyrefly: ignore[bad-assignment] if dim is None: # pyrefly: ignore[no-matching-overload] ret = [arg.new_empty((nnz,))] else: # pyrefly: ignore[no-matching-overload] ret = [arg.new_empty(*arg.shape[:dim], nnz, *arg.shape[dim + 1 :])] return_if_dim_and_cpu = dim is not None and arg.fake_device == torch.device("cpu") if return_inverse or return_if_dim_and_cpu: inverse = arg.new_empty( arg.shape if dim is None else (arg.shape[dim],), dtype=torch.int64 ) else: inverse = arg.new_empty(0, dtype=torch.int64) ret.append(inverse) if return_counts or return_if_dim_and_cpu: counts = arg.new_empty( ret[0].shape if dim is None else (ret[0].shape[dim],), dtype=torch.int64 ) else: counts = arg.new_empty(0, dtype=torch.int64) ret.append(counts) return tuple(ret) @register_op_impl(aten._unique2.default) def unique2( fake_mode: FakeTensorMode, func: OpOverload, arg: FakeTensor, sorted: bool = True, return_inverse: bool = False, return_counts: bool = False, ) -> tuple[FakeTensor, FakeTensor, FakeTensor]: return _unique(fake_mode, func, arg, None, sorted, return_inverse, return_counts) @register_op_impl(aten._unique.default) def unique( fake_mode: FakeTensorMode, func: OpOverload, arg: FakeTensor, sorted: bool = True, return_inverse: bool = False, ) -> tuple[FakeTensor, FakeTensor]: uniques, inverse, _counts = _unique( fake_mode, func, arg, None, sorted, return_inverse, False ) return uniques, inverse @register_op_impl(aten.select.int) def meta_select( fake_mode: FakeTensorMode, func: OpOverload, self: FakeTensor, dim: int, index: IntLikeType, ) -> FakeTensor: from torch.fx.experimental.symbolic_shapes import guard_or_false if self.is_sparse: return NotImplemented ndim = self.dim() torch._check_index( ndim != 0, lambda: "select() cannot be applied to a 0-dim tensor.", ) dim = dim if dim >= 0 else dim + ndim size = self.size(dim) if guard_or_false(index >= size) or guard_or_false(index < -size): torch._check_index( False, lambda: f"select(): index {index} out of range for tensor of size " f"{list(self.size())} at dimension {dim}", ) new_size = list(self.size()) new_stride = list(self.stride()) new_storage_offset = None if guard_or_false(index >= 0): new_storage_offset = self.storage_offset() + index * new_stride[dim] elif guard_or_false(index < 0): new_storage_offset = self.storage_offset() + (index + size) * new_stride[dim] if new_storage_offset is None: if fake_mode.shape_env is None or ( not fake_mode.shape_env.allow_scalar_outputs and not fake_mode.allow_scalar_outputs ): raise DataDependentOutputException(func) # index is data-dependent, we do not know which index we are accessing it could be index or index+size! # we assign a new data-dependent symbol for the storage offset. new_storage_offset = fake_mode.shape_env.create_unbacked_symint() del new_size[dim] del new_stride[dim] if new_storage_offset is None: raise AssertionError("new_storage_offset must not be None") # pyrefly: ignore[bad-return] return self.as_strided(new_size, new_stride, new_storage_offset) @register_op_impl(aten.unique_dim.default) def unique_dim( fake_mode: FakeTensorMode, func: OpOverload, arg: FakeTensor, dim: int, sorted: bool = True, return_inverse: bool = False, return_counts: bool = False, ) -> tuple[FakeTensor, FakeTensor, FakeTensor]: return _unique( fake_mode, func, arg, # normalize dim to be non-negative dim if dim >= 0 else dim % max(arg.ndim, 1), sorted, return_inverse, return_counts, ) @register_op_impl(aten.unique_consecutive.default) def unique_consecutive( fake_mode: FakeTensorMode, func: OpOverload, arg: FakeTensor, return_inverse: bool = False, return_counts: bool = False, dim: int | None = None, ) -> tuple[FakeTensor, FakeTensor, FakeTensor]: return _unique( fake_mode, func, arg, dim, False, return_inverse, return_counts, unique_consecutive=True, ) # This function is python match of computeStride_impl in TensorUtils.cpp def _compute_stride( old_shape: Sequence[IntLikeType], old_stride: Sequence[IntLikeType], new_shape: Sequence[IntLikeType], size_oblivious: bool = False, ) -> list[IntLikeType] | None: from torch.fx.experimental.symbolic_shapes import ( guard_or_false, guard_or_true, sym_eq, ) def maybe_guard_or_false(x: Any) -> Any: if size_oblivious: return guard_or_false(x) return x def maybe_guard_or_true(x: Any) -> Any: if size_oblivious: return guard_or_true(x) return x if len(old_shape) == 0: return [1] * len(new_shape) numel = reduce(operator.mul, old_shape, 1) zero_numel = maybe_guard_or_false(numel == 0) if zero_numel and maybe_guard_or_false(sym_eq(old_shape, new_shape)): return list(old_stride) new_stride: list[IntLikeType] = [0] * len(new_shape) if zero_numel: for view_d in range(len(new_shape) - 1, -1, -1): if view_d == len(new_shape) - 1: new_stride[view_d] = 1 else: new_stride[view_d] = ( max(new_shape[view_d + 1], 1) * new_stride[view_d + 1] ) return new_stride view_d = len(new_shape) - 1 # Annotate type here to support type checking chunk_base_stride: IntLikeType = old_stride[-1] tensor_numel: IntLikeType = 1 view_numel: IntLikeType = 1 for tensor_d in range(len(old_shape) - 1, -1, -1): tensor_numel *= old_shape[tensor_d] if tensor_d == 0 or ( maybe_guard_or_true(old_shape[tensor_d - 1] != 1) and maybe_guard_or_true( old_stride[tensor_d - 1] != tensor_numel * chunk_base_stride ) ): while view_d >= 0 and ( maybe_guard_or_true(view_numel < tensor_numel) or maybe_guard_or_false(new_shape[view_d] == 1) ): new_stride[view_d] = view_numel * chunk_base_stride view_numel *= new_shape[view_d] view_d -= 1 if maybe_guard_or_true(view_numel != tensor_numel): return None if tensor_d > 0: chunk_base_stride = old_stride[tensor_d - 1] tensor_numel = 1 view_numel = 1 if view_d != -1: return None return new_stride def _optimization_hint_or_none(value: Any) -> int | None: if type(value) is int: return value if isinstance(value, torch.SymInt): from torch.fx.experimental.symbolic_shapes import optimization_hint return optimization_hint(value, fallback=None) return None def _hinted_eq(lhs: Any, rhs: Any) -> bool: from torch.fx.experimental.symbolic_shapes import guard_or_false if guard_or_false(lhs == rhs): return True lhs_hint = _optimization_hint_or_none(lhs) rhs_hint = _optimization_hint_or_none(rhs) if lhs_hint is None or rhs_hint is None or lhs_hint != rhs_hint: return False # Hints are not shape semantics. They only show that the equality is true # for the traced example, so record the symbolic equality required for the # view rather than specializing either side to a concrete value. torch._check(lhs == rhs) return True def _is_contiguous_with_hinted_checks(a: torch.Tensor) -> bool: from torch.fx.experimental.symbolic_shapes import guard_or_false, is_nested_int if guard_or_false(a.numel() < 2): return True numel_hint = _optimization_hint_or_none(a.numel()) if numel_hint is None: return False if numel_hint < 2: torch._check(a.numel() < 2) return True expected_stride = 1 expected_stride_max = 1 for size, stride in reversed(tuple(zip(a.shape, a.stride()))): if guard_or_false(size == 1): continue size_hint = _optimization_hint_or_none(size) if size_hint == 1: torch._check(size == 1) continue if not _hinted_eq(stride, expected_stride) and not _hinted_eq( stride, expected_stride_max ): return False expected_stride_max *= size if is_nested_int(size) else torch.sym_max(size, 1) expected_stride *= size return True def _view_has_unbacked_input( a: torch.Tensor, shape: ShapeType | tuple[ShapeType] ) -> bool: from torch.fx.experimental.symbolic_shapes import has_guarding_hint shape = utils.extract_shape_from_varargs(shape, validate=False) return ( any(not has_guarding_hint(s) for s in a.size()) or any(not has_guarding_hint(s) for s in a.stride()) or any(not has_guarding_hint(s) for s in shape) ) def try_duck_specialization_first(a: torch.Tensor, shape) -> bool: """ Collect candidate (x, y) pairs whose runtime hints match (so they *could* be equal), then test whether substituting them into the view's numel equation makes the equation symbolically zero. Only commit the equalities (adds the real Eq guards via bool(x == y) which triggers set_replacement) if the substitution actually solves the view validity check. This avoids polluting the shape env with spurious guards from probing. Returns True if at least one equality was committed. Conservative: only considers SymInts that appear as a top-level dim of the input or target (skipping the -1 marker), and skips already-equal pairs, and skips unbacked symbols. """ import operator from functools import reduce from torch.fx.experimental.symbolic_shapes import free_unbacked_symbols def _atomic_syms(dims) -> list[torch.SymInt]: """Keep only SymInts whose expr is a single bare *backed* symbol.""" out: list[torch.SymInt] = [] for s in dims: if not isinstance(s, torch.SymInt): continue expr = s.node.expr free = expr.free_symbols if len(free) != 1 or expr not in free: continue if free_unbacked_symbols(expr): continue out.append(s) return out import sympy a_syms = _atomic_syms(a.size()) target_syms = _atomic_syms(shape) if not a_syms or not target_syms: return False # 1) Bucket symbols by hint, deduplicated by sympy expr (one SymInt per # unique expr per hint). Each non-trivial bucket is a duck-equality # class: every member of the class will be set equal to the bucket's # canonical symbol. This keeps `subs` and `candidates` perfectly in # sync so the numel check exactly reflects what we'll commit. from collections import defaultdict buckets: dict[int, dict[sympy.Expr, torch.SymInt]] = defaultdict(dict) for s in list(a_syms) + list(target_syms): # setdefault keeps the *first* SymInt seen for each (hint, expr). # pyrefly: ignore [bad-index] buckets[s.node.hint].setdefault(s.node.expr, s) candidates: list[tuple[torch.SymInt, torch.SymInt]] = [] for members in buckets.values(): canonical, *rest = members.values() for m in rest: candidates.append((canonical, m)) if not candidates: return False # `subs` is derived from `candidates`, so they cannot drift. subs: dict[sympy.Expr, sympy.Expr] = { m.node.expr: c.node.expr for c, m in candidates } # 2) Symbolic test: does the substitution make the view's numel match? def _expr_of(s): return s.node.expr if isinstance(s, torch.SymInt) else s try: a_numel = reduce(operator.mul, (_expr_of(s) for s in a.size()), 1) shape_numel = reduce(operator.mul, (_expr_of(s) for s in shape), 1) diff = sympy.simplify((a_numel - shape_numel).subs(subs)) if diff != 0: return False except (TypeError, ValueError, AttributeError, sympy.SympifyError): return False # 3) Commit the equalities for real (adds Eq guards, triggers set_replacement). for c, m in candidates: torch._check(c == m) return True def _view_unbacked_meta( a: torch.Tensor, shape: ShapeType | tuple[ShapeType], size_oblivious_enabled: bool = True, allow_copy: bool = False, tried_duck_specialize: bool = False, ) -> torch.Tensor: from torch._prims import view_of from torch.fx.experimental.symbolic_shapes import guard_or_false, sym_eq # Creates a valid shape shape = utils.extract_shape_from_varargs(shape, validate=False) # Reshape may be given a shape with a -1 length # This indicates that the dimension's length should be inferred shape = utils.infer_size(shape, a.numel()) # Special-cases reshaping zero dim tensors if a.ndim == 0: _a = a for length in shape: torch._check(length == 1) _a = torch._refs.unsqueeze(_a, -1) if _a is a: return view_of(a) else: return _a # type: ignore[return-value] # Special-cases reshaping to zero dim tensors if len(shape) == 0: _a = a for length in a.shape: torch._check(length == 1) _a = torch._refs.squeeze(_a, -1) if _a is a: return view_of(a) else: return _a # type: ignore[return-value] shape_numel = reduce(operator.mul, shape, 1) torch._check( a.numel() == shape_numel, lambda: f"Could not reshape a tensor with shape {a.shape} as a tensor with shape {shape}!", ) if len(shape) == len(a.shape) and guard_or_false(sym_eq(shape, a.shape)): return view_of(a) if is_contiguous_or_false(a) if size_oblivious_enabled else is_contiguous(a): strides = make_contiguous_strides_for(shape) return a.as_strided(shape, strides) # type: ignore[return-value] new_strides = _compute_stride( a.size(), a.stride(), shape, size_oblivious=size_oblivious_enabled ) if new_strides is not None: return a.as_strided(shape, new_strides) # type: ignore[return-value] # If we fail to do size oblivious view, and backed_size_oblivious was on, # then we redo everything by looking at hints and guarding instead of failing. # Also if the expression has unbacked symbols, then we run again with size_oblivious_enabled=False # to throw a data dependent error. if size_oblivious_enabled and ( torch.fx.experimental._config.backed_size_oblivious or _view_has_unbacked_input(a, shape) ): # Heuristic: before falling through to the specializing recursion # (which often emits Eq(s, 1) via eval_eager), try to discover # cross-symbol equalities between input and target shape symbols. # If a pair (x, y) is True at the runtime hint, the shape env will # record Eq(x, y) and set_replacement unifies them — letting the # size-oblivious view path succeed without specialization on x==1. # But with potential duck specializations which are more general. if ( torch.fx.experimental._config.unify_view_symbols_bso_meta and not tried_duck_specialize and try_duck_specialization_first(a, shape) ): return _view_unbacked_meta( a, shape, size_oblivious_enabled=True, allow_copy=allow_copy, tried_duck_specialize=True, ) if _is_contiguous_with_hinted_checks(a): strides = make_contiguous_strides_for(shape) return a.as_strided(shape, strides) # type: ignore[return-value] return _view_unbacked_meta( a, shape, size_oblivious_enabled=False, allow_copy=allow_copy ) # When allow_copy=True (i.e., view_copy), define unbacked semantics # as "materialize": clone the input to break aliasing, then reshape. if allow_copy: strides = make_contiguous_strides_for(shape) # pyrefly: ignore[bad-return] return a.clone(memory_format=torch.contiguous_format).as_strided(shape, strides) msg = f"Cannot view a tensor with shape {a.shape} and strides {a.stride()} as a tensor with shape {shape}!" raise ValueError(msg) @register_op_impl(aten._reshape_copy.default) def _reshape_copy( fake_mode: FakeTensorMode, func: OpOverload, a: FakeTensor, *shape: Any ) -> FakeTensor | Exception: if a.is_sparse or a.is_mkldnn: return NotImplemented # pyrefly: ignore[bad-argument-count] shape = utils.infer_size(*shape, a.numel()) if is_contiguous_or_false(a): view = _view_meta(fake_mode, func, a, *shape) return typing_cast( FakeTensor, view.clone(memory_format=torch.contiguous_format) ) else: return _view_meta( fake_mode, func, typing_cast(FakeTensor, a.clone(memory_format=torch.contiguous_format)), *shape, ) @register_op_impl(aten.view.default) @register_op_impl(aten._unsafe_view.default) def _view_meta( fake_mode: FakeTensorMode, func: OpOverload, a: FakeTensor, *shape: Any, allow_copy: bool = False, ) -> FakeTensor: if torch.fx.experimental._config.backed_size_oblivious or _view_has_unbacked_input( a, shape ): return typing_cast( FakeTensor, _view_unbacked_meta(a, shape, allow_copy=allow_copy) ) else: return typing_cast( FakeTensor, torch._refs._reshape_view_helper(a, *shape, allow_copy=allow_copy), ) @register_op_impl(aten.view_copy.default) def _view_meta_copy( fake_mode: FakeTensorMode, func: OpOverload, a: FakeTensor, *shape: IntLikeType, out: FakeTensor | None = None, ) -> FakeTensor: # view_copy is the non-aliasing counterpart of view. Eager may succeed on # cases where a pure view is impossible (e.g. expand -> flatten) by # materializing the result. Match eager by allowing copy-if-needed in meta. result = _view_meta(fake_mode, func, a, *shape, allow_copy=True) if out is not None: return result return pytree.tree_map( lambda x: x.clone(memory_format=torch.contiguous_format), result, ) @register_op_impl(aten.repeat_interleave.Tensor) def repeat_interleave_tensor( fake_mode: FakeTensorMode, func: OpOverload, repeats: FakeTensor, output_size: IntLikeType | None = None, ) -> FakeTensor: if output_size is None: if ( fake_mode.shape_env is None or not fake_mode.shape_env.allow_dynamic_output_shape_ops ): raise DynamicOutputShapeException(func) output_size = fake_mode.shape_env.create_unbacked_symint() # Avoid importing sympy at a module level from torch.fx.experimental.symbolic_shapes import _constrain_range_for_size _constrain_range_for_size(output_size) # TODO: consider a memo return repeats.new_empty(output_size) # type: ignore[return-value] @register_op_impl(torch.ops.aten.item.default) @register_op_impl(torch.ops.aten._local_scalar_dense.default) def local_scalar_dense( fake_mode: FakeTensorMode, func: OpOverload, arg: FakeTensor ) -> int | float | bool | torch.SymInt | torch.SymFloat | torch.SymBool: if (r := arg.item_memo) is not None: return r if fake_mode.shape_env is None or ( not fake_mode.shape_env.allow_scalar_outputs and not fake_mode.allow_scalar_outputs ): # Without symints/symfloats, cannot handle this raise DataDependentOutputException(func) if is_float_dtype(arg.dtype): r = fake_mode.shape_env.create_unbacked_symfloat() elif is_integer_dtype(arg.dtype): r = fake_mode.shape_env.create_unbacked_symint() elif is_boolean_dtype(arg.dtype): r = fake_mode.shape_env.create_unbacked_symbool() else: raise NotImplementedError(f"local_scalar_dense/item NYI for {arg.dtype}") arg.item_memo = r return r @register_op_impl(torch.ops.aten.nonzero_numpy.default) def nonzero_numpy( fake_mode: FakeTensorMode, func: OpOverload, arg: FakeTensor ) -> list[FakeTensor]: return torch.ops.aten.nonzero.default(arg).unbind(1) @register_op_impl(torch.ops.aten.nonzero.default) def nonzero(fake_mode: FakeTensorMode, func: OpOverload, arg: FakeTensor) -> FakeTensor: if ( fake_mode.shape_env is None or not fake_mode.shape_env.allow_dynamic_output_shape_ops ): # Without symints/symfloats, cannot handle this raise DynamicOutputShapeException(func) if (nnz := arg.nonzero_memo) is None: # Avoid importing sympy at a module level from torch.fx.experimental.symbolic_shapes import ( _constrain_range_for_size, has_free_symbols, ) from torch.utils._sympy.numbers import IntInfinity from torch.utils._sympy.value_ranges import bound_sympy if not has_free_symbols(arg.numel()) and arg.numel() == 0: # If numel is zero, then the output size must be zero. # In this case, we must not allocate an unbacked SymInt, # because if we do, it will immediately get refined to # zero, but this will be inconsistent with size oblivious # tests (which will continue to claim that the unbacked # symint cannot equal zero). We could also unconditionally # allocate an unbacked SymInt and not refine its range, # but this seems more precise. nnz = 0 else: nnz = fake_mode.shape_env.create_unbacked_symint() maxval = sys.maxsize - 1 if not has_free_symbols(arg.numel()): maxval = int(arg.numel()) else: prod_node = math.prod(arg.shape).node # type: ignore[union-attr] prod_range = bound_sympy( prod_node.expr, prod_node.shape_env.var_to_range ) if isinstance(prod_range.upper, IntInfinity): maxval = sys.maxsize - 1 else: maxval = prod_range.upper _constrain_range_for_size(nnz, max=maxval) arg.nonzero_memo = nnz # pyrefly: ignore[bad-assignment] return arg.new_empty_strided((nnz, arg.dim()), (1, nnz), dtype=torch.int64) # type: ignore[return] @register_op_impl(torch.ops.aten._padded_dense_to_jagged_forward.default) def _padded_dense_to_jagged_forward( fake_mode: FakeTensorMode, func: OpOverload, padded: FakeTensor, offsets: list[FakeTensor], total_L: IntLikeType | None = None, ) -> FakeTensor: # only one jagged dim is supported for now if len(offsets) != 1: raise AssertionError( f"Only one jagged dim is supported, got {len(offsets)} offsets" ) if total_L is None: if ( fake_mode.shape_env is None or not fake_mode.shape_env.allow_dynamic_output_shape_ops ): # Without symints/symfloats, cannot handle this raise DynamicOutputShapeException(func) total_L = fake_mode.shape_env.create_unbacked_symint() maxval = sys.maxsize - 1 # Avoid importing sympy at a module level from torch.fx.experimental.symbolic_shapes import ( _constrain_range_for_size, has_free_symbols, ) if not has_free_symbols(padded.numel()): maxval = int(padded.numel()) _constrain_range_for_size(total_L, min=0, max=maxval) output_shape = (total_L, *padded.shape[2:]) return padded.new_empty(output_shape) # type: ignore[return] def _compute_slice_index(size: IntLikeType, index: IntLikeType) -> IntLikeType | None: from torch.fx.experimental.symbolic_shapes import guard_or_false, sym_and if guard_or_false(sym_and(index >= 0, index <= size)): return index elif guard_or_false(sym_and(index < 0, index >= -size)): return index + size elif guard_or_false(index < -size): return 0 elif guard_or_false(index > size): return size elif guard_or_false(index >= 0): return torch.sym_min(index, size) elif guard_or_false(index < 0): return torch.sym_max(index + size, 0) return None @register_op_impl(torch.ops.aten.slice.Tensor) def slice_forward( fake_mode: FakeTensorMode, func: OpOverload, self: FakeTensor, dim: int = 0, start: int | None = None, end: int | None = None, step: int = 1, ) -> FakeTensor: from torch.fx.experimental.symbolic_shapes import ( guard_or_false, statically_known_true, ) shape_env = fake_mode.shape_env ndim = self.dim() if ndim == 0: raise RuntimeError("slice() cannot be applied to a 0-dim tensor.") dim = canonicalize_dim(self.dim(), dim) sizes = list(self.size()) strides = list(self.stride()) if step <= 0: raise RuntimeError("slice step must be positive") # start, end start_index = 0 if start is None else _compute_slice_index(sizes[dim], start) end_index = ( sizes[dim] if statically_known_true(end == sys.maxsize) or end is None else _compute_slice_index(sizes[dim], end) ) # size new_size: IntLikeType | None = None if start_index is not None and end_index is not None: if guard_or_false(end_index >= start_index): new_size = (end_index - start_index + step - 1) // step # type: ignore[bad-assignment] elif guard_or_false(start_index >= end_index): new_size = 0 else: # Both indices are resolved but we can't statically determine their # ordering (e.g., when they involve Min/Max). Compute the size via # max(end - start, 0) to avoid creating an unbacked symint. diff = torch.sym_max(end_index - start_index, 0) new_size = (diff + step - 1) // step # type: ignore[assignment] # create unbacked if case unknown if new_size is None: if shape_env is None: raise AssertionError("Must have shape_env to create symint") new_size = shape_env.create_unbacked_symint() torch._check(new_size >= 0) torch._check(new_size <= sizes[dim]) # stride new_stride = strides[dim] * step # storage offset if start_index is not None: storage_offset = self.storage_offset() + start_index * strides[dim] else: if shape_env is None: raise AssertionError("Must have shape_env to create symint") storage_offset = shape_env.create_unbacked_symint() torch._check(storage_offset >= 0) sizes[dim] = new_size # type: ignore[unsupported-operation] strides[dim] = new_stride if self.is_quantized: raise NotImplementedError( "Slice decomposition for quantized tensors aren't implemented" ) else: return self.as_strided(sizes, strides, storage_offset) # type: ignore[return-value] @register_op_impl(torch.ops.aten.masked_select.default) def masked_select( fake_mode: FakeTensorMode, func: OpOverload, self: FakeTensor, mask: FakeTensor ) -> FakeTensor: if ( fake_mode.shape_env is None or not fake_mode.shape_env.allow_dynamic_output_shape_ops ): # Without symints/symfloats, cannot handle this raise DynamicOutputShapeException(func) nnz = fake_mode.shape_env.create_unbacked_symint() # see nonzero for commentary maxval = sys.maxsize - 1 # Avoid importing sympy at a module level from torch.fx.experimental.symbolic_shapes import ( _constrain_range_for_size, has_free_symbols, ) from torch.utils._sympy.numbers import IntInfinity from torch.utils._sympy.value_ranges import bound_sympy # If num elements is expressed symbolically, calculate # the concrete value based on upper bounds. Otherwise, # we can set max val directly. if not has_free_symbols(self.numel()): num_elements = int(self.numel()) else: prod_node = math.prod(self.shape).node # type: ignore[union-attr] prod_range = bound_sympy(prod_node.expr, prod_node.shape_env.var_to_range) if isinstance(prod_range.upper, IntInfinity): num_elements = sys.maxsize - 1 else: num_elements = prod_range.upper if num_elements > 2: maxval = num_elements _constrain_range_for_size(nnz, max=maxval) return self.new_empty((nnz,)) # type: ignore[return] @register_op_impl(torch.ops.aten._assert_tensor_metadata.default) def assert_tensor_metadata( fake_mode: FakeTensorMode, func: OpOverload, t: FakeTensor, size: list[int] | None = None, stride: list[int] | None = None, dtype: torch.dtype | None = None, *, device: torch.device | None = None, layout: torch.layout | None = None, ) -> None: if size is not None: if t.size() != tuple(size): raise AssertionError( f"Tensor size mismatch! Expected: {size}, Got: {t.size()}" ) if stride is not None: if t.stride() != tuple(stride): raise AssertionError( f"Tensor stride mismatch! Expected: {stride}, Got: {t.stride()}" ) if dtype is not None: if t.dtype != dtype: raise AssertionError( f"Tensor dtype mismatch! Expected: {dtype}, Got: {t.dtype}" ) if layout is not None: if t.layout != layout: raise AssertionError( f"Tensor layout mismatch! Expected: {layout}, Got: {t.layout}" ) if device is not None: if t.device != device: raise AssertionError( f"Tensor device mismatch! Expected: {device}, Got: {t.device}" ) # NB: this must be ordered after local_scalar_dense @register_op_impl(lambda func: torch.Tag.data_dependent_output in func.tags) def data_dep( fake_mode: FakeTensorMode, func: OpOverload, *args: Any, **kwargs: Any ) -> None: raise DataDependentOutputException(func) # Bool Indices get Expanded as Masks # See: IndexingUtils.h:expandTensors def check_no_bool_index_tensors( func: OpOverload, self: FakeTensor, indices: list[FakeTensor | None] ) -> None: for index in indices: if index is not None and index.dtype in (torch.bool, torch.uint8): raise DynamicOutputShapeException(func) def run_and_return_new_tensor_of_input_device( fake_mode: FakeTensorMode, func: OpOverload, args: tuple[Any, ...], kwargs: dict[str, Any], ) -> FakeTensor: # TODO: ref _, new_kwargs = _normalize_function_or_error( func, args=args, kwargs=kwargs, normalize_to_only_use_kwargs=True ) out_device = new_kwargs["input"].device with in_kernel_invocation_manager(fake_mode): out = func(*args, **kwargs) if not is_noncontiguous_supported(out_device): out = out.new_empty(out.shape) if out is new_kwargs["input"]: return out # copy_ return FakeTensor(fake_mode, out, out_device) _is_builtin_namespaces = ordered_set("aten", "prims", "prim") def is_builtin(op: OpOverload) -> bool: return op.namespace in _is_builtin_namespaces def has_meta(func: OpOverload) -> bool: return torch._C._dispatch_has_computed_kernel_for_dispatch_key(func.name(), "Meta") def maybe_to_dense_mkldnn( fake_mode: FakeTensorMode, a: FakeTensor, dtype: torch.dtype | None = None, masked_grad: bool | None = None, ) -> object: # this function invokes in_kernel_invocation_manager and creates python # FakeTensor, revisit later for C++ behaviour if ( not isinstance(a, FakeTensor) # noqa: ISINSTANCE_FAKE_TENSOR or not a.is_mkldnn ): return NotImplemented out_dtype = dtype if dtype is not None else a.dtype if a.dtype not in _MKLDNN_TO_DENSE_DTYPES: raise RuntimeError( "mkldnn_to_dense expects float, bfloat16, half, uint8, int8, " "float8_e4m3fn tensor input" ) if out_dtype not in _MKLDNN_TO_DENSE_DTYPES: raise RuntimeError( "mkldnn tensor only can be converted to be a float, bfloat16, Half, " "uint8, int8, float8_e4m3fn cpu tensor" ) if a.dtype in _MKLDNN_DTYPE_CHANGE_RESTRICTED_DTYPES and out_dtype != a.dtype: raise RuntimeError( "For int8, uint8, float8 mkldnn_tensor input, we should not change " "the data type." ) shape = tuple(a.shape) with in_kernel_invocation_manager(fake_mode): out = torch.empty_strided( shape, make_contiguous_strides_for(shape), dtype=out_dtype, device="meta", ) return FakeTensor(fake_mode, out, a.fake_device) class _ToDenseMkldnn(torch.autograd.Function): @staticmethod def forward( self: torch.Tensor, dtype: torch.dtype | None, masked_grad: bool | None, ) -> torch.Tensor: return aten._to_dense.default(self, dtype, masked_grad) @staticmethod def setup_context( ctx: Any, inputs: tuple[torch.Tensor, torch.dtype | None, bool | None], output: torch.Tensor, ) -> None: ctx.set_materialize_grads(False) ctx.input_is_mkldnn = inputs[0].is_mkldnn ctx.input_dtype = inputs[0].dtype @staticmethod # pyrefly: ignore [bad-override] def backward( ctx: Any, grad: torch.Tensor | None ) -> tuple[torch.Tensor | None, None, None]: if grad is None: return None, None, None if ctx.input_is_mkldnn: return aten.to_mkldnn.default(grad, ctx.input_dtype), None, None # torch.func transforms may replay setup_context on a strided wrapper; # match that expected gradient layout instead of forcing MKLDNN. return grad.to(dtype=ctx.input_dtype), None, None # Fake MKLDNN tensors keep MKLDNN-ness in a side channel because the backing # meta tensor is strided. The native composite reads TensorImpl::layout() # directly, so this Python composite consults the layout override instead. def to_dense_composite_impl( self: torch.Tensor, dtype: torch.dtype | None = None, *, masked_grad: bool | None = None, ) -> torch.Tensor: layout = self.layout # This composite is installed globally so direct aten.to_dense can see fake # MKLDNN tensors. Keep the common strided path minimal. if layout == torch.strided: return self.to(dtype=dtype) if dtype is not None else self if layout == torch._mkldnn: # type: ignore[attr-defined] return _ToDenseMkldnn.apply(self, dtype, masked_grad) if layout in _TO_DENSE_SPARSE_LAYOUTS: return aten._to_dense.default(self, dtype, masked_grad) torch._check(False, lambda: f"to_dense does not support layout {layout}") raise AssertionError("unreachable") def to_dense_functorch_frontmode_impl( self: torch.Tensor, dtype: torch.dtype | None = None, *, masked_grad: bool | None = None, ) -> torch.Tensor: interpreter = retrieve_current_functorch_interpreter() if interpreter.key() != TransformType.Grad or not is_functorch_wrapped_tensor(self): with torch.enable_grad(), interpreter.lower(): return aten.to_dense.default(self, dtype=dtype, masked_grad=masked_grad) level = interpreter.level() class _ToDenseGrad(torch.autograd.function._SingleLevelFunction): @staticmethod def forward( ctx: Any, self: torch.Tensor, dtype: torch.dtype | None, masked_grad: bool | None, ) -> torch.Tensor: ctx.set_materialize_grads(False) unwrapped_self = _unwrap_for_grad(self, level) ctx.save_for_backward(unwrapped_self) ctx.input_dtype = unwrapped_self.dtype ctx.input_is_mkldnn = unwrapped_self.is_mkldnn ctx.masked_grad = masked_grad with torch.enable_grad(), interpreter.lower(): if unwrapped_self.is_mkldnn: out = _ToDenseMkldnn.apply(unwrapped_self, dtype, masked_grad) else: out = aten.to_dense.default( unwrapped_self, dtype=dtype, masked_grad=masked_grad ) return _wrap_for_grad(out, level) @staticmethod def backward(ctx: Any, *grads: Any) -> Any: (grad,) = grads if grad is None: return None, None, None if ctx.input_is_mkldnn: # Functorch grad transforms replay setup_context on a strided # wrapper, so return the wrapper's expected dense gradient. return grad.to(dtype=ctx.input_dtype), None, None (input,) = ctx.saved_tensors return ( aten.to_dense_backward.default(grad, input, ctx.masked_grad), None, None, ) with enable_single_level_autograd_function(): # pyrefly: ignore [missing-attribute] return _ToDenseGrad.apply(self, dtype, masked_grad) _to_dense_functorch_lib = torch.library.Library( "aten", "IMPL", "FuncTorchDynamicLayerFrontMode" ) _to_dense_functorch_lib.impl("to_dense", to_dense_functorch_frontmode_impl) def to_dense_python_tls_impl( self: torch.Tensor, dtype: torch.dtype | None = None, *, masked_grad: bool | None = None, ) -> torch.Tensor: from torch._subclasses.functional_tensor import FunctionalTensor if isinstance(self, (FakeTensor, FunctionalTensor)): # noqa: ISINSTANCE_FAKE_TENSOR return to_dense_composite_impl(self, dtype=dtype, masked_grad=masked_grad) with torch._C._ExcludeDispatchKeyGuard(_PYTHON_TLS_SNAPSHOT_KEYSET): return aten.to_dense.default(self, dtype=dtype, masked_grad=masked_grad) # Intercept fake/functional tensor calls before the native composite sees their # strided wrapper metadata, but keep ordinary eager CPU/CUDA to_dense on the C++ # dispatcher path. _to_dense_python_tls_lib = torch.library.Library("aten", "IMPL", "PythonTLSSnapshot") _to_dense_python_tls_lib.impl("to_dense", to_dense_python_tls_impl) # Keep this as a Python decomposition for FakeTensorMode fallback paths without # replacing the eager dispatcher entry for every ordinary to_dense() call. aten.to_dense.default.py_impl(torch._C.DispatchKey.CompositeImplicitAutograd)( to_dense_composite_impl ) @register_op_impl(aten.to_mkldnn.default) def to_mkldnn( fake_mode: FakeTensorMode, func: OpOverload, a: FakeTensor, dtype: torch.dtype | None = None, ) -> object: if not isinstance(a, FakeTensor): # noqa: ISINSTANCE_FAKE_TENSOR return NotImplemented out_dtype = dtype if dtype is not None else a.dtype if a.fake_device.type != "cpu": raise RuntimeError("dense_to_mkldnn expects CPU tensor input") if a.layout != torch.strided: raise RuntimeError("dense_to_mkldnn expects strided tensor input") if a.dtype not in _MKLDNN_DTYPES: raise RuntimeError( "dense_to_mkldnn expects float, bfloat16, half, uint8, int8 tensor input" ) if a.dim() > 5: raise RuntimeError("Can't convert cpu tensor with the number of dimensions > 5") if a.dtype in (torch.uint8, torch.int8) and out_dtype != a.dtype: raise RuntimeError( "For int8, uint8 cpu_tensor input, we should not change the data type." ) if out_dtype not in _MKLDNN_DTYPES: raise RuntimeError( "cpu tensor only can be converted to be a float, bfloat16, half, " "uint8, int8 mkldnn tensor" ) shape = tuple(a.shape) with in_kernel_invocation_manager(fake_mode): # Real MKLDNN tensors report opaque strides as (1, 0, ...); mirror that # while carrying the layout bit through dispatch_keys. out = torch.empty_strided( shape, (1,) + (0,) * (len(shape) - 1), dtype=out_dtype, device="meta", ) return FakeTensor( fake_mode, out, a.fake_device, dispatch_keys=_MKLDNN_DISPATCH_KEYS ) # These are for the `torch._foreach_...` ops like `torch._foreach_add`. @register_op_impl( lambda func: is_builtin(func) and func.name().startswith("aten::_foreach_") and has_meta(func) ) def foreach_run_and_map_input_device( fake_mode: FakeTensorMode, func: OpOverload, *args: Any, **kwargs: Any ) -> list[FakeTensor] | None: tensor_lists = [ arg for arg in itertools.chain(args, kwargs.values()) if isinstance(arg, (list, tuple)) and len(arg) and isinstance(arg[0], torch.Tensor) ] try: with in_kernel_invocation_manager(fake_mode): out_meta = func(*args, **kwargs) except NotImplementedError: return NotImplemented if not out_meta: return out_meta if not tensor_lists: raise AssertionError("tensor_lists must not be empty") out_fake = [] for i, meta_t in enumerate(out_meta): device, _ = FakeTensor._find_common_device(func, [tl[i] for tl in tensor_lists]) out_fake.append( fake_mode.fake_tensor_converter.from_meta_and_device( fake_mode, meta_t, device ) ) return out_fake # Don't default to default device handling, # Since op can take in non-zero sized cpu # index tensors with cuda self @register_op_impl(aten.index.Tensor) def index_tensor( fake_mode: FakeTensorMode, func: OpOverload, *args: Any, **kwargs: Any ) -> FakeTensor: from torch._meta_registrations import meta_index_Tensor _, new_kwargs = _normalize_function_or_error( func, args=args, kwargs=kwargs, normalize_to_only_use_kwargs=True ) out_device = new_kwargs["input"].device # ensure nonzero call goes to fake tensor with fake_mode: out = meta_index_Tensor(*args, **kwargs) return out.to(out_device) # Can take mixed meta/non-meta arguments; the meta registration # will roughly do the right thing even when given real devices @register_op_impl(aten._embedding_bag.default) def embedding_bag( fake_mode: FakeTensorMode, func: OpOverload, *args: Any, **kwargs: Any ) -> tuple[FakeTensor, FakeTensor, FakeTensor, FakeTensor]: from torch._meta_registrations import meta_embedding_bag with fake_mode: return meta_embedding_bag(*args, **kwargs) @register_op_impl(aten.embedding.default) def embedding( fake_mode: FakeTensorMode, func: OpOverload, *args: Any, **kwargs: Any ) -> Any: from torch._meta_registrations import embedding as meta_embedding _, new_kwargs = _normalize_function_or_error( func, args=args, kwargs=kwargs, normalize_to_only_use_kwargs=True ) weight = new_kwargs["weight"] indices = new_kwargs["indices"] if ( weight.device != indices.device and weight.device.type != "meta" and indices.device.type != "meta" ): return NotImplemented with fake_mode: return typing_cast(FakeTensor, meta_embedding(*args, **kwargs)) # takes in multiple-devices, don't default to default device handling @register_op_impl(aten._unsafe_index_put.default) @register_op_impl(aten.copy.default) @register_op_impl(aten.copy_.default) @register_op_impl(aten.slice_scatter.default) @register_op_impl(aten.diagonal_scatter.default) def multi_device_op_default( fake_mode: FakeTensorMode, func: OpOverload, *args: Any, **kwargs: Any ) -> FakeTensor: return run_and_return_new_tensor_of_input_device(fake_mode, func, args, kwargs) @register_op_impl(aten.shallow_copy_data_.default) def _( fake_mode: FakeTensorMode, func: OpOverload, *args: Any, **kwargs: Any ) -> FakeTensor: _, new_kwargs = _normalize_function_or_error( func, args=args, kwargs=kwargs, normalize_to_only_use_kwargs=True ) source_device = new_kwargs["source"].device with in_kernel_invocation_manager(fake_mode): func(*args, **kwargs) new_kwargs["input"].fake_device = source_device return new_kwargs["input"] # same with multi_device_op_default, but return the input @register_op_impl(aten.copy.out) @register_op_impl(aten.slice_scatter.out) def multi_device_op_out( fake_mode: FakeTensorMode, func: OpOverload, *args: Any, **kwargs: Any ) -> FakeTensor: with in_kernel_invocation_manager(fake_mode): func(*args, **kwargs) _, new_kwargs = _normalize_function_or_error( func, args=args, kwargs=kwargs, normalize_to_only_use_kwargs=True ) return new_kwargs["input"] @register_op_impl(aten.index_put.default) @register_op_impl(aten.index_put_.default) def index_put_impl( fake_mode: FakeTensorMode, func: OpOverload, *args: Any, **kwargs: Any ) -> FakeTensor: _, new_kwargs = _normalize_function_or_error( func, args=args, kwargs=kwargs, normalize_to_only_use_kwargs=True ) values = new_kwargs["values"] self_device = new_kwargs["input"].fake_device torch._check( self_device == values.fake_device or (values.ndim == 0 and values.numel() == 1), lambda: f"Mismatching {func} device between self ({self_device}) and values ({values.device})", ) out = run_and_return_new_tensor_of_input_device(fake_mode, func, args, kwargs) if func is aten.index_put_.default: return new_kwargs["input"] else: return out @register_op_impl(aten._nested_tensor_from_tensor_list.default) @register_op_impl(aten._nested_tensor_from_tensor_list.out) @register_op_impl(aten._nested_view_from_buffer.default) @register_op_impl(aten._nested_view_from_buffer_copy.default) def nested_tensors_unsupported( fake_mode: FakeTensorMode, func: OpOverload, *args: Any, **kwargs: Any ) -> None: raise UnsupportedOperatorException(func) @register_op_impl( [ x for x in _device_not_kwarg_ops if x not in ( # these are already registered elsewhere aten.is_pinned.default, aten.to.device, aten.to.prim_Device, aten._nested_tensor_from_tensor_list.default, aten._nested_tensor_from_tensor_list.out, ) ] ) def nyi(fake_mode: FakeTensorMode, func: OpOverload, *args: Any, **kwargs: Any) -> None: if func in _device_not_kwarg_ops: raise AssertionError(f"NYI: {func}") @register_op_impl( [ aten.convolution.default, aten._convolution.default, aten._convolution.deprecated, aten.convolution_backward.default, ] ) def conv( fake_mode: FakeTensorMode, func: OpOverload, *args: Any, **kwargs: Any ) -> FakeTensor | tuple[FakeTensor | None, FakeTensor | None, FakeTensor | None]: _, new_kwargs = _normalize_function_or_error( func, args=args, kwargs=kwargs, normalize_to_only_use_kwargs=True ) def expect_fake_tensor(name: str, value: object) -> FakeTensor: if not isinstance(value, FakeTensor): # noqa: ISINSTANCE_FAKE_TENSOR raise AssertionError( "Expected fake convolution tensor arguments to be FakeTensors, " f"but {name} was {type(value).__name__}" ) return value input_ = expect_fake_tensor("input", new_kwargs["input"]) weight = expect_fake_tensor("weight", new_kwargs["weight"]) device = input_.fake_device # Internal passes such as Inductor freezing may run fake propagation over # folded convs that do not need to match eager's public input checks. if ( func in ( aten.convolution.default, aten._convolution.default, aten._convolution.deprecated, ) and input_.dtype != weight.dtype and not input_.is_mkldnn and not fake_mode.allow_non_fake_inputs ): raise RuntimeError( f"Input type ({input_.dtype}) and weight type " f"({weight.dtype}) should be the same" ) for name, value in new_kwargs.items(): if isinstance(value, torch.Tensor): fake_value = expect_fake_tensor(name, value) if not _same_device_or_unspecified_index(fake_value.fake_device, device): raise RuntimeError( "Expected all tensors to be on the same device, but got " f"{name} is on {fake_value.fake_device}, different from " f"other tensors on {device}" ) # need to re-enable mode so the tensors report fake device with fake_mode: # if the input is unsqueezed in Convolution.cpp we get segfault k = weight.ndim # Avoid importing sympy at a module level from torch.fx.experimental.symbolic_shapes import has_guarding_hint all_hinted = all(has_guarding_hint(s) for s in input_.shape) and all( has_guarding_hint(s) for s in weight.shape ) if not all_hinted: # TODO: We can make this a little more faithful with best effort # channels last detection (but only if it's statically obvious!) mem_fmt = None elif input_.dim() == k - 1: # Unbatched input: eager routes directly to the slow dilated # backward kernels, which produce contiguous gradients and bypass # the channels-last backend-memory-format selection. Mirror that # here; _select_conv_backend would also reject the missing batch # dim. mem_fmt = None else: # convolution has "bias" but not "bias_sizes"; convolution_backward # has "bias_sizes" but not "bias". .get() handles both with one call. bias = new_kwargs.get("bias") select_kwargs: dict[str, object] = dict( stride=new_kwargs["stride"], padding=new_kwargs["padding"], dilation=new_kwargs["dilation"], transposed=new_kwargs["transposed"], output_padding=new_kwargs["output_padding"], groups=new_kwargs["groups"], bias=bias, ) if bias is None: select_kwargs["bias_sizes"] = new_kwargs.get("bias_sizes") conv_backend = torch._C._select_conv_backend( input_, weight, **select_kwargs ) # Expand 1d -> 2d. # Note: Avoid expanding before calling _select_conv_backend, # as the function handles 2D expansion internally. if k == 3 and not input_.is_mkldnn and not input_.is_xpu: # Note: Using input.to(memory_format=contiguous) does not work. input_ = input_.contiguous().unsqueeze(2) weight = weight.unsqueeze(2) mem_fmt = torch._C._conv_determine_backend_memory_format( input_, weight, conv_backend ) def convert( t: torch.Tensor | None, mem_fmt: torch.memory_format | None ) -> FakeTensor | None: if t is None: return t if mem_fmt is not None: # channels last only support 4d, try to expand dim then convert it back later. if t.dim() == 3 and mem_fmt == torch.channels_last: t = t.unsqueeze(2).to(memory_format=mem_fmt).squeeze(2) else: t = t.to(memory_format=mem_fmt) return FakeTensor(fake_mode, t, device) with in_kernel_invocation_manager(fake_mode): out = func(**new_kwargs) if func in ( aten.convolution.default, aten._convolution.default, aten._convolution.deprecated, ): return convert(out, mem_fmt) # type: ignore[return] else: return ( convert(out[0], mem_fmt), convert(out[1], mem_fmt), convert(out[2], None), ) @register_op_impl(torch.ops.aten.bincount.default) def bincount( fake_mode: FakeTensorMode, func: OpOverload, inputs: FakeTensor, weights: FakeTensor | None = None, minlength: IntLikeType = 0, ) -> FakeTensor: if ( fake_mode.shape_env is None or not fake_mode.shape_env.allow_dynamic_output_shape_ops ): # Without symints/symfloats, cannot handle this raise DynamicOutputShapeException(func) from torch.fx.experimental.symbolic_shapes import ( _constrain_range_for_size, has_free_symbols, ) if not has_free_symbols(inputs.numel()) and inputs.numel() == 0: return inputs.new_empty(minlength, dtype=torch.int64) # type: ignore[return] new_size = fake_mode.shape_env.create_unbacked_symint() _constrain_range_for_size(new_size) torch._check(new_size >= minlength) if weights is None: return inputs.new_empty(new_size, dtype=torch.int64) # type: ignore[return] if weights.device.type == "mps": dtype = ( weights.dtype if weights.dtype in (torch.float32, torch.int32, torch.float16) else torch.int32 ) else: dtype = weights.dtype if weights.dtype == torch.float32 else torch.float64 return weights.new_empty(new_size, dtype=dtype) # type: ignore[return] @register_op_impl(torch.ops.aten._pack_padded_sequence.default) def _pack_padded_sequence( fake_mode: FakeTensorMode, func: OpOverload, inputs: FakeTensor, lengths: FakeTensor, batch_first: bool, ) -> tuple[FakeTensor, FakeTensor]: if ( fake_mode.shape_env is None or not fake_mode.shape_env.allow_dynamic_output_shape_ops ): # Without symints/symfloats, cannot handle this raise DynamicOutputShapeException(func) new_batch_size = fake_mode.shape_env.create_unbacked_symint() from torch.fx.experimental.symbolic_shapes import _constrain_range_for_size _constrain_range_for_size(new_batch_size) if not batch_first: # Inputs should have shape (batch_size, seq_len, *) inputs = inputs.transpose(0, 1) # type: ignore[assignment] res_size = inputs.shape[1:] packed_data = inputs.new_empty(res_size) batch_size = inputs.new_empty((new_batch_size,)) return (packed_data, batch_size) # type: ignore[return] def _fake_alias(fake_mode: FakeTensorMode, x: FakeTensor) -> FakeTensor: with no_python_dispatcher(), in_kernel_invocation_manager(fake_mode): out = aten.alias.default(x) # Real MKLDNN alias is not public API, but compiler-generated alias nodes # must preserve fake MKLDNN layout state through tracing. return FakeTensor(fake_mode, out, x.device, dispatch_keys=x.dispatch_keys) @register_op_impl(aten.alias.default) def fake_alias( fake_mode: FakeTensorMode, func: OpOverload, x: FakeTensor ) -> FakeTensor | object: if not isinstance(x, FakeTensor): # noqa: ISINSTANCE_FAKE_TENSOR return NotImplemented return _fake_alias(fake_mode, x) # pyrefly: ignore [implicit-any] FAST_OP_IMPLEMENTATIONS = {} # Unlike register_op_impl, these don't do the slow iteration for # run_impl_check, and these run BEFORE decompositions def register_fast_op_impl( func: OpOverload, ) -> Callable[[Callable[_P, _R]], Callable[_P, _R]]: def impl_decorator(op_impl: Callable[_P, _R]) -> Callable[_P, _R]: FAST_OP_IMPLEMENTATIONS[func] = op_impl return op_impl return impl_decorator # infer_size_impl in ExpandUtils def infer_size( a: Sequence[IntLikeType], b: Sequence[IntLikeType] ) -> tuple[IntLikeType, ...]: from torch.fx.experimental.symbolic_shapes import guard_or_false dimsA = len(a) dimsB = len(b) ndim = max(dimsA, dimsB) expandedSizes: list[IntLikeType] = [0] * ndim for i in range(ndim - 1, -1, -1): offset = ndim - 1 - i dimA = dimsA - 1 - offset dimB = dimsB - 1 - offset sizeA = a[dimA] if dimA >= 0 else 1 sizeB = b[dimB] if dimB >= 0 else 1 # NB: It is very important to test for broadcasting, before testing # sizeA == sizeB. This is because the broadcasting tests are likely # to be statically known (in particular, if sizeA/sizeB is unbacked # but size-like, we will unsoundly assume they never equal 1), but # the sizeA == sizeB test may not be statically known. However, once # we have established that no broadcasting is happening, the # sizeA == sizeB is now expect_true and we can defer it as a runtime # assert (this works because Python will return the terminal # expression of an or statement as-is, without bool()'ing it; if this # were not the case, we'd need to write this using torch.sym_or() or # something like that). torch._check( guard_or_false(sizeA == 1) or guard_or_false(sizeB == 1) or sizeA == sizeB, lambda: f"The size of tensor a ({sizeA}) " f"must match the size of tensor b ({sizeB}) " f"at non-singleton dimension {i})", ) expandedSizes[i] = sizeB if guard_or_false(sizeA == 1) else sizeA return tuple(expandedSizes) def make_fast_binary_impl( slow_ref: Callable[..., Any], type_promotion_kind: ELEMENTWISE_TYPE_PROMOTION_KIND = ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT, ) -> Callable[..., FakeTensor]: def fast_binary_impl(mode: FakeTensorMode, *args: Any, **kwargs: Any) -> FakeTensor: def slow(msg: str) -> FakeTensor: count_label(f"slow {msg}") with mode: return slow_ref(*args, **kwargs) count_label("attempt fast") # Fast path (based off of TensorIterator fast path). # Unfortunately, there is no way to easily deduplicate # this with either the TensorIterator C++ implementation # (which we don't want to SymIntify, and also the algorithm # here is slightly different from TensorIterator to allow # for broadcasting), nor the PrimTorch implementation # (which does not actually implement a fast path.) operands = args # compute_shape final_shape: ShapeType | None = None for op in operands: shape: ShapeType = op.shape if isinstance(op, torch.Tensor) else () if final_shape is None: final_shape = shape # TODO: Minor optimization: track if the shapes # were equal so you can skip the equality check # below if unnecessary # pyrefly: ignore[bad-assignment] final_shape = infer_size(final_shape, shape) if final_shape is None: raise AssertionError("final_shape must not be None") from torch.fx.experimental.symbolic_shapes import guard_or_false, sym_eq # Do some extra safety checks to see if the output # stride is obvious for op in operands: if ( isinstance(op, torch.Tensor) and len(op.shape) == len(final_shape) # take the slow path if result is not determined. and guard_or_false(sym_eq(op.shape, final_shape)) # type: ignore[arg-type] ): break else: # if we never break in the for loop above we take the slow path. return slow("both tensors nontrivially broadcast") # compute_types cpu = torch.device("cpu") common_device: torch.device = cpu common_dtype: torch.dtype | None = None has_different_input_dtypes = False for op in operands: if not isinstance(op, torch.Tensor): # Use elementwise_dtypes for the tricky case has_different_input_dtypes = True continue if common_device == cpu and op.device.type != "cpu": common_device = op.device if common_dtype is None: if type_promotion_kind != ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT: has_different_input_dtypes = True else: common_dtype = op.dtype elif common_dtype != op.dtype: has_different_input_dtypes = True if has_different_input_dtypes: # compute promotion # TODO: we don't need the compute type _, common_dtype = elementwise_dtypes( *operands, type_promotion_kind=type_promotion_kind ) # check all tensors on same device # cpu scalars are assumed allow current_cpu_scalars_on_non_cpu = 0 max_cpu_scalars_on_non_cpu = 1 # hard coded atm for op in operands: if not isinstance(op, torch.Tensor): continue if common_device != cpu and op.dim() == 0 and op.device == cpu: if current_cpu_scalars_on_non_cpu >= max_cpu_scalars_on_non_cpu: return slow("error") current_cpu_scalars_on_non_cpu += 1 elif op.device != common_device: return slow("error") # compute_fast_setup_type definitely_contiguous = True definitely_channels_last = True # TODO: is_non-overlapping_and_dense not bound from Python # no inplace, no out, everything defined if is_noncontiguous_supported(common_device): for op in operands: if not isinstance(op, torch.Tensor): continue definitely_contiguous = ( definitely_contiguous and is_contiguous_for_memory_format_or_false( op, memory_format=torch.contiguous_format ) ) definitely_channels_last = ( definitely_channels_last and is_contiguous_for_memory_format_or_false( op, memory_format=torch.channels_last ) ) if definitely_contiguous: # do contiguous count_label("fast is_contiguous") return FakeTensor( mode, torch.empty( final_shape, dtype=common_dtype, device="meta", memory_format=torch.contiguous_format, ), device=common_device, ) if definitely_channels_last: count_label("fast channels_last") # do channels last return FakeTensor( mode, torch.empty( final_shape, dtype=common_dtype, device="meta", memory_format=torch.channels_last, ), device=common_device, ) return slow("no contiguity match") return fast_binary_impl # disable the python dispatcher to avoid decomposing detach() further # (proxy_mode should still decompose detach() though) def fast_detach( fake_mode: FakeTensorMode | None, x: FakeTensor | torch.Tensor, include_real: bool = False, ) -> torch.Tensor: if ( not isinstance(x, FakeTensor) # noqa: ISINSTANCE_FAKE_TENSOR or fake_mode is None ): raise AssertionError( "type widening added for cpp faketensor but this is not used yet" ) with no_python_dispatcher(), in_kernel_invocation_manager(fake_mode): out = torch.ops.aten.detach.default(x) dispatch_keys = x.dispatch_keys if include_real: return FakeTensor( fake_mode, out, x.device, real_tensor=x.real_tensor, dispatch_keys=dispatch_keys, ) return FakeTensor(fake_mode, out, x.device, dispatch_keys=dispatch_keys) def fast_alias(fake_mode: FakeTensorMode, x: FakeTensor) -> FakeTensor: return _fake_alias(fake_mode, x) @functools.cache def get_fast_op_impls() -> dict[OpOverload, Callable[..., Any]]: import torch._refs register_fast_op_impl(torch.ops.aten.add.Tensor)( make_fast_binary_impl(torch._refs.add) ) register_fast_op_impl(torch.ops.aten.sub.Tensor)( make_fast_binary_impl(torch._refs.sub) ) register_fast_op_impl(torch.ops.aten.mul.Tensor)( make_fast_binary_impl(torch._refs.mul) ) # type: ignore[has-type] register_fast_op_impl(torch.ops.aten.div.Tensor)( make_fast_binary_impl( torch._refs.div, type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.INT_TO_FLOAT, ) ) register_fast_op_impl(torch.ops.aten.detach.default)(fast_detach) register_fast_op_impl(torch.ops.aten.alias.default)(fast_alias) return FAST_OP_IMPLEMENTATIONS