_decompositions.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. # mypy: allow-untyped-defs
  2. import torch
  3. from torch import Tensor
  4. aten = torch.ops.aten
  5. import inspect
  6. import warnings
  7. from typing import Callable, Optional, TypeVar
  8. from typing_extensions import ParamSpec
  9. from torch.types import Number
  10. decomposition_table: dict[str, torch.jit.ScriptFunction] = {}
  11. function_name_set: set[str] = set()
  12. _T = TypeVar("_T")
  13. _P = ParamSpec("_P")
  14. def check_decomposition_has_type_annotations(f):
  15. inspect_empty = inspect._empty # type: ignore[attr-defined]
  16. sig = inspect.signature(f)
  17. for param in sig.parameters.values():
  18. assert param.annotation != inspect_empty, (
  19. f"No signature on param {param.name} for function {f.name}"
  20. )
  21. assert sig.return_annotation != inspect_empty, (
  22. f"No return annotation for function {f.name}"
  23. )
  24. def signatures_match(decomposition_sig, torch_op_sig):
  25. decomp_params = decomposition_sig.parameters
  26. op_params = torch_op_sig.parameters
  27. if len(decomp_params) != len(op_params):
  28. return False
  29. for decomp_param, op_param in zip(decomp_params.values(), op_params.values()):
  30. # can't check full equality yet because not all fields are correctly deduced
  31. # in the torch_op_sig - like default value
  32. # can't check 'kind' bc
  33. # kwarg-only values with defaults not yet supported in TS
  34. inspect_empty = inspect._empty # type: ignore[attr-defined]
  35. for field in ["name", "annotation"]:
  36. if field == "name" and decomp_param.name == "self":
  37. warnings.warn("PyTorch uses 'input' instead of 'self' on public api")
  38. if getattr(decomp_param, field) != getattr(op_param, field):
  39. return False
  40. decomp_default = decomp_param.default
  41. op_default = op_param.default
  42. # default value not always correctly inferred as being present on torch schema,
  43. # but if specified on both they should be equal
  44. if decomp_default != inspect_empty and op_default != inspect_empty:
  45. if decomp_default != op_default:
  46. return False
  47. return decomposition_sig.return_annotation == torch_op_sig.return_annotation
  48. def register_decomposition(
  49. aten_op: torch._ops.OpOverload,
  50. registry: Optional[dict[str, torch.jit.ScriptFunction]] = None,
  51. ) -> Callable[[Callable[_P, _T]], Callable[_P, _T]]:
  52. def decomposition_decorator(f: Callable[_P, _T]) -> Callable[_P, _T]:
  53. nonlocal registry
  54. if registry is None:
  55. registry = decomposition_table
  56. assert isinstance(aten_op, torch._ops.OpOverload)
  57. # Need unique name for jit function serialization
  58. assert f.__name__ not in function_name_set, (
  59. f"Duplicated function name {f.__name__}"
  60. )
  61. function_name_set.add(f.__name__)
  62. scripted_func = torch.jit.script(f)
  63. torch._C._jit_pass_inline(scripted_func.graph)
  64. for _ in range(2):
  65. torch._C._jit_pass_peephole(scripted_func.graph)
  66. torch._C._jit_pass_constant_propagation(scripted_func.graph)
  67. registry[str(aten_op._schema)] = scripted_func
  68. return f
  69. return decomposition_decorator
  70. # TODO: replace torch.sigmoid -> aten.sigmoid
  71. @register_decomposition(aten.var.correction)
  72. def var_decomposition(
  73. input: Tensor,
  74. dim: Optional[list[int]] = None,
  75. correction: Optional[Number] = None,
  76. keepdim: bool = False,
  77. ) -> Tensor:
  78. if dim is None:
  79. dim_i: list[int] = []
  80. dim = dim_i
  81. if isinstance(dim, (tuple, list)) and len(dim) == 0:
  82. n = input.numel()
  83. else:
  84. n = 1
  85. for dim_i in dim: # type: ignore[assignment]
  86. n *= input.shape[dim_i] # type: ignore[call-overload]
  87. mean = aten.mean(input, dim, True)
  88. sub = input - mean
  89. sq = sub * sub
  90. sum = aten.sum(sq, dim, keepdim)
  91. if correction is None:
  92. denom = float(n - 1)
  93. else:
  94. if isinstance(correction, int):
  95. denom = float(n - correction)
  96. elif isinstance(correction, float):
  97. denom = float(n) - correction
  98. else:
  99. raise RuntimeError("correction must be int or float")
  100. return sum / max(0, denom)
  101. @register_decomposition(aten.var.default)
  102. def var(input: Tensor, unbiased: bool = True) -> Tensor:
  103. return var_decomposition(input, correction=(1 if unbiased else 0))