structured.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  1. from typing import List, Union
  2. from torchgen.api import cpp
  3. from torchgen.api.types import (
  4. ArgName,
  5. ArrayRefCType,
  6. BaseCType,
  7. Binding,
  8. ConstRefCType,
  9. dimnameListT,
  10. intArrayRefT,
  11. iOptTensorListRefT,
  12. iTensorListRefT,
  13. NamedCType,
  14. OptionalCType,
  15. optionalIntArrayRefT,
  16. optionalScalarRefT,
  17. optionalTensorRefT,
  18. scalarT,
  19. tensorT,
  20. )
  21. from torchgen.model import (
  22. Argument,
  23. BaseTy,
  24. BaseType,
  25. ListType,
  26. NativeFunctionsGroup,
  27. OptionalType,
  28. SelfArgument,
  29. TensorOptionsArguments,
  30. Type,
  31. )
  32. from torchgen.utils import assert_never
  33. # This file describes the translation of JIT schema to the structured functions API.
  34. # This is similar to native API, but a number of historical problems with native
  35. # API have been fixed.
  36. # Translation of types occuring in JIT arguments to a C++ argument type.
  37. # NB: For now, mutable doesn't do anything; but it could if we make
  38. # some more nominal types
  39. def argumenttype_type(t: Type, *, mutable: bool, binds: ArgName) -> NamedCType:
  40. # If it's a value type, do the value type translation
  41. # NB: structured kernels ALWAYS have symint off, since they involve actual
  42. # kernels that require real ints. The one exception is the
  43. # CompositeExplicitAutograd and the meta function (which could
  44. # hypothetically be SymInt), but for simplicity we plan for these to just
  45. # be handled in Python
  46. r = cpp.valuetype_type(t, symint=False, binds=binds)
  47. if r is not None:
  48. return r
  49. if isinstance(t, BaseType):
  50. if t.name == BaseTy.Tensor:
  51. return NamedCType(binds, ConstRefCType(BaseCType(tensorT)))
  52. elif t.name == BaseTy.Scalar:
  53. return NamedCType(binds, ConstRefCType(BaseCType(scalarT)))
  54. else:
  55. raise AssertionError(f"base type should have been value type {t}")
  56. elif isinstance(t, OptionalType):
  57. if t.elem == BaseType(BaseTy.Tensor):
  58. return NamedCType(binds, BaseCType(optionalTensorRefT))
  59. elif t.elem == BaseType(BaseTy.Scalar):
  60. return NamedCType(binds, BaseCType(optionalScalarRefT))
  61. elif isinstance(t.elem, ListType) and str(t.elem.elem) == "int":
  62. return NamedCType(binds, BaseCType(optionalIntArrayRefT))
  63. elem = argumenttype_type(t.elem, mutable=mutable, binds=binds)
  64. return NamedCType(binds, OptionalCType(elem.type))
  65. elif isinstance(t, ListType):
  66. if t.elem == BaseType(BaseTy.Tensor):
  67. return NamedCType(binds, ConstRefCType(BaseCType(iTensorListRefT)))
  68. elif t.elem == OptionalType(BaseType(BaseTy.Tensor)):
  69. return NamedCType(binds, BaseCType(iOptTensorListRefT))
  70. # TODO: delete these special cases; see torchgen.api.cpp--these
  71. # must be changed in tandem, but there are problems; see
  72. # https://github.com/pytorch/pytorch/pull/51485
  73. elif str(t.elem) == "int":
  74. return NamedCType(binds, BaseCType(intArrayRefT))
  75. elif str(t.elem) == "Dimname":
  76. return NamedCType(binds, BaseCType(dimnameListT))
  77. elem = argumenttype_type(t.elem, mutable=mutable, binds=binds)
  78. return NamedCType(binds, ArrayRefCType(elem.type))
  79. else:
  80. raise AssertionError(f"unrecognized type {repr(t)}")
  81. def argument_type(a: Argument, *, binds: ArgName) -> NamedCType:
  82. return argumenttype_type(a.type, mutable=a.is_write, binds=binds)
  83. # returns_type intentionally omitted, because structured kernels never "return";
  84. # instead, they always indirectly report their outputs (in the case of a meta
  85. # function, by calling set_output; in the case of an impl function, by writing
  86. # directly into the provided out argument).
  87. # Structured kernels are never defaulted
  88. def argument(a: Union[Argument, SelfArgument, TensorOptionsArguments]) -> List[Binding]:
  89. if isinstance(a, Argument):
  90. return [
  91. Binding(
  92. nctype=argument_type(a, binds=a.name),
  93. name=a.name,
  94. default=None,
  95. argument=a,
  96. )
  97. ]
  98. elif isinstance(a, SelfArgument):
  99. return argument(a.argument)
  100. elif isinstance(a, TensorOptionsArguments):
  101. raise AssertionError("structured kernels don't support TensorOptions yet")
  102. else:
  103. assert_never(a)
  104. def impl_arguments(g: NativeFunctionsGroup) -> List[Binding]:
  105. args: List[Union[Argument, TensorOptionsArguments, SelfArgument]] = []
  106. if g.out.precomputed:
  107. # A list of parameters for the impl function with
  108. # certain parameters replaced with precomputed counterparts
  109. # as specified in native_functions.yaml.
  110. non_out_args_replaced: List[
  111. Union[Argument, TensorOptionsArguments, SelfArgument]
  112. ] = []
  113. for a in g.out.func.arguments.non_out:
  114. if isinstance(a, Argument) and a.name in g.out.precomputed.replace:
  115. # If a is in precompute.replace, append the parameters
  116. # that should replace it onto non_out_args_replaced.
  117. for replacement in g.out.precomputed.replace[a.name]:
  118. non_out_args_replaced.append(replacement)
  119. else:
  120. # If not, push a as it is.
  121. non_out_args_replaced.append(a)
  122. args.extend(non_out_args_replaced)
  123. # g.out.precomputed.add is the list of parameters that are added
  124. # without replacement after the non out args and just before the out args
  125. args.extend(g.out.precomputed.add)
  126. else:
  127. args.extend(g.out.func.arguments.non_out)
  128. args.extend(g.out.func.arguments.out)
  129. return [r for arg in args for r in argument(arg)]
  130. def meta_arguments(g: NativeFunctionsGroup) -> List[Binding]:
  131. args: List[Union[Argument, TensorOptionsArguments, SelfArgument]] = []
  132. args.extend(g.functional.func.arguments.non_out)
  133. return [r for arg in args for r in argument(arg)]
  134. def out_arguments(g: NativeFunctionsGroup) -> List[Binding]:
  135. args: List[Union[Argument, TensorOptionsArguments, SelfArgument]] = []
  136. args.extend(g.out.func.arguments.out)
  137. return [r for arg in args for r in argument(arg)]