structured.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. from __future__ import annotations
  2. from typing_extensions import assert_never
  3. from torchgen.api import cpp
  4. from torchgen.api.types import (
  5. ArgName,
  6. ArrayRefCType,
  7. BaseCType,
  8. Binding,
  9. ConstRefCType,
  10. dimnameListT,
  11. intArrayRefT,
  12. iOptTensorListRefT,
  13. iTensorListRefT,
  14. NamedCType,
  15. OptionalCType,
  16. optionalIntArrayRefT,
  17. optionalScalarRefT,
  18. optionalTensorRefT,
  19. scalarT,
  20. tensorT,
  21. )
  22. from torchgen.model import (
  23. Argument,
  24. BaseTy,
  25. BaseType,
  26. ListType,
  27. NativeFunctionsGroup,
  28. OptionalType,
  29. SelfArgument,
  30. TensorOptionsArguments,
  31. Type,
  32. )
  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 occurring 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, mutable=mutable)
  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: 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[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. 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. non_out_args_replaced.extend(g.out.precomputed.replace[a.name])
  118. else:
  119. # If not, push a as it is.
  120. non_out_args_replaced.append(a)
  121. args.extend(non_out_args_replaced)
  122. # g.out.precomputed.add is the list of parameters that are added
  123. # without replacement after the non out args and just before the out args
  124. args.extend(g.out.precomputed.add)
  125. else:
  126. args.extend(g.out.func.arguments.non_out)
  127. args.extend(g.out.func.arguments.out)
  128. return [r for arg in args for r in argument(arg)]
  129. def meta_arguments(g: NativeFunctionsGroup) -> list[Binding]:
  130. args: list[Argument | TensorOptionsArguments | SelfArgument] = []
  131. args.extend(g.functional.func.arguments.non_out)
  132. return [r for arg in args for r in argument(arg)]
  133. def out_arguments(g: NativeFunctionsGroup) -> list[Binding]:
  134. args: list[Argument | TensorOptionsArguments | SelfArgument] = []
  135. args.extend(g.out.func.arguments.out)
  136. return [r for arg in args for r in argument(arg)]