translate.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  1. from typing import Dict, Sequence, List, NoReturn, Union
  2. from torchgen.api.types import (
  3. ListCType,
  4. tensorListT,
  5. BaseCType,
  6. Binding,
  7. ConstRefCType,
  8. Expr,
  9. MutRefCType,
  10. OptionalCType,
  11. NamedCType,
  12. SpecialArgName,
  13. tensorT,
  14. memoryFormatT,
  15. tensorOptionsT,
  16. scalarTypeT,
  17. boolT,
  18. deviceT,
  19. layoutT,
  20. optionalTensorRefT,
  21. iTensorListRefT,
  22. iOptTensorListRefT,
  23. scalarT,
  24. optionalScalarRefT,
  25. VectorCType,
  26. longT,
  27. intArrayRefT,
  28. scalar_t,
  29. opmath_t,
  30. optionalIntArrayRefT,
  31. )
  32. # This file implements a small program synthesis engine that implements
  33. # conversions between one API to another.
  34. #
  35. # The key data type in this file in NamedCType, short for Named C++ semantic type. A NamedCType
  36. # represents a C++ type, plus semantic information about what it represents.
  37. # For example, consider the argument "bool pin_memory"; its normal C++ type is
  38. # "bool", but its C++ semantic type also keeps track that this represents a
  39. # "pin_memory"; you can't just use a random other boolean in a context where you
  40. # need a "pin_memory"!
  41. #
  42. # The translator takes a list of needed NamedCTypes, and then figures out how
  43. # to construct expressions with these NamedCTypes from the given bindings. Many
  44. # of these expressions are trivial (I need a Tensor other; there's a Tensor
  45. # other scope); others are more nontrivial and may require packing/unpacking.
  46. # Some examples of non-trivial action:
  47. #
  48. # - Need the "dtype" binding? Well, maybe "dtype" isn't available
  49. # in the context, instead, "options" is, and you need to extract
  50. # it from there. (Gather)
  51. #
  52. # - Need the "context" binding? Well, maybe "context" isn't available
  53. # in the context, and you need to construct it from "dtype", "device",
  54. # etc. (Scatter)
  55. #
  56. # - Need the "memory_format" binding? Well, actually, it's available
  57. # from both "memory_format" and "options", so you had better make sure
  58. # they are consistent. (Join)
  59. options_ctype = NamedCType("options", ConstRefCType(BaseCType(tensorOptionsT)))
  60. out_tensor_ctype = NamedCType("out", ConstRefCType(BaseCType(tensorT)))
  61. longVec_ctype = VectorCType(BaseCType(longT))
  62. optionalLongVec_ctype = OptionalCType(VectorCType(BaseCType(longT)))
  63. optionalScalar_ctype = OptionalCType(BaseCType(scalarT))
  64. optionalTensor_ctype = OptionalCType(BaseCType(tensorT))
  65. class UnsatError(RuntimeError):
  66. pass
  67. # Given a set of in-scope bindings and a set of target bindings, synthesize
  68. # a list of expressions that uses only the in-scope bindings (bindings) that
  69. # have all of the types of goals. You may want to use this function if
  70. # you're generating code for a function like:
  71. #
  72. # void f({args}) {
  73. # g({exprs}); // g is a different API
  74. # }
  75. #
  76. # and you need to generate "exprs".
  77. #
  78. # Typically, a list of Bindings is convenient to get (you usually call something
  79. # like arguments() to get them); but technically you only need less information:
  80. # for 'bindings' an (un-ordered) list of Exprs is sufficient; similarly, for
  81. # 'goals', an (ordered) list of NamedCType goals is sufficient. If you are doing
  82. # something more complicated, e.g., tracking the set of bindings in a context,
  83. # you may find using these smaller types more convenient.
  84. def translate(
  85. bindings: Sequence[Union[Expr, Binding]],
  86. goals: Sequence[Union[NamedCType, Binding]],
  87. *,
  88. method: bool = False,
  89. allow_expensive_conversions: bool = False,
  90. ) -> List[Expr]:
  91. binding_exprs: List[Expr] = []
  92. for b in bindings:
  93. if isinstance(b, Binding):
  94. binding_exprs.append(
  95. Expr(
  96. expr=b.name,
  97. type=b.nctype,
  98. )
  99. )
  100. else:
  101. binding_exprs.append(b)
  102. goal_ctypes: List[NamedCType] = []
  103. for g in goals:
  104. if isinstance(g, Binding):
  105. goal_ctypes.append(g.nctype)
  106. else:
  107. goal_ctypes.append(g)
  108. # Add all the bindings to the context
  109. ctx: Dict[NamedCType, str] = {}
  110. for b in binding_exprs:
  111. ctx[b.type] = b.expr
  112. # While we're at it, do some simple forward inference, looking through
  113. # constructors.
  114. #
  115. # NB: When should you do forward inference versus backward inference?
  116. # The general idea:
  117. #
  118. # - Backward inference WHEN the goal gets smaller
  119. # - Forward inference WHEN the hypothesis gets smaller
  120. #
  121. # This helps ensure termination: backward inference starts with a goal
  122. # and tries to make it simpler and simpler until it's trivial; if the
  123. # goal can grow in size, we blow up to a really huge goal size.
  124. # Similarly, with forward inference we take hypotheses and decompose
  125. # them into simpler hypotheses; if hypotheses could expand in size,
  126. # we also have potential nontermination. (In the code below, forward
  127. # inference is only ever carried out at a single step, but you could
  128. # imagine repeated application of forward inference being profitable.)
  129. #
  130. # A good starting point in the literature for exploring more about proof
  131. # search are these lecture notes
  132. # https://www.cs.cmu.edu/~fp/courses/oregon-m10/04-focusing.pdf
  133. #
  134. # TODO: My kingdom for a pattern matcher
  135. # https://www.python.org/dev/peps/pep-0634/
  136. #
  137. # TODO: This could get us in recomputation trouble if b.expr is nontrivial.
  138. # Fix this by implementing some sort of sharing so that if multiple
  139. # goals share the same expression, we only compute it once. This seems
  140. # to matter in practice as compiler is often unwilling to CSE nontrivial
  141. # expressions like scalar.to<scalar_t>()
  142. t = b.type
  143. if (
  144. isinstance(t, ConstRefCType)
  145. and isinstance(t.elem, OptionalCType)
  146. and isinstance(t.elem.elem, BaseCType)
  147. and str(t.elem.elem.type) == "at::Tensor"
  148. ):
  149. ctx[
  150. NamedCType(t.elem.elem.name, ConstRefCType(BaseCType(tensorT)))
  151. ] = f"({b.expr}.has_value() ? *{b.expr} : at::Tensor())"
  152. if t.type == ConstRefCType(OptionalCType(BaseCType(tensorT))):
  153. ctx[
  154. NamedCType(t.name, BaseCType(optionalTensorRefT))
  155. ] = f"(({b.expr}.has_value() && (*{b.expr}).defined()) ? at::OptionalTensorRef(*{b.expr}) : at::OptionalTensorRef())"
  156. if t.type == ConstRefCType(BaseCType(scalarT)):
  157. ctx[NamedCType(t.name, BaseCType(opmath_t))] = f"({b.expr}).to<opmath_t>()"
  158. if t.type == ConstRefCType(OptionalCType(BaseCType(scalarT))):
  159. ctx[
  160. NamedCType(t.name, BaseCType(optionalScalarRefT))
  161. ] = f"({b.expr}.has_value() ? at::OptionalScalarRef(&({b.expr}.value())) : at::OptionalScalarRef())"
  162. if t.type == BaseCType(scalar_t):
  163. ctx[
  164. NamedCType(t.name, BaseCType(opmath_t))
  165. ] = f"static_cast<opmath_t>({b.expr})"
  166. # [Note: ITensorListRef]
  167. if t.type == BaseCType(tensorListT):
  168. ctx[
  169. NamedCType(t.name, BaseCType(iTensorListRefT))
  170. ] = f"at::ITensorListRef({b.expr})"
  171. # [Note: IOptTensorListRef]
  172. if t.type == ConstRefCType(ListCType(OptionalCType(BaseCType(tensorT)))):
  173. ctx[
  174. NamedCType(t.name, BaseCType(iOptTensorListRefT))
  175. ] = f"at::IOptTensorListRef({b.expr})"
  176. # Add implicit bindings if the generated code is inside a Tensor method
  177. if method:
  178. ctx[
  179. NamedCType("self", MutRefCType(BaseCType(tensorT)))
  180. ] = "const_cast<Tensor&>(*this)"
  181. ctx[
  182. NamedCType("self", ConstRefCType(BaseCType(tensorT)))
  183. ] = "const_cast<Tensor&>(*this)"
  184. # This is better! Byte-for-byte compat
  185. # ctx[NamedCType("self", ConstRefCType(BaseCType(tensorT)))] = "*this"
  186. def unsat(goal: NamedCType) -> NoReturn:
  187. ctx_desc = "\n".join(
  188. f" {t.cpp_type()} {t.name}; // {e}" for t, e in ctx.items()
  189. )
  190. raise UnsatError(
  191. f"""
  192. Failed to synthesize the expression "{goal.cpp_type()} {goal.name}".
  193. When I failed, the following bindings were available in the context:
  194. {ctx_desc}
  195. This probably means there is a missing rule in the rules of torchgen.api.translate.
  196. Check this module for more information.
  197. """
  198. )
  199. # A shitty backtracking search implementation. It's shitty because it
  200. # does backtracking via stack (bad idea!) and for the most part tries to
  201. # avoid backtracking. In particular, if
  202. # direct=True, we won't try to do any fancy synthesis, just trivial
  203. # conversions (e.g., "T a" is OK for "const T& a"). So all of the
  204. # existing rules in this function simply try to solve immediately,
  205. # and bail if things don't work out.
  206. def solve(goal: NamedCType, *, direct: bool) -> str:
  207. def direct_solve(goal: NamedCType) -> str:
  208. return solve(goal, direct=True)
  209. if goal in ctx:
  210. # Trivial
  211. return ctx[goal]
  212. # const & is satisfied with mutable &
  213. if isinstance(goal.type, ConstRefCType):
  214. try:
  215. # WARNING: not strictly decreasing; be careful not
  216. # to add a direct conversion that goes satisfies
  217. # mutable& with const&
  218. return solve(
  219. NamedCType(goal.name, MutRefCType(goal.type.elem)), direct=direct
  220. )
  221. except UnsatError:
  222. pass
  223. # mutable & is satisfied with value
  224. if isinstance(goal.type, MutRefCType):
  225. try:
  226. return solve(NamedCType(goal.name, goal.type.elem), direct=direct)
  227. except UnsatError:
  228. pass
  229. if direct:
  230. unsat(goal)
  231. # For now, all of these rules are mutually exclusive.
  232. if goal == NamedCType("memory_format", OptionalCType(BaseCType(memoryFormatT))):
  233. memory_format = direct_solve(
  234. NamedCType(
  235. SpecialArgName.possibly_redundant_memory_format,
  236. OptionalCType(BaseCType(memoryFormatT)),
  237. )
  238. )
  239. # No need to join "memory_format" and "options" if the target API takes "options" directly.
  240. # Otherwise it will cause the redundant memory_format error.
  241. if options_ctype in goal_ctypes:
  242. return memory_format
  243. try:
  244. options = direct_solve(options_ctype)
  245. return f"c10::impl::check_tensor_options_and_extract_memory_format({options}, {memory_format})"
  246. except UnsatError:
  247. return memory_format
  248. elif goal == NamedCType("options", BaseCType(tensorOptionsT)):
  249. dtype = direct_solve(
  250. NamedCType("dtype", OptionalCType(BaseCType(scalarTypeT)))
  251. )
  252. pin_memory = direct_solve(
  253. NamedCType("pin_memory", OptionalCType(BaseCType(boolT)))
  254. )
  255. device = direct_solve(
  256. NamedCType("device", OptionalCType(BaseCType(deviceT)))
  257. )
  258. layout = direct_solve(
  259. NamedCType("layout", OptionalCType(BaseCType(layoutT)))
  260. )
  261. return f"TensorOptions().dtype({dtype}).layout({layout}).device({device}).pinned_memory({pin_memory})"
  262. elif goal == NamedCType("dtype", OptionalCType(BaseCType(scalarTypeT))):
  263. try:
  264. options = direct_solve(options_ctype)
  265. return f"optTypeMetaToScalarType({options}.dtype_opt())"
  266. except UnsatError:
  267. out_tensor = direct_solve(out_tensor_ctype)
  268. return f"{out_tensor}.scalar_type()"
  269. elif goal == NamedCType("layout", OptionalCType(BaseCType(layoutT))):
  270. try:
  271. options = direct_solve(options_ctype)
  272. return f"{options}.layout_opt()"
  273. except UnsatError:
  274. out_tensor = direct_solve(out_tensor_ctype)
  275. return f"{out_tensor}.layout()"
  276. elif goal == NamedCType("device", OptionalCType(BaseCType(deviceT))):
  277. try:
  278. options = direct_solve(options_ctype)
  279. return f"{options}.device_opt()"
  280. except UnsatError:
  281. out_tensor = direct_solve(out_tensor_ctype)
  282. return f"{out_tensor}.device()"
  283. elif goal == NamedCType("pin_memory", OptionalCType(BaseCType(boolT))):
  284. try:
  285. options = direct_solve(options_ctype)
  286. return f"{options}.pinned_memory_opt()"
  287. except UnsatError:
  288. # If we're calling a factory op from its out= variant,
  289. # We don't actually care about the value of pin_memory.
  290. out_tensor = direct_solve(out_tensor_ctype)
  291. return "c10::nullopt"
  292. # We can always do translations from value types to reference types, like vector<int> -> IntArrayRef
  293. elif goal.type == BaseCType(intArrayRefT):
  294. return direct_solve(NamedCType(goal.name, longVec_ctype))
  295. elif goal.type == BaseCType(optionalIntArrayRefT):
  296. return direct_solve(NamedCType(goal.name, optionalLongVec_ctype))
  297. elif goal.type == BaseCType(optionalScalarRefT):
  298. return direct_solve(NamedCType(goal.name, optionalScalar_ctype))
  299. elif goal.type == BaseCType(optionalTensorRefT):
  300. return direct_solve(NamedCType(goal.name, optionalTensor_ctype))
  301. # Note [translation from C++ reference to value types]
  302. # The below cases are all for when we have an argument with a reference type,
  303. # and a corresponding goal with a value type.
  304. # These are needed when we populate the inputs to a lambda capture and we need
  305. # to guarantee the lifetime of each captured argument.
  306. # We guard it with an explicit kwarg because converting to a value type is expensive
  307. # (O(n)) to convert from IntArrayRef to vector<int>),
  308. # so the caller of translate() should be explicit that they need it.
  309. if allow_expensive_conversions:
  310. if goal.type == VectorCType(BaseCType(longT)):
  311. intArrayRef_ctype = NamedCType(goal.name, BaseCType(intArrayRefT))
  312. argname = direct_solve(intArrayRef_ctype)
  313. return f"{argname}.vec()"
  314. elif goal.type == OptionalCType(VectorCType(BaseCType(longT))):
  315. optionalIntArrayRef_ctype = NamedCType(
  316. goal.name, BaseCType(optionalIntArrayRefT)
  317. )
  318. argname = direct_solve(optionalIntArrayRef_ctype)
  319. return f"{argname}.has_value() ? c10::make_optional({argname}->vec()) : c10::nullopt"
  320. elif goal.type == OptionalCType(BaseCType(scalarT)):
  321. optionalScalarRef_ctype = NamedCType(
  322. goal.name, BaseCType(optionalScalarRefT)
  323. )
  324. argname = direct_solve(optionalScalarRef_ctype)
  325. return f"{argname}.has_value() ? c10::make_optional({argname}) : c10::nullopt"
  326. elif goal.type == OptionalCType(BaseCType(scalarT)):
  327. optionalTensorRef_ctype = NamedCType(
  328. goal.name, BaseCType(optionalTensorRefT)
  329. )
  330. argname = direct_solve(optionalTensorRef_ctype)
  331. return f"{argname}.has_value() ? c10::make_optional({argname}) : c10::nullopt"
  332. # Technically, we also need to handle cases of C++ containers holding reference types.
  333. # But there currently aren't any ops that require lambda capture codegen
  334. # With arguments like std::vector<IntArrayRef>.
  335. # If that changes, we'll have to add the translation here.
  336. # We allow const casting on tensors, since const-correctness is a bit broken for at::Tensor.
  337. # We could probably generalize this to non-tensor types too.
  338. if goal.type == MutRefCType(BaseCType(tensorT)):
  339. const_ref_tensor_ctype = NamedCType(
  340. goal.name, ConstRefCType(BaseCType(tensorT))
  341. )
  342. argname = direct_solve(const_ref_tensor_ctype)
  343. return f"const_cast<Tensor&>({argname})"
  344. unsat(goal)
  345. return [Expr(solve(g, direct=False), g) for g in goal_ctypes]