comptime.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. # This file establishes the public comptime interface to Dynamo.
  2. # This allows Dynamo users to execute arbitrary Python code while
  3. # Dynamo is symbolically evaluating their original programs.
  4. #
  5. # The goal of the public API is to give users rope, without actually
  6. # leaking private implementation details of Dynamo.
  7. import dis
  8. import traceback
  9. from .exc import unimplemented
  10. class ComptimeVar:
  11. """
  12. A ComptimeVar represents a Python value, at some particular point
  13. in time, in the Python code we are symbolically evaluating with
  14. torchdynamo. This must be distinguished from a runtime value, as
  15. at compile-time there are some properties of the variable we
  16. do not know (for example, if the ComptimeVar represents a Tensor,
  17. we only know metadata about the tensor; we do NOT know what the
  18. actual data in the Tensor is.)
  19. """
  20. def __init__(self, v):
  21. self.__variable = v
  22. def as_proxy(self):
  23. """
  24. Returns an fx.Proxy (or tuple/list of fx.Proxy) representing
  25. this variable in the FX graph we are assembling to pass
  26. to the user compiler.
  27. This method only works for variables we actually track in
  28. the FX graph, aka Tensors (and ints, if you are compiling
  29. with dynamic shapes). In particular, if you have a list
  30. or tuple of tensors, you will get a list/tuple of proxies
  31. (not a single proxy representing the entire list/tuple).
  32. """
  33. return self.__variable.as_proxy()
  34. def is_proxy(self):
  35. """
  36. Returns True if as_proxy() would succeed.
  37. """
  38. return self.__variable.is_proxy()
  39. def as_fake(self):
  40. """
  41. Returns a "fake" value (either a FakeTensor or a SymInt)
  42. representing the variable in question. This only works
  43. for variables that denote Tensor or int. You can use
  44. this to query metadata; e.g., v.as_fake().size(0) will
  45. tell you the compile-time known size of the tensor.
  46. WARNING: Do NOT mutate the returned tensor.
  47. """
  48. return self.__variable.as_proxy().node.meta["example_value"]
  49. def python_type(self):
  50. """
  51. Returns what type(v) would have returned for the variable
  52. at compile time.
  53. """
  54. return self.__variable.python_type()
  55. def as_python_constant(self):
  56. """
  57. Returns the Python value this variable would have, but only if it is
  58. completely known at compile-time (e.g., it is constant).
  59. WARNING: Do NOT mutate the returned constant. The returned constant
  60. may or may not correspond to the actual value this variable may take
  61. on at runtime; for example, if the variable in question is a constant
  62. list, we may return a copy of that list.
  63. """
  64. return self.__variable.as_python_constant()
  65. def is_python_constant(self):
  66. """
  67. Returns True if as_python_constant would succeed.
  68. """
  69. return self.__variable.is_python_constant()
  70. def _i_will_not_complain_if_bc_breaks_VariableTracker(self):
  71. """
  72. Returns the internal data structure VariableTracker that Dynamo uses
  73. to represent variables at compile time. There are no BC guarantees on
  74. this API and WE RESERVE THE RIGHT TO BREAK YOUR CODE if you rely on
  75. it.
  76. """
  77. return self.__variable
  78. def __repr__(self):
  79. # TODO: The default repr is pretty bad, do better
  80. return repr(self.__variable)
  81. # TODO: API for adding a custom guard
  82. class ComptimeContext:
  83. """
  84. This context class provides access to a public API for Dynamo's internals.
  85. If there is something here you would find useful that is missing, please
  86. file a feature request at https://github.com/pytorch/pytorch/
  87. """
  88. def __init__(self, tx):
  89. self.__tx = tx
  90. def get_local(self, name: str, *, stacklevel=0) -> ComptimeVar:
  91. """
  92. Retrieve the compile-time known information about a local.
  93. """
  94. tx = self.__get_tx(stacklevel)
  95. return ComptimeVar(tx.symbolic_locals[name])
  96. def graph_break(self, msg="ComptimeContext.graph_break"):
  97. """
  98. Manually trigger a graph break
  99. """
  100. unimplemented(msg)
  101. def graph(self):
  102. """
  103. Retrieve the partially constructed FX graph that would be
  104. passed to the user compiler after compilation.
  105. """
  106. return self.__tx.output.graph
  107. def print_graph(self, *, verbose=True, file=None):
  108. """
  109. Print the partially constructed FX graph that would be passed
  110. to the user compiler after compilation.
  111. """
  112. print(
  113. self.__tx.output.graph.python_code("self", verbose=verbose).src, file=file
  114. )
  115. def __get_tx(self, stacklevel):
  116. tx = self.__tx
  117. for _ in range(stacklevel):
  118. tx = tx.parent
  119. return tx
  120. def print_disas(self, *, file=None, stacklevel=0):
  121. """
  122. Print the current series of opcodes being executed (not including
  123. parent frames), including where you are in the particular opcode
  124. stream.
  125. """
  126. tx = self.__get_tx(stacklevel)
  127. print(
  128. dis.Bytecode(
  129. tx.f_code,
  130. current_offset=tx.instructions[tx.instruction_pointer].offset,
  131. ).dis(),
  132. file=file,
  133. )
  134. def print_value_stack(self, *, file=None, stacklevel=0):
  135. """
  136. Print the current Python value stack. Note that this is NOT the same
  137. as the traceback; use print_bt() to print that. Note that at
  138. stacklevel=0, this will typically be empty, as comptime cannot
  139. currently be used in an expression context where there would be
  140. intermediates on the stack. If you would find this useful, please
  141. file a bug at https://github.com/pytorch/pytorch/
  142. NB: Stack grows downwards in our print
  143. """
  144. # TODO: improve printing
  145. tx = self.__get_tx(stacklevel)
  146. for s in tx.stack:
  147. print(f"- {s}", file=file)
  148. def print_locals(self, *, file=None, stacklevel=0):
  149. """
  150. Print all of the locals available in the current context.
  151. By default this view is very limited; you can get more information
  152. about any individual local using get_local().
  153. """
  154. # TODO: improve by improving the VariableTracker printing
  155. tx = self.__get_tx(stacklevel)
  156. for k, v in tx.symbolic_locals.items():
  157. print(f"{k} = {v}", file=file)
  158. def print_bt(self, *, file=None, stacklevel=0):
  159. """
  160. Print the user code backtrace, starting at the beginning of the
  161. frame Dynamo started evaluating. Note that this MAY NOT go all
  162. the way to the torch.compile invocation, as we may have done
  163. a graph break and are compiling an intermediate frame as the
  164. starting point. If you think the other behavior would be better,
  165. file a bug at https://github.com/pytorch/pytorch/
  166. """
  167. stack = []
  168. tx = self.__get_tx(stacklevel)
  169. while tx is not None:
  170. stack.append(tx.frame_summary())
  171. tx = getattr(tx, "parent", None)
  172. print(
  173. "".join(traceback.StackSummary.from_list(reversed(stack)).format()),
  174. file=file,
  175. )
  176. def print_guards(self, *, file=None):
  177. """
  178. Print the currently installed guards for the Dynamo context.
  179. This does NOT include guards associated with variables that
  180. may or may not be installed in the future if those variables
  181. are used.
  182. """
  183. # TODO: improve print format, current guard format is extremely
  184. # verbose
  185. print(
  186. "\n".join(f"-{str(guard)}" for guard in sorted(self.__tx.output.guards)),
  187. file=file,
  188. )
  189. def _i_will_not_complain_if_bc_breaks_InstructionTranslator(self):
  190. """
  191. Returns the internal data structure InstructionTranslator that Dynamo
  192. uses to track state of symbolic evaluation. There are no BC
  193. guarantees on this API and WE RESERVE THE RIGHT TO BREAK YOUR CODE if
  194. you rely on it.
  195. """
  196. return self.__tx
  197. # Convenience wrappers that are more compact to use
  198. def graph_break():
  199. comptime(lambda ctx: ctx.graph_break())
  200. def print_graph():
  201. comptime(lambda ctx: ctx.print_graph())
  202. def print_disas(*, stacklevel=0):
  203. comptime(
  204. lambda ctx: ctx.print_disas(
  205. stacklevel=ctx.get_local("stacklevel").as_python_constant() + 1
  206. )
  207. )
  208. def print_value_stack(*, stacklevel=0):
  209. comptime(
  210. lambda ctx: ctx.print_value_stack(
  211. stacklevel=ctx.get_local("stacklevel").as_python_constant() + 1
  212. )
  213. )
  214. # This is a more useful variant of print_value_stack that can be used
  215. # in an expression context; e.g., x + print_value_stack_and_return(y + z),
  216. # you will see x on the stack prior to the addition operation
  217. def print_value_stack_and_return(e, *, stacklevel=0):
  218. comptime(
  219. lambda ctx: ctx.print_value_stack(
  220. stacklevel=ctx.get_local("stacklevel").as_python_constant() + 1
  221. )
  222. )
  223. return e
  224. def print_locals(*, stacklevel=0):
  225. comptime(
  226. lambda ctx: ctx.print_locals(
  227. stacklevel=ctx.get_local("stacklevel").as_python_constant() + 1
  228. )
  229. )
  230. def print_bt(*, stacklevel=0):
  231. comptime(
  232. lambda ctx: ctx.print_bt(
  233. stacklevel=ctx.get_local("stacklevel").as_python_constant() + 1
  234. )
  235. )
  236. def print_guards():
  237. comptime(lambda ctx: ctx.print_guards())
  238. def comptime(fn):
  239. """fn gets called at compile time in TorchDynamo, does nothing otherwise"""
  240. return
  241. comptime.graph_break = graph_break
  242. comptime.print_graph = print_graph
  243. comptime.print_disas = print_disas
  244. comptime.print_value_stack = print_value_stack
  245. comptime.print_value_stack_and_return = print_value_stack_and_return
  246. comptime.print_locals = print_locals
  247. comptime.print_bt = print_bt
  248. comptime.print_guards = print_guards