functionalization.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. from __future__ import annotations
  2. from torchgen.api import dispatcher
  3. from torchgen.api.types import (
  4. BaseCppType,
  5. BaseCType,
  6. Binding,
  7. boolT,
  8. ConstRefCType,
  9. CType,
  10. longT,
  11. NamedCType,
  12. tensorT,
  13. )
  14. from torchgen.model import (
  15. Argument,
  16. BaseTy,
  17. BaseType,
  18. FunctionSchema,
  19. NativeFunction,
  20. NativeFunctionsViewGroup,
  21. )
  22. # This file describes the translation of JIT schema to API's used
  23. # when creating `ViewMeta` specializations that are used by the functionalization pass.
  24. # These API's mostly follow the dispatcher API, with one difference:
  25. # - While the forward function just directly calls into the at::_ops API
  26. # (following the dispatcher convention), the logic here for the reverse function
  27. # is responsible for generating both the call-site, and the declarations
  28. # (which are implemented manually in the at::functionalization::impl namespace).
  29. # Define some specific lambda input arguments.
  30. base_binding = Binding(
  31. name="base",
  32. nctype=NamedCType(name="base", type=ConstRefCType(BaseCType(tensorT))),
  33. argument=Argument(
  34. name="base", type=BaseType(BaseTy.Tensor), default=None, annotation=None
  35. ),
  36. default=None,
  37. )
  38. has_symbolic_inputs_binding = Binding(
  39. name="has_symbolic_inputs",
  40. nctype=NamedCType(name="has_symbolic_inputs", type=BaseCType(boolT)),
  41. argument=Argument(
  42. name="has_symbolic_inputs",
  43. type=BaseType(BaseTy.bool),
  44. default=None,
  45. annotation=None,
  46. ),
  47. default=None,
  48. )
  49. mutated_view_binding = Binding(
  50. name="mutated_view",
  51. nctype=NamedCType(name="mutated_view", type=ConstRefCType(BaseCType(tensorT))),
  52. argument=Argument(
  53. name="base", type=BaseType(BaseTy.Tensor), default=None, annotation=None
  54. ),
  55. default=None,
  56. )
  57. out_index_binding = Binding(
  58. name="out_index",
  59. nctype=NamedCType(name="out_index", type=BaseCType(longT)),
  60. argument=Argument(
  61. name="out_index", type=BaseType(BaseTy.int), default=None, annotation=None
  62. ),
  63. default=None,
  64. )
  65. reapply_views_binding = Binding(
  66. name="reapply_views",
  67. nctype=NamedCType(name="reapply_views", type=BaseCType(boolT)),
  68. argument=Argument(
  69. name="reapply_views", type=BaseType(BaseTy.bool), default=None, annotation=None
  70. ),
  71. default=None,
  72. )
  73. InverseReturnModeT = BaseCppType("at::functionalization", "InverseReturnMode")
  74. inverse_return_mode_binding = Binding(
  75. name="inverse_return_mode",
  76. nctype=NamedCType(name="inverse_return_mode", type=BaseCType(InverseReturnModeT)),
  77. argument=Argument(
  78. name="inverse_return_mode",
  79. # NB: not actually a bool but it doesn't matter because this isn't used
  80. type=BaseType(BaseTy.bool),
  81. default=None,
  82. annotation=None,
  83. ),
  84. default=None,
  85. )
  86. # Name of the `ViewMeta` specialization class created.
  87. def classname(func: FunctionSchema, with_namespace: bool = False) -> str:
  88. namespace = "at::functionalization::" if with_namespace else ""
  89. return f"{namespace}{func.name.unambiguous_name()}_ViewMeta"
  90. # Name of the operation called inside the `forward`/`reverse` implementations.
  91. def name(
  92. g: NativeFunctionsViewGroup,
  93. *,
  94. is_reverse: bool,
  95. include_namespace: bool,
  96. reapply_views: bool | None = None,
  97. ) -> str:
  98. if reapply_views is None:
  99. # reapply_views is only important for the fwd lambda,
  100. # since we always plumb the runtime "reapply_views" argument into the reverse function.
  101. assert is_reverse
  102. if is_reverse:
  103. return reverse_name(g.view, include_namespace)
  104. # in the forward case, we just directly call into the at::_ops API (so we always need the namespace)
  105. assert include_namespace
  106. assert g.view_copy is not None
  107. api_name = (
  108. g.view.func.name.unambiguous_name()
  109. if reapply_views
  110. else g.view_copy.func.name.unambiguous_name()
  111. )
  112. return f"at::_ops::{api_name}::call"
  113. def reverse_name(f: NativeFunction, include_namespace: bool) -> str:
  114. # for the reverse: we plumb the "reapply_views" flag into that function and support
  115. # both copy and non-copy variants. (We could avoid doing that, but that would require
  116. # writing out twice as many view inverse functions).
  117. api_name = f.func.name.unambiguous_name()
  118. # in the reverse case, we codegen both the call-sites (which need the full namespace) and the declarations (which don't)
  119. if include_namespace:
  120. return f"at::functionalization::FunctionalInverses::{api_name}_inverse"
  121. else:
  122. return f"{api_name}_inverse"
  123. def returns_type(func: FunctionSchema) -> CType:
  124. # Assertion: all view ops return tensor-like outputs
  125. assert len(func.returns) >= 1
  126. for ret in func.returns:
  127. assert ret.type.is_tensor_like()
  128. # However, the return type of the lambda is always an individual tensor.
  129. # For multi-tensor outputs, each tensor needs to be tracked individually.
  130. return BaseCType(tensorT)
  131. # Checks whether `func` might return more than one value.
  132. def is_multi_output(func: FunctionSchema) -> bool:
  133. return len(func.returns) > 1 or (
  134. len(func.returns) == 1 and func.returns[0].type.is_list_like() is not None
  135. )
  136. # `ViewMeta` specialization constructor parameters.
  137. def base_ctor_arguments(func: FunctionSchema) -> list[Binding]:
  138. # All specializations are parematerized by `has_symbolic_inputs` flag.
  139. arguments = [has_symbolic_inputs_binding]
  140. # If `func` might return more than 1 value, we also parameterize this specialization
  141. # with the output index.
  142. if is_multi_output(func):
  143. arguments.append(out_index_binding)
  144. return arguments
  145. # `ViewMeta` specialized class' constructor arguments.
  146. #
  147. # Values needed specifically by this specialization, that the base class does not need.
  148. # Same as the class' attributes, but non-owning.
  149. def extra_ctor_arguments(func: FunctionSchema) -> list[Binding]:
  150. return attributes(func, owning=False)
  151. # `ViewMeta` specialized class' non-static member data.
  152. #
  153. # Essential data for calling the instance's `forward` and `reverse functions. You can
  154. # think of them as values that should be captured from the functionalization kernel.
  155. def attributes(func: FunctionSchema, owning: bool = True) -> list[Binding]:
  156. args = func.arguments.flat_all
  157. assert args[0].type == BaseType(BaseTy.Tensor)
  158. return [
  159. reapply_views_binding,
  160. inverse_return_mode_binding,
  161. *[dispatcher.argument(a, remove_non_owning_ref_types=owning) for a in args[1:]],
  162. ]
  163. def op_arguments(func: FunctionSchema, is_reverse: bool) -> list[Binding]:
  164. args = func.arguments.flat_all
  165. assert args[0].type == BaseType(BaseTy.Tensor)
  166. non_self_args = args[1:]
  167. # The forward lambda calls the at::_ops API, while the reverse lambda calls the view inverse API.
  168. # Both of these follow the dispatcher API.
  169. non_self_bindings = [dispatcher.argument(a) for a in non_self_args]
  170. if not is_reverse:
  171. # the forward lambda swaps out the original tensor argument with the lambd arg "base"
  172. return [base_binding] + non_self_bindings
  173. else:
  174. # the reverse lambda does the same, but with an additional "mutated_view" arg
  175. # additionally, we have a calling convention: for view ops that return multiple tensor outputs
  176. # their corresponding view_inverse function takes in an additional index argument.
  177. if is_multi_output(func):
  178. return [
  179. base_binding,
  180. mutated_view_binding,
  181. inverse_return_mode_binding,
  182. out_index_binding,
  183. ] + non_self_bindings
  184. else:
  185. return [
  186. base_binding,
  187. mutated_view_binding,
  188. inverse_return_mode_binding,
  189. ] + non_self_bindings