applied-ai-018 commited on
Commit
6e3288a
·
verified ·
1 Parent(s): 5cc41a3

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. llmeval-env/lib/python3.10/site-packages/torch/_dynamo/_trace_wrapped_higher_order_op.py +120 -0
  2. llmeval-env/lib/python3.10/site-packages/torch/_dynamo/bytecode_transformation.py +1114 -0
  3. llmeval-env/lib/python3.10/site-packages/torch/_dynamo/cache_size.py +172 -0
  4. llmeval-env/lib/python3.10/site-packages/torch/_dynamo/code_context.py +29 -0
  5. llmeval-env/lib/python3.10/site-packages/torch/_dynamo/codegen.py +398 -0
  6. llmeval-env/lib/python3.10/site-packages/torch/_dynamo/compiled_autograd.py +280 -0
  7. llmeval-env/lib/python3.10/site-packages/torch/_dynamo/comptime.py +373 -0
  8. llmeval-env/lib/python3.10/site-packages/torch/_dynamo/config.py +423 -0
  9. llmeval-env/lib/python3.10/site-packages/torch/_dynamo/convert_frame.py +924 -0
  10. llmeval-env/lib/python3.10/site-packages/torch/_dynamo/current_scope_id.py +23 -0
  11. llmeval-env/lib/python3.10/site-packages/torch/_dynamo/device_interface.py +199 -0
  12. llmeval-env/lib/python3.10/site-packages/torch/_dynamo/exc.py +335 -0
  13. llmeval-env/lib/python3.10/site-packages/torch/_dynamo/external_utils.py +103 -0
  14. llmeval-env/lib/python3.10/site-packages/torch/_dynamo/funcname_cache.py +57 -0
  15. llmeval-env/lib/python3.10/site-packages/torch/_dynamo/guards.py +1505 -0
  16. llmeval-env/lib/python3.10/site-packages/torch/_dynamo/logging.py +57 -0
  17. llmeval-env/lib/python3.10/site-packages/torch/_dynamo/output_graph.py +2063 -0
  18. llmeval-env/lib/python3.10/site-packages/torch/_dynamo/polyfill.py +47 -0
  19. llmeval-env/lib/python3.10/site-packages/torch/_dynamo/profiler.py +155 -0
  20. llmeval-env/lib/python3.10/site-packages/torch/_dynamo/resume_execution.py +648 -0
  21. llmeval-env/lib/python3.10/site-packages/torch/_dynamo/side_effects.py +542 -0
  22. llmeval-env/lib/python3.10/site-packages/torch/_dynamo/symbolic_convert.py +2603 -0
  23. llmeval-env/lib/python3.10/site-packages/torch/_dynamo/tensor_version_op.py +57 -0
  24. llmeval-env/lib/python3.10/site-packages/torch/_dynamo/test_minifier_common.py +244 -0
  25. llmeval-env/lib/python3.10/site-packages/torch/_dynamo/testing.py +378 -0
  26. llmeval-env/lib/python3.10/site-packages/torch/_dynamo/trace_rules.py +0 -0
  27. llmeval-env/lib/python3.10/site-packages/torch/_dynamo/utils.py +2548 -0
  28. llmeval-env/lib/python3.10/site-packages/torch/utils/__pycache__/__init__.cpython-310.pyc +0 -0
  29. llmeval-env/lib/python3.10/site-packages/torch/utils/__pycache__/_config_module.cpython-310.pyc +0 -0
  30. llmeval-env/lib/python3.10/site-packages/torch/utils/__pycache__/_contextlib.cpython-310.pyc +0 -0
  31. llmeval-env/lib/python3.10/site-packages/torch/utils/__pycache__/_cxx_pytree.cpython-310.pyc +0 -0
  32. llmeval-env/lib/python3.10/site-packages/torch/utils/__pycache__/_freeze.cpython-310.pyc +0 -0
  33. llmeval-env/lib/python3.10/site-packages/torch/utils/__pycache__/_import_utils.cpython-310.pyc +0 -0
  34. llmeval-env/lib/python3.10/site-packages/torch/utils/__pycache__/_stats.cpython-310.pyc +0 -0
  35. llmeval-env/lib/python3.10/site-packages/torch/utils/__pycache__/_traceback.cpython-310.pyc +0 -0
  36. llmeval-env/lib/python3.10/site-packages/torch/utils/__pycache__/_triton.cpython-310.pyc +0 -0
  37. llmeval-env/lib/python3.10/site-packages/torch/utils/__pycache__/_typing_utils.cpython-310.pyc +0 -0
  38. llmeval-env/lib/python3.10/site-packages/torch/utils/__pycache__/bundled_inputs.cpython-310.pyc +0 -0
  39. llmeval-env/lib/python3.10/site-packages/torch/utils/__pycache__/collect_env.cpython-310.pyc +0 -0
  40. llmeval-env/lib/python3.10/site-packages/torch/utils/__pycache__/cpp_backtrace.cpython-310.pyc +0 -0
  41. llmeval-env/lib/python3.10/site-packages/torch/utils/__pycache__/cpp_extension.cpython-310.pyc +0 -0
  42. llmeval-env/lib/python3.10/site-packages/torch/utils/__pycache__/dlpack.cpython-310.pyc +0 -0
  43. llmeval-env/lib/python3.10/site-packages/torch/utils/__pycache__/weak.cpython-310.pyc +0 -0
  44. llmeval-env/lib/python3.10/site-packages/torch/utils/_sympy/__init__.py +0 -0
  45. llmeval-env/lib/python3.10/site-packages/torch/utils/_sympy/__pycache__/__init__.cpython-310.pyc +0 -0
  46. llmeval-env/lib/python3.10/site-packages/torch/utils/_sympy/__pycache__/functions.cpython-310.pyc +0 -0
  47. llmeval-env/lib/python3.10/site-packages/torch/utils/_sympy/__pycache__/interp.cpython-310.pyc +0 -0
  48. llmeval-env/lib/python3.10/site-packages/torch/utils/_sympy/__pycache__/reference.cpython-310.pyc +0 -0
  49. llmeval-env/lib/python3.10/site-packages/torch/utils/_sympy/__pycache__/singleton_int.cpython-310.pyc +0 -0
  50. llmeval-env/lib/python3.10/site-packages/torch/utils/_sympy/__pycache__/solve.cpython-310.pyc +0 -0
llmeval-env/lib/python3.10/site-packages/torch/_dynamo/_trace_wrapped_higher_order_op.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch._C import DispatchKey
3
+ from torch._higher_order_ops.utils import autograd_not_implemented
4
+
5
+ from torch._ops import HigherOrderOperator
6
+ from torch._subclasses import FakeTensorMode
7
+ from torch.fx.experimental._backward_state import BackwardState
8
+
9
+ from torch.fx.experimental.proxy_tensor import ProxyTorchDispatchMode, track_tensor_tree
10
+ from torch.utils._python_dispatch import _get_current_dispatch_mode
11
+ from torch.utils._pytree import tree_map_only
12
+
13
+
14
+ __all__ = ["trace_wrapped"]
15
+
16
+
17
+ # trace_wrapped(*args, fn) is equivalent to fn(*args), but with a twist:
18
+ # if you make_fx trace through this call, we will not actually trace into fn; instead,
19
+ # we will directly insert it as a call_function to fn in the graph.
20
+ # (Unlike make_fx, Dynamo WILL inline into fn.)
21
+ # You can think of this as a one off allow_in_graph equivalent for proxy tensor tracing.
22
+ #
23
+ # Because proxy tensor tracing does not actually run the function, there are
24
+ # requirements on the behavior of fn. We are still figuring it out, but here is the current state:
25
+ #
26
+ # 1) fn SHOULD only take a single argument, which must be a tensor
27
+ # 2) fn MUST return a new tensor with the same metadata as the original tensor
28
+ # (e.g., zeros_like(input) is a permissible implementation of fn).
29
+ # This is verified via an extra assert that is inserted into the traced graph.
30
+ # 3) fn MAY have side effects, but it MAY NOT perform metadata mutation on other tensors
31
+ # participating in proxy tensor tracing (it MAY mutate other tensors, it MAY mutate Python state)
32
+ # These requirements stem from the requirement that we need to continue performing proxy tensor tracing,
33
+ # which assumes accurate fake tensor metadata, without actually running fn.
34
+ # In the future, we may allow for a "meta" function associated with fn to allow for more interesting input-output patterns.
35
+ #
36
+ # Note that tensors / Python state are allowed to be mutated.
37
+ # This is relaxed constraint is not always sound, but it is sound for backward tracing with fake
38
+ # tensors as it takes place in AOTAutograd, as the backward pass is guaranteed not to depend on concrete
39
+ # tensor values (via fake tensor) or Python state (because the autograd engine doesn't depend on Python).
40
+ #
41
+ # The intended use case for this function is to allow AOTAutograd to defer complex
42
+ # backward hooks to compiled autograd. AOTAutograd performs a make_fx trace which preserves
43
+ # the function call as is in the graph, and only when we Dynamo through the backward graph in
44
+ # compiled autograd do we inline into the function.
45
+
46
+
47
+ def trace_wrapped(*args, **kwargs):
48
+ with torch.no_grad():
49
+ return _trace_wrapped_op(*args, **kwargs)
50
+
51
+
52
+ # TODO(jansel): need to ensure this does not get DCEed
53
+ _trace_wrapped_op = HigherOrderOperator("trace_wrapped")
54
+
55
+
56
+ def _assert_meta(grad, size, stride, dtype):
57
+ assert grad.size() == size, "size mismatch"
58
+ assert grad.stride() == stride, "stride mismatch"
59
+ assert grad.dtype == dtype, "dtype mismatch"
60
+ return grad
61
+
62
+
63
+ @_trace_wrapped_op.py_impl(ProxyTorchDispatchMode)
64
+ def inner_trace(mode, *args, bw_state=None, **kwargs):
65
+ def self_invoke(*args, **dyn_kwargs):
66
+ with torch.no_grad():
67
+ return _trace_wrapped_op(*args, **dyn_kwargs, **kwargs)
68
+
69
+ def unwrap_proxies(x):
70
+ if isinstance(x, torch.Tensor):
71
+ return mode.tracer.unwrap_proxy(x)
72
+ if isinstance(x, (list, tuple)):
73
+ return type(x)(map(unwrap_proxies, x))
74
+ if x is None:
75
+ return None
76
+ raise AssertionError(f"unhandled type: {type(x)}")
77
+
78
+ proxy_kwargs = {}
79
+ if bw_state is not None:
80
+ assert isinstance(bw_state, BackwardState) and bw_state.proxy is not None
81
+ proxy_kwargs["bw_state"] = bw_state.proxy
82
+ out_proxy = mode.tracer.create_proxy(
83
+ "call_function",
84
+ self_invoke,
85
+ unwrap_proxies(args),
86
+ proxy_kwargs,
87
+ name="trace_wrapped",
88
+ )
89
+
90
+ if args[0] is None:
91
+ grad = args[1] # module backward hooks
92
+ else:
93
+ grad = args[0] # other backward hooks
94
+ grad = tree_map_only(torch.Tensor, torch.empty_like, grad)
95
+ track_tensor_tree(grad, out_proxy, constant=None, tracer=mode.tracer)
96
+ return grad
97
+
98
+
99
+ @_trace_wrapped_op.py_impl(FakeTensorMode)
100
+ def inner_fake(*args, **kwargs):
101
+ raise RuntimeError("This op should never be invoked here")
102
+
103
+
104
+ @_trace_wrapped_op.py_impl(DispatchKey.CompositeExplicitAutograd)
105
+ def _trace_wrapped_op_dense(*args, fn, **kwargs):
106
+ mode = _get_current_dispatch_mode()
107
+ assert mode is None, "Mode should never be enabled for CPU/CUDA key"
108
+ return fn(*args, **kwargs)
109
+
110
+
111
+ _trace_wrapped_op.py_impl(DispatchKey.Autograd)(
112
+ autograd_not_implemented(_trace_wrapped_op, deferred_error=True)
113
+ )
114
+
115
+
116
+ @_trace_wrapped_op.py_functionalize_impl
117
+ def _trace_wrapped_functionalized(ctx, *args, **kwargs):
118
+ unwrapped_args = ctx.unwrap_tensors(args)
119
+ with ctx.redispatch_to_next():
120
+ return ctx.wrap_tensors(_trace_wrapped_op(*unwrapped_args, **kwargs))
llmeval-env/lib/python3.10/site-packages/torch/_dynamo/bytecode_transformation.py ADDED
@@ -0,0 +1,1114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ import dataclasses
3
+ import dis
4
+ import itertools
5
+ import sys
6
+ import types
7
+ from typing import Any, Callable, cast, Dict, Iterator, List, Optional, Tuple
8
+
9
+ from .bytecode_analysis import (
10
+ get_indexof,
11
+ propagate_line_nums,
12
+ remove_extra_line_nums,
13
+ stacksize_analysis,
14
+ )
15
+
16
+
17
+ @dataclasses.dataclass
18
+ class InstructionExnTabEntry:
19
+ start: "Instruction"
20
+ end: "Instruction"
21
+ target: "Instruction"
22
+ depth: int
23
+ lasti: bool
24
+
25
+ def __repr__(self) -> str:
26
+ return (
27
+ f"InstructionExnTabEntry(start={self.start.short_inst_repr()}, "
28
+ f"end={self.end.short_inst_repr()}, "
29
+ f"target={self.target.short_inst_repr()}, "
30
+ f"depth={self.depth}, lasti={self.lasti})"
31
+ )
32
+
33
+ def __eq__(self, o) -> bool:
34
+ return (
35
+ self.start is o.start
36
+ and self.end is o.end
37
+ and self.target is o.target
38
+ and self.depth == o.depth
39
+ and self.lasti == o.lasti
40
+ )
41
+
42
+
43
+ @dataclasses.dataclass
44
+ class Instruction:
45
+ """A mutable version of dis.Instruction"""
46
+
47
+ opcode: int
48
+ opname: str
49
+ arg: Optional[int]
50
+ argval: Any
51
+ offset: Optional[int] = None
52
+ starts_line: Optional[int] = None
53
+ is_jump_target: bool = False
54
+ positions: Optional["dis.Positions"] = None
55
+ # extra fields to make modification easier:
56
+ target: Optional["Instruction"] = None
57
+ exn_tab_entry: Optional[InstructionExnTabEntry] = None
58
+
59
+ def __hash__(self) -> int:
60
+ return id(self)
61
+
62
+ def __eq__(self, other) -> bool:
63
+ return id(self) == id(other)
64
+
65
+ def short_inst_repr(self) -> str:
66
+ return f"Instruction(opname={self.opname}, offset={self.offset})"
67
+
68
+
69
+ def convert_instruction(i: dis.Instruction) -> Instruction:
70
+ return Instruction(
71
+ i.opcode,
72
+ i.opname,
73
+ i.arg,
74
+ i.argval,
75
+ i.offset,
76
+ i.starts_line,
77
+ i.is_jump_target,
78
+ getattr(i, "positions", None),
79
+ )
80
+
81
+
82
+ class _NotProvided:
83
+ def __repr__(self) -> str:
84
+ return "_NotProvided"
85
+
86
+
87
+ def create_instruction(
88
+ name, *, arg=None, argval=_NotProvided, target=None
89
+ ) -> Instruction:
90
+ """
91
+ At most one of `arg`, `argval`, and `target` can be not None/_NotProvided.
92
+ This is to prevent ambiguity, e.g. does
93
+ create_instruction("LOAD_CONST", 5)
94
+ mean load the constant at co_consts[5], or load the constant 5?
95
+
96
+ If `arg` is not provided, it will be computed during assembly from
97
+ `argval` or `target`.
98
+
99
+ Do not use for LOAD_GLOBAL - use create_load_global instead.
100
+ """
101
+ assert name != "LOAD_GLOBAL"
102
+ cnt = (arg is not None) + (argval is not _NotProvided) + (target is not None)
103
+ if cnt > 1:
104
+ raise RuntimeError(
105
+ "only one of arg, argval, and target can be not None/_NotProvided"
106
+ )
107
+ if arg is not None and not isinstance(arg, int):
108
+ raise RuntimeError("instruction arg must be int or None")
109
+ return Instruction(
110
+ opcode=dis.opmap[name], opname=name, arg=arg, argval=argval, target=target
111
+ )
112
+
113
+
114
+ # Python 3.11 remaps
115
+ def create_jump_absolute(target) -> Instruction:
116
+ inst = "JUMP_FORWARD" if sys.version_info >= (3, 11) else "JUMP_ABSOLUTE"
117
+ return create_instruction(inst, target=target)
118
+
119
+
120
+ def create_load_global(name, push_null) -> Instruction:
121
+ """
122
+ `name` is the name of the global to be loaded.
123
+ `push_null` specifies whether or not a NULL should be pushed to the stack
124
+ before the global (Python 3.11+ only).
125
+
126
+ Python 3.11 changed the LOAD_GLOBAL instruction in that the first bit of
127
+ the instruction arg specifies whether a NULL should be pushed to the stack
128
+ before the global. The remaining bits of the instruction arg contain the
129
+ name index. See `create_call_function` for why this NULL is needed.
130
+
131
+ The instruction's `arg` is actually computed when assembling the bytecode.
132
+ For Python 3.11, push_null information is propagated through the arg.
133
+
134
+ NOTE: we don't use create_instruction since LOAD_GLOBAL is the only instruction
135
+ where both arg and argval need to be specified.
136
+ """
137
+ return Instruction(
138
+ opcode=dis.opmap["LOAD_GLOBAL"],
139
+ opname="LOAD_GLOBAL",
140
+ arg=push_null,
141
+ argval=name,
142
+ )
143
+
144
+
145
+ def create_dup_top() -> Instruction:
146
+ if sys.version_info >= (3, 11):
147
+ return create_instruction("COPY", arg=1)
148
+ return create_instruction("DUP_TOP")
149
+
150
+
151
+ def create_rot_n(n) -> List[Instruction]:
152
+ """
153
+ Returns a "simple" sequence of instructions that rotates TOS to the n-th
154
+ position in the stack. For Python < 3.11, returns a single ROT_*
155
+ instruction. If no such instruction exists, an error is raised and the
156
+ caller is expected to generate an equivalent sequence of instructions.
157
+ For Python >= 3.11, any rotation can be expressed as a simple sequence of
158
+ swaps.
159
+ """
160
+ if n <= 1:
161
+ # don't rotate
162
+ return []
163
+
164
+ if sys.version_info >= (3, 11):
165
+ # rotate can be expressed as a sequence of swap operations
166
+ # e.g. rotate 3 is equivalent to swap 3, swap 2
167
+ return [create_instruction("SWAP", arg=i) for i in range(n, 1, -1)]
168
+
169
+ # ensure desired rotate function exists
170
+ if sys.version_info < (3, 8) and n >= 4:
171
+ raise AttributeError(f"rotate {n} not supported for Python < 3.8")
172
+ if sys.version_info < (3, 10) and n >= 5:
173
+ raise AttributeError(f"rotate {n} not supported for Python < 3.10")
174
+
175
+ if n <= 4:
176
+ return [create_instruction("ROT_" + ["TWO", "THREE", "FOUR"][n - 2])]
177
+ return [create_instruction("ROT_N", arg=n)]
178
+
179
+
180
+ def create_call_function(nargs, push_null) -> List[Instruction]:
181
+ """
182
+ Creates a sequence of instructions that makes a function call.
183
+
184
+ `push_null` is used in Python 3.11+ only. It is used in codegen when
185
+ a function call is intended to be made with the NULL + fn convention,
186
+ and we know that the NULL has not been pushed yet. We will push a
187
+ NULL and rotate it to the correct position immediately before making
188
+ the function call.
189
+ push_null should default to True unless you know you are calling a function
190
+ that you codegen'd with a null already pushed, for example
191
+ (assume `math` is available in the global scope),
192
+
193
+ create_load_global("math", True) # pushes a null
194
+ create_instruction("LOAD_ATTR", argval="sqrt")
195
+ create_instruction("LOAD_CONST", argval=25)
196
+ create_call_function(1, False)
197
+ """
198
+ if sys.version_info >= (3, 11):
199
+ output = []
200
+ if push_null:
201
+ output.append(create_instruction("PUSH_NULL"))
202
+ output.extend(create_rot_n(nargs + 2))
203
+ output.append(create_instruction("PRECALL", arg=nargs))
204
+ output.append(create_instruction("CALL", arg=nargs))
205
+ return output
206
+ return [create_instruction("CALL_FUNCTION", arg=nargs)]
207
+
208
+
209
+ def create_call_method(nargs) -> List[Instruction]:
210
+ if sys.version_info >= (3, 11):
211
+ return [
212
+ create_instruction("PRECALL", arg=nargs),
213
+ create_instruction("CALL", arg=nargs),
214
+ ]
215
+ return [create_instruction("CALL_METHOD", arg=nargs)]
216
+
217
+
218
+ def lnotab_writer(
219
+ lineno: int, byteno: int = 0
220
+ ) -> Tuple[List[int], Callable[[int, int], None]]:
221
+ """
222
+ Used to create typing.CodeType.co_lnotab
223
+ See https://github.com/python/cpython/blob/main/Objects/lnotab_notes.txt
224
+ This is the internal format of the line number table if Python < 3.10
225
+ """
226
+ assert sys.version_info < (3, 10)
227
+ lnotab: List[int] = []
228
+
229
+ def update(lineno_new, byteno_new):
230
+ nonlocal byteno, lineno
231
+ while byteno_new != byteno or lineno_new != lineno:
232
+ byte_offset = max(0, min(byteno_new - byteno, 255))
233
+ line_offset = max(-128, min(lineno_new - lineno, 127))
234
+ assert byte_offset != 0 or line_offset != 0
235
+ byteno += byte_offset
236
+ lineno += line_offset
237
+ lnotab.extend((byte_offset, line_offset & 0xFF))
238
+
239
+ return lnotab, update
240
+
241
+
242
+ def linetable_310_writer(first_lineno):
243
+ """
244
+ Used to create typing.CodeType.co_linetable
245
+ See https://github.com/python/cpython/blob/main/Objects/lnotab_notes.txt
246
+ This is the internal format of the line number table for Python 3.10
247
+ """
248
+ assert sys.version_info >= (3, 10) and sys.version_info < (3, 11)
249
+ linetable: List[int] = []
250
+ lineno = first_lineno
251
+ lineno_delta = 0
252
+ byteno = 0
253
+
254
+ def _update(byteno_delta, lineno_delta):
255
+ while byteno_delta != 0 or lineno_delta != 0:
256
+ byte_offset = max(0, min(byteno_delta, 254))
257
+ line_offset = max(-127, min(lineno_delta, 127))
258
+ assert byte_offset != 0 or line_offset != 0
259
+ byteno_delta -= byte_offset
260
+ lineno_delta -= line_offset
261
+ linetable.extend((byte_offset, line_offset & 0xFF))
262
+
263
+ def update(lineno_new, byteno_new):
264
+ nonlocal lineno, lineno_delta, byteno
265
+ byteno_delta = byteno_new - byteno
266
+ byteno = byteno_new
267
+ _update(byteno_delta, lineno_delta)
268
+ lineno_delta = lineno_new - lineno
269
+ lineno = lineno_new
270
+
271
+ def end(total_bytes):
272
+ _update(total_bytes - byteno, lineno_delta)
273
+
274
+ return linetable, update, end
275
+
276
+
277
+ def encode_varint(n: int) -> List[int]:
278
+ """
279
+ 6-bit chunk encoding of an unsigned integer
280
+ See https://github.com/python/cpython/blob/3.11/Objects/locations.md
281
+ """
282
+ assert n >= 0
283
+ b = [n & 63]
284
+ n >>= 6
285
+ while n > 0:
286
+ b[-1] |= 64
287
+ b.append(n & 63)
288
+ n >>= 6
289
+ return b
290
+
291
+
292
+ def linetable_311_writer(first_lineno: int):
293
+ """
294
+ Used to create typing.CodeType.co_linetable
295
+ See https://github.com/python/cpython/blob/3.11/Objects/locations.md
296
+ This is the internal format of the line number table for Python 3.11
297
+ """
298
+ assert sys.version_info >= (3, 11)
299
+ linetable = []
300
+ lineno = first_lineno
301
+
302
+ def update(positions: "dis.Positions", inst_size):
303
+ nonlocal lineno
304
+ lineno_new = positions.lineno if positions else None
305
+
306
+ def _update(delta, size):
307
+ assert 0 < size <= 8
308
+ # first byte - use 13 (no column info) is positions is
309
+ # malformed, otherwise use 14 (long form)
310
+ other_varints: Tuple[int, ...] = ()
311
+ if (
312
+ positions
313
+ and positions.lineno is not None
314
+ and positions.end_lineno is not None
315
+ and positions.col_offset is not None
316
+ and positions.end_col_offset is not None
317
+ ):
318
+ linetable.append(0b1_1110_000 + size - 1)
319
+ # for whatever reason, column offset needs `+ 1`
320
+ # https://github.com/python/cpython/blob/1931c2a438c50e6250725c84dff94fc760b9b951/Python/compile.c#L7603
321
+ other_varints = (
322
+ positions.end_lineno - positions.lineno,
323
+ positions.col_offset + 1,
324
+ positions.end_col_offset + 1,
325
+ )
326
+ else:
327
+ linetable.append(0b1_1101_000 + size - 1)
328
+ # encode signed int
329
+ if delta < 0:
330
+ delta = ((-delta) << 1) | 1
331
+ else:
332
+ delta <<= 1
333
+ # encode unsigned int
334
+ linetable.extend(encode_varint(delta))
335
+ for n in other_varints:
336
+ linetable.extend(encode_varint(n))
337
+
338
+ if lineno_new is None:
339
+ lineno_delta = 0
340
+ else:
341
+ lineno_delta = lineno_new - lineno
342
+ lineno = lineno_new
343
+ while inst_size > 8:
344
+ _update(lineno_delta, 8)
345
+ inst_size -= 8
346
+ _update(lineno_delta, inst_size)
347
+
348
+ return linetable, update
349
+
350
+
351
+ @dataclasses.dataclass
352
+ class ExceptionTableEntry:
353
+ start: int
354
+ end: int
355
+ target: int
356
+ depth: int
357
+ lasti: bool
358
+
359
+
360
+ def encode_exception_table_varint(n: int) -> List[int]:
361
+ """
362
+ Similar to `encode_varint`, but the 6-bit chunks are ordered in reverse.
363
+ """
364
+ assert n >= 0
365
+ b = [n & 63]
366
+ n >>= 6
367
+ while n > 0:
368
+ b.append(n & 63)
369
+ n >>= 6
370
+ b.reverse()
371
+ for i in range(len(b) - 1):
372
+ b[i] |= 64
373
+ return b
374
+
375
+
376
+ def decode_exception_table_varint(bytes_iter: Iterator[int]) -> int:
377
+ """
378
+ Inverse of `encode_exception_table_varint`.
379
+ """
380
+ b = next(bytes_iter)
381
+ val = b & 63
382
+ while b & 64:
383
+ val <<= 6
384
+ b = next(bytes_iter)
385
+ val |= b & 63
386
+ return val
387
+
388
+
389
+ def check_exception_table(tab: List[ExceptionTableEntry]) -> None:
390
+ """
391
+ Verifies that a list of ExceptionTableEntries will make a well-formed
392
+ jump table: entries are non-empty, sorted, and do not overlap.
393
+ """
394
+ for i in range(len(tab) - 1):
395
+ assert (
396
+ tab[i].start <= tab[i].end
397
+ and tab[i].end < tab[i + 1].start
398
+ and tab[i + 1].start <= tab[i + 1].end
399
+ )
400
+
401
+
402
+ def parse_exception_table(exntab: bytes) -> List[ExceptionTableEntry]:
403
+ """
404
+ Parse the exception table according to
405
+ https://github.com/python/cpython/blob/3.11/Objects/exception_handling_notes.txt
406
+ """
407
+ exntab_iter = iter(exntab)
408
+ tab = []
409
+ try:
410
+ while True:
411
+ start = decode_exception_table_varint(exntab_iter) * 2
412
+ length = decode_exception_table_varint(exntab_iter) * 2
413
+ end = start + length - 2
414
+ target = decode_exception_table_varint(exntab_iter) * 2
415
+ dl = decode_exception_table_varint(exntab_iter)
416
+ depth = dl >> 1
417
+ lasti = bool(dl & 1)
418
+ tab.append(ExceptionTableEntry(start, end, target, depth, lasti))
419
+ except StopIteration:
420
+ check_exception_table(tab)
421
+ return tab
422
+
423
+
424
+ def assemble_exception_table(tab: List[ExceptionTableEntry]) -> bytes:
425
+ """
426
+ Inverse of parse_exception_table - encodes list of exception
427
+ table entries into bytes.
428
+ """
429
+ b = []
430
+ for entry in tab:
431
+ first_entry = encode_exception_table_varint(entry.start // 2)
432
+ first_entry[0] |= 1 << 7
433
+ b.extend(first_entry)
434
+ length = entry.end - entry.start + 2
435
+ b.extend(encode_exception_table_varint(length // 2))
436
+ b.extend(encode_exception_table_varint(entry.target // 2))
437
+ dl = (entry.depth << 1) + entry.lasti
438
+ b.extend(encode_exception_table_varint(dl))
439
+ return bytes(b)
440
+
441
+
442
+ def assemble(instructions: List[Instruction], firstlineno: int) -> Tuple[bytes, bytes]:
443
+ """Do the opposite of dis.get_instructions()"""
444
+ code: List[int] = []
445
+ if sys.version_info >= (3, 11):
446
+ lnotab, update_lineno = linetable_311_writer(firstlineno)
447
+ num_ext = 0
448
+ for i, inst in enumerate(instructions):
449
+ if inst.opname == "EXTENDED_ARG":
450
+ inst_size = 1
451
+ num_ext += 1
452
+ # copy positions from the actual instruction
453
+ for j in (1, 2, 3):
454
+ if instructions[i + j].opname != "EXTENDED_ARG":
455
+ inst.positions = instructions[i + j].positions
456
+ break
457
+ else:
458
+ inst_size = instruction_size(inst) // 2 + num_ext
459
+ num_ext = 0
460
+ update_lineno(inst.positions, inst_size)
461
+ num_ext = 0
462
+ arg = inst.arg or 0
463
+ code.extend((inst.opcode, arg & 0xFF))
464
+ for _ in range(instruction_size(inst) // 2 - 1):
465
+ code.extend((0, 0))
466
+ else:
467
+ if sys.version_info < (3, 10):
468
+ lnotab, update_lineno = lnotab_writer(firstlineno)
469
+ else:
470
+ lnotab, update_lineno, end = linetable_310_writer(firstlineno)
471
+
472
+ for inst in instructions:
473
+ if inst.starts_line is not None:
474
+ update_lineno(inst.starts_line, len(code))
475
+ arg = inst.arg or 0
476
+ code.extend((inst.opcode, arg & 0xFF))
477
+
478
+ if sys.version_info >= (3, 10):
479
+ end(len(code))
480
+
481
+ return bytes(code), bytes(lnotab)
482
+
483
+
484
+ def _get_instruction_by_offset(offset_to_inst: Dict[int, Instruction], offset: int):
485
+ """
486
+ Get the instruction located at a given offset, accounting for EXTENDED_ARGs
487
+ """
488
+ for n in (0, 2, 4, 6):
489
+ if offset_to_inst[offset + n].opcode != dis.EXTENDED_ARG:
490
+ return offset_to_inst[offset + n]
491
+ return None
492
+
493
+
494
+ def virtualize_jumps(instructions) -> None:
495
+ """Replace jump targets with pointers to make editing easier"""
496
+ jump_targets = {inst.offset: inst for inst in instructions}
497
+
498
+ for inst in instructions:
499
+ if inst.opcode in dis.hasjabs or inst.opcode in dis.hasjrel:
500
+ inst.target = _get_instruction_by_offset(jump_targets, inst.argval)
501
+
502
+
503
+ _REL_JUMPS = set(dis.hasjrel)
504
+
505
+
506
+ def flip_jump_direction(instruction: Instruction) -> None:
507
+ if sys.version_info < (3, 11):
508
+ raise RuntimeError("Cannot flip jump direction in Python < 3.11")
509
+ if "FORWARD" in instruction.opname:
510
+ instruction.opname = instruction.opname.replace("FORWARD", "BACKWARD")
511
+ elif "BACKWARD" in instruction.opname:
512
+ instruction.opname = instruction.opname.replace("BACKWARD", "FORWARD")
513
+ else:
514
+ raise AttributeError("Instruction is not a forward or backward jump")
515
+ instruction.opcode = dis.opmap[instruction.opname]
516
+ assert instruction.opcode in _REL_JUMPS
517
+
518
+
519
+ def _get_instruction_front(instructions: List[Instruction], idx: int):
520
+ """
521
+ i.e. get the first EXTENDED_ARG instruction (if any) when targeting
522
+ instructions[idx] with a jump.
523
+ """
524
+ target = instructions[idx]
525
+ for offset in (1, 2, 3):
526
+ if idx >= offset and instructions[idx - offset].opcode == dis.EXTENDED_ARG:
527
+ target = instructions[idx - offset]
528
+ else:
529
+ break
530
+ return target
531
+
532
+
533
+ def devirtualize_jumps(instructions):
534
+ """Fill in args for virtualized jump target after instructions may have moved"""
535
+ indexof = get_indexof(instructions)
536
+ jumps = set(dis.hasjabs).union(set(dis.hasjrel))
537
+
538
+ for inst in instructions:
539
+ if inst.opcode in jumps:
540
+ target = _get_instruction_front(instructions, indexof[inst.target])
541
+ if inst.opcode in dis.hasjabs:
542
+ if sys.version_info < (3, 10):
543
+ inst.arg = target.offset
544
+ elif sys.version_info < (3, 11):
545
+ # `arg` is expected to be bytecode offset, whereas `offset` is byte offset.
546
+ # Divide since bytecode is 2 bytes large.
547
+ inst.arg = int(target.offset / 2)
548
+ else:
549
+ raise RuntimeError("Python 3.11+ should not have absolute jumps")
550
+ else: # relative jump
551
+ # byte offset between target and next instruction
552
+ inst.arg = int(target.offset - inst.offset - instruction_size(inst))
553
+ if inst.arg < 0:
554
+ if sys.version_info < (3, 11):
555
+ raise RuntimeError("Got negative jump offset for Python < 3.11")
556
+ inst.arg = -inst.arg
557
+ # forward jumps become backward
558
+ if "FORWARD" in inst.opname:
559
+ flip_jump_direction(inst)
560
+ elif inst.arg > 0:
561
+ # backward jumps become forward
562
+ if sys.version_info >= (3, 11) and "BACKWARD" in inst.opname:
563
+ flip_jump_direction(inst)
564
+ if sys.version_info >= (3, 10):
565
+ # see bytecode size comment in the absolute jump case above
566
+ inst.arg //= 2
567
+ inst.argval = target.offset
568
+ inst.argrepr = f"to {target.offset}"
569
+
570
+
571
+ def virtualize_exception_table(exn_tab_bytes: bytes, instructions: List[Instruction]):
572
+ """Replace exception table entries with pointers to make editing easier"""
573
+ exn_tab = parse_exception_table(exn_tab_bytes)
574
+ offset_to_inst = {cast(int, inst.offset): inst for inst in instructions}
575
+ offsets = sorted(offset_to_inst.keys())
576
+ end_offset_idx = 0
577
+ exn_tab_iter = iter(exn_tab)
578
+ try:
579
+
580
+ def step():
581
+ nonlocal end_offset_idx
582
+ entry = next(exn_tab_iter)
583
+ # find rightmost offset <= entry.end, since entry.end may not be
584
+ # an actual instruction, e.g. if the end instruction is LOAD_GLOBAL,
585
+ # which takes more than 2 bytes, then entry.end points to the end
586
+ # of the LOAD_GLOBAL instruction, not the beginning.
587
+ while (
588
+ end_offset_idx < len(offsets) and offsets[end_offset_idx] <= entry.end
589
+ ):
590
+ end_offset_idx += 1
591
+ assert end_offset_idx > 0
592
+ end_offset = offsets[end_offset_idx - 1]
593
+ inst_entry = InstructionExnTabEntry(
594
+ _get_instruction_by_offset(offset_to_inst, entry.start),
595
+ _get_instruction_by_offset(offset_to_inst, end_offset),
596
+ _get_instruction_by_offset(offset_to_inst, entry.target),
597
+ entry.depth,
598
+ entry.lasti,
599
+ )
600
+ return entry, inst_entry
601
+
602
+ entry, inst_entry = step()
603
+ for inst in instructions:
604
+ while inst.offset > entry.end:
605
+ entry, inst_entry = step()
606
+ if inst.offset >= entry.start:
607
+ inst.exn_tab_entry = copy.copy(inst_entry)
608
+ except StopIteration:
609
+ pass
610
+
611
+
612
+ def compute_exception_table(
613
+ instructions: List[Instruction],
614
+ ) -> List[ExceptionTableEntry]:
615
+ """Compute exception table in list format from instructions with exn_tab_entries"""
616
+ exn_dict: Dict[Tuple[int, int], Tuple[int, int, bool]] = {}
617
+ indexof = get_indexof(instructions)
618
+
619
+ for inst in instructions:
620
+ if inst.exn_tab_entry:
621
+ # account for prefixed EXTENDED_ARGS
622
+ start = _get_instruction_front(
623
+ instructions, indexof[inst.exn_tab_entry.start]
624
+ ).offset
625
+ # point to the last 2 bytes of the end instruction
626
+ end = (
627
+ cast(int, inst.exn_tab_entry.end.offset)
628
+ + instruction_size(inst.exn_tab_entry.end)
629
+ - 2
630
+ )
631
+ target = _get_instruction_front(
632
+ instructions, indexof[inst.exn_tab_entry.target]
633
+ ).offset
634
+ key = (start, end)
635
+ val = (target, inst.exn_tab_entry.depth, inst.exn_tab_entry.lasti)
636
+ if key in exn_dict:
637
+ assert exn_dict[key] == val
638
+ exn_dict[key] = val
639
+
640
+ # Dynamo may construct nested exception table entries for convenience,
641
+ # but Python expects exception table entries to not overlap.
642
+ # NOTE: below, "keys" refer to old instruction entries' starts and ends,
643
+ # and "entries" refer to the generated exception table entries.
644
+
645
+ # Sort keys by increasing start, then decreasing end
646
+ keys_sorted = sorted(exn_dict.keys(), key=lambda t: (t[0], -t[1]))
647
+ # smallest byte that the next exception table entry can start at
648
+ nexti = 0
649
+ # stack of current nested keys
650
+ key_stack: List[Tuple[int, int]] = []
651
+ exn_tab: List[ExceptionTableEntry] = []
652
+
653
+ def pop():
654
+ """
655
+ Pop the key_stack and append an exception table entry if possible.
656
+ """
657
+ nonlocal nexti
658
+ if key_stack:
659
+ key = key_stack.pop()
660
+ if nexti <= key[1]:
661
+ exn_tab.append(
662
+ ExceptionTableEntry(max(key[0], nexti), key[1], *exn_dict[key])
663
+ )
664
+ nexti = key[1] + 2
665
+
666
+ for key in keys_sorted:
667
+ # pop keys that are no longer nested over the current key
668
+ while key_stack and key_stack[-1][1] < key[0]:
669
+ pop()
670
+ if key_stack:
671
+ # create an entry covering to the current key, if possible
672
+ assert key_stack[-1][0] <= key[0] <= key[1] <= key_stack[-1][1]
673
+ left = max(nexti, key_stack[-1][0])
674
+ if left < key[0]:
675
+ exn_tab.append(
676
+ ExceptionTableEntry(left, key[0] - 2, *exn_dict[key_stack[-1]])
677
+ )
678
+ nexti = key[0]
679
+ key_stack.append(key)
680
+ while key_stack:
681
+ pop()
682
+ check_exception_table(exn_tab)
683
+ return exn_tab
684
+
685
+
686
+ def check_inst_exn_tab_entries_nested(
687
+ tab: List[InstructionExnTabEntry], indexof
688
+ ) -> None:
689
+ """
690
+ Checks `tab` is a properly sorted list of nested InstructionExnTabEntry's,
691
+ i.e. no entries partially overlap.
692
+ "Properly sorted" means entries are sorted by increasing starts, then
693
+ decreasing ends.
694
+ """
695
+ entry_stack: List[Tuple[int, int]] = []
696
+ for entry in tab:
697
+ key = (indexof[entry.start], indexof[entry.end])
698
+ while entry_stack and entry_stack[-1][1] < key[0]:
699
+ entry_stack.pop()
700
+ if entry_stack:
701
+ assert entry_stack[-1][0] <= key[0] <= key[1] <= entry_stack[-1][1]
702
+ entry_stack.append(key)
703
+
704
+
705
+ def propagate_inst_exn_table_entries(instructions: List[Instruction]) -> None:
706
+ """
707
+ Copies exception table entries to all instructions in an entry's range.
708
+ Supports nested exception table entries.
709
+ """
710
+ indexof = get_indexof(instructions)
711
+ entries: Dict[Tuple[int, int], InstructionExnTabEntry] = {}
712
+ for inst in instructions:
713
+ if inst.exn_tab_entry:
714
+ key = (
715
+ indexof[inst.exn_tab_entry.start],
716
+ indexof[inst.exn_tab_entry.end],
717
+ )
718
+ if key in entries:
719
+ assert inst.exn_tab_entry == entries[key]
720
+ entries[key] = inst.exn_tab_entry
721
+ sorted_entries = [
722
+ entries[key] for key in sorted(entries.keys(), key=lambda t: (t[0], -t[1]))
723
+ ]
724
+ check_inst_exn_tab_entries_nested(sorted_entries, indexof)
725
+ # Propagation of nested entries works since nested entries come later
726
+ # in sorted order.
727
+ for entry in sorted_entries:
728
+ for i in range(indexof[entry.start], indexof[entry.end] + 1):
729
+ instructions[i].exn_tab_entry = copy.copy(entry)
730
+
731
+
732
+ def check_inst_exn_tab_entries_valid(instructions: List[Instruction]):
733
+ """
734
+ Checks that exn_tab_entries of instructions are valid.
735
+ An entry's start, end, and target must be in instructions.
736
+ Instructions with an exn_tab_entry are located within
737
+ the entry's start and end instructions.
738
+ Instructions do not share exn_tab_entries.
739
+
740
+ Implicitly checks for no duplicate instructions.
741
+ """
742
+ indexof = get_indexof(instructions)
743
+ exn_tab_entry_set = set()
744
+ for i, inst in enumerate(instructions):
745
+ if inst.exn_tab_entry:
746
+ assert sys.version_info >= (3, 11)
747
+ assert id(inst.exn_tab_entry) not in exn_tab_entry_set
748
+ exn_tab_entry_set.add(id(inst.exn_tab_entry))
749
+ entry = inst.exn_tab_entry
750
+ assert entry.start in indexof
751
+ assert entry.end in indexof
752
+ assert entry.target in indexof
753
+ assert indexof[entry.start] <= i <= indexof[entry.end]
754
+
755
+
756
+ def strip_extended_args(instructions: List[Instruction]) -> None:
757
+ instructions[:] = [i for i in instructions if i.opcode != dis.EXTENDED_ARG]
758
+
759
+
760
+ def remove_load_call_method(instructions: List[Instruction]) -> List[Instruction]:
761
+ """LOAD_METHOD puts a NULL on the stack which causes issues, so remove it"""
762
+ rewrites = {"LOAD_METHOD": "LOAD_ATTR", "CALL_METHOD": "CALL_FUNCTION"}
763
+ for inst in instructions:
764
+ if inst.opname in rewrites:
765
+ inst.opname = rewrites[inst.opname]
766
+ inst.opcode = dis.opmap[inst.opname]
767
+ return instructions
768
+
769
+
770
+ def remove_jump_if_none(instructions: List[Instruction]) -> None:
771
+ new_insts = []
772
+ for inst in instructions:
773
+ new_insts.append(inst)
774
+ if "_NONE" in inst.opname:
775
+ is_op = create_instruction("IS_OP", arg=int("NOT" in inst.opname))
776
+ is_op.argval = is_op.arg
777
+ jump_op = create_instruction(
778
+ "POP_JUMP_FORWARD_IF_TRUE"
779
+ if "FORWARD" in inst.opname
780
+ else "POP_JUMP_BACKWARD_IF_TRUE",
781
+ target=inst.target,
782
+ )
783
+ # modify inst in-place to preserve jump target
784
+ inst.opcode = dis.opmap["LOAD_CONST"]
785
+ inst.opname = "LOAD_CONST"
786
+ inst.arg = None
787
+ inst.argval = None
788
+ new_insts.extend([is_op, jump_op])
789
+ instructions[:] = new_insts
790
+
791
+
792
+ def explicit_super(code: types.CodeType, instructions: List[Instruction]) -> None:
793
+ """convert super() with no args into explicit arg form"""
794
+ cell_and_free = (code.co_cellvars or tuple()) + (code.co_freevars or tuple())
795
+ if not len(code.co_varnames):
796
+ # A function with no argument cannot contain a valid "super()" call
797
+ return
798
+ output = []
799
+ for idx, inst in enumerate(instructions):
800
+ output.append(inst)
801
+ if inst.opname == "LOAD_GLOBAL" and inst.argval == "super":
802
+ nexti = instructions[idx + 1]
803
+ if nexti.opname in ("CALL_FUNCTION", "PRECALL") and nexti.arg == 0:
804
+ assert "__class__" in cell_and_free
805
+ output.append(create_instruction("LOAD_DEREF", argval="__class__"))
806
+ first_var = code.co_varnames[0]
807
+ if first_var in cell_and_free:
808
+ output.append(create_instruction("LOAD_DEREF", argval=first_var))
809
+ else:
810
+ output.append(create_instruction("LOAD_FAST", argval=first_var))
811
+ nexti.arg = 2
812
+ nexti.argval = 2
813
+ if nexti.opname == "PRECALL":
814
+ # also update the following CALL instruction
815
+ call_inst = instructions[idx + 2]
816
+ call_inst.arg = 2
817
+ call_inst.argval = 2
818
+
819
+ instructions[:] = output
820
+
821
+
822
+ def fix_extended_args(instructions: List[Instruction]) -> int:
823
+ """Fill in correct argvals for EXTENDED_ARG ops"""
824
+ output: List[Instruction] = []
825
+
826
+ def maybe_pop_n(n):
827
+ for _ in range(n):
828
+ if output and output[-1].opcode == dis.EXTENDED_ARG:
829
+ output.pop()
830
+
831
+ for inst in instructions:
832
+ if inst.opcode == dis.EXTENDED_ARG:
833
+ # Leave this instruction alone for now so we never shrink code
834
+ inst.arg = 0
835
+ elif inst.arg and inst.arg > 0xFFFFFF:
836
+ maybe_pop_n(3)
837
+ output.append(create_instruction("EXTENDED_ARG", arg=inst.arg >> 24))
838
+ output.append(create_instruction("EXTENDED_ARG", arg=inst.arg >> 16))
839
+ output.append(create_instruction("EXTENDED_ARG", arg=inst.arg >> 8))
840
+ elif inst.arg and inst.arg > 0xFFFF:
841
+ maybe_pop_n(2)
842
+ output.append(create_instruction("EXTENDED_ARG", arg=inst.arg >> 16))
843
+ output.append(create_instruction("EXTENDED_ARG", arg=inst.arg >> 8))
844
+ elif inst.arg and inst.arg > 0xFF:
845
+ maybe_pop_n(1)
846
+ output.append(create_instruction("EXTENDED_ARG", arg=inst.arg >> 8))
847
+ output.append(inst)
848
+
849
+ added = len(output) - len(instructions)
850
+ assert added >= 0
851
+ instructions[:] = output
852
+ return added
853
+
854
+
855
+ # from https://github.com/python/cpython/blob/v3.11.1/Include/internal/pycore_opcode.h#L41
856
+ # TODO use the actual object instead, can interface from eval_frame.c
857
+ _PYOPCODE_CACHES = {
858
+ "BINARY_SUBSCR": 4,
859
+ "STORE_SUBSCR": 1,
860
+ "UNPACK_SEQUENCE": 1,
861
+ "STORE_ATTR": 4,
862
+ "LOAD_ATTR": 4,
863
+ "COMPARE_OP": 2,
864
+ "LOAD_GLOBAL": 5,
865
+ "BINARY_OP": 1,
866
+ "LOAD_METHOD": 10,
867
+ "PRECALL": 1,
868
+ "CALL": 4,
869
+ }
870
+
871
+
872
+ def instruction_size(inst) -> int:
873
+ if sys.version_info >= (3, 11):
874
+ return 2 * (_PYOPCODE_CACHES.get(dis.opname[inst.opcode], 0) + 1)
875
+ return 2
876
+
877
+
878
+ def check_offsets(instructions) -> None:
879
+ offset = 0
880
+ for inst in instructions:
881
+ assert inst.offset == offset
882
+ offset += instruction_size(inst)
883
+
884
+
885
+ def update_offsets(instructions) -> None:
886
+ offset = 0
887
+ for inst in instructions:
888
+ inst.offset = offset
889
+ offset += instruction_size(inst)
890
+
891
+
892
+ def debug_bytes(*args) -> str:
893
+ index = range(max(map(len, args)))
894
+ result = []
895
+ for arg in (
896
+ [index] + list(args) + [[int(a != b) for a, b in zip(args[-1], args[-2])]]
897
+ ):
898
+ result.append(" ".join(f"{x:03}" for x in arg))
899
+
900
+ return "bytes mismatch\n" + "\n".join(result)
901
+
902
+
903
+ def debug_checks(code):
904
+ """Make sure our assembler produces same bytes as we start with"""
905
+ dode = transform_code_object(code, lambda x, y: None, safe=True)
906
+ assert code.co_code == dode.co_code, debug_bytes(code.co_code, dode.co_code)
907
+ assert code.co_lnotab == dode.co_lnotab, debug_bytes(code.co_lnotab, dode.co_lnotab)
908
+
909
+
910
+ HAS_LOCAL = set(dis.haslocal)
911
+ HAS_NAME = set(dis.hasname)
912
+ HAS_FREE = set(dis.hasfree)
913
+ HAS_CONST = set(dis.hasconst)
914
+
915
+
916
+ def get_const_index(code_options, val) -> int:
917
+ for i, v in enumerate(code_options["co_consts"]):
918
+ # NOTE: stronger comparison is required, since we have
919
+ # examples where two values compare equal but have
920
+ # different semantic meaning in some cases, e.g.
921
+ # 0.0 == -0.0 but have different effects in torch.copysign.
922
+ if val is v:
923
+ return i
924
+ code_options["co_consts"] += (val,)
925
+ return len(code_options["co_consts"]) - 1
926
+
927
+
928
+ def fix_vars(instructions: List[Instruction], code_options, varname_from_oparg=None):
929
+ # compute instruction arg from argval if arg is not provided
930
+ names = {name: idx for idx, name in enumerate(code_options["co_names"])}
931
+ if sys.version_info < (3, 11):
932
+ assert varname_from_oparg is None
933
+ varnames = {name: idx for idx, name in enumerate(code_options["co_varnames"])}
934
+ freenames = {
935
+ name: idx
936
+ for idx, name in enumerate(
937
+ code_options["co_cellvars"] + code_options["co_freevars"]
938
+ )
939
+ }
940
+ else:
941
+ assert callable(varname_from_oparg)
942
+ allnames = {}
943
+ for idx in itertools.count():
944
+ try:
945
+ name = varname_from_oparg(idx)
946
+ allnames[name] = idx
947
+ except IndexError:
948
+ break
949
+ varnames = {name: allnames[name] for name in code_options["co_varnames"]}
950
+ freenames = {
951
+ name: allnames[name]
952
+ for name in code_options["co_cellvars"] + code_options["co_freevars"]
953
+ }
954
+ for i in range(len(instructions)):
955
+
956
+ def should_compute_arg():
957
+ # argval is prioritized over arg
958
+ return instructions[i].argval is not _NotProvided
959
+
960
+ if instructions[i].opname == "LOAD_GLOBAL":
961
+ # 3.11 LOAD_GLOBAL requires both arg and argval - see create_load_global
962
+ assert instructions[i].arg is not None
963
+ assert instructions[i].argval is not _NotProvided
964
+ if sys.version_info >= (3, 11):
965
+ instructions[i].arg = (names[instructions[i].argval] << 1) + (
966
+ cast(int, instructions[i].arg) % 2
967
+ )
968
+ else:
969
+ instructions[i].arg = names[instructions[i].argval]
970
+ elif instructions[i].opcode in HAS_LOCAL:
971
+ if should_compute_arg():
972
+ instructions[i].arg = varnames[instructions[i].argval]
973
+ elif instructions[i].opcode in HAS_NAME:
974
+ if should_compute_arg():
975
+ instructions[i].arg = names[instructions[i].argval]
976
+ elif instructions[i].opcode in HAS_FREE:
977
+ if should_compute_arg():
978
+ instructions[i].arg = freenames[instructions[i].argval]
979
+ elif instructions[i].opcode in HAS_CONST:
980
+ # NOTE: only update argval if arg is not provided. This assumes
981
+ # that any additions to co_consts are appended.
982
+ if instructions[i].arg is None:
983
+ # cannot use a dictionary since consts may not be hashable
984
+ idx = get_const_index(code_options, instructions[i].argval)
985
+ assert idx >= 0
986
+ instructions[i].arg = idx
987
+
988
+
989
+ def get_code_keys() -> List[str]:
990
+ # Python 3.11 changes to code keys are not fully documented.
991
+ # See https://github.com/python/cpython/blob/3.11/Objects/clinic/codeobject.c.h#L24
992
+ # for new format.
993
+ keys = ["co_argcount"]
994
+ keys.append("co_posonlyargcount")
995
+ keys.extend(
996
+ [
997
+ "co_kwonlyargcount",
998
+ "co_nlocals",
999
+ "co_stacksize",
1000
+ "co_flags",
1001
+ "co_code",
1002
+ "co_consts",
1003
+ "co_names",
1004
+ "co_varnames",
1005
+ "co_filename",
1006
+ "co_name",
1007
+ ]
1008
+ )
1009
+ if sys.version_info >= (3, 11):
1010
+ keys.append("co_qualname")
1011
+ keys.append("co_firstlineno")
1012
+ if sys.version_info >= (3, 10):
1013
+ keys.append("co_linetable")
1014
+ else:
1015
+ keys.append("co_lnotab")
1016
+ if sys.version_info >= (3, 11):
1017
+ # not documented, but introduced in https://github.com/python/cpython/issues/84403
1018
+ keys.append("co_exceptiontable")
1019
+ keys.extend(
1020
+ [
1021
+ "co_freevars",
1022
+ "co_cellvars",
1023
+ ]
1024
+ )
1025
+ return keys
1026
+
1027
+
1028
+ def transform_code_object(code, transformations, safe=False) -> types.CodeType:
1029
+ keys = get_code_keys()
1030
+ code_options = {k: getattr(code, k) for k in keys}
1031
+ assert len(code_options["co_varnames"]) == code_options["co_nlocals"]
1032
+
1033
+ instructions = cleaned_instructions(code, safe)
1034
+ propagate_line_nums(instructions)
1035
+
1036
+ transformations(instructions, code_options)
1037
+ return clean_and_assemble_instructions(instructions, keys, code_options)[1]
1038
+
1039
+
1040
+ def clean_and_assemble_instructions(
1041
+ instructions: List[Instruction], keys: List[str], code_options: Dict[str, Any]
1042
+ ) -> Tuple[List[Instruction], types.CodeType]:
1043
+ # also implicitly checks for no duplicate instructions
1044
+ check_inst_exn_tab_entries_valid(instructions)
1045
+
1046
+ code_options["co_nlocals"] = len(code_options["co_varnames"])
1047
+ varname_from_oparg = None
1048
+ if sys.version_info >= (3, 11):
1049
+ # temporary code object with updated names
1050
+ tmp_code = types.CodeType(*[code_options[k] for k in keys])
1051
+ varname_from_oparg = tmp_code._varname_from_oparg # type: ignore[attr-defined]
1052
+ fix_vars(instructions, code_options, varname_from_oparg=varname_from_oparg)
1053
+
1054
+ dirty = True
1055
+ while dirty:
1056
+ update_offsets(instructions)
1057
+ devirtualize_jumps(instructions)
1058
+ # this pass might change offsets, if so we need to try again
1059
+ dirty = bool(fix_extended_args(instructions))
1060
+
1061
+ remove_extra_line_nums(instructions)
1062
+ bytecode, lnotab = assemble(instructions, code_options["co_firstlineno"])
1063
+ if sys.version_info < (3, 10):
1064
+ code_options["co_lnotab"] = lnotab
1065
+ else:
1066
+ code_options["co_linetable"] = lnotab
1067
+
1068
+ code_options["co_code"] = bytecode
1069
+ code_options["co_stacksize"] = stacksize_analysis(instructions)
1070
+ assert set(keys) - {"co_posonlyargcount"} == set(code_options.keys()) - {
1071
+ "co_posonlyargcount"
1072
+ }
1073
+ if sys.version_info >= (3, 11):
1074
+ code_options["co_exceptiontable"] = assemble_exception_table(
1075
+ compute_exception_table(instructions)
1076
+ )
1077
+ return instructions, types.CodeType(*[code_options[k] for k in keys])
1078
+
1079
+
1080
+ def populate_kw_names_argval(instructions, consts):
1081
+ for inst in instructions:
1082
+ if inst.opname == "KW_NAMES":
1083
+ inst.argval = consts[inst.arg]
1084
+
1085
+
1086
+ def cleaned_instructions(code, safe=False) -> List[Instruction]:
1087
+ instructions = list(map(convert_instruction, dis.get_instructions(code)))
1088
+ check_offsets(instructions)
1089
+ if sys.version_info >= (3, 11):
1090
+ populate_kw_names_argval(instructions, code.co_consts)
1091
+ virtualize_exception_table(code.co_exceptiontable, instructions)
1092
+ virtualize_jumps(instructions)
1093
+ strip_extended_args(instructions)
1094
+ if not safe:
1095
+ if sys.version_info < (3, 11):
1096
+ remove_load_call_method(instructions)
1097
+ else:
1098
+ remove_jump_if_none(instructions)
1099
+ update_offsets(instructions)
1100
+ devirtualize_jumps(instructions)
1101
+ explicit_super(code, instructions)
1102
+ return instructions
1103
+
1104
+
1105
+ _unique_id_counter = itertools.count()
1106
+
1107
+
1108
+ def unique_id(name) -> str:
1109
+ return f"{name}_{next(_unique_id_counter)}"
1110
+
1111
+
1112
+ def is_generator(code: types.CodeType) -> bool:
1113
+ co_generator = 0x20
1114
+ return (code.co_flags & co_generator) > 0
llmeval-env/lib/python3.10/site-packages/torch/_dynamo/cache_size.py ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import types
3
+ import weakref
4
+ from dataclasses import dataclass
5
+ from typing import Tuple
6
+
7
+ from . import config
8
+
9
+ log = logging.getLogger(__name__)
10
+ """
11
+ [Note on cache size limit]
12
+
13
+ Background - TorchDynamo cache is a linked list. Each cache entry is a
14
+ (check_fn, out_code, next pointer). These are stored on the f_code's co_extra
15
+ scratch space. When a frame is invoked, we walk this linked list and run
16
+ check_fn in each cache_entry to decide if the frame needs recompilation. If none
17
+ of the check_fn's returns True, we recompile and add a new entry. To ensure we
18
+ don't end up recompiling infinitely, we put limits on the cache size.
19
+
20
+ There are two limits
21
+ 1) cache_size_limit
22
+ 2) accumulated_cache_size_limit
23
+
24
+
25
+ Earlier we used to have only limit - maximum number of entries in 1 cache line
26
+ (which is now represented by (2) above). So, why do we need two limits? Lets try
27
+ to understand that.
28
+
29
+ In general, we want our cache limit value to be a small number (e.g. 8 or even
30
+ lower). This ensures that for frames that cause too many recompilation fall to
31
+ eager quickly. However, there is another problem that prevents us from lowering
32
+ the value of cache_size_limit. This is due to ID_MATCH'd guards. Today, we put
33
+ ID_MATCH guards on nn module if there is a graph break. This means we will have
34
+ many recompilations for the same code object because the ID_MATCH guard fails
35
+ for different instances of the nn module. This is a common pattern in how models
36
+ are authored. Therefore, this requires us to keep the cache_size_limit high.
37
+
38
+ We resolve this by introducing these two limits. The first limit (1) limits the
39
+ number of cache entries that have an ID_MATCH'd guard for an nn module instance.
40
+ And, (2)nd limit becomes a safeguard mechanism to have a maximum compilations
41
+ for a code object. One important question is - what is the limit for the code
42
+ object that does not have any ID_MATCH guard? For such code objects, we choose
43
+ (1) as the cache size limit.
44
+
45
+ Lets take an example to understand how these limits help. Suppose, we have 16
46
+ instances of a nn module and we ID_MATCH on the self object. Further, suppose
47
+ the inputs to these functions have varying batch size, leading to one
48
+ recompilation. In total, there will be 32 recompilations, and therefore 32 cache
49
+ entries on the forward code object. In the older case when we had only 1 limit,
50
+ our cache size limit must be >= 32 to capture all these recompilations. Now,
51
+ suppose there is a separate function in the same program which is very dynamic
52
+ and unsuitable for compilation. Such a function will need to undergo 32
53
+ compilations to burst the cache and fallback to eager. These 32 recompilations
54
+ are too many and we want to fallback for these compilation-unfriendly functions
55
+ sooner.
56
+
57
+ In the new scenario, we can have (1) cache_size_limit = 2, (2)
58
+ accumulated_cache_size_limit = 32. This means that each ID_MATCH'd object can
59
+ have maximum of two cache entries, and the maximum number of cache entries
60
+ (irrespective of ID_MATCH obj) is 32. This covers the case of forward code
61
+ object which has 32 recompilations. For the other function, the one unsuitable
62
+ for recompilation, our limit is 2. So, we will burst the cache in just 2
63
+ recompilations. In this manner, these 2 limits help us resolve the tension
64
+ mentioned earlier.
65
+ """
66
+
67
+
68
+ @dataclass
69
+ class CacheSizeRelevantForFrame:
70
+ """
71
+ We track the number of cache entries that have same id_match objects as the
72
+ given frame.
73
+
74
+ TODO(janimesh) - Consider adding a map from tuple_of_match_ids to count -
75
+ https://github.com/pytorch/pytorch/pull/107496#discussion_r1304564682 - this
76
+ could be useful for debugging as well.
77
+ """
78
+
79
+ # Total number of CacheEntry objects in the Dynamo linked list
80
+ num_cache_entries: int = 0
81
+
82
+ # Number of CacheEntry objects having same ID_MATCH'd objects as given frame.
83
+ num_cache_entries_with_same_id_matched_objs: int = 0
84
+
85
+ def will_compilation_exceed(self, limit: int) -> bool:
86
+ # Checks if a compilation will exceed the given limit (thats why >=).
87
+ return (
88
+ self.will_compilation_exceed_accumulated_limit()
89
+ or self.will_compilation_exceed_specific_limit(limit)
90
+ )
91
+
92
+ def will_compilation_exceed_accumulated_limit(self) -> bool:
93
+ return self.num_cache_entries >= config.accumulated_cache_size_limit
94
+
95
+ def will_compilation_exceed_specific_limit(self, limit: int) -> bool:
96
+ return self.num_cache_entries_with_same_id_matched_objs >= limit
97
+
98
+
99
+ def _get_weakref_from_f_locals(frame: types.FrameType, local_name: str):
100
+ obj = frame.f_locals.get(local_name, None)
101
+ weak_id = None
102
+ try:
103
+ weak_id = weakref.ref(obj)
104
+ except TypeError:
105
+ pass # cannot weakref bool object
106
+ return weak_id
107
+
108
+
109
+ def _has_same_id_matched_objs(frame: types.FrameType, cache_entry) -> bool:
110
+ """
111
+ Checks if the ID_MATCH'd objects saved on cache_entry are same as the ones
112
+ in frame.f_locals.
113
+ """
114
+ if not cache_entry:
115
+ return False
116
+
117
+ for (
118
+ local_name,
119
+ weakref_from_cache_entry,
120
+ ) in cache_entry.check_fn.id_matched_objs.items():
121
+ if weakref_from_cache_entry() is not None:
122
+ weakref_from_frame = _get_weakref_from_f_locals(frame, local_name)
123
+ if weakref_from_frame != weakref_from_cache_entry:
124
+ return False
125
+
126
+ # Also covers the case where no ID_MATCH objects are saved in frame.f_locals
127
+ return True
128
+
129
+
130
+ def compute_cache_size(
131
+ frame: types.FrameType, cache_entry
132
+ ) -> CacheSizeRelevantForFrame:
133
+ # Walk the linked list to calculate the cache size
134
+ num_cache_entries = 0
135
+ num_cache_entries_with_same_id_matched_objs = 0
136
+
137
+ while cache_entry:
138
+ num_cache_entries += 1
139
+ # Track the number of cache entries having same ID_MATCH'd objects as
140
+ # that of frame.f_locals. This will be used later to compare against the
141
+ # cache_size_limit.
142
+ if _has_same_id_matched_objs(frame, cache_entry):
143
+ num_cache_entries_with_same_id_matched_objs += 1
144
+ cache_entry = cache_entry.next
145
+
146
+ return CacheSizeRelevantForFrame(
147
+ num_cache_entries, num_cache_entries_with_same_id_matched_objs
148
+ )
149
+
150
+
151
+ def is_recompilation(cache_size: CacheSizeRelevantForFrame) -> bool:
152
+ """
153
+ If the frame (earlier parsed by compute_cache_size) has more than 1 cache
154
+ entry with same ID_MATCH'd objects, then its a recompilation.
155
+ """
156
+ # Note that you can have multiple entries in the cache but still not a
157
+ # recompile, e.g., you can have 64 nn module instances, each one having an
158
+ # ID_MATCH guard, and each one having just 1 cache entry in the cache. In
159
+ # this case, we can have 64 entries in the cache, but no recompilation
160
+ # because there is only one entry for each id_matched_obj.
161
+ return cache_size.will_compilation_exceed(1)
162
+
163
+
164
+ def exceeds_cache_size_limit(cache_size: CacheSizeRelevantForFrame) -> Tuple[bool, str]:
165
+ """
166
+ Checks if we are exceeding the cache size limit.
167
+ """
168
+ if cache_size.will_compilation_exceed_accumulated_limit():
169
+ return True, "accumulated_cache_size_limit"
170
+ if cache_size.will_compilation_exceed_specific_limit(config.cache_size_limit):
171
+ return True, "cache_size_limit"
172
+ return False, ""
llmeval-env/lib/python3.10/site-packages/torch/_dynamo/code_context.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import types
2
+
3
+ from .utils import ExactWeakKeyDictionary
4
+
5
+
6
+ class CodeContextDict:
7
+ def __init__(self):
8
+ self.code_context = ExactWeakKeyDictionary()
9
+
10
+ def has_context(self, code: types.CodeType):
11
+ return code in self.code_context
12
+
13
+ def get_context(self, code: types.CodeType):
14
+ ctx = self.code_context.get(code)
15
+ if ctx is None:
16
+ ctx = {}
17
+ self.code_context[code] = ctx
18
+ return ctx
19
+
20
+ def pop_context(self, code: types.CodeType):
21
+ ctx = self.get_context(code)
22
+ self.code_context._remove_id(id(code))
23
+ return ctx
24
+
25
+ def clear(self):
26
+ self.code_context.clear()
27
+
28
+
29
+ code_context = CodeContextDict()
llmeval-env/lib/python3.10/site-packages/torch/_dynamo/codegen.py ADDED
@@ -0,0 +1,398 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import collections
2
+ import dataclasses
3
+ import re
4
+ import sys
5
+ import types
6
+ from typing import Counter, Dict, List, Optional
7
+
8
+ import torch.nn
9
+ from . import utils
10
+
11
+ from .bytecode_transformation import (
12
+ create_call_function,
13
+ create_dup_top,
14
+ create_instruction,
15
+ create_load_global,
16
+ create_rot_n,
17
+ Instruction,
18
+ )
19
+ from .exc import unimplemented
20
+ from .source import AttrSource, Source
21
+ from .utils import is_safe_constant, rot_n_helper
22
+ from .variables.base import VariableTracker
23
+ from .variables.nn_module import NNModuleVariable
24
+ from .variables.tensor import (
25
+ NumpyNdarrayVariable,
26
+ SymNodeVariable,
27
+ TensorVariable,
28
+ UnspecializedPythonVariable,
29
+ )
30
+ from .variables.torch_function import TensorWithTFOverrideVariable
31
+
32
+
33
+ @dataclasses.dataclass
34
+ class GraphOutputEntry:
35
+ index: int
36
+ variable: VariableTracker
37
+
38
+
39
+ class PyCodegen:
40
+ """
41
+ Helper class uses for constructing Python bytecode
42
+ """
43
+
44
+ def __init__(
45
+ self,
46
+ tx=None,
47
+ root: Optional[torch.nn.Module] = None,
48
+ graph_output_var: Optional[str] = None,
49
+ tempvars=None,
50
+ ):
51
+ self.root = root
52
+ self.top_of_stack: Optional[VariableTracker] = None
53
+ self.uses: Counter[VariableTracker] = collections.Counter()
54
+ self.graph_outputs: Dict[int, GraphOutputEntry] = {}
55
+ self._output: List[Instruction] = []
56
+ self.tempvars = tempvars or {}
57
+ self.tx = tx
58
+ self.graph_output_var = graph_output_var
59
+ self.code_options = self.tx.output.code_options
60
+ self.cell_and_freevars = self.tx.cell_and_freevars
61
+ self.new_var = self.tx.output.new_var
62
+ self.mutable_side_effects_from_source = False
63
+ self.value_from_source: bool = True
64
+
65
+ def restore_stack(self, stack_values, *, value_from_source=True):
66
+ prior = self.mutable_side_effects_from_source
67
+ self.mutable_side_effects_from_source = True
68
+ prev = self.value_from_source
69
+ self.value_from_source &= value_from_source
70
+ try:
71
+ self.foreach(stack_values)
72
+ finally:
73
+ self.mutable_side_effects_from_source = prior
74
+ self.value_from_source = prev
75
+
76
+ def graph_output_vars(self):
77
+ return [x.variable for x in self.graph_outputs.values()]
78
+
79
+ def call_reconstruct(self, value):
80
+ res = value.reconstruct(self)
81
+ assert res is None, f"reconstruct!=None {value}"
82
+
83
+ def __call__(self, value, allow_cache=True):
84
+ """Generate code such that top-of-stack (TOS) is set to value"""
85
+ if isinstance(value, Source):
86
+ self.call_reconstruct(value)
87
+ self.clear_tos()
88
+ return
89
+
90
+ assert isinstance(value, VariableTracker)
91
+ output = self._output
92
+ graph_outputs = self.graph_outputs
93
+
94
+ if self.top_of_stack is value and allow_cache:
95
+ output.append(create_dup_top())
96
+ return
97
+
98
+ if self.mutable_side_effects_from_source:
99
+ # this is needed to get aliasing relationships right
100
+ # value.mutable_local.source will get mutated to hold `value`
101
+ # mutable_side_effects_from_source=False is used to codegen the mutation
102
+ # mutable_side_effects_from_source=True is used to codegen a reference
103
+ from .side_effects import MutableSideEffects
104
+
105
+ if isinstance(value.mutable_local, MutableSideEffects):
106
+ self(value.mutable_local.source)
107
+ return
108
+
109
+ if allow_cache:
110
+ if value.mutable_local and value.mutable_local in self.tempvars:
111
+ output.append(self.create_load(self.tempvars[value.mutable_local]))
112
+ self.top_of_stack = value
113
+ return
114
+ if self.tempvars.get(value) is not None:
115
+ output.append(self.create_load(self.tempvars[value]))
116
+ self.top_of_stack = value
117
+ return
118
+
119
+ if value.source is not None and allow_cache and self.value_from_source:
120
+ self.call_reconstruct(value.source)
121
+ elif value.is_python_constant() and is_safe_constant(
122
+ value.as_python_constant()
123
+ ):
124
+ output.append(self.create_load_const(value.as_python_constant()))
125
+ elif isinstance(value, TensorWithTFOverrideVariable):
126
+ graph_outputs_key = self.add_graph_output(value)
127
+
128
+ self.load_import_from(utils.__name__, "to_subclass")
129
+ self.load_graph_output(graph_outputs[graph_outputs_key].index)
130
+ output.append(
131
+ self.create_load_global(
132
+ value.global_mangled_class_name(self.tx), False, add=True
133
+ )
134
+ )
135
+ output.extend(create_call_function(2, True))
136
+ elif isinstance(
137
+ value,
138
+ (
139
+ TensorVariable,
140
+ SymNodeVariable,
141
+ UnspecializedPythonVariable,
142
+ NumpyNdarrayVariable,
143
+ ),
144
+ ):
145
+ graph_outputs_key = self.add_graph_output(value)
146
+
147
+ if isinstance(value, NumpyNdarrayVariable):
148
+ self.load_import_from(utils.__name__, "to_numpy_helper")
149
+
150
+ self.load_graph_output(graph_outputs[graph_outputs_key].index)
151
+
152
+ if isinstance(value, NumpyNdarrayVariable):
153
+ output.extend(create_call_function(1, True))
154
+ elif isinstance(value, UnspecializedPythonVariable) and value.need_unwrap:
155
+ output.extend(
156
+ [self.create_load_attr("item")] + create_call_function(0, True)
157
+ )
158
+ elif isinstance(value, NNModuleVariable):
159
+ parts = value.module_key.split(".")
160
+ if parts[0] in self.code_options["co_varnames"]:
161
+ output.append(self.create_load(parts[0]))
162
+ parts = parts[1:]
163
+ else:
164
+ assert self.root is not None
165
+ output.append(self.create_load_output(self.root))
166
+ for part in parts:
167
+ output.append(self.create_load_attr(part))
168
+ else:
169
+ self.uses[value] += 1
170
+ try:
171
+ self.call_reconstruct(value)
172
+ except NotImplementedError:
173
+ unimplemented(f"reconstruct: {value}")
174
+ if allow_cache and value in self.tempvars:
175
+ self._output.append(create_dup_top())
176
+ self.add_cache(value)
177
+
178
+ self.top_of_stack = value
179
+
180
+ def add_graph_output(self, value):
181
+ graph_outputs_key = id(value.as_proxy())
182
+ if graph_outputs_key not in self.graph_outputs:
183
+ self.graph_outputs[graph_outputs_key] = GraphOutputEntry(
184
+ len(self.graph_outputs), value
185
+ )
186
+ return graph_outputs_key
187
+
188
+ def load_graph_output(self, index):
189
+ output = self._output
190
+ output.append(self.create_load(self.graph_output_var))
191
+ output.append(self._create_load_const(index))
192
+ output.append(create_instruction("BINARY_SUBSCR"))
193
+
194
+ def add_cache(self, value):
195
+ var = self.new_var()
196
+ self.tempvars[value] = var
197
+ if value.mutable_local:
198
+ self.tempvars[value.mutable_local] = var
199
+ self._output.append(self.create_store(var))
200
+
201
+ def foreach(self, items):
202
+ for i in items:
203
+ self(i)
204
+
205
+ def setup_globally_cached(self, name, value, push_null):
206
+ """Store value in a new global"""
207
+ name = re.sub(r"[^a-zA-Z0-9_]+", "_", name)
208
+ f_globals = self.tx.f_globals
209
+ if name in f_globals:
210
+ assert id(f_globals[name]) == id(value)
211
+ else:
212
+ f_globals[name] = value
213
+ return [self.create_load_global(name, push_null, add=True)]
214
+
215
+ def clear_tos(self):
216
+ self.top_of_stack = None
217
+
218
+ def append_output(self, inst):
219
+ assert isinstance(inst, Instruction)
220
+ self._output.append(inst)
221
+ self.clear_tos()
222
+
223
+ def extend_output(self, insts):
224
+ assert all(isinstance(x, Instruction) for x in insts)
225
+ self._output.extend(insts)
226
+ self.clear_tos()
227
+
228
+ def get_instructions(self) -> List[Instruction]:
229
+ return self._output
230
+
231
+ def create_load(self, name) -> Instruction:
232
+ if name in self.cell_and_freevars():
233
+ return create_instruction("LOAD_DEREF", argval=name)
234
+ assert name in self.code_options["co_varnames"], f"{name} missing"
235
+ return create_instruction("LOAD_FAST", argval=name)
236
+
237
+ def create_load_closure(self, name) -> Instruction:
238
+ assert name in self.cell_and_freevars()
239
+ return create_instruction("LOAD_CLOSURE", argval=name)
240
+
241
+ def create_store(self, name) -> Instruction:
242
+ if name in self.cell_and_freevars():
243
+ return create_instruction("STORE_DEREF", argval=name)
244
+ assert name in self.code_options["co_varnames"]
245
+ return create_instruction("STORE_FAST", argval=name)
246
+
247
+ def create_load_global(self, name, push_null, add=False) -> Instruction:
248
+ if add:
249
+ self.tx.output.update_co_names(name)
250
+ assert name in self.code_options["co_names"], f"{name} not in co_names"
251
+ return create_load_global(name, push_null)
252
+
253
+ def create_load_const(self, value) -> Instruction:
254
+ assert is_safe_constant(value), f"unsafe constant {value}"
255
+ return self._create_load_const(value)
256
+
257
+ def _create_load_const(self, value) -> Instruction:
258
+ return create_instruction("LOAD_CONST", argval=value)
259
+
260
+ create_load_output = _create_load_const
261
+
262
+ def create_load_method(self, name):
263
+ self.tx.output.update_co_names(name)
264
+ return create_instruction("LOAD_METHOD", argval=name)
265
+
266
+ def create_load_attr(self, name) -> Instruction:
267
+ if name not in self.code_options["co_names"]:
268
+ self.code_options["co_names"] += (name,)
269
+ return create_instruction("LOAD_ATTR", argval=name)
270
+
271
+ def load_attr(self, name):
272
+ self.append_output(self.create_load_attr(name))
273
+
274
+ def create_load_attrs(self, names):
275
+ return [self.create_load_attr(name) for name in names.split(".")]
276
+
277
+ def create_store_attr(self, name) -> Instruction:
278
+ if name not in self.code_options["co_names"]:
279
+ self.code_options["co_names"] += (name,)
280
+ return create_instruction("STORE_ATTR", argval=name)
281
+
282
+ def store_attr(self, name):
283
+ self.append_output(self.create_store_attr(name))
284
+
285
+ def load_function_name(self, fn_name, push_null, num_on_stack=0):
286
+ """Load the global fn_name on the stack num_on_stack down"""
287
+ output = []
288
+ if push_null and sys.version_info >= (3, 11):
289
+ output.extend(
290
+ [create_instruction("PUSH_NULL"), *self.rot_n(num_on_stack + 1)]
291
+ )
292
+ output.extend(
293
+ [
294
+ self.create_load_global(fn_name, False, add=True),
295
+ *self.rot_n(num_on_stack + 1),
296
+ ]
297
+ )
298
+ return output
299
+
300
+ def rot_n(self, n):
301
+ try:
302
+ return create_rot_n(n)
303
+ except AttributeError:
304
+ # desired rotate bytecode doesn't exist, generate equivalent bytecode
305
+ return [
306
+ create_instruction("BUILD_TUPLE", arg=n),
307
+ self._create_load_const(rot_n_helper(n)),
308
+ *create_rot_n(2),
309
+ create_instruction("CALL_FUNCTION_EX", arg=0),
310
+ create_instruction("UNPACK_SEQUENCE", arg=n),
311
+ ]
312
+
313
+ def pop_null(self):
314
+ # POP_TOP doesn't work for null, so we pop nulls by pushing in a
315
+ # nop function, calling it (which consumes the null), and popping the result.
316
+ assert sys.version_info >= (3, 11)
317
+ return [
318
+ self._create_load_const(lambda: None),
319
+ *create_call_function(0, False),
320
+ create_instruction("POP_TOP"),
321
+ ]
322
+
323
+ def call_function(self, nargs: int, push_null: bool):
324
+ self.extend_output(create_call_function(nargs, push_null=push_null))
325
+
326
+ def dup_top(self):
327
+ self.append_output(create_dup_top())
328
+
329
+ def store(self, varname):
330
+ self.append_output(self.create_store(varname))
331
+
332
+ def make_function_with_closure(
333
+ self, fn_name: str, code: types.CodeType, push_null: bool, num_on_stack=0
334
+ ):
335
+ freevars = code.co_freevars
336
+ assert freevars
337
+ output = self._output
338
+ if sys.version_info >= (3, 11) and push_null:
339
+ output.append(create_instruction("PUSH_NULL"))
340
+ output.extend(self.rot_n(num_on_stack + 1))
341
+ for var in freevars:
342
+ assert var in self.cell_and_freevars()
343
+ output.append(create_instruction("LOAD_CLOSURE", argval=var))
344
+ output.append(create_instruction("BUILD_TUPLE", arg=len(freevars)))
345
+ output.append(self.create_load_const(code))
346
+ if sys.version_info < (3, 11):
347
+ output.append(self.create_load_const(fn_name))
348
+ output.append(create_instruction("MAKE_FUNCTION", arg=0x08))
349
+ output.extend(self.rot_n(num_on_stack + 1))
350
+ self.clear_tos()
351
+
352
+ def create_load_python_module(self, mod, push_null) -> Instruction:
353
+ """
354
+ Generate a LOAD_GLOBAL instruction to fetch a given python module.
355
+ """
356
+ output = self.tx.output
357
+ global_scope = output.global_scope
358
+ name = re.sub(r"^.*[.]", "", mod.__name__)
359
+ if global_scope.get(name, None) is mod:
360
+ return self.create_load_global(name, push_null, add=True)
361
+ prefix = f"___module_{name}"
362
+ global_name = self.tx.output.install_global_by_id(prefix, mod)
363
+ return self.create_load_global(global_name, push_null, add=True)
364
+
365
+ def make_call_generated_code(self, fn_name: str) -> None:
366
+ """Call the generated code function stored in fn_name"""
367
+ self.extend_output(self.load_function_name(fn_name, True))
368
+
369
+ graphargs = self.tx.output.graphargs
370
+ for arg in graphargs:
371
+ if arg.is_unspecialized:
372
+ self.extend_output(
373
+ [
374
+ self.create_load_python_module(torch, True),
375
+ self.create_load_attr("as_tensor"),
376
+ ]
377
+ )
378
+ self.call_reconstruct(arg)
379
+ self.extend_output(create_call_function(1, False))
380
+ else:
381
+ self.call_reconstruct(arg)
382
+
383
+ self.extend_output(create_call_function(len(graphargs), False))
384
+
385
+ def load_import_from(self, module_name, object_name) -> None:
386
+ self(AttrSource(self.tx.import_source(module_name), object_name))
387
+
388
+ def create_call_function_kw(self, nargs, kw_names, push_null) -> List[Instruction]:
389
+ if sys.version_info >= (3, 11):
390
+ output = create_call_function(nargs, push_null)
391
+ assert output[-2].opname == "PRECALL"
392
+ kw_names_inst = create_instruction("KW_NAMES", argval=kw_names)
393
+ output.insert(-2, kw_names_inst)
394
+ return output
395
+ return [
396
+ self.create_load_const(kw_names),
397
+ create_instruction("CALL_FUNCTION_KW", arg=nargs),
398
+ ]
llmeval-env/lib/python3.10/site-packages/torch/_dynamo/compiled_autograd.py ADDED
@@ -0,0 +1,280 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import contextlib
2
+ import functools
3
+ from typing import List, Optional
4
+
5
+ import torch
6
+ from torch._dynamo.external_utils import call_backward, call_hook
7
+ from torch._dynamo.source import GetItemSource, LocalSource
8
+ from torch._dynamo.utils import counters, lazy_format_graph_code
9
+ from torch._logging import getArtifactLogger, trace_structured
10
+ from torch._prims_common import clone_preserve_strides
11
+ from torch._subclasses import FakeTensorMode
12
+ from torch.fx import GraphModule
13
+ from torch.fx.experimental._backward_state import BackwardState
14
+ from torch.fx.experimental.proxy_tensor import (
15
+ decompose,
16
+ disable_autocast_cache,
17
+ disable_proxy_modes_tracing,
18
+ fetch_object_proxy,
19
+ ProxyTorchDispatchMode,
20
+ PythonKeyTracer,
21
+ track_tensor_tree,
22
+ )
23
+ from torch.fx.experimental.symbolic_shapes import DimDynamic, ShapeEnv
24
+ from torch.fx.proxy import Proxy
25
+
26
+ compiled_autograd_log = getArtifactLogger(__name__, "compiled_autograd")
27
+
28
+
29
+ def maybe_clone(x):
30
+ if x is not None:
31
+ return clone_preserve_strides(x)
32
+ return x
33
+
34
+
35
+ class AutogradCompilerInstance:
36
+ def __init__(self, compiler_fn) -> None:
37
+ self.compiler_fn = compiler_fn
38
+ self.stack = contextlib.ExitStack()
39
+ self.close = self.stack.close
40
+ self.shape_env = ShapeEnv()
41
+ self.fake_tensor_mode = FakeTensorMode(
42
+ allow_fallback_kernels=True,
43
+ allow_non_fake_inputs=True,
44
+ shape_env=self.shape_env,
45
+ )
46
+ self.fx_tracer = PythonKeyTracer()
47
+ self.proxy_mode = ProxyTorchDispatchMode(self.fx_tracer, "symbolic")
48
+ self.hooks_proxy: Optional[Proxy] = None
49
+
50
+ def wrap_fake(self, x, source):
51
+ assert isinstance(x, torch.Tensor)
52
+ return self.fake_tensor_mode.from_tensor(x, source=source)
53
+
54
+ @staticmethod
55
+ def source(name, idx) -> GetItemSource:
56
+ return GetItemSource(LocalSource(name), idx)
57
+
58
+ def begin_capture(self, inputs: List[torch.Tensor], sizes: List[int]):
59
+ counters["compiled_autograd"]["captures"] += 1
60
+ self.fx_tracer.root = torch.nn.Module()
61
+ self.fx_tracer.graph = torch.fx.Graph(tracer_cls=PythonKeyTracer)
62
+ self.fx_tracer.tensor_attrs = {}
63
+ args_proxy = self.fx_tracer.create_proxy("placeholder", "inputs", (), {})
64
+ sizes_proxy = self.fx_tracer.create_proxy("placeholder", "sizes", (), {})
65
+ self.hooks_proxy = self.fx_tracer.create_proxy("placeholder", "hooks", (), {})
66
+
67
+ # tensor inputs to fake tensors
68
+ inputs = [
69
+ self.wrap_fake(x, self.source("inputs", idx))
70
+ for idx, x in enumerate(inputs)
71
+ ]
72
+ proxies = [args_proxy[i] for i in range(len(inputs))]
73
+ self.bind_tensors_to_proxies(inputs, proxies)
74
+
75
+ # size inputs to symints
76
+ sizes = [
77
+ self.shape_env.create_unspecified_symint_and_symbol(
78
+ val,
79
+ self.source("sizes", idx),
80
+ DimDynamic.DYNAMIC,
81
+ )
82
+ for idx, val in enumerate(sizes)
83
+ ]
84
+ self.bind_tensors_to_proxies(sizes, sizes_proxy)
85
+
86
+ # TODO(jansel): are all these modes needed?
87
+ self.stack.enter_context(decompose({}))
88
+ self.stack.enter_context(self.fake_tensor_mode)
89
+ self.stack.enter_context(self.proxy_mode.sym_mode)
90
+ self.stack.enter_context(self.proxy_mode)
91
+ self.stack.enter_context(disable_autocast_cache())
92
+ return inputs, sizes
93
+
94
+ def proxy_call_backward(
95
+ self,
96
+ inputs,
97
+ output_metadatas,
98
+ saved_tensors,
99
+ backward_idx: int,
100
+ ):
101
+ assert self.hooks_proxy is not None
102
+ backward_fn = self.hooks_proxy[backward_idx] # type: ignore[index]
103
+ proxies = self.fx_tracer.create_proxy(
104
+ kind="call_function",
105
+ target=call_backward,
106
+ args=(
107
+ backward_fn,
108
+ self.to_proxy(saved_tensors),
109
+ *self.to_proxy(inputs),
110
+ ),
111
+ kwargs={},
112
+ )
113
+
114
+ with disable_proxy_modes_tracing():
115
+ # create fake Tensors
116
+ grad_ins: List[Optional[torch.Tensor]] = []
117
+ for output_metadata in output_metadatas:
118
+ if output_metadata is None:
119
+ grad_ins.append(None)
120
+ continue
121
+
122
+ layout, device, dtype, size = output_metadata
123
+ grad_ins.append(
124
+ torch.empty(size=size, dtype=dtype, layout=layout, device=device)
125
+ )
126
+ self.bind_tensors_to_proxies(grad_ins, proxies)
127
+ return tuple(grad_ins)
128
+
129
+ def proxy_call_hook(self, hook, *args):
130
+ return self.fx_tracer.create_proxy(
131
+ "call_function",
132
+ call_hook,
133
+ (
134
+ hook,
135
+ *[self.to_proxy(x) for x in args],
136
+ ),
137
+ {},
138
+ )
139
+
140
+ def tensor_pre_hook(self, inputs, hook_id, i: int):
141
+ assert self.hooks_proxy is not None
142
+ hook = self.hooks_proxy[hook_id] # type: ignore[index]
143
+ proxy = self.proxy_call_hook(
144
+ hook,
145
+ inputs[i],
146
+ )
147
+ with disable_proxy_modes_tracing():
148
+ inputs[i] = maybe_clone(inputs[i])
149
+ self.bind_tensors_to_proxies([inputs[i]], [proxy])
150
+ return inputs
151
+
152
+ def pre_hook(self, inputs, hook_id):
153
+ assert self.hooks_proxy is not None
154
+ hook = self.hooks_proxy[hook_id] # type: ignore[index]
155
+ proxies = self.proxy_call_hook(
156
+ hook,
157
+ inputs,
158
+ )
159
+ with disable_proxy_modes_tracing():
160
+ inputs = [maybe_clone(x) for x in inputs]
161
+ self.bind_tensors_to_proxies(inputs, proxies)
162
+ return inputs
163
+
164
+ def post_hook(self, outputs, inputs, hook_id):
165
+ assert self.hooks_proxy is not None
166
+ hook = self.hooks_proxy[hook_id] # type: ignore[index]
167
+ proxies = self.proxy_call_hook(
168
+ hook,
169
+ outputs,
170
+ inputs,
171
+ )
172
+ with disable_proxy_modes_tracing():
173
+ outputs = [maybe_clone(x) for x in outputs]
174
+ self.bind_tensors_to_proxies(outputs, proxies)
175
+ return outputs
176
+
177
+ def post_acc_grad_hook(self, input, hook_id):
178
+ assert isinstance(input, torch.Tensor)
179
+ assert self.hooks_proxy is not None
180
+ hook = self.hooks_proxy[hook_id] # type: ignore[index]
181
+ proxies = self.proxy_call_hook(
182
+ hook,
183
+ input,
184
+ )
185
+ with disable_proxy_modes_tracing():
186
+ input = [maybe_clone(input)]
187
+ self.bind_tensors_to_proxies(input, proxies)
188
+ return input
189
+
190
+ def end_capture(self, outputs):
191
+ self.stack.close()
192
+ self.fx_tracer.create_node(
193
+ "output",
194
+ "output",
195
+ (self.fx_tracer.create_arg(self.to_proxy(outputs)),),
196
+ {},
197
+ )
198
+ graph = GraphModule(
199
+ self.fx_tracer.root, self.fx_tracer.graph, "CompiledAutograd"
200
+ )
201
+ compiled_autograd_log.info(
202
+ "%s", lazy_format_graph_code("Compiled autograd graph", graph)
203
+ )
204
+ trace_structured(
205
+ "compiled_autograd_graph",
206
+ payload_fn=lambda: graph.print_readable(print_output=False),
207
+ )
208
+ return self.compiler_fn(graph)
209
+
210
+ def to_proxy(self, t):
211
+ if t is None:
212
+ return None
213
+ if isinstance(t, list):
214
+ return [self.to_proxy(x) for x in t]
215
+ if isinstance(t, tuple):
216
+ return tuple(self.to_proxy(x) for x in t)
217
+ assert isinstance(t, (torch.Tensor, torch.SymInt))
218
+ return fetch_object_proxy(self.fx_tracer)(t).proxy
219
+
220
+ def bind_tensors_to_proxies(self, tensors, proxies):
221
+ if isinstance(proxies, torch.fx.Proxy):
222
+ proxies = [proxies[i] for i in range(len(tensors))]
223
+ assert len(tensors) == len(proxies)
224
+ track_tensor_tree(tensors, proxies, constant=None, tracer=self.fx_tracer)
225
+
226
+ def bind_backward_state(self, index: int):
227
+ assert self.hooks_proxy is not None
228
+ proxy = self.hooks_proxy[index] # type: ignore[index]
229
+ bw_state = BackwardState()
230
+ track_tensor_tree(bw_state, proxy, constant=None, tracer=self.fx_tracer)
231
+ return bw_state
232
+
233
+
234
+ compiled_autograd_enabled = False
235
+
236
+ # We may have code like:
237
+ # with enable(compiler_fn):
238
+ # ...
239
+ # with disable():
240
+ # ...
241
+ # ...
242
+ # The disable() call just want to disable compiled autograd temporarily.
243
+ # But overall the feature is enabled.
244
+ #
245
+ # The code covered by the disable context manager has no way to know if
246
+ # compiled autograd is overall eanbled. Use another variable
247
+ # compiled_autograd_enabled_count to indicate how many times compiled
248
+ # autograd has been enabled in the call stack for this purpose.
249
+ compiled_autograd_enabled_count = 0
250
+
251
+
252
+ @contextlib.contextmanager
253
+ def enable(compiler_fn):
254
+ prior = torch._C._dynamo.compiled_autograd.set_autograd_compiler(
255
+ functools.partial(AutogradCompilerInstance, compiler_fn)
256
+ )
257
+ global compiled_autograd_enabled, compiled_autograd_enabled_count
258
+ compiled_autograd_enabled = True
259
+ compiled_autograd_enabled_count += 1
260
+ try:
261
+ with torch.autograd.set_multithreading_enabled(False):
262
+ yield
263
+ finally:
264
+ compiled_autograd_enabled_count -= 1
265
+ if not prior:
266
+ compiled_autograd_enabled = False
267
+ torch._C._dynamo.compiled_autograd.set_autograd_compiler(prior)
268
+
269
+
270
+ @contextlib.contextmanager
271
+ def disable():
272
+ prior = torch._C._dynamo.compiled_autograd.set_autograd_compiler(None)
273
+ global compiled_autograd_enabled
274
+ compiled_autograd_enabled = False
275
+ try:
276
+ yield
277
+ finally:
278
+ if prior:
279
+ compiled_autograd_enabled = True
280
+ torch._C._dynamo.compiled_autograd.set_autograd_compiler(prior)
llmeval-env/lib/python3.10/site-packages/torch/_dynamo/comptime.py ADDED
@@ -0,0 +1,373 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
8
+ import builtins
9
+ import dis
10
+ import traceback
11
+ from typing import Optional, Union
12
+
13
+ import torch
14
+ from torch.fx.experimental.symbolic_shapes import free_symbols
15
+
16
+ from .exc import unimplemented
17
+ from .variables.constant import ConstantVariable
18
+ from .variables.tensor import SymNodeVariable
19
+
20
+
21
+ class ComptimeVar:
22
+ """
23
+ A ComptimeVar represents a Python value, at some particular point
24
+ in time, in the Python code we are symbolically evaluating with
25
+ torchdynamo. This must be distinguished from a runtime value, as
26
+ at compile-time there are some properties of the variable we
27
+ do not know (for example, if the ComptimeVar represents a Tensor,
28
+ we only know metadata about the tensor; we do NOT know what the
29
+ actual data in the Tensor is.)
30
+ """
31
+
32
+ def __init__(self, v):
33
+ self.__variable = v
34
+
35
+ def as_proxy(self):
36
+ """
37
+ Returns an fx.Proxy (or tuple/list of fx.Proxy) representing
38
+ this variable in the FX graph we are assembling to pass
39
+ to the user compiler.
40
+
41
+ This method only works for variables we actually track in
42
+ the FX graph, aka Tensors (and ints, if you are compiling
43
+ with dynamic shapes). In particular, if you have a list
44
+ or tuple of tensors, you will get a list/tuple of proxies
45
+ (not a single proxy representing the entire list/tuple).
46
+ """
47
+ return self.__variable.as_proxy()
48
+
49
+ def is_proxy(self):
50
+ """
51
+ Returns True if as_proxy() would succeed.
52
+ """
53
+ return self.__variable.is_proxy()
54
+
55
+ def as_fake(self):
56
+ """
57
+ Returns a "fake" value (either a FakeTensor or a SymInt)
58
+ representing the variable in question. This only works
59
+ for variables that denote Tensor or int. You can use
60
+ this to query metadata; e.g., v.as_fake().size(0) will
61
+ tell you the compile-time known size of the tensor.
62
+
63
+ WARNING: Do NOT mutate the returned tensor.
64
+ """
65
+ return self.__variable.as_proxy().node.meta["example_value"]
66
+
67
+ def size(self, dim: Optional[int] = None) -> Union[int, torch.SymInt]:
68
+ """
69
+ Returns the size of the tensor (if dim is None) or the size
70
+ at the dimension dim. The returned size may be a SymInt.
71
+ """
72
+ return self.as_fake().size(dim)
73
+
74
+ def python_type(self):
75
+ """
76
+ Returns what type(v) would have returned for the variable
77
+ at compile time.
78
+ """
79
+ return self.__variable.python_type()
80
+
81
+ def as_python_constant(self):
82
+ """
83
+ Returns the Python value this variable would have, but only if it is
84
+ completely known at compile-time (e.g., it is constant).
85
+
86
+ WARNING: Do NOT mutate the returned constant. The returned constant
87
+ may or may not correspond to the actual value this variable may take
88
+ on at runtime; for example, if the variable in question is a constant
89
+ list, we may return a copy of that list.
90
+ """
91
+ return self.__variable.as_python_constant()
92
+
93
+ def is_python_constant(self):
94
+ """
95
+ Returns True if as_python_constant would succeed.
96
+ """
97
+ return self.__variable.is_python_constant()
98
+
99
+ def is_dynamic(self):
100
+ if isinstance(self.__variable, SymNodeVariable):
101
+ fs = free_symbols(self.__variable.sym_num)
102
+ return bool(fs)
103
+ return False
104
+
105
+ def force_static(self):
106
+ """
107
+ Forces that a value is static, inducing a guard on its specific value
108
+ """
109
+ if isinstance(self.__variable, SymNodeVariable):
110
+ self.__variable.evaluate_expr()
111
+ elif isinstance(self.__variable, ConstantVariable):
112
+ # TODO: Maybe complain if this isn't a int/bool/float variable
113
+ pass
114
+ else:
115
+ raise AssertionError(
116
+ f"cannot force {self.__variable} ({type(self.__variable)}) static"
117
+ )
118
+
119
+ def _i_will_not_complain_if_bc_breaks_VariableTracker(self):
120
+ """
121
+ Returns the internal data structure VariableTracker that Dynamo uses
122
+ to represent variables at compile time. There are no BC guarantees on
123
+ this API and WE RESERVE THE RIGHT TO BREAK YOUR CODE if you rely on
124
+ it.
125
+ """
126
+ return self.__variable
127
+
128
+ def __repr__(self):
129
+ # TODO: The default repr is pretty bad, do better
130
+ return repr(self.__variable)
131
+
132
+ # TODO: API for adding a custom guard
133
+
134
+
135
+ class ComptimeContext:
136
+ """
137
+ This context class provides access to a public API for Dynamo's internals.
138
+ If there is something here you would find useful that is missing, please
139
+ file a feature request at https://github.com/pytorch/pytorch/
140
+ """
141
+
142
+ def __init__(self, tx):
143
+ self.__tx = tx
144
+
145
+ def get_local(self, name: str, *, stacklevel=0) -> ComptimeVar:
146
+ """
147
+ Retrieve the compile-time known information about a local.
148
+ """
149
+ tx = self.__get_tx(stacklevel)
150
+ return ComptimeVar(tx.symbolic_locals[name])
151
+
152
+ def graph_break(self, msg="ComptimeContext.graph_break"):
153
+ """
154
+ Manually trigger a graph break
155
+ """
156
+ unimplemented(msg)
157
+
158
+ def graph(self):
159
+ """
160
+ Retrieve the partially constructed FX graph that would be
161
+ passed to the user compiler after compilation.
162
+ """
163
+ return self.__tx.output.graph
164
+
165
+ def assert_static(self, val):
166
+ """
167
+ Asserts that the int is static (and not dynamic, per dynamic shapes)
168
+ """
169
+ assert (
170
+ not val.is_dynamic()
171
+ ), "expected static but got dynamic (run with TORCH_LOGS=dynamic for more info)"
172
+
173
+ def print_graph(self, *, verbose=True, file=None):
174
+ """
175
+ Print the partially constructed FX graph that would be passed
176
+ to the user compiler after compilation.
177
+ """
178
+ print(
179
+ self.__tx.output.graph.python_code("self", verbose=verbose).src, file=file
180
+ )
181
+
182
+ def parent(self):
183
+ return ComptimeContext(self.__tx.parent)
184
+
185
+ def __get_tx(self, stacklevel):
186
+ tx = self.__tx
187
+ for _ in range(stacklevel):
188
+ tx = tx.parent
189
+ return tx
190
+
191
+ def print_disas(self, *, file=None, stacklevel=0):
192
+ """
193
+ Print the current series of opcodes being executed (not including
194
+ parent frames), including where you are in the particular opcode
195
+ stream.
196
+ """
197
+ tx = self.__get_tx(stacklevel)
198
+ print(
199
+ dis.Bytecode(
200
+ tx.f_code,
201
+ current_offset=tx.instructions[tx.instruction_pointer].offset,
202
+ ).dis(),
203
+ file=file,
204
+ )
205
+
206
+ def print_value_stack(self, *, file=None, stacklevel=0):
207
+ """
208
+ Print the current Python value stack. Note that this is NOT the same
209
+ as the traceback; use print_bt() to print that. Note that at
210
+ stacklevel=0, this will typically be empty, as comptime cannot
211
+ currently be used in an expression context where there would be
212
+ intermediates on the stack. If you would find this useful, please
213
+ file a bug at https://github.com/pytorch/pytorch/
214
+
215
+ NB: Stack grows downwards in our print
216
+ """
217
+ # TODO: improve printing
218
+ tx = self.__get_tx(stacklevel)
219
+ for s in tx.stack:
220
+ print(f"- {s}", file=file)
221
+
222
+ def print_locals(self, *, file=None, stacklevel=0):
223
+ """
224
+ Print all of the locals available in the current context.
225
+ By default this view is very limited; you can get more information
226
+ about any individual local using get_local().
227
+ """
228
+ # TODO: improve by improving the VariableTracker printing
229
+ tx = self.__get_tx(stacklevel)
230
+ for k, v in tx.symbolic_locals.items():
231
+ print(f"{k} = {v}", file=file)
232
+
233
+ def print_bt(self, *, file=None, stacklevel=0):
234
+ """
235
+ Print the user code backtrace, starting at the beginning of the
236
+ frame Dynamo started evaluating. Note that this MAY NOT go all
237
+ the way to the torch.compile invocation, as we may have done
238
+ a graph break and are compiling an intermediate frame as the
239
+ starting point. If you think the other behavior would be better,
240
+ file a bug at https://github.com/pytorch/pytorch/
241
+ """
242
+ stack = []
243
+ tx = self.__get_tx(stacklevel)
244
+ while tx is not None:
245
+ stack.append(tx.frame_summary())
246
+ tx = getattr(tx, "parent", None)
247
+ print(
248
+ "".join(traceback.StackSummary.from_list(reversed(stack)).format()),
249
+ file=file,
250
+ )
251
+
252
+ def print_guards(self, *, file=None):
253
+ """
254
+ Print the currently installed guards for the Dynamo context.
255
+ This does NOT include guards associated with variables that
256
+ may or may not be installed in the future if those variables
257
+ are used.
258
+ """
259
+ # TODO: improve print format, current guard format is extremely
260
+ # verbose
261
+ print(
262
+ "\n".join(f"{repr(guard)}" for guard in sorted(self.__tx.output.guards)),
263
+ file=file,
264
+ )
265
+
266
+ def _i_will_not_complain_if_bc_breaks_InstructionTranslator(self):
267
+ """
268
+ Returns the internal data structure InstructionTranslator that Dynamo
269
+ uses to track state of symbolic evaluation. There are no BC
270
+ guarantees on this API and WE RESERVE THE RIGHT TO BREAK YOUR CODE if
271
+ you rely on it.
272
+ """
273
+ return self.__tx
274
+
275
+
276
+ class _Comptime:
277
+ @staticmethod
278
+ def __call__(fn):
279
+ """fn gets called at compile time in TorchDynamo, does nothing otherwise"""
280
+ return
281
+
282
+ # Convenience wrappers that are more compact to use
283
+
284
+ @staticmethod
285
+ def graph_break():
286
+ comptime(lambda ctx: ctx.graph_break())
287
+
288
+ @staticmethod
289
+ def print_graph():
290
+ comptime(lambda ctx: ctx.print_graph())
291
+
292
+ @staticmethod
293
+ def print_disas(*, stacklevel=0):
294
+ comptime(
295
+ lambda ctx: ctx.print_disas(
296
+ stacklevel=ctx.get_local("stacklevel").as_python_constant() + 1
297
+ )
298
+ )
299
+
300
+ @staticmethod
301
+ def print_value_stack(*, stacklevel=0):
302
+ comptime(
303
+ lambda ctx: ctx.print_value_stack(
304
+ stacklevel=ctx.get_local("stacklevel").as_python_constant() + 1
305
+ )
306
+ )
307
+
308
+ # This is a more useful variant of print_value_stack that can be used
309
+ # in an expression context; e.g., x + print_value_stack_and_return(y + z),
310
+ # you will see x on the stack prior to the addition operation
311
+ @staticmethod
312
+ def print_value_stack_and_return(e, *, stacklevel=0):
313
+ comptime(
314
+ lambda ctx: ctx.print_value_stack(
315
+ stacklevel=ctx.get_local("stacklevel").as_python_constant() + 1
316
+ )
317
+ )
318
+ return e
319
+
320
+ @staticmethod
321
+ def print_locals(*, stacklevel=0):
322
+ comptime(
323
+ lambda ctx: ctx.print_locals(
324
+ stacklevel=ctx.get_local("stacklevel").as_python_constant() + 1
325
+ )
326
+ )
327
+
328
+ @staticmethod
329
+ def print_bt(*, stacklevel=0):
330
+ comptime(
331
+ lambda ctx: ctx.print_bt(
332
+ stacklevel=ctx.get_local("stacklevel").as_python_constant() + 1
333
+ )
334
+ )
335
+
336
+ @staticmethod
337
+ def print_guards():
338
+ comptime(lambda ctx: ctx.print_guards())
339
+
340
+ @staticmethod
341
+ def assert_static(val):
342
+ comptime(lambda ctx: ctx.assert_static(ctx.get_local("val")))
343
+
344
+ @staticmethod
345
+ def force_static(val):
346
+ comptime(lambda ctx: ctx.get_local("val").force_static())
347
+
348
+ @staticmethod
349
+ def breakpoint():
350
+ """
351
+ Like pdb breakpoint(), but drop into pdb whenever this line
352
+ of code is compiled by dynamo. Use it by putting
353
+ this in your model code::
354
+
355
+ from torch._dynamo.comptime import comptime
356
+ comptime.breakpoint()
357
+
358
+ And then, inside pdb, you can access 'ctx' to query things
359
+ about the compilation context::
360
+
361
+ (Pdb) !ctx.print_bt()
362
+ (Pdb) !ctx.print_locals()
363
+ (Pdb) p ctx.get_local("attention").as_fake()
364
+ """
365
+
366
+ def inner(inner_ctx):
367
+ ctx = inner_ctx.parent()
368
+ builtins.breakpoint()
369
+
370
+ comptime(inner)
371
+
372
+
373
+ comptime = _Comptime()
llmeval-env/lib/python3.10/site-packages/torch/_dynamo/config.py ADDED
@@ -0,0 +1,423 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import getpass
2
+ import inspect
3
+ import os
4
+ import re
5
+ import sys
6
+ import tempfile
7
+ from os.path import abspath, dirname
8
+ from typing import Any, Callable, Dict, Optional, Set, Type, TYPE_CHECKING, Union
9
+
10
+ import torch
11
+
12
+ # to configure logging for dynamo, aot, and inductor
13
+ # use the following API in the torch._logging module
14
+ # torch._logging.set_logs(dynamo=<level>, aot=<level>, inductor<level>)
15
+ # or use the environment variable TORCH_LOGS="dynamo,aot,inductor" (use a prefix + to indicate higher verbosity)
16
+ # see this design doc for more detailed info
17
+ # Design doc: https://docs.google.com/document/d/1ZRfTWKa8eaPq1AxaiHrq4ASTPouzzlPiuquSBEJYwS8/edit#
18
+ # the name of a file to write the logs to
19
+ # [@compile_ignored: debug]
20
+ log_file_name: Optional[str] = None
21
+
22
+ # [@compile_ignored: debug] Verbose will print full stack traces on warnings and errors
23
+ verbose = os.environ.get("TORCHDYNAMO_VERBOSE", "0") == "1"
24
+
25
+ # [@compile_ignored: runtime_behaviour] verify the correctness of optimized backend
26
+ verify_correctness = False
27
+
28
+ # need this many ops to create an FX graph
29
+ minimum_call_count = 1
30
+
31
+ # turn on/off DCE pass
32
+ dead_code_elimination = True
33
+
34
+ # disable (for a function) when cache reaches this size
35
+
36
+ # controls the maximum number of cache entries with a guard on same ID_MATCH'd
37
+ # object. It also controls the maximum size of cache entries if they don't have
38
+ # any ID_MATCH'd guards.
39
+ # [@compile_ignored: runtime_behaviour]
40
+ cache_size_limit = 8
41
+
42
+ # [@compile_ignored: runtime_behaviour] controls the maximum number of entries for a code object.
43
+ accumulated_cache_size_limit = 64
44
+
45
+ # whether or not to specialize on int inputs. This only has an effect with
46
+ # dynamic_shapes; when dynamic_shapes is False, we ALWAYS specialize on int
47
+ # inputs. Note that assume_static_by_default will also cause ints to get
48
+ # specialized, so this is mostly useful for export, where we want inputs
49
+ # to be dynamic, but accesses to ints should NOT get promoted into inputs.
50
+ specialize_int = False
51
+
52
+ # legacy config, does nothing now!
53
+ dynamic_shapes = True
54
+
55
+ use_lazy_graph_module = (
56
+ os.environ.get("TORCH_COMPILE_USE_LAZY_GRAPH_MODULE", "1") == "1"
57
+ )
58
+
59
+ # This is a temporarily flag, which changes the behavior of dynamic_shapes=True.
60
+ # When assume_static_by_default is True, we only allocate symbols for shapes marked dynamic via mark_dynamic.
61
+ # NOTE - this flag can be removed once we can run dynamic_shapes=False w/ the mark_dynamic API
62
+ # see [Note - on the state of mark_dynamic]
63
+ assume_static_by_default = True
64
+
65
+ # This flag changes how dynamic_shapes=True works, and is meant to be used in conjunction
66
+ # with assume_static_by_default=True.
67
+ # With this flag enabled, we always compile a frame as fully static for the first time, and, if we fail
68
+ # any guards due to wobbles in shape, we recompile with *all* the wobbled shapes as being marked dynamic.
69
+ automatic_dynamic_shapes = True
70
+
71
+ # This flag changes how the shapes of parameters are treated.
72
+ # If this flag is set to True, then the shapes of torch.nn.Parameter as well as of torch.Tensor are attempted to be dynamic
73
+ # If this flag is set to False, then the shapes of torch.nn.Parameter are assumed to be static,
74
+ # while the shapes of torch.Tensor are assumed to be dynamic.
75
+ force_parameter_static_shapes = True
76
+
77
+ # This flag ensures that the shapes of a nn module are always assumed to be static
78
+ # If the flag is set to True, then the shapes of a nn.module are assumed to be static
79
+ # If the flag is set to False, then the shapes of a nn.module can be dynamic
80
+ force_nn_module_property_static_shapes = True
81
+
82
+ # Typically, if you mark_dynamic a dimension, we will error if the dimension
83
+ # actually ended up getting specialized. This knob changes the behavior so
84
+ # that we don't error at all. This is helpful for our CI where I'm using a
85
+ # heuristic to mark batch dimensions as dynamic and the heuristic may get it
86
+ # wrong.
87
+ allow_ignore_mark_dynamic = False
88
+
89
+ # Set this to False to assume nn.Modules() contents are immutable (similar assumption as freezing)
90
+ guard_nn_modules = False
91
+
92
+ # Uses CPython internal dictionary tags to detect mutation. There is some
93
+ # overlap between guard_nn_modules_using_dict_tags and guard_nn_modules flag.
94
+ # guard_nn_modules unspecializes the nn module instance and adds guard for each
95
+ # relevant member of the nn modules. On the other hand,
96
+ # guard_nn_modules_using_dict_tags specializes on each nn module instance but
97
+ # uses low overhead dict version matching to detect mutations, obviating the
98
+ # need to guard on members of the nn modules. With
99
+ # guard_nn_modules_using_dict_tags, the guard_nn_modules is not really required
100
+ # but kept around for debugging and discussing unspecializing nn module
101
+ # variables.
102
+ # TODO(janimesh, voz): Remove both of these flags (or atleast guard_nn_modules)
103
+ # once we have reached stability for the guard_nn_modules_using_dict_tags.
104
+ guard_nn_modules_using_dict_tags = True
105
+
106
+ # This feature doesn't really work. We offer this flag for experimental
107
+ # purposes / if you want to help us build out support.
108
+ #
109
+ # torchdynamo has very limited support for tensor subclasses that implement
110
+ # __torch_function__. Our current support is limited to tensor subclasses
111
+ # that DO NOT store metadata on the tensor (in general, dynamo does not
112
+ # support Python code that stores extra attributes on tensors at present).
113
+ # If your tensor subclass purely changes function call behavior via
114
+ # __torch_function__, you can allow torchdynamo to trace into it by
115
+ # adding it to traceable_tensor_subclasses. We don't do any safety checks,
116
+ # so it is up to you to ensure that your subclass is well behaved. See also
117
+ # https://github.com/pytorch/torchdynamo/issues/1948
118
+ #
119
+ # We do NOT currently support __torch_dispatch__. The implementation is
120
+ # currently buggy, the main show stopper for nontrivial use is
121
+ # https://github.com/pytorch/torchdynamo/issues/1952
122
+ traceable_tensor_subclasses: Set[Type[Any]] = set()
123
+
124
+ # Suppress errors in torch._dynamo.optimize, instead forcing a fallback to eager.
125
+ # This is a good way to get your model to work one way or another, but you may
126
+ # lose optimization opportunities this way. Devs, if your benchmark model is failing
127
+ # this way, you should figure out why instead of suppressing it.
128
+ suppress_errors = bool(os.environ.get("TORCHDYNAMO_SUPPRESS_ERRORS", False))
129
+
130
+ # Record and write an execution record of the current frame to a file
131
+ # if an exception is encountered
132
+ # @compile_ignored[debug]
133
+ replay_record_enabled = os.environ.get("TORCH_COMPILE_DEBUG", "0") == "1"
134
+
135
+ # Rewrite assert statement in python with torch._assert
136
+ rewrite_assert_with_torch_assert = True
137
+
138
+ # Disable dynamo
139
+ disable = os.environ.get("TORCH_COMPILE_DISABLE", False)
140
+
141
+ # [@compile_ignored: runtime_behaviour] Get a cprofile trace of Dynamo
142
+ cprofile = os.environ.get("TORCH_COMPILE_CPROFILE", False)
143
+
144
+ # legacy config, does nothing now!
145
+ skipfiles_inline_module_allowlist: Dict[Any, Any] = {}
146
+
147
+ # If a string representing a PyTorch module is in this ignorelist,
148
+ # the `allowed_functions.is_allowed` function will not consider it
149
+ # when creating a list of PyTorch functions that will appear in
150
+ # FX IR.
151
+ allowed_functions_module_string_ignorelist = {
152
+ "torch.distributions",
153
+ "torch.testing",
154
+ "torch._refs",
155
+ "torch._prims",
156
+ "torch._decomp",
157
+ }
158
+
159
+ # Debug Flag to try minifier at different stages. Possible values are {None, "aot", "dynamo"}
160
+ # None - Minifier is switched off
161
+ # dynamo - Runs minifier on the TorchDynamo produced graphs, if compilation fails
162
+ # aot - Runs minifier on the Aot Autograd produced graphs, if compilation fails
163
+ # [@compile_ignored: debug]
164
+ repro_after = os.environ.get("TORCHDYNAMO_REPRO_AFTER", None)
165
+
166
+ # Compiler compilation debug info
167
+ # 1: Dumps the original graph out to repro.py if compilation fails
168
+ # 2: Dumps a minifier_launcher.py if compilation fails.
169
+ # 3: Always dumps a minifier_launcher.py. Good for segfaults.
170
+ # 4: Dumps a minifier_launcher.py if the accuracy fails.
171
+ # [@compile_ignored: debug]
172
+ repro_level = int(os.environ.get("TORCHDYNAMO_REPRO_LEVEL", 2))
173
+
174
+ # By default, we try to detect accuracy failure by running both forward
175
+ # and backward of a torchdynamo produced graph (if you are using repro_after
176
+ # 'dynamo'). This setting forces us to only test the forward graph and
177
+ # not the backward graph. This can be helpful if you're trying to debug
178
+ # an inference only problem, but the minifier seems to be choking on the
179
+ # backwards step
180
+ # TODO: Detect this situation automatically so the user doesn't need
181
+ # to manually configure this
182
+ # [@compile_ignored: debug]
183
+ repro_forward_only = os.environ.get("TORCHDYNAMO_REPRO_FORWARD_ONLY") == "1"
184
+
185
+ # The tolerance we should use when testing if a compiled graph
186
+ # has diverged so that we should treat it as an accuracy failure
187
+ # [@compile_ignored: debug]
188
+ repro_tolerance = 1e-3
189
+
190
+ # If True, when testing if two models are the same, we will test them against
191
+ # a third fp64 reference and only report a problem if the RMSE relative to the
192
+ # fp64 is greater. However, this will use more memory; you may disable this
193
+ # if memory usage is too high.
194
+ # [@compile_ignored: runtime_behaviour]
195
+ same_two_models_use_fp64 = True
196
+
197
+ # Not all backends support scalars. Some calls on torch.Tensor (like .item()) return a scalar type.
198
+ # When this flag is set to False, we introduce a graph break instead of capturing.
199
+ # This requires dynamic_shapes to be True.
200
+ capture_scalar_outputs = False
201
+
202
+ # Not all backends support operators that have dynamic output shape (e.g.,
203
+ # nonzero, unique). When this flag is set to False, we introduce a graph
204
+ # break instead of capturing. This requires dynamic_shapes to be True.
205
+ # If you set this to True, you probably also want capture_scalar_outputs
206
+ # (these are separated for historical reasons).
207
+ capture_dynamic_output_shape_ops = False
208
+
209
+ # By default, dynamo will treat all ints as backed SymInts, which means (1) it
210
+ # will wait to see the int change over multiple runs before generalizing and
211
+ # (2) it will still always 0/1 specialize an int. When true, this knob
212
+ # forces dynamo to treat _length_per_key and _offset_per_key on
213
+ # KeyedJaggedTensor from torchrec as size-like unbacked SymInts, so that
214
+ # they (1) generalize immediately and (2) unsoundly never compare equal to
215
+ # 0/1. This is not on by default as AOTAutograd/Inductor cannot currently
216
+ # compile this code; however, this can be useful for export.
217
+ force_unspec_int_unbacked_size_like_on_torchrec_kjt = False
218
+
219
+ # Should almost always be true in prod. This relaxes the requirement that cond's true_fn and
220
+ # false_fn produces code with identical guards.
221
+ enforce_cond_guards_match = True
222
+
223
+ # Specify how to optimize a compiiled DDP module. The flag accepts a bollean
224
+ # value or a string. There are 4 modes.
225
+ # 1. "ddp_optimizer" (or True): with "ddp_ptimizer", Dynamo will automatically
226
+ # split model graph into pieces to match DDP bucket sizes to allow DDP
227
+ # comm/compute overlap.
228
+ # 2. "python_reducer" (experimental): this optimization requires the usage
229
+ # of compiled_autograd. With "python_reducer", DDP will disable the C++ reducer
230
+ # and use the Python reducer to allow compiled_autograd to trace the
231
+ # communication and allow comm/compute overlap without graph-breaks.
232
+ # 3. "python_reducer_without_compiled_forward" (experimental): this mode is
233
+ # similar to "python_reducer". One should only use this optimization mode
234
+ # when compiled_autograd is used but the DDP module is not compiled.
235
+ # 4. "no_optimization" (or False): Dynamo won't split the model graph, nor
236
+ # will Python reducer be used. With this mode, there will be no graph-breaks
237
+ # and the original DDP C++ reducer will be used. There will no comm/compute
238
+ # overlap. This mode CANNOT be used with compiled_autograd.
239
+ # Note that to avoid breaking the existing usage, mode 1 and mode 4 can be
240
+ # specified with a boolean value. True is using ddp_optimizer and False is
241
+ # no optimization.
242
+ optimize_ddp: Union[bool, str] = True
243
+
244
+ _ddp_optimization_mode = [
245
+ "ddp_optimizer",
246
+ "python_reducer", # experimental mode
247
+ "python_reducer_without_compiled_forward", # experimental mode
248
+ "no_optimization",
249
+ ]
250
+
251
+
252
+ def _get_optimize_ddp_mode():
253
+ m = sys.modules[__name__]
254
+ if isinstance(m.optimize_ddp, bool):
255
+ if m.optimize_ddp:
256
+ mode = "ddp_optimizer"
257
+ else:
258
+ mode = "no_optimization"
259
+ elif isinstance(m.optimize_ddp, str):
260
+ mode = m.optimize_ddp
261
+ else:
262
+ raise ValueError(f"Invalid type, {type(optimize_ddp)=}")
263
+
264
+ assert mode in m._ddp_optimization_mode, f"Invalid mode {mode=}"
265
+ return mode
266
+
267
+
268
+ # If True, delays DDPOptimizer submodule compilation to 1st run of the model,
269
+ # so that real tensor strides are used in all submodules
270
+ # (instead of using FakeTensor strides which can differ from real tensor strides and causes error in some cases).
271
+ # This feature is not hardened yet and it's known to cause issues to some models, so False by default.
272
+ optimize_ddp_lazy_compile = False
273
+
274
+ # Whether to skip guarding on FSDP-managed modules
275
+ skip_fsdp_guards = True
276
+
277
+ # Make dynamo skip guarding on hooks on nn modules
278
+ # Note: unsafe: if your model actually has hooks and you remove them, or doesn't and you add them,
279
+ # dynamo will not notice and will execute whichever version you first compiled.
280
+ skip_nnmodule_hook_guards = True
281
+
282
+ # If True, raises exception if TorchDynamo is called with a context manager
283
+ raise_on_ctx_manager_usage = True
284
+
285
+ # If True, raise when aot autograd is unsafe to use
286
+ raise_on_unsafe_aot_autograd = False
287
+
288
+ # If true, error if you torch.jit.trace over a dynamo-optimized function.
289
+ # If false, silently suppress dynamo
290
+ error_on_nested_jit_trace = True
291
+
292
+ # If true, error with a better message if we symbolically trace over a
293
+ # dynamo-optimized function. If false, silently suppress dynamo.
294
+ error_on_nested_fx_trace = True
295
+
296
+ # Disables graph breaking on rnn. YMMV with backends.
297
+ allow_rnn = False
298
+
299
+ # If true, error if we try to compile a function that has
300
+ # been seen before.
301
+ # [@compile_ignored: runtime_behaviour]
302
+ error_on_recompile = False
303
+
304
+ # [@compile_ignored: debug] Whether to report any guard failures (deprecated: does not do anything)
305
+ report_guard_failures = True
306
+
307
+ # [@compile_ignored: debug] root folder of the project
308
+ base_dir = dirname(dirname(dirname(abspath(__file__))))
309
+
310
+ # Trace through NumPy or graphbreak
311
+ trace_numpy = True
312
+
313
+ # Trace through torch.distributed code
314
+ trace_distributed = False
315
+
316
+ # Default NumPy dtypes when tracing with torch.compile
317
+ # We default to 64bits. For efficiency, one may want to change these to float32
318
+ numpy_default_float = "float64"
319
+ numpy_default_complex = "complex128"
320
+ numpy_default_int = "int64"
321
+
322
+ # use numpy's PRNG if True, pytorch otherwise
323
+ use_numpy_random_stream = False
324
+
325
+
326
+ def is_fbcode():
327
+ return not hasattr(torch.version, "git_version")
328
+
329
+
330
+ def default_debug_dir_root():
331
+ # [@compile_ignored: debug]
332
+ DEBUG_DIR_VAR_NAME = "TORCH_COMPILE_DEBUG_DIR"
333
+ if DEBUG_DIR_VAR_NAME in os.environ:
334
+ return os.path.join(os.environ[DEBUG_DIR_VAR_NAME], "torch_compile_debug")
335
+ elif is_fbcode():
336
+ return os.path.join(
337
+ tempfile.gettempdir(), getpass.getuser(), "torch_compile_debug"
338
+ )
339
+ else:
340
+ return os.path.join(os.getcwd(), "torch_compile_debug")
341
+
342
+
343
+ # [@compile_ignored: debug]
344
+ debug_dir_root = default_debug_dir_root()
345
+
346
+ # [@compile_ignored: debug]
347
+ _save_config_ignore = {
348
+ "repro_after",
349
+ "repro_level",
350
+ # workaround: "cannot pickle PyCapsule"
351
+ "constant_functions",
352
+ # workaround: "cannot pickle module"
353
+ "skipfiles_inline_module_allowlist",
354
+ }
355
+
356
+ # for backend="cudagraphs", mutations on input be sent to the cudagraph backend
357
+ # or replayed in aot_autograd epilogue. default is False because mutation on inputs
358
+ # can prevent cudagraphing.
359
+ cudagraph_backend_keep_input_mutation = False
360
+
361
+ # When True, only ops that have the torch.Tag.pt2_compliant tag
362
+ # will be allowed into the graph; all other ops will be disallowed
363
+ # and will fall back to eager-mode PyTorch. Useful to ensure
364
+ # correctness of custom ops.
365
+ only_allow_pt2_compliant_ops = False
366
+
367
+ capture_autograd_function = True
368
+
369
+ # enable/disable dynamo tracing for `torch.func` transforms
370
+ capture_func_transforms = False
371
+
372
+ # enable/disable user-defined triton kernel optimizations
373
+ optimize_user_defined_triton_kernels = True
374
+
375
+ # If to log Dynamo compilation metrics into log files (for OSS) and Scuba tables (for fbcode).
376
+ log_compilation_metrics = True
377
+
378
+ # A set of logging functions which will be reordered to the end of graph breaks,
379
+ # allowing dynamo to construct larget graph. Note that there are some
380
+ # limitations to this, such as how it does not correctly print objects that were
381
+ # mutated after the print statement.
382
+ reorderable_logging_functions: Set[Callable[[Any], None]] = set()
383
+
384
+ # simulates what would happen if we didn't have support for BUILD_SET opcode,
385
+ # used for testing
386
+ inject_BUILD_SET_unimplemented_TESTING_ONLY = False
387
+
388
+ _autograd_backward_strict_mode_banned_ops = [
389
+ "stride",
390
+ "requires_grad",
391
+ "storage_offset",
392
+ "layout",
393
+ "data",
394
+ ]
395
+
396
+ _autograd_backward_strict_mode_banned_ops.extend(
397
+ [name for name, _ in inspect.getmembers(torch.Tensor) if re.match(r"^is_.*", name)]
398
+ )
399
+
400
+ # Enables caching of dispatches to fake tensors.
401
+ fake_tensor_cache_enabled = (
402
+ os.environ.get("TORCH_FAKE_TENSOR_DISPATCH_CACHE", "1") == "1"
403
+ )
404
+
405
+ # Enables cross checking between the fake tensor cache and dispatch.
406
+ fake_tensor_cache_crosscheck_enabled = (
407
+ os.environ.get("TORCH_FAKE_TENSOR_DISPATCH_CACHE_CROSSCHECK", "0") == "1"
408
+ )
409
+
410
+ # support `context_fn` in torch.utils.checkpoint.checkpoint API under torch.compile().
411
+ # WARNING: this is an experimental flag and is subject to change.
412
+ _experimental_support_context_fn_in_torch_utils_checkpoint = False
413
+
414
+ if TYPE_CHECKING:
415
+ from torch.utils._config_typing import * # noqa: F401, F403
416
+
417
+ def _make_closure_patcher(**changes):
418
+ ...
419
+
420
+
421
+ from torch.utils._config_module import install_config_module
422
+
423
+ install_config_module(sys.modules[__name__])
llmeval-env/lib/python3.10/site-packages/torch/_dynamo/convert_frame.py ADDED
@@ -0,0 +1,924 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import collections
2
+ import dis
3
+ import functools
4
+ import itertools
5
+ import logging
6
+ import os
7
+ import random
8
+ import sys
9
+ import threading
10
+ import time
11
+ import traceback
12
+ import types
13
+ import typing
14
+ import weakref
15
+ from typing import Any, Callable, Dict, List, Optional, Set
16
+
17
+ from torch.fx._lazy_graph_module import ( # type: ignore[attr-defined]
18
+ _use_lazy_graph_module,
19
+ )
20
+
21
+ try:
22
+ import numpy as np
23
+ except ModuleNotFoundError:
24
+ np = None # type: ignore[assignment]
25
+
26
+ import torch
27
+ import torch._logging
28
+ from torch._guards import compile_context, CompileContext, CompileId, tracing
29
+ from torch._logging import structured
30
+ from torch._utils_internal import signpost_event
31
+ from torch.fx.experimental.symbolic_shapes import (
32
+ ConstraintViolationError,
33
+ GuardOnDataDependentSymNode,
34
+ )
35
+ from torch.fx.graph_module import _forward_from_src as original_forward_from_src
36
+ from torch.nn.parallel.distributed import DistributedDataParallel
37
+ from torch.utils._python_dispatch import _disable_current_modes
38
+ from torch.utils._traceback import format_traceback_short
39
+
40
+ from . import config, exc, trace_rules
41
+ from .backends.registry import CompilerFn
42
+ from .bytecode_analysis import remove_dead_code, remove_pointless_jumps
43
+ from .bytecode_transformation import (
44
+ check_inst_exn_tab_entries_valid,
45
+ Instruction,
46
+ is_generator,
47
+ propagate_inst_exn_table_entries,
48
+ transform_code_object,
49
+ )
50
+ from .cache_size import (
51
+ CacheSizeRelevantForFrame,
52
+ compute_cache_size,
53
+ exceeds_cache_size_limit,
54
+ is_recompilation,
55
+ )
56
+ from .eval_frame import always_optimize_code_objects, skip_code, TorchPatcher
57
+ from .exc import (
58
+ augment_exc_message,
59
+ BackendCompilerFailed,
60
+ format_error_msg,
61
+ InternalTorchDynamoError,
62
+ TorchRuntimeError,
63
+ UncapturedHigherOrderOpError,
64
+ unimplemented,
65
+ Unsupported,
66
+ )
67
+ from .guards import (
68
+ CheckFunctionManager,
69
+ get_and_maybe_log_recompilation_reason,
70
+ GuardedCode,
71
+ )
72
+ from .hooks import Hooks
73
+ from .output_graph import OutputGraph
74
+ from .replay_record import ExecutionRecord
75
+ from .symbolic_convert import InstructionTranslator, SpeculationLog
76
+ from .trace_rules import is_numpy
77
+ from .types import BytecodeHook
78
+ from .utils import (
79
+ CleanupManager,
80
+ CompilationMetrics,
81
+ counters,
82
+ dynamo_timed,
83
+ format_bytecode,
84
+ frame_phase_timing,
85
+ gen_record_file_name,
86
+ increment_frame,
87
+ is_namedtuple,
88
+ istype,
89
+ LazyString,
90
+ maybe_cprofile,
91
+ orig_code_map,
92
+ record_compilation_metrics,
93
+ reset_graph_break_dup_checker,
94
+ setup_compile_debug,
95
+ troubleshooting_url,
96
+ write_record_to_file,
97
+ )
98
+
99
+ log = logging.getLogger(__name__)
100
+ bytecode_log = torch._logging.getArtifactLogger(__name__, "bytecode")
101
+ GlobalStateGuard = torch._C._dynamo.guards.GlobalStateGuard
102
+
103
+ compile_lock = threading.RLock()
104
+
105
+
106
+ class Tracker:
107
+ def __init__(self):
108
+ self.seen = []
109
+ self.seen_ids = set()
110
+
111
+ def add(self, strong_obj):
112
+ idx = id(strong_obj)
113
+ if idx not in self.seen_ids:
114
+ obj = weakref.ref(strong_obj, lambda _: self.seen_ids.remove(idx))
115
+ self.seen.append(obj)
116
+ self.seen_ids.add(idx)
117
+
118
+ def __contains__(self, item):
119
+ return id(item) in self.seen_ids
120
+
121
+ def clear(self):
122
+ self.seen.clear()
123
+ self.seen_ids.clear()
124
+
125
+
126
+ input_codes = Tracker()
127
+ output_codes = Tracker()
128
+
129
+ initial_global_state: Optional[GlobalStateGuard] = None
130
+
131
+
132
+ @functools.wraps(original_forward_from_src)
133
+ def fx_forward_from_src_skip_result(*args, **kwargs):
134
+ # we monkey patch FX to prevent infinite loop of trying to convert
135
+ # our generated code
136
+ result: types.FunctionType = original_forward_from_src(*args, **kwargs)
137
+ skip_code(result.__code__)
138
+ return result
139
+
140
+
141
+ def preserve_global_state(fn):
142
+ """
143
+ Context manager to:
144
+ 1) Save/restore torch.is_grad_enabled() state
145
+ 2) Save/restore python random state
146
+ 3) Save/restore torch random state
147
+ 4) Monkey patch torch.fx.graph_module._forward_from_src
148
+ """
149
+
150
+ @functools.wraps(fn)
151
+ def _fn(*args, **kwargs):
152
+ guards = GlobalStateGuard()
153
+ prior_grad_mode = torch.is_grad_enabled()
154
+ prior_inference_mode = torch.is_inference_mode_enabled()
155
+ prior_deterministic = torch.are_deterministic_algorithms_enabled()
156
+ prior_warn_only = torch.is_deterministic_algorithms_warn_only_enabled()
157
+ py_rng_state = random.getstate()
158
+ torch_rng_state = torch.random.get_rng_state()
159
+ if torch.cuda.is_available():
160
+ cuda_rng_state = torch.cuda.get_rng_state()
161
+ prior_fwd_from_src = torch.fx.graph_module._forward_from_src
162
+ torch.fx.graph_module._forward_from_src = fx_forward_from_src_skip_result
163
+ cleanup = setup_compile_debug()
164
+ try:
165
+ return fn(*args, **kwargs)
166
+ finally:
167
+ cleanup.close()
168
+ torch._C._set_grad_enabled(prior_grad_mode)
169
+ torch.torch.autograd.grad_mode._enter_inference_mode(prior_inference_mode)
170
+ torch.use_deterministic_algorithms(
171
+ prior_deterministic, warn_only=prior_warn_only
172
+ )
173
+ random.setstate(py_rng_state)
174
+ torch.random.set_rng_state(torch_rng_state)
175
+ if torch.cuda.is_available():
176
+ torch.cuda.set_rng_state(cuda_rng_state) # type: ignore[possibly-undefined]
177
+ torch.fx.graph_module._forward_from_src = prior_fwd_from_src
178
+ assert (
179
+ guards.check()
180
+ ), "Global state changed while dynamo tracing, please report a bug"
181
+
182
+ _fn._torchdynamo_orig_callable = fn # type: ignore[attr-defined]
183
+ return _fn
184
+
185
+
186
+ @TorchPatcher.suppress_torch_distributed_warnings
187
+ def has_tensor_in_frame(frame):
188
+ """Check if the frame has torch.* related bits"""
189
+ # Check if the function was decorated using torch._dynamo.optimize
190
+ if frame.f_code in always_optimize_code_objects:
191
+ return True
192
+
193
+ # Check if there is global import of torch.*
194
+ for co_name in frame.f_code.co_names:
195
+ if co_name in frame.f_globals:
196
+ obj = frame.f_globals[co_name]
197
+ if isinstance(obj, types.ModuleType) and (
198
+ obj.__name__.startswith("torch.") or obj is torch
199
+ ):
200
+ return True
201
+ # ... or a global import of numpy.*
202
+ if np and config.trace_numpy and (obj is np or is_numpy(obj)):
203
+ return True
204
+
205
+ seen_ids: Dict[int, bool] = dict()
206
+
207
+ def has_tensor(obj):
208
+ """Recursively check if the obj has a tensor"""
209
+ obj_id = id(obj)
210
+ if obj_id in seen_ids:
211
+ return seen_ids[obj_id]
212
+ seen_ids[obj_id] = False
213
+
214
+ if isinstance(obj, (torch.Tensor, torch.nn.Module)) or (
215
+ istype(obj, type) and issubclass(obj, torch.nn.Module)
216
+ ):
217
+ seen_ids[obj_id] = True
218
+ return seen_ids[obj_id]
219
+ elif (
220
+ config.trace_numpy
221
+ and np
222
+ and (istype(obj, np.ndarray) or isinstance(obj, np.generic))
223
+ ):
224
+ seen_ids[obj_id] = True
225
+ return seen_ids[obj_id]
226
+ elif istype(obj, (list, tuple)):
227
+ seen_ids[obj_id] = any(has_tensor(v) for v in obj)
228
+ return seen_ids[obj_id]
229
+ elif istype(obj, dict):
230
+ # Some packages like pytest can be updated during runtime. So, make a
231
+ # copy of values to avoid issues like "RuntimeError: dictionary
232
+ # changed size during iteration"
233
+ values = list(obj.values())
234
+ seen_ids[obj_id] = any(has_tensor(v) for v in values)
235
+ return seen_ids[obj_id]
236
+ elif istype(obj, (str, int, float, type(None), bool)):
237
+ seen_ids[obj_id] = False
238
+ return seen_ids[obj_id]
239
+ elif is_namedtuple(obj) and hasattr(obj, "_fields"):
240
+ seen_ids[obj_id] = any(has_tensor(getattr(obj, v)) for v in obj._fields)
241
+ return seen_ids[obj_id]
242
+ else:
243
+ # if config.debug:
244
+ # print(
245
+ # f"Assuming that object of type {type(obj)} does not have a tensor"
246
+ # )
247
+ return False
248
+
249
+ # Check if the passed arguments are of type Tensor
250
+ for value in frame.f_locals.values():
251
+ if has_tensor(value):
252
+ return True
253
+
254
+ log.debug(
255
+ "skipping because no torch.* %s \
256
+ %s %s",
257
+ frame.f_code.co_name,
258
+ frame.f_code.co_filename,
259
+ frame.f_code.co_firstlineno,
260
+ )
261
+
262
+ return False
263
+
264
+
265
+ def exception_handler(e, code, frame=None, export=False):
266
+ record_filename = None
267
+ if hasattr(e, "exec_record"):
268
+ record_filename = gen_record_file_name(e, code)
269
+ write_record_to_file(record_filename, e.exec_record)
270
+ e.record_filename = record_filename
271
+
272
+ augment_exc_message(e, export=export)
273
+
274
+
275
+ FRAME_COUNTER = 0
276
+ FRAME_COMPILE_COUNTER: typing.Counter[int] = collections.Counter()
277
+
278
+
279
+ def convert_frame_assert(
280
+ compiler_fn: CompilerFn,
281
+ one_graph: bool = True,
282
+ export: bool = False,
283
+ export_constraints=None,
284
+ ):
285
+ """Fully convert a frame into an FX graph"""
286
+ reset_graph_break_dup_checker()
287
+
288
+ def _convert_frame_assert(
289
+ frame: types.FrameType, cache_entry, hooks: Hooks, frame_state, *, skip: int = 0
290
+ ):
291
+ increment_frame()
292
+
293
+ code = frame.f_code
294
+
295
+ cache_size = compute_cache_size(frame, cache_entry)
296
+ recompile_reasons = None
297
+ if is_recompilation(cache_size):
298
+ recompile_reasons = get_and_maybe_log_recompilation_reason(
299
+ cache_entry, frame
300
+ )
301
+
302
+ input_codes.add(code)
303
+ if code in output_codes:
304
+ return None
305
+ if (
306
+ os.environ.get("TORCHDYNAMO_DEBUG_FUNCTION")
307
+ and os.environ.get("TORCHDYNAMO_DEBUG_FUNCTION") != code.co_name
308
+ ):
309
+ return None
310
+ if code.co_name == "<genexpr>" and code.co_filename.endswith(
311
+ (
312
+ "transformers/file_utils.py",
313
+ "transformers/utils/generic.py",
314
+ "diffusers/utils/outputs.py",
315
+ )
316
+ ):
317
+ # not needed, but cleans up torchbench error stats
318
+ return None
319
+ if code.co_name == "__setattr__":
320
+ # setattr could be tricky to handle generally,
321
+ # but also not likely useful to compile- skip the whole frame
322
+ return None
323
+ if code.co_name == "__init__" and code.co_filename.startswith(
324
+ os.path.dirname(torch.optim.__file__)
325
+ ):
326
+ # optimizer support is still incomplete see
327
+ # test_state_dict in test/dynamo/test_optimizers.py
328
+ return None
329
+
330
+ # Check if the frame is generated by an exec builtin call
331
+ # TODO - Running exec generated frame seems propagates f_globals to the
332
+ # next frames.
333
+ if code.co_name == "<module>" and code.co_filename == "<string>":
334
+ return None
335
+
336
+ if (
337
+ code.co_name == "<lambda>"
338
+ and code.co_filename == "<string>"
339
+ and not bool(frame.f_builtins)
340
+ ):
341
+ # namedtuple subclass constructor. Empty builtins cause issue with
342
+ # len keyword in LIST_LEN guard.
343
+ return None
344
+
345
+ if is_generator(code):
346
+ unimplemented("generator")
347
+ exceeded, limit_type = exceeds_cache_size_limit(cache_size)
348
+ if exceeded:
349
+
350
+ def format_func_info(code):
351
+ return f"'{code.co_name}' ({code.co_filename}:{code.co_firstlineno})"
352
+
353
+ def format_guard_failures():
354
+ assert recompile_reasons, "TODO(whc) any other recompile reasons?"
355
+ return recompile_reasons[-1]
356
+
357
+ log.warning(
358
+ "torch._dynamo hit config.%s (%s)\n"
359
+ " function: %s\n"
360
+ " last reason: %s\n"
361
+ 'To log all recompilation reasons, use TORCH_LOGS="recompiles".\n'
362
+ "To diagnose recompilation issues, see %s.",
363
+ limit_type,
364
+ getattr(config, limit_type),
365
+ format_func_info(code),
366
+ format_guard_failures(),
367
+ troubleshooting_url,
368
+ )
369
+ unimplemented(f"{limit_type} reached")
370
+
371
+ if not has_tensor_in_frame(frame):
372
+ return None
373
+
374
+ global initial_global_state
375
+ initial_global_state = GlobalStateGuard()
376
+
377
+ global FRAME_COUNTER
378
+ if "_id" not in frame_state:
379
+ frame_state["_id"] = FRAME_COUNTER
380
+ FRAME_COUNTER += 1
381
+ frame_id = frame_state["_id"]
382
+
383
+ frame_compile_id = FRAME_COMPILE_COUNTER[frame_id]
384
+ FRAME_COMPILE_COUNTER[frame_id] += 1
385
+
386
+ compile_id = CompileId(frame_id, frame_compile_id)
387
+
388
+ signpost_event(
389
+ "dynamo",
390
+ "_convert_frame_assert._compile",
391
+ {
392
+ "co_name": code.co_name,
393
+ "co_filename": code.co_filename,
394
+ "co_firstlineno": code.co_firstlineno,
395
+ "cache_size": cache_size.num_cache_entries_with_same_id_matched_objs,
396
+ "accumulated_cache_size": cache_size.num_cache_entries,
397
+ },
398
+ )
399
+
400
+ return _compile(
401
+ frame.f_code,
402
+ frame.f_globals,
403
+ frame.f_locals,
404
+ frame.f_builtins,
405
+ compiler_fn,
406
+ one_graph,
407
+ export,
408
+ export_constraints,
409
+ hooks,
410
+ cache_size,
411
+ frame,
412
+ frame_state=frame_state,
413
+ compile_id=compile_id,
414
+ skip=skip + 1,
415
+ )
416
+
417
+ _convert_frame_assert._torchdynamo_orig_callable = compiler_fn # type: ignore[attr-defined]
418
+
419
+ def _clone_with_backend(backend):
420
+ return convert_frame_assert(backend, one_graph, export, export_constraints)
421
+
422
+ _convert_frame_assert._clone_with_backend = _clone_with_backend # type: ignore[attr-defined]
423
+ return _convert_frame_assert
424
+
425
+
426
+ from collections import OrderedDict
427
+
428
+ from torch.utils.hooks import RemovableHandle
429
+
430
+ # we have to use `OrderedDict` to make `RemovableHandle` work.
431
+ _bytecode_hooks: Dict[int, BytecodeHook] = OrderedDict()
432
+
433
+
434
+ def register_bytecode_hook(hook: BytecodeHook) -> RemovableHandle:
435
+ """Register hooks for bytecode generated by Dynamo. The hook can do some
436
+ logging, as well as return a new code object to be used. Please refer
437
+ to `BytecodeHook` for the hook signature.
438
+ """
439
+ handle = RemovableHandle(_bytecode_hooks)
440
+ _bytecode_hooks[handle.id] = hook
441
+ return handle
442
+
443
+
444
+ @_use_lazy_graph_module(config.use_lazy_graph_module)
445
+ @maybe_cprofile
446
+ def _compile(
447
+ code: types.CodeType,
448
+ globals: Dict[str, object],
449
+ locals: Dict[str, object],
450
+ builtins: Dict[str, object],
451
+ compiler_fn: CompilerFn,
452
+ one_graph: bool,
453
+ export: bool,
454
+ export_constraints,
455
+ hooks: Hooks,
456
+ cache_size: CacheSizeRelevantForFrame,
457
+ frame: Optional[types.FrameType] = None,
458
+ frame_state=None,
459
+ compile_id=None,
460
+ *,
461
+ skip: int = 0,
462
+ ) -> Optional[GuardedCode]:
463
+ from torch.fx.experimental.validator import (
464
+ bisect,
465
+ BisectValidationException,
466
+ translation_validation_enabled,
467
+ ValidationException,
468
+ )
469
+
470
+ output: Optional[OutputGraph] = None
471
+ tracer: Optional[InstructionTranslator] = None
472
+ # This is shared across restarts
473
+ mutated_closure_cell_contents: Set[str] = set()
474
+ speculation_log = SpeculationLog()
475
+ torch._dynamo.callback_handler.run_start_callbacks()
476
+
477
+ @preserve_global_state
478
+ def transform(instructions, code_options):
479
+ nonlocal output
480
+ nonlocal tracer
481
+ speculation_log.restart()
482
+ tracer = InstructionTranslator(
483
+ instructions,
484
+ code,
485
+ locals,
486
+ globals,
487
+ builtins,
488
+ code_options,
489
+ compiler_fn,
490
+ one_graph,
491
+ export,
492
+ export_constraints,
493
+ mutated_closure_cell_contents,
494
+ frame_state=frame_state,
495
+ speculation_log=speculation_log,
496
+ )
497
+
498
+ try:
499
+ with tracing(tracer.output.tracing_context), tracer.set_current_tx():
500
+ tracer.run()
501
+ except exc.UnspecializeRestartAnalysis:
502
+ speculation_log.clear()
503
+ raise
504
+ except (exc.SpeculationRestartAnalysis, exc.SkipFrame):
505
+ raise
506
+ except Exception:
507
+ if translation_validation_enabled():
508
+ bisect(tracer.output.shape_env)
509
+ raise
510
+ finally:
511
+ tracer.output.call_cleanup_hooks()
512
+
513
+ output = tracer.output
514
+ assert output is not None
515
+ assert output.output_instructions
516
+ instructions[:] = output.output_instructions
517
+ code_options.update(output.code_options)
518
+
519
+ if config.dead_code_elimination:
520
+ propagate_inst_exn_table_entries(instructions)
521
+ check_inst_exn_tab_entries_valid(instructions)
522
+ instructions[:] = remove_pointless_jumps(remove_dead_code(instructions))
523
+
524
+ @dynamo_timed(phase_name="entire_frame_compile")
525
+ def compile_inner(
526
+ code: types.CodeType,
527
+ one_graph: bool,
528
+ hooks: Hooks,
529
+ transform: Callable[[List[Instruction], Dict[str, Any]], Any],
530
+ ) -> Optional[GuardedCode]:
531
+ nonlocal output
532
+ for attempt in itertools.count():
533
+ CompileContext.get().attempt = attempt
534
+ try:
535
+ out_code = transform_code_object(code, transform)
536
+ break
537
+ except exc.RestartAnalysis as e:
538
+ log.info(
539
+ "Restarting analysis due to %s",
540
+ LazyString(format_traceback_short, e.__traceback__),
541
+ )
542
+ if attempt > 100:
543
+ unimplemented("100+ RestartAnalysis() calls")
544
+ except exc.SkipFrame as e:
545
+ log.debug(
546
+ "Skipping frame %s %s \
547
+ %s %s",
548
+ e,
549
+ code.co_name,
550
+ code.co_filename,
551
+ code.co_firstlineno,
552
+ )
553
+ if one_graph:
554
+ log.debug("No graph captured with one_graph=True")
555
+ return None
556
+
557
+ def log_bytecode(prefix, name, filename, line_no, code):
558
+ if bytecode_log.isEnabledFor(logging.DEBUG):
559
+ bytecode_log.debug(
560
+ format_bytecode(prefix, name, filename, line_no, code)
561
+ )
562
+
563
+ log_bytecode(
564
+ "ORIGINAL BYTECODE",
565
+ code.co_name,
566
+ code.co_filename,
567
+ code.co_firstlineno,
568
+ code,
569
+ )
570
+ log_bytecode(
571
+ "MODIFIED BYTECODE",
572
+ code.co_name,
573
+ code.co_filename,
574
+ code.co_firstlineno,
575
+ out_code, # type: ignore[possibly-undefined]
576
+ )
577
+
578
+ for hook in _bytecode_hooks.values():
579
+ hook_output = hook(code, out_code)
580
+ if hook_output is not None:
581
+ out_code = hook_output
582
+
583
+ orig_code_map[out_code] = code
584
+ output_codes.add(out_code)
585
+
586
+ assert output is not None
587
+
588
+ # Tests for new code objects.
589
+ # The rationale for these tests can be found in torch/csrc/dynamo/eval_frame.c
590
+ # Only test once the code object is created.
591
+ # They are not tested during runtime.
592
+
593
+ def count_args(code):
594
+ import inspect
595
+
596
+ return (
597
+ code.co_argcount
598
+ + code.co_kwonlyargcount
599
+ + bool(code.co_flags & inspect.CO_VARARGS)
600
+ + bool(code.co_flags & inspect.CO_VARKEYWORDS)
601
+ )
602
+
603
+ total_argcount_old = count_args(code)
604
+ total_argcount_new = count_args(out_code)
605
+ msg = "arg mismatch: "
606
+ msg += f"old code object has args {code.co_varnames[:total_argcount_old]}, "
607
+ msg += f"new code object has args {out_code.co_varnames[:total_argcount_new]}"
608
+ assert (
609
+ code.co_varnames[:total_argcount_old]
610
+ == out_code.co_varnames[:total_argcount_new]
611
+ ), msg
612
+
613
+ msg = "free var mismatch: "
614
+ msg += f"old code object has free var {code.co_freevars}, "
615
+ msg += f"new code object has free var {out_code.co_freevars}"
616
+ assert code.co_freevars == out_code.co_freevars, msg
617
+
618
+ msg = "cell var mismatch: "
619
+ msg += f"old code object has cell var {code.co_cellvars}, "
620
+ msg += f"new code object has cell var {out_code.co_cellvars}"
621
+ assert code.co_cellvars == out_code.co_cellvars, msg
622
+
623
+ # Skipping Dynamo on a frame without any extracted graph.
624
+ # This does not affect eager functionality. But this is necessary
625
+ # for export for cases where Dynamo-reconstructed bytecode can create
626
+ # new function frames, confusing export in thinking that there
627
+ # are extra graphs now.
628
+
629
+ if output.export and output.is_empty_graph():
630
+ return None
631
+
632
+ assert output.guards is not None
633
+ CleanupManager.instance[out_code] = output.cleanups
634
+ check_fn = CheckFunctionManager(
635
+ output,
636
+ hooks.guard_fail_fn if hooks else None,
637
+ )
638
+
639
+ guarded_code = GuardedCode(out_code, check_fn.check_fn)
640
+
641
+ if not output.is_empty_graph() and hooks.guard_export_fn is not None:
642
+ # We should not run the guard_export_fn when Dynamo does not
643
+ # generate any graph. This can happen in export when TorchDynamo
644
+ # generated bytecode has some reconstruction logic for mutated
645
+ # variables which can trigger TorchDynamo on the children frames but
646
+ # they are benign and do not generate any new graphs.
647
+ hooks.guard_export_fn(output.guards)
648
+
649
+ return guarded_code
650
+
651
+ with compile_context(CompileContext(compile_id)):
652
+ log.debug(
653
+ "torchdynamo start compiling %s %s:%s, stack (elided %s frames):\n%s",
654
+ code.co_name,
655
+ code.co_filename,
656
+ code.co_firstlineno,
657
+ skip + 2,
658
+ # -2: omit current frame, omit contextlib decorator
659
+ "".join(traceback.format_list(traceback.extract_stack()[: -2 - skip])),
660
+ )
661
+ # -4: -2 as above, plus trace_structured frames
662
+ torch._logging.trace_structured(
663
+ "dynamo_start",
664
+ lambda: {
665
+ "stack": structured.from_traceback(
666
+ traceback.extract_stack()[: -4 - skip]
667
+ )
668
+ },
669
+ )
670
+ start_time = time.time()
671
+ fail_type: Optional[str] = None
672
+ fail_reason: Optional[str] = None
673
+ fail_user_frame_filename: Optional[str] = None
674
+ fail_user_frame_lineno: Optional[int] = None
675
+ try:
676
+ guarded_code = compile_inner(code, one_graph, hooks, transform)
677
+ return guarded_code
678
+ except (
679
+ Unsupported,
680
+ TorchRuntimeError,
681
+ BackendCompilerFailed,
682
+ AssertionError,
683
+ ConstraintViolationError,
684
+ GuardOnDataDependentSymNode,
685
+ ValidationException,
686
+ UncapturedHigherOrderOpError,
687
+ BisectValidationException,
688
+ ) as e:
689
+ fail_type = str(type(e))
690
+ fail_reason = str(e)
691
+ exception_handler(e, code, frame, export=export)
692
+ if e.innermost_user_frame_summary is not None: # type: ignore[union-attr]
693
+ fail_user_frame_filename = e.innermost_user_frame_summary.filename # type: ignore[union-attr]
694
+ fail_user_frame_lineno = e.innermost_user_frame_summary.lineno # type: ignore[union-attr]
695
+ raise
696
+ except Exception as e:
697
+ fail_type = str(type(e))
698
+ fail_reason = str(e)
699
+ exception_handler(e, code, frame, export=export)
700
+ if e.innermost_user_frame_summary is not None: # type: ignore[attr-defined]
701
+ fail_user_frame_filename = e.innermost_user_frame_summary.filename # type: ignore[attr-defined]
702
+ fail_user_frame_lineno = e.innermost_user_frame_summary.lineno # type: ignore[attr-defined]
703
+ raise InternalTorchDynamoError(str(e)).with_traceback(
704
+ e.__traceback__
705
+ ) from None
706
+ finally:
707
+ if tracer:
708
+ tracer.output.local_scope = {}
709
+
710
+ from .utils import curr_frame
711
+
712
+ frame_key = str(curr_frame)
713
+ if (
714
+ fail_reason is None
715
+ and output is not None
716
+ and frame_key in frame_phase_timing
717
+ ):
718
+ guard_count = len(output.guards)
719
+ shape_env_guard_count = len(output.shape_env.guards)
720
+ graph_op_count = output.count_calls()
721
+ graph_node_count = len(output.graph.nodes)
722
+ graph_input_count = len(output.placeholders)
723
+ entire_frame_compile_time = frame_phase_timing[frame_key].get(
724
+ "entire_frame_compile", None
725
+ )
726
+ backend_compile_time = frame_phase_timing[frame_key].get(
727
+ "backend_compile", None
728
+ )
729
+ inductor_compile_time = frame_phase_timing[frame_key].get(
730
+ "inductor_compile", None
731
+ )
732
+ code_gen_time = frame_phase_timing[frame_key].get("code_gen", None)
733
+ non_compliant_ops = {op.__qualname__ for op in output.non_compliant_ops}
734
+ compliant_custom_ops = {
735
+ op.__qualname__ for op in output.compliant_custom_ops
736
+ }
737
+ else:
738
+ guard_count = None
739
+ shape_env_guard_count = None
740
+ graph_op_count = None
741
+ graph_node_count = None
742
+ graph_input_count = None
743
+ entire_frame_compile_time = None
744
+ backend_compile_time = None
745
+ inductor_compile_time = None
746
+ code_gen_time = None
747
+ non_compliant_ops = set({})
748
+ compliant_custom_ops = set({})
749
+ metrics = CompilationMetrics(
750
+ frame_key,
751
+ code.co_name,
752
+ code.co_filename,
753
+ code.co_firstlineno,
754
+ cache_size.num_cache_entries_with_same_id_matched_objs,
755
+ cache_size.num_cache_entries,
756
+ guard_count,
757
+ shape_env_guard_count,
758
+ graph_op_count,
759
+ graph_node_count,
760
+ graph_input_count,
761
+ start_time,
762
+ entire_frame_compile_time,
763
+ backend_compile_time,
764
+ inductor_compile_time,
765
+ code_gen_time,
766
+ fail_type,
767
+ fail_reason,
768
+ fail_user_frame_filename,
769
+ fail_user_frame_lineno,
770
+ non_compliant_ops,
771
+ compliant_custom_ops,
772
+ )
773
+ record_compilation_metrics(metrics)
774
+ torch._dynamo.callback_handler.run_end_callbacks()
775
+
776
+
777
+ def convert_frame(compiler_fn: CompilerFn, hooks: Hooks):
778
+ """Try to convert a frame into an FX graph, if error leave frame unmodified"""
779
+ inner_convert = convert_frame_assert(compiler_fn, one_graph=False)
780
+
781
+ def _convert_frame(
782
+ frame: types.FrameType, cache_entry, hooks: Hooks, frame_state, skip: int = 0
783
+ ):
784
+ counters["frames"]["total"] += 1
785
+ try:
786
+ result = inner_convert(
787
+ frame, cache_entry, hooks, frame_state, skip=skip + 1
788
+ )
789
+ counters["frames"]["ok"] += 1
790
+ return result
791
+ except Exception as e:
792
+ # These two exception types are "soft" failure, in the sense that
793
+ # we know this is due to something we didn't implement all the
794
+ # way, scare the user less about it. That being said, if you
795
+ # are trying to understand why a graph break happened, it's still
796
+ # important to have this information, so offer it.
797
+ #
798
+ # NB: NotImplementedError used to be on this list, but actually
799
+ # it is impossible for it to reach here, as it is converted into
800
+ # InternalTorchDynamoError. This behavior seemed reasonable
801
+ # to me (ezyang, Aug 2023) so I kept it, but maybe at some point
802
+ # someone wanted these to also get suppressed. If so, you'll
803
+ # need to make these exceptions not get wrapped
804
+
805
+ # We intentionally don't want to suppress error here.
806
+ if isinstance(e, UncapturedHigherOrderOpError):
807
+ raise
808
+
809
+ soft_fail = isinstance(e, Unsupported)
810
+ if not config.suppress_errors and not soft_fail:
811
+ raise
812
+
813
+ # Suppress the error. NB: It's very important to do the
814
+ # suppression logging HERE, where the actual suppression
815
+ # happens. Previously it was somewhere else and so it was
816
+ # possible to accidentally not log at all.
817
+ record_filename = getattr(e, "record_filename", None)
818
+ code = frame.f_code
819
+ error_msg = format_error_msg(e, code, record_filename, frame)
820
+
821
+ if soft_fail:
822
+ log.info(error_msg, exc_info=True)
823
+ else:
824
+ log.warning(error_msg, exc_info=True)
825
+ return None
826
+
827
+ _convert_frame._torchdynamo_orig_callable = compiler_fn # type: ignore[attr-defined]
828
+ _convert_frame._clone_with_backend = lambda backend: convert_frame(backend, hooks) # type: ignore[attr-defined]
829
+ return _convert_frame
830
+
831
+
832
+ # TODO mlazos: add support for same args, or record them
833
+ def replay(filename):
834
+ from .backends.debugging import eager
835
+
836
+ original_replay_val = config.replay_record_enabled
837
+ config.replay_record_enabled = False
838
+ with open(filename, "rb") as in_file:
839
+ record = ExecutionRecord.load(in_file)
840
+ record.globals = dict(itertools.chain(record.globals.items(), globals().items()))
841
+
842
+ try:
843
+ _compile(
844
+ record.code,
845
+ record.globals,
846
+ record.locals,
847
+ record.builtins,
848
+ compiler_fn=eager,
849
+ one_graph=False,
850
+ export=False,
851
+ export_constraints=None,
852
+ hooks=Hooks(),
853
+ cache_size=CacheSizeRelevantForFrame(0, 0),
854
+ frame=None,
855
+ frame_state={},
856
+ )
857
+ finally:
858
+ config.replay_record_enabled = original_replay_val
859
+
860
+
861
+ def first_real_inst_idx(code):
862
+ if sys.version_info < (3, 11):
863
+ return 0
864
+ for inst in dis.get_instructions(code):
865
+ if inst.opname == "RESUME":
866
+ return inst.offset // 2
867
+ raise RuntimeError("RESUME instruction not found in code")
868
+
869
+
870
+ def catch_errors_wrapper(callback, hooks: Hooks):
871
+ @functools.wraps(callback)
872
+ def catch_errors(frame, cache_entry, frame_state):
873
+ assert frame_state is not None
874
+
875
+ is_skipfile = trace_rules.check(frame.f_code)
876
+ if (
877
+ # TODO: the first condition is not covered by any test
878
+ frame.f_lasti >= first_real_inst_idx(frame.f_code)
879
+ or is_skipfile
880
+ or config.disable
881
+ ):
882
+ if log.isEnabledFor(logging.DEBUG):
883
+ skip_reason = (
884
+ "traced frame already"
885
+ if frame.f_lasti >= first_real_inst_idx(frame.f_code)
886
+ else "in skipfiles"
887
+ if trace_rules.check(frame.f_code)
888
+ else "dynamo tracing is disabled"
889
+ )
890
+ if not is_skipfile or config.verbose:
891
+ log.debug(
892
+ "skipping: %s (reason: %s, file: %s)",
893
+ frame.f_code.co_name,
894
+ skip_reason,
895
+ frame.f_code.co_filename,
896
+ )
897
+ return None
898
+ if frame.f_code.co_filename == "<string>" and frame.f_code.co_name == "__new__":
899
+ # nametuple constructor
900
+ return None
901
+ if config._get_optimize_ddp_mode() == "ddp_optimizer":
902
+ ddp_module = DistributedDataParallel._get_active_ddp_module()
903
+ if ddp_module:
904
+ with compile_lock:
905
+ from torch._dynamo.backends.distributed import DDPOptimizer
906
+
907
+ ddp_optimizer = DDPOptimizer(
908
+ bucket_bytes_cap=ddp_module.bucket_bytes_cap,
909
+ backend_compile_fn=callback._torchdynamo_orig_callable,
910
+ )
911
+ assert hasattr(
912
+ callback, "_clone_with_backend"
913
+ ), "DDPOptimizer only supports callback fns that know how to clone themselves."
914
+ hijacked_callback = callback._clone_with_backend(
915
+ ddp_optimizer.compile_fn,
916
+ )
917
+ return hijacked_callback(frame, cache_entry, hooks, frame_state)
918
+
919
+ with compile_lock, _disable_current_modes():
920
+ # skip=1: skip this frame
921
+ return callback(frame, cache_entry, hooks, frame_state, skip=1)
922
+
923
+ catch_errors._torchdynamo_orig_callable = callback # type: ignore[attr-defined]
924
+ return catch_errors
llmeval-env/lib/python3.10/site-packages/torch/_dynamo/current_scope_id.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import contextlib
2
+ import threading
3
+
4
+ # Global variable to identify which SubgraphTracer we are in.
5
+ # It is sometimes difficult to find an InstructionTranslator to use.
6
+ _current_scope_id = threading.local()
7
+
8
+
9
+ def current_scope_id():
10
+ global _current_scope_id
11
+ if not hasattr(_current_scope_id, "value"):
12
+ _current_scope_id.value = 1
13
+ return _current_scope_id.value
14
+
15
+
16
+ @contextlib.contextmanager
17
+ def enter_new_scope():
18
+ global _current_scope_id
19
+ try:
20
+ _current_scope_id.value = current_scope_id() + 1
21
+ yield
22
+ finally:
23
+ _current_scope_id.value = current_scope_id() - 1
llmeval-env/lib/python3.10/site-packages/torch/_dynamo/device_interface.py ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import inspect
2
+ from typing import Any, Callable, Dict, Iterable, Optional, Tuple, Type, Union
3
+
4
+ import torch
5
+ from torch._streambase import _EventBase, _StreamBase
6
+
7
+ get_cuda_stream: Optional[Callable[[int], int]]
8
+ if torch.cuda._is_compiled():
9
+ from torch._C import _cuda_getCurrentRawStream as get_cuda_stream
10
+ else:
11
+ get_cuda_stream = None
12
+
13
+ _device_t = Union[torch.device, str, int, None]
14
+
15
+ # Recording the device properties in the main process but used in worker process.
16
+ caching_worker_device_properties: Dict[str, Any] = {}
17
+ caching_worker_current_devices: Dict[str, int] = {}
18
+
19
+
20
+ class DeviceInterfaceMeta(type):
21
+ def __new__(metacls, *args, **kwargs):
22
+ class_member = args[2]
23
+ if "Event" in class_member:
24
+ assert inspect.isclass(class_member["Event"]) and issubclass(
25
+ class_member["Event"], _EventBase
26
+ ), "DeviceInterface member Event should be inherit from _EventBase"
27
+ if "Stream" in class_member:
28
+ assert inspect.isclass(class_member["Stream"]) and issubclass(
29
+ class_member["Stream"], _StreamBase
30
+ ), "DeviceInterface member Stream should be inherit from _StreamBase"
31
+ return super().__new__(metacls, *args, **kwargs)
32
+
33
+
34
+ class DeviceInterface(metaclass=DeviceInterfaceMeta):
35
+ """
36
+ This is a simple device runtime interface for Inductor. It enables custom
37
+ backends to be integrated with Inductor in a device-agnostic semantic.
38
+ """
39
+
40
+ class device:
41
+ def __new__(cls, device: _device_t):
42
+ raise NotImplementedError()
43
+
44
+ class Worker:
45
+ """
46
+ Worker API to query device properties that will work in multi processing
47
+ workers that cannot use the GPU APIs (due to processing fork() and
48
+ initialization time issues). Properties are recorded in the main process
49
+ before we fork the workers.
50
+ """
51
+
52
+ @staticmethod
53
+ def set_device(device: int):
54
+ raise NotImplementedError()
55
+
56
+ @staticmethod
57
+ def current_device() -> int:
58
+ raise NotImplementedError()
59
+
60
+ @staticmethod
61
+ def get_device_properties(device: _device_t = None):
62
+ raise NotImplementedError()
63
+
64
+ @staticmethod
65
+ def current_device():
66
+ raise NotImplementedError()
67
+
68
+ @staticmethod
69
+ def set_device(device: _device_t):
70
+ raise NotImplementedError()
71
+
72
+ @staticmethod
73
+ def device_count():
74
+ raise NotImplementedError()
75
+
76
+ @staticmethod
77
+ def is_available() -> bool:
78
+ raise NotImplementedError()
79
+
80
+ @staticmethod
81
+ def stream(stream: torch.Stream):
82
+ raise NotImplementedError()
83
+
84
+ @staticmethod
85
+ def current_stream():
86
+ raise NotImplementedError()
87
+
88
+ @staticmethod
89
+ def set_stream(stream: torch.Stream):
90
+ raise NotImplementedError()
91
+
92
+ @staticmethod
93
+ def _set_stream_by_id(stream_id: int, device_index: int, device_type: int):
94
+ raise NotImplementedError()
95
+
96
+ @staticmethod
97
+ def get_raw_stream():
98
+ raise NotImplementedError()
99
+
100
+ @staticmethod
101
+ def synchronize(device: _device_t = None):
102
+ raise NotImplementedError()
103
+
104
+ @staticmethod
105
+ def get_device_properties(device: _device_t = None):
106
+ raise NotImplementedError()
107
+
108
+ @staticmethod
109
+ def get_compute_capability(device: _device_t = None):
110
+ raise NotImplementedError()
111
+
112
+
113
+ class CudaInterface(DeviceInterface):
114
+ device = torch.cuda.device
115
+
116
+ # register Event and Stream class into the backend interface
117
+ # make sure Event and Stream are implemented and inherited from the _EventBase and _StreamBase
118
+ Event = torch.cuda.Event
119
+ Stream = torch.cuda.Stream
120
+
121
+ class Worker:
122
+ @staticmethod
123
+ def set_device(device: int):
124
+ caching_worker_current_devices["cuda"] = device
125
+
126
+ @staticmethod
127
+ def current_device() -> int:
128
+ if "cuda" in caching_worker_current_devices:
129
+ return caching_worker_current_devices["cuda"]
130
+ return torch.cuda.current_device()
131
+
132
+ @staticmethod
133
+ def get_device_properties(device: _device_t = None):
134
+ if device is not None:
135
+ if isinstance(device, str):
136
+ device = torch.device(device)
137
+ assert device.type == "cuda"
138
+ if isinstance(device, torch.device):
139
+ device = device.index
140
+ if device is None:
141
+ device = CudaInterface.Worker.current_device()
142
+
143
+ if "cuda" not in caching_worker_device_properties:
144
+ device_prop = [
145
+ torch.cuda.get_device_properties(i)
146
+ for i in range(torch.cuda.device_count())
147
+ ]
148
+ caching_worker_device_properties["cuda"] = device_prop
149
+
150
+ return caching_worker_device_properties["cuda"][device]
151
+
152
+ current_device = staticmethod(torch.cuda.current_device)
153
+ set_device = staticmethod(torch.cuda.set_device)
154
+ device_count = staticmethod(torch.cuda.device_count)
155
+ stream = staticmethod(torch.cuda.stream) # type: ignore[assignment]
156
+ current_stream = staticmethod(torch.cuda.current_stream)
157
+ set_stream = staticmethod(torch.cuda.set_stream) # type: ignore[assignment]
158
+ _set_stream_by_id = staticmethod(torch.cuda._set_stream_by_id) # type: ignore[assignment]
159
+ synchronize = staticmethod(torch.cuda.synchronize)
160
+ get_device_properties = staticmethod(torch.cuda.get_device_properties) # type: ignore[assignment]
161
+ get_raw_stream = staticmethod(get_cuda_stream) # type: ignore[arg-type]
162
+
163
+ # Can be mock patched by @patch decorator.
164
+ @staticmethod
165
+ def is_available() -> bool:
166
+ return torch.cuda.is_available()
167
+
168
+ @staticmethod
169
+ def get_compute_capability(device: _device_t = None):
170
+ major, min = torch.cuda.get_device_capability(device)
171
+ return major * 10 + min
172
+
173
+
174
+ device_interfaces: Dict[str, Type[DeviceInterface]] = {}
175
+
176
+
177
+ def register_interface_for_device(
178
+ device: Union[str, torch.device], device_interface: Type[DeviceInterface]
179
+ ):
180
+ if isinstance(device, torch.device):
181
+ device = str(device)
182
+ device_interfaces[device] = device_interface
183
+
184
+
185
+ def get_interface_for_device(device: Union[str, torch.device]) -> Type[DeviceInterface]:
186
+ if isinstance(device, torch.device):
187
+ device = str(device)
188
+ if device in device_interfaces:
189
+ return device_interfaces[device]
190
+ raise NotImplementedError(f"No interface for device {device}")
191
+
192
+
193
+ def get_registered_device_interfaces() -> Iterable[Tuple[str, Type[DeviceInterface]]]:
194
+ return device_interfaces.items()
195
+
196
+
197
+ register_interface_for_device("cuda", CudaInterface)
198
+ for i in range(torch.cuda.device_count()):
199
+ register_interface_for_device(f"cuda:{i}", CudaInterface)
llmeval-env/lib/python3.10/site-packages/torch/_dynamo/exc.py ADDED
@@ -0,0 +1,335 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import textwrap
3
+ from enum import auto, Enum
4
+ from traceback import extract_stack, format_exc, format_list, StackSummary
5
+ from typing import cast, NoReturn, Optional
6
+
7
+ import torch._guards
8
+
9
+ from . import config
10
+
11
+ from .utils import counters
12
+
13
+
14
+ def exportdb_error_message(case_name):
15
+ return (
16
+ "For more information about this error, see: "
17
+ + "https://pytorch.org/docs/main/generated/exportdb/index.html#"
18
+ + case_name.replace("_", "-")
19
+ )
20
+
21
+
22
+ import logging
23
+
24
+ log = logging.getLogger(__name__)
25
+ graph_breaks_log = torch._logging.getArtifactLogger(__name__, "graph_breaks")
26
+
27
+
28
+ class TorchDynamoException(RuntimeError):
29
+ pass
30
+
31
+
32
+ class InternalTorchDynamoError(TorchDynamoException):
33
+ pass
34
+
35
+
36
+ class RestartAnalysis(TorchDynamoException):
37
+ pass
38
+
39
+
40
+ class SpeculationRestartAnalysis(RestartAnalysis):
41
+ pass
42
+
43
+
44
+ class UnspecializeRestartAnalysis(RestartAnalysis):
45
+ pass
46
+
47
+
48
+ class SkipFrame(TorchDynamoException):
49
+ pass
50
+
51
+
52
+ class TorchRuntimeError(TorchDynamoException):
53
+ pass
54
+
55
+
56
+ class InvalidBackend(TorchDynamoException):
57
+ def __init__(self, name):
58
+ super().__init__(
59
+ f"Invalid backend: {name!r}, see `torch._dynamo.list_backends()` for available backends."
60
+ )
61
+
62
+
63
+ class ResetRequired(TorchDynamoException):
64
+ def __init__(self):
65
+ super().__init__(
66
+ textwrap.dedent(
67
+ """
68
+ Must call `torch._dynamo.reset()` before changing backends. Detected two calls to
69
+ `torch.compile()` with a different backend compiler arguments.
70
+ """
71
+ )
72
+ )
73
+
74
+
75
+ class BackendCompilerFailed(TorchDynamoException):
76
+ def __init__(self, backend_fn, inner_exception):
77
+ self.backend_name = getattr(backend_fn, "__name__", "?")
78
+ self.inner_exception = inner_exception
79
+ msg = f"backend={self.backend_name!r} raised:\n{type(inner_exception).__name__}: {inner_exception}"
80
+ super().__init__(msg)
81
+
82
+
83
+ class Unsupported(TorchDynamoException):
84
+ def __init__(self, msg):
85
+ super().__init__(msg)
86
+ self.real_stack = torch._guards.TracingContext.extract_stack()
87
+ self.msg = msg
88
+ self.category: Optional[str] = None
89
+ self.add_to_stats()
90
+
91
+ def remove_from_stats(self):
92
+ assert self.category is not None
93
+ counters[self.category][self.msg] -= 1
94
+ if counters[self.category][self.msg] <= 0:
95
+ del counters[self.category][self.msg]
96
+
97
+ def add_to_stats(self, category="unimplemented"):
98
+ self.category = category
99
+ counters[category][self.msg] += 1
100
+
101
+
102
+ class RecompileError(TorchDynamoException):
103
+ pass
104
+
105
+
106
+ class ArgsMismatchError(Unsupported):
107
+ def __init__(self, msg):
108
+ super().__init__(msg)
109
+
110
+
111
+ class AttributeMutationError(Unsupported):
112
+ def __init__(self, msg):
113
+ super().__init__(msg)
114
+
115
+
116
+ class CondOpArgsMismatchError(ArgsMismatchError):
117
+ """
118
+ Internal error from cond() due to arguments mismatch.
119
+ """
120
+
121
+ def __init__(self, msg):
122
+ super().__init__(msg)
123
+
124
+
125
+ class UserErrorType(Enum):
126
+ DYNAMIC_CONTROL_FLOW = auto()
127
+ ANTI_PATTERN = auto()
128
+ STANDARD_LIBRARY = auto()
129
+ CONSTRAINT_VIOLATION = auto()
130
+ DYNAMIC_DIM = auto()
131
+ INVALID_INPUT = auto()
132
+ INVALID_OUTPUT = auto()
133
+
134
+
135
+ class UserError(Unsupported):
136
+ def __init__(self, error_type: UserErrorType, msg, case_name=None):
137
+ """
138
+ Type of errors that would be valid in Eager, but not supported in TorchDynamo.
139
+ The error message should tell user about next actions.
140
+
141
+ error_type: Type of user error
142
+ msg: Actionable error message
143
+ case_name: (Optional) Unique name (snake case) for the usage example in exportdb.
144
+ """
145
+ if case_name is not None:
146
+ assert isinstance(case_name, str)
147
+ if msg.endswith("."):
148
+ msg += " "
149
+ else:
150
+ msg += "\n"
151
+ msg += exportdb_error_message(case_name)
152
+ super().__init__(msg)
153
+ self.error_type = error_type
154
+ self.message = msg
155
+
156
+
157
+ class UncapturedHigherOrderOpError(TorchDynamoException):
158
+ pass
159
+
160
+
161
+ class IncorrectUsage(Exception):
162
+ pass
163
+
164
+
165
+ # These exceptions are ok to fallback to eager/graph_break.
166
+ exceptions_allowed_to_be_fallback = (
167
+ torch._subclasses.fake_tensor.DataDependentOutputException,
168
+ torch._subclasses.fake_tensor.DynamicOutputShapeException,
169
+ torch._subclasses.fake_tensor.UnsupportedOperatorException,
170
+ torch._subclasses.fake_tensor.UnsupportedFakeTensorException,
171
+ )
172
+
173
+
174
+ def unimplemented_with_warning(e: Exception, code, msg: str) -> NoReturn:
175
+ # This function calls unimplemented internally and eventually graph breaks
176
+ # or falls to eager. unimplemented itself does not print any user warnings,
177
+ # i.e., its very silent. This helper function is intended when an error is
178
+ # encountered in the torch.compile stack which is worth showing as warning
179
+ # to the user. For example, if AOT Autograd backend fails with a fake tensor
180
+ # exception, its ok to fallback to eager but not silently. Here, we can use
181
+ # this function to log the message and the stack trace.
182
+ graph_break_msg = format_error_msg_verbose(e, code)
183
+ graph_breaks_log.debug("%s", graph_break_msg)
184
+ log.warning(msg)
185
+ raise unimplemented(msg) from e
186
+
187
+
188
+ def unimplemented(msg: str) -> NoReturn:
189
+ assert msg != os.environ.get("BREAK", False)
190
+ raise Unsupported(msg)
191
+
192
+
193
+ def warning(msg: str) -> None:
194
+ counters["warnings"][msg] += 1
195
+ assert msg != os.environ.get("BREAK", False)
196
+
197
+
198
+ # KeyError has special handling for its args
199
+ # see https://github.com/python/cpython/blob/3.11/Objects/exceptions.c#L2534 for details
200
+ class KeyErrorMsg:
201
+ def __init__(self, value):
202
+ self.value = value
203
+
204
+ def __str__(self):
205
+ return str(self.value)
206
+
207
+ def __repr__(self) -> str:
208
+ return self.__str__()
209
+
210
+
211
+ def augment_exc_message(exc: Exception, msg: str = "\n", export: bool = False) -> None:
212
+ import traceback
213
+
214
+ exc.innermost_user_frame_summary = None # type: ignore[attr-defined]
215
+
216
+ real_stack = get_real_stack(exc)
217
+ if real_stack is not None and len(real_stack) > 0:
218
+ exc.innermost_user_frame_summary = real_stack[-1] # type: ignore[attr-defined]
219
+ msg += f"\nfrom user code:\n {''.join(traceback.format_list(real_stack))}"
220
+
221
+ if config.replay_record_enabled and hasattr(exc, "record_filename"):
222
+ msg += f"\nLast frame execution written to {exc.record_filename}. To run only this frame while debugging, run\
223
+ torch._dynamo.replay('{exc.record_filename}').\n"
224
+
225
+ if not config.verbose and hasattr(exc, "real_stack"):
226
+ msg += '\nSet TORCH_LOGS="+dynamo" and TORCHDYNAMO_VERBOSE=1 for more information\n'
227
+
228
+ if hasattr(exc, "inner_exception") and hasattr(
229
+ exc.inner_exception, "minifier_path"
230
+ ):
231
+ if hasattr(exc.inner_exception, "buck_command"):
232
+ msg += (
233
+ f"\nMinifier script written to {exc.inner_exception.minifier_path}. Run "
234
+ f"this buck command to find the smallest traced graph "
235
+ f"which reproduces this error: {exc.inner_exception.buck_command}\n"
236
+ )
237
+ else:
238
+ msg += (
239
+ f"\nMinifier script written to {exc.inner_exception.minifier_path}. Run "
240
+ "this script to find the smallest traced graph which reproduces this error.\n"
241
+ )
242
+
243
+ if not config.suppress_errors and not export:
244
+ msg += (
245
+ "\n\n"
246
+ "You can suppress this exception and fall back to eager by setting:\n"
247
+ " import torch._dynamo\n"
248
+ " torch._dynamo.config.suppress_errors = True\n"
249
+ )
250
+
251
+ old_msg = "" if len(exc.args) == 0 else str(exc.args[0])
252
+
253
+ if isinstance(exc, KeyError):
254
+ exc.args = (KeyErrorMsg(old_msg + msg),) + exc.args[1:]
255
+ else:
256
+ new_msg = old_msg + msg
257
+ exc.args = (new_msg,) + exc.args[1:]
258
+
259
+
260
+ def get_real_stack(exc: Exception, frame=None) -> Optional[StackSummary]:
261
+ real_stack = getattr(exc, "real_stack", None)
262
+ if real_stack is None:
263
+ return None
264
+
265
+ # NB: it's possible for real_stack to be []; we still attempt to
266
+ # report a stack anyway because the stack_above_dynamo may still
267
+ # be useful for debugging
268
+
269
+ stack_above_dynamo = []
270
+ if frame is not None:
271
+ # NB: frame is PyInterpreterFrame on Python 3.11 and later,
272
+ # not a TRUE frame object. You can't actually feed it
273
+ # to traceback because it doesn't have enough information.
274
+ # To solve this problem, we technically should just materialize
275
+ # the frame, the same way _PyFrame_GetFrameObject would do
276
+ # (but we cannot actually do this, because this populates
277
+ # frame_obj field, which default eval frame doesn't like).
278
+ #
279
+ # Fortunately, in this case, we can hack it: there's no need
280
+ # to actually use the truly top frame, we can just extract
281
+ # from where we are right now and rely on filter_stack to
282
+ # get rid of all the dynamo frames. For ease of testing
283
+ # we apply this behavior to ALL Python versions
284
+ stack_above_dynamo = filter_stack(extract_stack())
285
+
286
+ return cast(StackSummary, stack_above_dynamo + real_stack)
287
+
288
+
289
+ # filter out all frames after entering dynamo
290
+ def filter_stack(stack):
291
+ user_stack = []
292
+ for frame in stack:
293
+ if "convert_frame" in frame.filename:
294
+ break
295
+ if "eval_frame" in frame.filename or "torch._dynamo.optimize(" in frame.line:
296
+ continue
297
+ user_stack.append(frame)
298
+
299
+ return user_stack
300
+
301
+
302
+ def format_error_msg_verbose(
303
+ exc: Exception, code, record_filename=None, frame=None
304
+ ) -> str:
305
+ msg = (
306
+ f"WON'T CONVERT {code.co_name} {code.co_filename} line {code.co_firstlineno}\n"
307
+ )
308
+ msg += "=" * 10 + " TorchDynamo Stack Trace " + "=" * 10 + "\n"
309
+ msg += format_exc()
310
+ real_stack = get_real_stack(exc, frame)
311
+ if real_stack is not None:
312
+ msg += (
313
+ "\n"
314
+ + "=" * 10
315
+ + " The above exception occurred while processing the following code "
316
+ + "=" * 10
317
+ + "\n\n"
318
+ )
319
+ msg += "".join(format_list(real_stack))
320
+ msg += "\n"
321
+ msg += "=" * 10
322
+
323
+ return msg
324
+
325
+
326
+ def format_error_msg(exc: Exception, code, record_filename=None, frame=None) -> str:
327
+ msg = os.linesep * 2
328
+
329
+ if config.verbose:
330
+ msg = format_error_msg_verbose(exc, code, record_filename, frame)
331
+ else:
332
+ msg = f"WON'T CONVERT {code.co_name} {code.co_filename}\
333
+ line {code.co_firstlineno} \ndue to: \n{format_exc()}"
334
+
335
+ return msg
llmeval-env/lib/python3.10/site-packages/torch/_dynamo/external_utils.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This module contains functions that *will be allowed* by dynamo
2
+
3
+ import functools
4
+
5
+ import torch
6
+ import torch.utils._pytree as pytree
7
+
8
+ try:
9
+ import numpy as np
10
+ except ModuleNotFoundError:
11
+ np = None # type: ignore[assignment]
12
+
13
+
14
+ def is_compiling() -> bool:
15
+ """
16
+ Indicates whether we are tracing/compiling with torch.compile() or torch.export().
17
+
18
+ If need to check specifically that TorchDynamo is used, then use
19
+ torch.compiler.is_dynamo_compiling().
20
+
21
+ TODO(khabinov): we should deprecate this function and use one of these two:
22
+ * torch.compiler.is_compiling(),
23
+ * torch.compiler.is_dynamo_compiling().
24
+ It will depend on the context where to use what.
25
+ """
26
+ return torch.compiler.is_compiling()
27
+
28
+
29
+ def wrap_inline(fn):
30
+ """
31
+ Create an extra frame around fn that is not in skipfiles
32
+ """
33
+
34
+ @functools.wraps(fn)
35
+ def inner(*args, **kwargs):
36
+ return fn(*args, **kwargs)
37
+
38
+ return inner
39
+
40
+
41
+ def call_hook(hook, *args):
42
+ """
43
+ Used by compiled autograd to handle hook returning None
44
+ """
45
+ result = hook(*args)
46
+ if result is None:
47
+ return args[0]
48
+ return result
49
+
50
+
51
+ def wrap_numpy(f):
52
+ r"""Decorator that turns a function from ``np.ndarray``s to ``np.ndarray``s into a function
53
+ from ``torch.Tensor``s to ``torch.Tensor``s.
54
+ """
55
+ if not np:
56
+ return f
57
+
58
+ @functools.wraps(f)
59
+ def wrap(*args, **kwargs):
60
+ args, kwargs = pytree.tree_map_only(
61
+ torch.Tensor, lambda x: x.numpy(), (args, kwargs)
62
+ )
63
+ out = f(*args, **kwargs)
64
+ return pytree.tree_map_only(np.ndarray, lambda x: torch.as_tensor(x), out)
65
+
66
+ return wrap
67
+
68
+
69
+ class FakeContext:
70
+ def __init__(self, saved_tensors):
71
+ # this will cache the results of saved_tensors
72
+ # and will no longer call into c++ binding
73
+ self.saved_tensors = saved_tensors
74
+
75
+
76
+ def call_backward(backward_fn, saved_tensors, *args):
77
+ grads = backward_fn(FakeContext(saved_tensors), *args)
78
+
79
+ # in eager, we wrap in a tuple when there's only one grad output
80
+ if type(grads) is not tuple:
81
+ grads = (grads,)
82
+
83
+ return grads
84
+
85
+
86
+ def untyped_storage_size(x: torch.Tensor):
87
+ return x.untyped_storage().size()
88
+
89
+
90
+ def call_hook_from_backward_state(*args, bw_state, hook_name: str, **kwargs):
91
+ return getattr(bw_state, hook_name)(*args, **kwargs)
92
+
93
+
94
+ def call_module_hooks_from_backward_state(
95
+ _, result, *args, bw_state, hooks_name: str, module_name: str
96
+ ):
97
+ module = getattr(bw_state, module_name)
98
+ hooks = getattr(bw_state, hooks_name)
99
+ for hook in hooks:
100
+ new_result = hook(module, result, *args)
101
+ if new_result is not None:
102
+ result = new_result
103
+ return result
llmeval-env/lib/python3.10/site-packages/torch/_dynamo/funcname_cache.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import tokenize
2
+
3
+ from typing import Dict, List, Optional
4
+
5
+ cache: Dict[str, Dict[int, str]] = {}
6
+
7
+
8
+ def clearcache() -> None:
9
+ cache.clear()
10
+
11
+
12
+ def _add_file(filename: str) -> None:
13
+ try:
14
+ with open(filename) as f:
15
+ tokens = list(tokenize.generate_tokens(f.readline))
16
+ except OSError:
17
+ cache[filename] = {}
18
+ return
19
+
20
+ # NOTE: undefined behavior if file is not valid Python source,
21
+ # since tokenize will have undefined behavior.
22
+ result: Dict[int, str] = {}
23
+ # current full funcname, e.g. xxx.yyy.zzz
24
+ cur_name = ""
25
+ cur_indent = 0
26
+ significant_indents: List[int] = []
27
+
28
+ for i, token in enumerate(tokens):
29
+ if token.type == tokenize.INDENT:
30
+ cur_indent += 1
31
+ elif token.type == tokenize.DEDENT:
32
+ cur_indent -= 1
33
+ # possible end of function or class
34
+ if significant_indents and cur_indent == significant_indents[-1]:
35
+ significant_indents.pop()
36
+ # pop the last name
37
+ cur_name = cur_name.rpartition(".")[0]
38
+ elif (
39
+ token.type == tokenize.NAME
40
+ and i + 1 < len(tokens)
41
+ and tokens[i + 1].type == tokenize.NAME
42
+ and (token.string == "class" or token.string == "def")
43
+ ):
44
+ # name of class/function always follows class/def token
45
+ significant_indents.append(cur_indent)
46
+ if cur_name:
47
+ cur_name += "."
48
+ cur_name += tokens[i + 1].string
49
+ result[token.start[0]] = cur_name
50
+
51
+ cache[filename] = result
52
+
53
+
54
+ def get_funcname(filename: str, lineno: int) -> Optional[str]:
55
+ if filename not in cache:
56
+ _add_file(filename)
57
+ return cache[filename].get(lineno, None)
llmeval-env/lib/python3.10/site-packages/torch/_dynamo/guards.py ADDED
@@ -0,0 +1,1505 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import ast
4
+ import builtins
5
+ import collections
6
+ import dataclasses
7
+ import enum
8
+ import functools
9
+ import importlib
10
+ import inspect
11
+ import itertools
12
+ import logging
13
+ import math
14
+ import os
15
+ import re
16
+ import sys
17
+ import textwrap
18
+ import types
19
+ import weakref
20
+ from inspect import currentframe, getframeinfo
21
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Type, Union
22
+ from weakref import ReferenceType
23
+
24
+
25
+ try:
26
+ import numpy as np
27
+ except ModuleNotFoundError:
28
+ np = None # type: ignore[assignment]
29
+
30
+ import torch
31
+ import torch.utils._device
32
+ from torch._dynamo.source import (
33
+ is_from_local_source,
34
+ TensorProperty,
35
+ TensorPropertySource,
36
+ )
37
+
38
+ from torch._guards import (
39
+ DuplicateInputs,
40
+ Guard,
41
+ GuardBuilderBase,
42
+ GuardEnvExpr,
43
+ GuardSource,
44
+ Source,
45
+ )
46
+
47
+ from torch._logging import structured
48
+ from torch.fx.experimental.symbolic_shapes import (
49
+ EqualityConstraint,
50
+ is_symbolic,
51
+ SYMPY_INTERP,
52
+ )
53
+ from torch.utils._traceback import format_frame, report_compile_source_on_error
54
+ from torch.utils.weak import TensorWeakRef
55
+
56
+ from . import config, convert_frame, exc, mutation_guard
57
+ from .eval_frame import set_guard_error_hook
58
+ from .source import AttrSource, DefaultsSource, LocalSource, TypeSource
59
+ from .types import CacheEntry, ExtraState, GuardedCode, GuardFail, GuardFn # noqa: F401
60
+ from .utils import (
61
+ common_constant_types,
62
+ dict_keys_repr,
63
+ guard_failures,
64
+ istype,
65
+ key_is_id,
66
+ key_to_id,
67
+ orig_code_map,
68
+ tensor_always_has_static_shape,
69
+ tuple_iterator_getitem,
70
+ tuple_iterator_len,
71
+ )
72
+
73
+ log = logging.getLogger(__name__)
74
+ guards_log = torch._logging.getArtifactLogger(__name__, "guards")
75
+ recompiles_log = torch._logging.getArtifactLogger(__name__, "recompiles")
76
+ recompiles_verbose_log = torch._logging.getArtifactLogger(
77
+ __name__, "recompiles_verbose"
78
+ )
79
+ verbose_guards_log = torch._logging.getArtifactLogger(__name__, "verbose_guards")
80
+
81
+ TensorGuards = torch._C._dynamo.guards.TensorGuards
82
+ check_obj_id = torch._C._dynamo.guards.check_obj_id
83
+ check_type_id = torch._C._dynamo.guards.check_type_id
84
+ dict_version = torch._C._dynamo.guards.dict_version
85
+
86
+
87
+ # For user stack printing
88
+ @functools.lru_cache(None)
89
+ def uninteresting_files():
90
+ import torch._dynamo.external_utils
91
+
92
+ mods = [
93
+ torch._dynamo.external_utils,
94
+ ]
95
+ return {inspect.getfile(m) for m in mods}
96
+
97
+
98
+ CLOSURE_VARS = {
99
+ "___check_type_id": check_type_id,
100
+ "___check_obj_id": check_obj_id,
101
+ "___odict_getitem": collections.OrderedDict.__getitem__,
102
+ "___key_to_id": key_to_id,
103
+ "___dict_version": dict_version,
104
+ "___dict_contains": lambda a, b: a in b,
105
+ "___tuple_iterator_len": tuple_iterator_len,
106
+ "___tuple_iterator_getitem": tuple_iterator_getitem,
107
+ "__math_isnan": math.isnan,
108
+ "__numpy_isnan": None if np is None else np.isnan,
109
+ "inf": float("inf"),
110
+ "__load_module": importlib.import_module,
111
+ "utils_device": torch.utils._device,
112
+ "device": torch.device,
113
+ "___from_numpy":
114
+ # If not numpy array, piggy back on e.g. tensor guards to check type
115
+ (lambda a: torch.as_tensor(a) if isinstance(a, (np.generic, np.ndarray)) else a),
116
+ "torch": torch,
117
+ "inspect": inspect,
118
+ }
119
+
120
+ if sys.version_info[:2] <= (3, 8):
121
+ # [Note: Python Version <= 3.8]
122
+ # This branch should be dropped when we drop support for Python 3.8.
123
+ # Reason: 'ast.unparse' function was introduced in Python 3.9.
124
+
125
+ try:
126
+ import astunparse # type: ignore[import]
127
+
128
+ def _ast_unparse(node: ast.AST) -> str:
129
+ return astunparse.unparse(node).replace("\n", "")
130
+
131
+ HAS_UNPARSE_FUNCTIONS = True
132
+ except ImportError:
133
+ HAS_UNPARSE_FUNCTIONS = False
134
+ pass
135
+ else:
136
+ HAS_UNPARSE_FUNCTIONS = True
137
+
138
+ def _ast_unparse(node: ast.AST) -> str:
139
+ return ast.unparse(node).replace("\n", "")
140
+
141
+
142
+ def strip_function_call(name):
143
+ """
144
+ "___odict_getitem(a, 1)" => "a"
145
+ "a.layers[slice(2)][0]._xyz" ==> "a"
146
+ "getattr(a.layers[slice(2)][0]._abc, '0')" ==> "a"
147
+ "getattr(getattr(a.x[3], '0'), '3')" ==> "a"
148
+ "a.layers[slice(None, -1, None)][0]._xyz" ==> "a"
149
+ """
150
+ # recursively find valid object name in function
151
+ valid_name = re.compile("[A-Za-z_].*")
152
+ curr = ""
153
+ for char in name:
154
+ if char in " (":
155
+ curr = ""
156
+ elif char in "),[]":
157
+ if curr and curr != "None" and valid_name.match(curr):
158
+ return strip_function_call(curr)
159
+ else:
160
+ curr += char
161
+
162
+ return strip_getattr_getitem(name)
163
+
164
+
165
+ def strip_getattr_getitem(name):
166
+ """
167
+ "a[1]" => "a"
168
+ "a.foo" => "a"
169
+ """
170
+ return re.split(r"[.\[]", name)[0]
171
+
172
+
173
+ def get_verbose_code_part(code_part, guard):
174
+ extra = ""
175
+ if guard.user_stack:
176
+ for fs in reversed(guard.user_stack):
177
+ if fs.filename not in uninteresting_files():
178
+ extra = f" # {format_frame(fs, line=True)}"
179
+ break
180
+ elif guard.stack:
181
+ extra = f" # {format_frame(guard.stack.summary()[-1])}"
182
+
183
+ return f"{code_part:<60}{extra}"
184
+
185
+
186
+ def convert_to_concrete_values(size_or_stride):
187
+ converted: List[Optional[int]] = []
188
+ for dim in size_or_stride:
189
+ if not is_symbolic(dim):
190
+ converted.append(dim)
191
+ else:
192
+ assert isinstance(dim, torch.SymInt)
193
+ converted.append(dim.node.maybe_as_int())
194
+ return converted
195
+
196
+
197
+ def get_tensor_guard_code_part(value, name, sizes, strides):
198
+ pytype = type(value)
199
+ dispatch_key = (
200
+ torch._C._dispatch_keys(value) | torch._C._dispatch_tls_local_include_set()
201
+ ) - torch._C._dispatch_tls_local_exclude_set()
202
+ dtype = value.dtype
203
+ device_index = value.device.index
204
+ requires_grad = value.requires_grad
205
+ guard_str = (
206
+ f"check_tensor({name}, {pytype.__qualname__}, {dispatch_key}, {dtype}, "
207
+ f"device={device_index}, requires_grad={requires_grad}, size={sizes}, stride={strides})"
208
+ )
209
+ return guard_str
210
+
211
+
212
+ # The ready to eval generated code (possibly multiple parts) for a guard, plus
213
+ # the original guard object that created it for provenance
214
+ @dataclasses.dataclass
215
+ class GuardCodeList:
216
+ code_list: List[str]
217
+ guard: Guard
218
+
219
+
220
+ class GuardBuilder(GuardBuilderBase):
221
+ def __init__(
222
+ self,
223
+ id_ref: Callable[[Any], str],
224
+ source_ref: Callable[[Source], str],
225
+ lookup_weakrefs: Callable[[object], ReferenceType[object]],
226
+ local_scope: Dict[str, object],
227
+ global_scope: Dict[str, object],
228
+ check_fn_manager: CheckFunctionManager,
229
+ ):
230
+ self.id_ref = id_ref
231
+ self.source_ref = source_ref
232
+ self.lookup_weakrefs = lookup_weakrefs
233
+ self.scope: Dict[str, Dict[str, object]] = {"L": local_scope, "G": global_scope}
234
+ self.scope["__builtins__"] = builtins.__dict__.copy()
235
+ for (
236
+ name,
237
+ package_module,
238
+ ) in torch.package.package_importer._package_imported_modules.items():
239
+ name = name.replace(">", "_").replace("<", "_").replace(".", "_dot_")
240
+ # Write the package module into the scope so that we can import it
241
+ self.scope["__builtins__"][name] = package_module
242
+ # Write the demangled name to the scope so that we can use it
243
+ self.scope[name] = package_module
244
+
245
+ self.argnames: List[str] = []
246
+ # Code is python expression strings generated for each guard
247
+ self.code: List[GuardCodeList] = []
248
+ # shape_env_code is only used by builder and is used for
249
+ # shape env code. This exists only because we need to make sure
250
+ # shape env guards get run after tensor match guards (since the
251
+ # tensor match guards make sure we actually have tensors)
252
+ self.shape_env_code: List[GuardCodeList] = []
253
+
254
+ # [Note - On Eager Tensor Guards]
255
+ # Most of the time, we generate Python code in a guard to directly
256
+ # check various properties. However, tensors are a bit special;
257
+ # it is too slow to check their properties one-by-one in Python.
258
+ # Instead, there is a C++ function TensorGuards.check which takes
259
+ # all of the tensor arguments and checks them all against compile-time
260
+ # examples entirely in C++. Thus, every time we process a
261
+ # TENSOR_MATCH guard, we just add another entry to
262
+ # tensor_check_names/tensor_check_examples, saying "for this local,
263
+ # check it against this example", and it all ends up getting
264
+ # swept up into a single call to ___check_tensors. Invariant:
265
+ # len(tensor_check_names) == len(tensor_check_examples).
266
+ # TODO: something here
267
+ self.tensor_check_names: List[str] = []
268
+ self.tensor_check_examples: List[torch.Tensor] = []
269
+ self.tensor_check_guards: List[Guard] = []
270
+
271
+ self.check_fn_manager: CheckFunctionManager = check_fn_manager
272
+ # Keep track of weak references of objects with ID_MATCH guard. This
273
+ # info is stored alongside optimized_code and check_fn and is used to
274
+ # limit the number of cache entries with same ID_MATCH'd object.
275
+ self.id_matched_objs: Dict[str, ReferenceType[object]] = {}
276
+
277
+ # Warning: use this with care! This lets you access what the current
278
+ # value of the value you are guarding on is. You probably don't want
279
+ # to actually durably save this value though (because it's specific
280
+ # to this frame!) Instead, you should be reading out some property
281
+ # (like its type) which is what you permanently install into the
282
+ # guard code.
283
+ def get(self, name: str) -> Any:
284
+ return eval(name, self.scope, CLOSURE_VARS)
285
+
286
+ # Registers the usage of the source name referenced by the
287
+ # string (or stored in the Guard) as being guarded upon. It's important
288
+ # to call this before generating some code that makes use of 'guard',
289
+ # because without this call, we won't actually bind the variable
290
+ # you reference in the actual guard closure (oops!)
291
+ def arg_ref(self, guard: Union[str, Guard]) -> str:
292
+ name: str
293
+ if isinstance(guard, str):
294
+ name = guard
295
+ else:
296
+ name = guard.name
297
+ base = strip_getattr_getitem(strip_function_call(name))
298
+ if base not in self.argnames:
299
+ if re.match(r"[a-zA-Z0-9_]+", base):
300
+ if re.match(r"^\d+$", base):
301
+ log.warning("invalid var name: %s", guard)
302
+ self.argnames.append(base)
303
+
304
+ return name
305
+
306
+ def _guard_on_attribute(self, guard: Guard, attr_name: str, guard_fn):
307
+ attr_source = AttrSource(guard.originating_source, attr_name)
308
+ # Copy the stack info
309
+ new_guard = Guard(
310
+ attr_source, guard_fn, stack=guard.stack, user_stack=guard.user_stack
311
+ )
312
+ new_guard.create(self)
313
+
314
+ def TYPE_MATCH(self, guard: Guard) -> None:
315
+ # ___check_type_id is same as `id(type(x)) == y`
316
+ t = type(self.get(guard.name))
317
+ obj_id = self.id_ref(t)
318
+ code = f"___check_type_id({self.arg_ref(guard)}, {obj_id})"
319
+ self._produce_guard_code(guard, [code])
320
+
321
+ def DICT_VERSION(self, guard: Guard):
322
+ # ___check_dict_version is same as `dict_version(x) == y`
323
+ ref = self.arg_ref(guard)
324
+ version = dict_version(self.get(guard.name))
325
+ code = f"___dict_version({ref}) == {version}"
326
+ self._produce_guard_code(guard, [code])
327
+
328
+ def DICT_CONTAINS(self, guard: Guard, key: str, invert: bool):
329
+ dict_ref = self.arg_ref(guard)
330
+
331
+ maybe_not = "not " if invert else ""
332
+ code = f"{maybe_not}___dict_contains({key!r}, {dict_ref})"
333
+ return self._produce_guard_code(guard, [code])
334
+
335
+ def BOOL_FALSE(self, guard: Guard):
336
+ # Guard on the runtime value being 'False',
337
+ # can be faster than seemingly equivalent checks like DICT_KEYS for empty dict
338
+ #
339
+ # WARNING: this guard is not safe to use generally. It only works if the runtime
340
+ # value is of a type that supports bool(), and some types e.g. Tensor do not.
341
+ # Only use this guard in cases you can guarantee the runtime type will be friendly.
342
+ # (e.g. Specialized NNModule with mutation protection via setattr)
343
+ #
344
+ # Why not simply check the runtime type inside this guard? It's slow enough to defeat
345
+ # the purpose of using this guard, which itself is supposed to be a faster alternative
346
+ # to DICT_KEYS.
347
+ ref = self.arg_ref(guard)
348
+ code = f"not {ref}"
349
+ self._produce_guard_code(guard, [code])
350
+
351
+ def ID_MATCH(self, guard: Guard):
352
+ # ___check_obj_id is same as `id(x) == y`
353
+ if isinstance(guard.originating_source, TypeSource):
354
+ # optional optimization to produce cleaner/faster guard code
355
+ return self.TYPE_MATCH(
356
+ Guard(guard.originating_source.base, GuardBuilder.TYPE_MATCH) # type: ignore[arg-type]
357
+ )
358
+
359
+ ref = self.arg_ref(guard)
360
+ val = self.get(guard.name)
361
+ code = f"___check_obj_id({ref}, {self.id_ref(val)})"
362
+ self._produce_guard_code(guard, [code])
363
+
364
+ # Keep track of ID_MATCH'd objects. This will be used to modify the
365
+ # cache size logic
366
+ if isinstance(guard.originating_source, LocalSource):
367
+ # TODO(janimesh) - This is currently restricted to nn.Module objects
368
+ # because many other ID_MATCH'd objects fail - like DeviceMesh.
369
+ # Increase the scope of ID_MATCH'd objects.
370
+ if isinstance(val, torch.nn.Module):
371
+ local_name = guard.originating_source.local_name
372
+ weak_id = self.lookup_weakrefs(val)
373
+ if weak_id is not None:
374
+ self.id_matched_objs[local_name] = weak_id
375
+
376
+ def NAME_MATCH(self, guard: Guard):
377
+ obj = self.get(guard.name)
378
+ self._guard_on_attribute(guard, "__name__", GuardBuilder.EQUALS_MATCH)
379
+
380
+ def DATA_PTR_MATCH(self, guard: Guard):
381
+ obj = self.get(guard.name)
382
+ code = f"{self.arg_ref(guard)}.data_ptr() == {obj.data_ptr()}"
383
+ self._produce_guard_code(guard, [code])
384
+
385
+ def HASATTR(self, guard: Guard):
386
+ assert isinstance(
387
+ guard.originating_source, AttrSource
388
+ ), f"invalid source {guard.name}"
389
+ base_source = guard.originating_source.base
390
+ base = base_source.name()
391
+ attr = guard.originating_source.member
392
+
393
+ ref = self.arg_ref(base)
394
+ val = hasattr(self.get(base), attr)
395
+ code = None
396
+ if val:
397
+ code = f"hasattr({ref}, {attr!r})"
398
+ else:
399
+ code = f"not hasattr({ref}, {attr!r})"
400
+
401
+ self._produce_guard_code(guard, [code], provided_guarded_object=self.get(base))
402
+
403
+ def FUNCTORCH_STACK_MATCH(self, guard: Guard):
404
+ # Invalidate functorch code if current level is different than
405
+ # the one when FX graph was generated
406
+ # if torch._C._functorch.peek_interpreter_stack() is not None:
407
+ cis = torch._functorch.pyfunctorch.retrieve_all_functorch_interpreters()
408
+ states = [ci.get_state() for ci in cis]
409
+ code = [f"torch._functorch.pyfunctorch.compare_functorch_state({states})"]
410
+ self._produce_guard_code(guard, code)
411
+
412
+ def EQUALS_MATCH(self, guard: Guard):
413
+ ref = self.arg_ref(guard)
414
+ val = self.get(guard.name)
415
+ t = type(val)
416
+ if np:
417
+ np_types: Tuple[Type[Any], ...] = (
418
+ np.int8,
419
+ np.int16,
420
+ np.int32,
421
+ np.int64,
422
+ np.uint8,
423
+ np.uint16,
424
+ np.uint32,
425
+ np.uint64,
426
+ np.float16,
427
+ np.float32,
428
+ np.float64,
429
+ )
430
+ else:
431
+ np_types = ()
432
+ ok_types = tuple(
433
+ common_constant_types
434
+ | {
435
+ type,
436
+ list,
437
+ tuple,
438
+ set,
439
+ frozenset,
440
+ slice,
441
+ range,
442
+ torch.Size,
443
+ *np_types,
444
+ }
445
+ )
446
+ if istype(val, dict):
447
+ assert all(
448
+ istype(x, ok_types) for x in itertools.chain(val.keys(), val.values())
449
+ )
450
+ else:
451
+ assert istype(
452
+ val,
453
+ ok_types,
454
+ ), f"Unexpected type {type(val)}, not in {ok_types}"
455
+
456
+ # Special case for nan because float("nan") == float("nan") evaluates to False
457
+ if istype(val, float) and math.isnan(val):
458
+ self.TYPE_MATCH(guard)
459
+ code = list()
460
+ code.append(f"__math_isnan({ref})")
461
+ self._produce_guard_code(guard, code)
462
+ return
463
+ # Python math library doesn't support complex nan, so we need to use numpy
464
+ elif istype(val, complex) and np.isnan(val):
465
+ self.TYPE_MATCH(guard)
466
+ code = list()
467
+ code.append(f"__numpy_isnan({ref})")
468
+ self._produce_guard_code(guard, code)
469
+ return
470
+
471
+ code = list()
472
+
473
+ # If matching equality against list/tuple, we must also check that
474
+ # the internal types match. (TODO: what about nested lists?)
475
+ if istype(val, (list, tuple)):
476
+ # NB: SEQUENCE_LENGTH takes care of the outer __check_type_id test
477
+ self.SEQUENCE_LENGTH(guard)
478
+
479
+ for idx, elem in enumerate(val):
480
+ code.append(
481
+ f"___check_type_id({ref}[{idx}], {self.id_ref(type(elem))})"
482
+ )
483
+ else:
484
+ # Add type check to prevent equality check between tensor and non-tensor.
485
+ self.TYPE_MATCH(guard)
486
+
487
+ if istype(val, torch.Size):
488
+ val = tuple(val)
489
+
490
+ # Code object can not be compared against their string representation
491
+ # I.e `eval(f"{compile('2+2','','exec')!r}")` raises SyntaxError
492
+ assert not istype(val, types.CodeType)
493
+
494
+ # TODO: It feels like it would be better to just implement our own
495
+ # equality test in C that handles all of the necessary type checking
496
+ # and NaN tests
497
+ code.append(f"{ref} == {val!r}")
498
+ self._produce_guard_code(guard, code)
499
+
500
+ def CONSTANT_MATCH(self, guard: Guard):
501
+ val = self.get(guard.name)
502
+ if istype(val, (bool, type(None), types.CodeType)):
503
+ self.ID_MATCH(guard)
504
+ else:
505
+ self.EQUALS_MATCH(guard)
506
+
507
+ def NN_MODULE(self, guard: Guard):
508
+ self.ID_MATCH(guard)
509
+ ref = self.arg_ref(guard)
510
+ val = self.get(guard.name)
511
+
512
+ def setup_guard():
513
+ assert istype(val.training, bool)
514
+ self._guard_on_attribute(guard, "training", GuardBuilder.CONSTANT_MATCH)
515
+
516
+ if hasattr(val, "training"):
517
+ # There are cases where a monkeypatched object has a guard made between __new__ and __init__
518
+ setup_guard()
519
+ else:
520
+ exc.unimplemented(f"Guard setup for uninitialized class {type(val)}")
521
+
522
+ def FUNCTION_MATCH(self, guard: Guard):
523
+ """things like torch.add and user defined functions"""
524
+ if guard.is_local():
525
+ return self.ID_MATCH(guard)
526
+
527
+ def CLOSURE_MATCH(self, guard: Guard):
528
+ """matches a closure by __code__ id."""
529
+ if guard.is_local():
530
+ val = self.get(guard.name)
531
+ # Strictly only want user-defined functions
532
+ if type(val) == types.FunctionType and hasattr(val, "__code__"):
533
+ self._guard_on_attribute(guard, "__code__", GuardBuilder.HASATTR)
534
+ self._guard_on_attribute(guard, "__code__", GuardBuilder.FUNCTION_MATCH)
535
+ else:
536
+ self.FUNCTION_MATCH(guard)
537
+
538
+ def BUILTIN_MATCH(self, guard: Guard):
539
+ return self.FUNCTION_MATCH(guard)
540
+
541
+ def PYMODULE_MATCH(self, guard: Guard):
542
+ return self.FUNCTION_MATCH(guard)
543
+
544
+ def SEQUENCE_LENGTH(self, guard):
545
+ # This guard is used to check lenght of PySequence objects like list,
546
+ # tuple, collections.deque etc
547
+ ref = self.arg_ref(guard)
548
+ value = self.get(guard.name)
549
+ t = type(value)
550
+
551
+ self.TYPE_MATCH(guard)
552
+ code = list()
553
+ if len(value) == 0:
554
+ code.append(f"not {ref}")
555
+ else:
556
+ code.append(f"len({ref}) == {len(value)}")
557
+
558
+ self._produce_guard_code(guard, code)
559
+
560
+ def DICT_LENGTH(self, guard):
561
+ self.SEQUENCE_LENGTH(guard)
562
+
563
+ def TUPLE_ITERATOR_LEN(self, guard):
564
+ ref = self.arg_ref(guard)
565
+ value = self.get(guard.name)
566
+ t = type(value)
567
+
568
+ self.TYPE_MATCH(guard)
569
+ code = list()
570
+ code.append(f"___tuple_iterator_len({ref}) == {tuple_iterator_len(value)}")
571
+
572
+ self._produce_guard_code(guard, code)
573
+
574
+ # TODO(voz): Deduplicate w/ AOTAutograd dupe input guards
575
+ def DUPLICATE_INPUT(self, guard, source_b):
576
+ ref_a = self.arg_ref(guard)
577
+ ref_b = self.arg_ref(source_b.name())
578
+
579
+ code = [f"{ref_b} is {ref_a}"]
580
+ self._produce_guard_code(guard, code)
581
+
582
+ def DICT_KEYS(self, guard):
583
+ # Guard on the keys and their order
584
+ ref = self.arg_ref(guard)
585
+ value = self.get(guard.name)
586
+ t = type(value)
587
+
588
+ self.TYPE_MATCH(guard)
589
+ code = list()
590
+ any_key_is_id = any(key_is_id(k) for k in value.keys())
591
+ const_keys_repr = dict_keys_repr(
592
+ key_to_id(value),
593
+ local=is_from_local_source(guard.originating_source),
594
+ )
595
+ if any_key_is_id:
596
+ code.append(f"___key_to_id({ref}) == {const_keys_repr}")
597
+ else:
598
+ code.append(f"list({ref}.keys()) == {const_keys_repr}")
599
+
600
+ self._produce_guard_code(guard, code)
601
+
602
+ def WEAKREF_ALIVE(self, guard):
603
+ self._produce_guard_code(guard, [f"{self.arg_ref(guard)} is not None"])
604
+
605
+ def NN_MODULE_PARAM_NAMES(self, guard):
606
+ ref = self.arg_ref(guard)
607
+ value = self.get(guard.name)
608
+ t = type(value)
609
+ keys = {k for k, v in value.named_parameters()}
610
+
611
+ self.TYPE_MATCH(guard)
612
+ code = list()
613
+ code.append(f"{{k for k, v in {ref}.named_parameters()}} == {keys!r}")
614
+
615
+ self._produce_guard_code(guard, code)
616
+
617
+ def DICT_CONST_KEYS(self, guard):
618
+ """Constant keys match"""
619
+ ref = self.arg_ref(guard)
620
+ value = self.get(guard.name)
621
+ t = type(value)
622
+
623
+ self.TYPE_MATCH(guard)
624
+ code = list()
625
+ code.append(f"list({ref}.keys()) == {list(value.keys())!r}")
626
+
627
+ self._produce_guard_code(guard, code)
628
+
629
+ def OBJECT_MUTATION(self, guard: Guard):
630
+ mutation_guard.watch(self.get(guard.name), self.check_fn_manager)
631
+
632
+ def GRAD_MODE(self, guard: Guard):
633
+ pass # we always guard on this via GlobalStateGuard()
634
+
635
+ def DETERMINISTIC_ALGORITHMS(self, guard: Guard):
636
+ pass # we always guard on this via GlobalStateGuard()
637
+
638
+ def TORCH_FUNCTION_STATE(self, guard: Guard):
639
+ pass # we always guard on this via GlobalStateGuard()
640
+
641
+ def DEFAULT_DEVICE(self, guard: Guard):
642
+ """Guard on CURRENT_DEVICE per torch.utils._device"""
643
+ assert guard.source is GuardSource.GLOBAL
644
+ import torch.utils._device as m
645
+
646
+ self._produce_guard_code(
647
+ guard, [f"utils_device.CURRENT_DEVICE == {m.CURRENT_DEVICE!r}"]
648
+ )
649
+
650
+ def BACKEND_MATCH(self, guard: Guard):
651
+ """Guard on backend matching based on id of current_backend"""
652
+ assert guard.source is GuardSource.GLOBAL
653
+ backend_id = (
654
+ f"{id(torch._dynamo.eval_frame.guarded_backend_cache.current_backend)}"
655
+ )
656
+ code = [f"___check_current_backend({backend_id})"]
657
+ self._produce_guard_code(guard, code)
658
+
659
+ def SHAPE_ENV(self, guard: Guard):
660
+ # Let's handle ShapeEnv guards. To do this, we will resolve
661
+ # shape variables to sources from tracked_fakes. This must happen after
662
+ # tensor checks.
663
+ assert guard.name == ""
664
+ output_graph = self.check_fn_manager.output_graph
665
+ # NB: self.output_graph can be None in the debug_nops tests
666
+ fs = output_graph.tracked_fakes
667
+ input_contexts = [a.symbolic_context for a in fs]
668
+
669
+ def get_sources(t_id, dim):
670
+ # Looks up base sources mapped to a tensor id and uses them to create
671
+ # sources for the corresponding tensor dimension.
672
+ return [
673
+ TensorPropertySource(source, TensorProperty.SIZE, dim)
674
+ for source in output_graph.tracked_fakes_id_to_source[t_id]
675
+ ]
676
+
677
+ if output_graph.export_constraints:
678
+ from sympy import Symbol
679
+
680
+ source_pairs: List[Tuple[Source, Source]] = []
681
+ derived_equalities: List[ # type: ignore[type-arg]
682
+ Tuple[Source, Union[Source, Symbol], Callable]
683
+ ] = []
684
+ phantom_symbols: Dict[str, Symbol] = {}
685
+ for constraint in output_graph.export_constraints:
686
+ if constraint.t_id in output_graph.tracked_fakes_id_to_source:
687
+ torch.export.dynamic_shapes._process_equalities(
688
+ constraint,
689
+ get_sources,
690
+ output_graph.shape_env,
691
+ source_pairs,
692
+ derived_equalities,
693
+ phantom_symbols,
694
+ )
695
+ else:
696
+ log.warning("Untracked tensor used in export constraints")
697
+ equalities_inputs = EqualityConstraint(
698
+ source_pairs=source_pairs,
699
+ derived_equalities=derived_equalities,
700
+ phantom_symbols=list(phantom_symbols.values()),
701
+ warn_only=False,
702
+ )
703
+ else:
704
+ equalities_inputs = None
705
+ guards = output_graph.shape_env.produce_guards(
706
+ [a.fake for a in fs],
707
+ [a.source for a in fs],
708
+ input_contexts=input_contexts,
709
+ equalities_inputs=equalities_inputs,
710
+ source_ref=self.source_ref,
711
+ # Export keeps static.
712
+ ignore_static=(not self.check_fn_manager.output_graph.export),
713
+ )
714
+ # When exporting, we may work with the shape constraints some more in
715
+ # postprocessing, so don't freeze yet
716
+ if not self.check_fn_manager.output_graph.export:
717
+ output_graph.shape_env.freeze()
718
+ for shape_guard in guards:
719
+ self._produce_guard_code(guard, [shape_guard], shape_env=True)
720
+
721
+ def TENSOR_MATCH(self, guard: Guard, value=None):
722
+ if guard.is_nn_module() or guard.originating_source.is_dict_key():
723
+ self.ID_MATCH(guard)
724
+ else:
725
+ if isinstance(value, TensorWeakRef):
726
+ value = value()
727
+
728
+ value = value if value is not None else self.get(guard.name)
729
+ assert isinstance(value, torch.Tensor)
730
+
731
+ tensor_name = self.arg_ref(guard)
732
+ # [Note - On Export Tensor Guards]
733
+ #
734
+ # In eager mode, tensor guards are evaluated through C++, in guards.cpp
735
+ # see [Note - On Eager Tensor Guards] for more info.
736
+ #
737
+ # In export mode, we instead maintain parallel logic between C++ and python
738
+ # here, with an exception of checking the dispatch key - with the idea that a dispatch key
739
+ # is an entirely runtime notion that would make no sense to keep in an exported graph.
740
+ #
741
+ # Now, this idea is okay, but to paraphrase @ezyang, this mental model is sufficient for now, although
742
+ # not entirely true.
743
+ # For example, suppose one of the input tensors had the negative dispatch key.
744
+ # You should end up with a graph that is specialized for tensors that have a negative dispatch key.
745
+ # If you allow a Tensor that does NOT have this bit set, you will accidentally run it "as if" it were negated.
746
+ # Now, negative key only shows up for complex numbers, and most likely, the exported to target doesn't
747
+ # support this feature at all, but the point stands that :some: tensor state only shows up on dispatch key.
748
+ # TODO(voz): Either populate a dispatch_key check into the guards, or error on users passing in an unsupported
749
+ # subset of keys during export.
750
+ #
751
+ # The list of tensor fields and calls we care about can be found in `terms` below.
752
+ # TODO(voz): We are missing storage offset in all our tensor guards?
753
+ code: List[str] = list()
754
+ if self.check_fn_manager.output_graph.export:
755
+ self.TYPE_MATCH(guard)
756
+ terms = [
757
+ "dtype",
758
+ "device",
759
+ "requires_grad",
760
+ "ndimension()",
761
+ ]
762
+
763
+ for term in terms:
764
+ real_value = self.get(tensor_name + "." + term)
765
+ if istype(real_value, (torch.device, torch.dtype)):
766
+ # copy pasted from EQUALS_MATCH
767
+ code.append(f"str({tensor_name}.{term}) == {str(real_value)!r}")
768
+ else:
769
+ code.append(f"{tensor_name}.{term} == {real_value}")
770
+ else:
771
+ self.tensor_check_names.append(tensor_name)
772
+ self.tensor_check_examples.append(value)
773
+ self.tensor_check_guards.append(guard)
774
+
775
+ # A frame is valid for reuse with dynamic dimensions if the new
776
+ # (user-requested) dynamic dimensions are a subset of the old
777
+ # (already compiled) dynamic dimensions.
778
+ #
779
+ # It's a little non-obvious why you'd want this: in particular,
780
+ # if an already compiled frame matches all of the guards, why
781
+ # not just use it, why force a recompile?
782
+ #
783
+ # We force it for two reasons:
784
+ #
785
+ # - The user *required* us to compile with a new dynamic dimension,
786
+ # we should not ignore that and serve up the old, specialized
787
+ # frame. Listen to the user!
788
+ #
789
+ # - In fact, we are obligated to *raise an error* if we fail to
790
+ # make the requested dimension dynamic. If we don't
791
+ # recompile, we can't tell if that dimension can actually be
792
+ # made dynamic.
793
+ #
794
+ # If the new dynamic dims are a subset of the old, we already know
795
+ # we can make them dynamic (since we made them dynamic in old).
796
+ # This is slightly unsound, because maybe your input size is
797
+ # [s0, s0, s1] and so you can do it dynamic if you say dynamic
798
+ # dims {0, 1, 2} but you can't if you only do {0, 2} (because now
799
+ # the second s0 is specialized). But we're not entirely sure if
800
+ # this is a good idea anyway lol... (if you want to try removing
801
+ # this logic, be my guest! -- ezyang 2024)
802
+ #
803
+ assert guard.source is not None
804
+ static, reason = tensor_always_has_static_shape(
805
+ value, is_tensor=True, guard_source=guard.source
806
+ )
807
+ if not static:
808
+ if hasattr(value, "_dynamo_dynamic_indices"):
809
+ code.append(
810
+ f"(({tensor_name}._dynamo_dynamic_indices.issubset({value._dynamo_dynamic_indices})) if hasattr({tensor_name}, '_dynamo_dynamic_indices') else True)" # noqa: B950
811
+ )
812
+ # In the case of us not having any dynamic dimension indices, we compiled the frame with no chance of
813
+ # raising for this specific tensor - and any inputs with more dynamic user directives specified must be recompiled.
814
+ else:
815
+ code.append(
816
+ f"hasattr({tensor_name}, '_dynamo_dynamic_indices') == False"
817
+ )
818
+ if len(code) > 0:
819
+ self._produce_guard_code(guard, code)
820
+
821
+ # A util that appends guarded code, or, in the case of export, adds data onto guards
822
+ def _produce_guard_code(
823
+ self, guard, code_list, provided_guarded_object=None, shape_env=False
824
+ ):
825
+ # WARNING: It is important that cur_frame/caller do NOT stay in
826
+ # the current frame, because they will keep things live longer
827
+ # than they should. See TestMisc.test_release_module_memory
828
+ cur_frame = currentframe()
829
+ assert cur_frame is not None
830
+ caller = cur_frame.f_back
831
+ del cur_frame
832
+ assert caller is not None
833
+ func_name = getframeinfo(caller)[2]
834
+ del caller
835
+ # We use func_name for export, so might as well get a nice defensive check out of it
836
+ assert func_name in dir(
837
+ self.__class__
838
+ ), f"_produce_guard_code must be called from inside GuardedCode. Called from {func_name}"
839
+
840
+ if shape_env:
841
+ self.shape_env_code.append(GuardCodeList(code_list, guard))
842
+ else:
843
+ self.code.append(GuardCodeList(code_list, guard))
844
+
845
+ # Not all guards have names, some can be installed globally (see asserts on HAS_GRAD)
846
+ if provided_guarded_object is None:
847
+ name_valid = guard.name is not None and guard.name != ""
848
+
849
+ guarded_object = self.get(guard.name) if name_valid else None
850
+ else:
851
+ guarded_object = provided_guarded_object
852
+
853
+ guarded_object_type = (
854
+ weakref.ref(type(guarded_object)) if guarded_object is not None else None
855
+ )
856
+ obj_ref = None
857
+ # Not necessary to have weakref for Enum type, but there is a bug that
858
+ # makes hasattr(guarded_object.__class__, "__weakref__") return True.
859
+ if hasattr(guarded_object.__class__, "__weakref__") and not isinstance(
860
+ guarded_object, enum.Enum
861
+ ):
862
+ obj_ref = weakref.ref(guarded_object)
863
+
864
+ guard.set_export_info(
865
+ func_name,
866
+ guarded_object_type,
867
+ code_list,
868
+ obj_ref,
869
+ )
870
+
871
+
872
+ # Common Sub-Expression Elimination for Python expressions.
873
+ #
874
+ # There are 2 steps to this pass:
875
+ # 1. Count the frequency of each sub-expression (i.e. inner
876
+ # node in the AST tree)
877
+ #
878
+ # 2. Replace those that occur more than once by a fresh variable 'v'.
879
+ # 'v' will be defined in the 'preface' list (output argument to
880
+ # 'NodeTransformer')
881
+ #
882
+ # NB: the use of 'ast.unparse' while visiting the nodes makes this pass
883
+ # quadratic on the depth of the tree.
884
+ #
885
+ # NB: this pass creates a new variable for each AST node that is repeated
886
+ # more than 'USE_THRESHOLD'. e.g. if 'a.b.c.d' is used 10 times, 'a.b.c'
887
+ # and 'a.b' are also used 10 times. So, there will be a new variable for
888
+ # each of them.
889
+ class PyExprCSEPass:
890
+ # Maximum number of times a given expression can be used without being
891
+ # replaced by a fresh variable.
892
+ USE_THRESHOLD = 1
893
+
894
+ # Ad-Hoc: AST nodes this pass focuses on.
895
+ ALLOWED_NODE_TYPES = (ast.Attribute, ast.Call, ast.Subscript)
896
+
897
+ @dataclasses.dataclass
898
+ class Config:
899
+ expr_count: Dict[str, int]
900
+ expr_to_name: Dict[str, str]
901
+
902
+ class ExprCounter(ast.NodeVisitor):
903
+ def __init__(self, config: PyExprCSEPass.Config) -> None:
904
+ self._config = config
905
+
906
+ def visit(self, node: ast.AST) -> Any:
907
+ if isinstance(node, PyExprCSEPass.ALLOWED_NODE_TYPES):
908
+ self._config.expr_count[_ast_unparse(node)] += 1
909
+ super().visit(node)
910
+
911
+ class Replacer(ast.NodeTransformer):
912
+ def __init__(
913
+ self,
914
+ config: PyExprCSEPass.Config,
915
+ gen_name: Callable[[], str],
916
+ ) -> None:
917
+ super().__init__()
918
+ self._config = config
919
+ self._gen_name = gen_name
920
+ self.preface: List[str] = []
921
+
922
+ def visit(self, node: ast.AST) -> Any:
923
+ if isinstance(node, PyExprCSEPass.ALLOWED_NODE_TYPES):
924
+ expr = _ast_unparse(node)
925
+
926
+ # Replacement only occurs if a given expression is used more
927
+ # than once.
928
+ if self._config.expr_count[expr] > PyExprCSEPass.USE_THRESHOLD:
929
+ if expr not in self._config.expr_to_name:
930
+ # Parent 'visit' is called so that we CSE the inner expressions first.
931
+ #
932
+ # The resulting expression is used as right-hand-side of the variable
933
+ # assignment. i.e. we are CSE-ing the children before the parents.
934
+ #
935
+ # Indexing still uses the old 'node', since that's what was counted
936
+ # by the 'NodeVisitor'.
937
+ node_ = super().visit(node)
938
+ expr_ = _ast_unparse(node_)
939
+ var_name = self._gen_name()
940
+ self.preface.append(f"{var_name} = {expr_}")
941
+ self._config.expr_to_name[expr] = var_name
942
+ else:
943
+ var_name = self._config.expr_to_name[expr]
944
+ return ast.Name(var_name, ast.Load())
945
+
946
+ return super().visit(node)
947
+
948
+ def __init__(self) -> None:
949
+ self._counter = 0
950
+ self._config = self.Config(
951
+ expr_count=collections.defaultdict(lambda: 0), expr_to_name={}
952
+ )
953
+
954
+ def _new_var(self, prefix: str = "_var") -> str:
955
+ name = f"{prefix}{self._counter}"
956
+ self._counter += 1
957
+ return name
958
+
959
+ def count(self, exprs: List[str]) -> None:
960
+ counter = self.ExprCounter(self._config)
961
+ for e in exprs:
962
+ try:
963
+ counter.visit(ast.parse(e))
964
+ except SyntaxError as ex:
965
+ log.exception("Failed to visit expr at line %s.\n%s", ex.lineno, e)
966
+ raise
967
+
968
+ def replace(self, expr: str) -> Tuple[List[str], str]:
969
+ replacer = self.Replacer(self._config, self._new_var)
970
+ new_node = replacer.visit(ast.parse(expr))
971
+ return replacer.preface, _ast_unparse(new_node)
972
+
973
+
974
+ def must_add_nn_module_guards(guard):
975
+ # For config.guard_nn_modules=False, we can skip all the guards that
976
+ # originate from inside of nn module except for a few categories.
977
+ return (
978
+ # Guard for defaults
979
+ isinstance(guard.originating_source, DefaultsSource)
980
+ # Guard using dict tags if the config flag is set
981
+ or (
982
+ config.guard_nn_modules_using_dict_tags
983
+ and guard.create_fn is GuardBuilder.NN_MODULE
984
+ )
985
+ )
986
+
987
+
988
+ class DeletedGuardFn:
989
+ pass
990
+
991
+
992
+ # NB: Naively, you'd expect this to only be a function that produces
993
+ # the callable that constitutes the guard. However, there is some
994
+ # delicate handling for invalidating this check function when the
995
+ # locals/globals get invalidated, so there's some extra state
996
+ # we have to hold in this manager class.
997
+ class CheckFunctionManager:
998
+ def __init__(
999
+ self,
1000
+ output_graph=None,
1001
+ guard_fail_fn: Optional[Callable[[GuardFail], None]] = None,
1002
+ ):
1003
+ guards = output_graph.guards if output_graph else None
1004
+ self._weakrefs: Dict[int, ReferenceType[object]] = {}
1005
+ self.output_graph = output_graph
1006
+ w_builder = None
1007
+
1008
+ def source_ref(source):
1009
+ guard_source = source.guard_source()
1010
+ if guard_source is GuardSource.CONSTANT:
1011
+ # No need to track constants
1012
+ return source.name()
1013
+ assert w_builder
1014
+ r_builder = w_builder()
1015
+ assert r_builder is not None
1016
+ return r_builder.arg_ref(source.name())
1017
+
1018
+ builder = GuardBuilder(
1019
+ self.id_ref,
1020
+ source_ref,
1021
+ self.lookup_weakrefs,
1022
+ output_graph.local_scope,
1023
+ output_graph.global_scope,
1024
+ self,
1025
+ )
1026
+
1027
+ # Break retain cycle. See test_release_scope_memory
1028
+ def cleanup_builder(weak_b):
1029
+ b = weak_b()
1030
+ if b:
1031
+ b.scope = None
1032
+
1033
+ # Break retain cycle. See test_release_input_memory
1034
+ w_builder = weakref.ref(builder, cleanup_builder)
1035
+
1036
+ for guard in sorted(guards or [], key=Guard.sort_key):
1037
+ if (
1038
+ not config.guard_nn_modules
1039
+ and guard.is_nn_module()
1040
+ # Default func args must be guarded on.
1041
+ # TODO: we could make use of 'DefaultsSource' and offer a .guard.is_defaults() API
1042
+ and "__defaults__" not in guard.name
1043
+ and "__kwdefaults__" not in guard.name
1044
+ and (config.skip_nnmodule_hook_guards or "hooks" not in guard.name)
1045
+ ):
1046
+ continue
1047
+
1048
+ guard.create(builder)
1049
+ self.check_fn = self.compile_check_fn(builder, guards, guard_fail_fn)
1050
+ # Keep track of weak references of objects with ID_MATCH guard. This
1051
+ # info is stored alongside optimized_code and check_fn and is used to
1052
+ # limit the number of cache entries with same ID_MATCH'd object.
1053
+ # TODO(janimesh) - Currently this information is stored as an attr on
1054
+ # the check_fn itself to avoid changing CacehEntry datastructure in
1055
+ # eval_frame.c. In future, we should probably replace check_fn with a
1056
+ # queryable data structure such that this information is already present
1057
+ # in some form.
1058
+ self.check_fn.id_matched_objs = builder.id_matched_objs
1059
+
1060
+ # NB - We have to very careful of cleaning up here. Because of the
1061
+ # invalidate function, we can create a weakref finalizer that keeps
1062
+ # `self` alive for very long. Sometimes by mistake, we can run
1063
+ # invalidate for a type/object (check id_ref method) that Python can
1064
+ # leak by design, preventing us from calling the finalizer. In that
1065
+ # case, the `self` will be alive even though the cache entry will be
1066
+ # deleted (check invalidate method), which can cause a memory leak,
1067
+ # e.g., not setting output_graph = None can keep hold of nn_modules.
1068
+ self._weakrefs.clear()
1069
+ self.output_graph = None
1070
+
1071
+ def compile_check_fn(self, builder, guards_out, guard_fail_fn):
1072
+ # see parallel handling of ".0" / "___implicit0" in _eval_frame.c
1073
+ largs = builder.argnames
1074
+ largs += ["**___kwargs_ignored"]
1075
+
1076
+ guards_log.debug("GUARDS:")
1077
+
1078
+ # Don't report this guard, it's always the same, useless!
1079
+ code_parts = ["___check_global_state()"]
1080
+ verbose_code_parts = code_parts[:]
1081
+ structured_guard_fns = []
1082
+
1083
+ def add_code_part(code_part, guard, log_only=False):
1084
+ verbose_code_part = get_verbose_code_part(code_part, guard)
1085
+ guards_log.debug("%s", verbose_code_part)
1086
+
1087
+ structured_guard_fns.append(
1088
+ lambda: {
1089
+ "code": code_part,
1090
+ "stack": structured.from_traceback(guard.stack.summary())
1091
+ if guard.stack
1092
+ else None,
1093
+ "user_stack": structured.from_traceback(guard.user_stack)
1094
+ if guard.user_stack
1095
+ else None,
1096
+ }
1097
+ )
1098
+
1099
+ if verbose_guards_log.isEnabledFor(logging.DEBUG):
1100
+ maybe_stack = ""
1101
+ maybe_user_stack = ""
1102
+ if guard is not None:
1103
+ if guard.stack:
1104
+ maybe_stack = f"\nStack:\n{''.join(guard.stack.format())}"
1105
+ if guard.user_stack:
1106
+ maybe_user_stack = (
1107
+ f"\nUser stack:\n{''.join(guard.user_stack.format())}"
1108
+ )
1109
+ verbose_guards_log.debug(
1110
+ "Guard: %s%s%s",
1111
+ code_part,
1112
+ maybe_stack,
1113
+ maybe_user_stack,
1114
+ )
1115
+
1116
+ if not log_only:
1117
+ code_parts.append(code_part)
1118
+ verbose_code_parts.append(verbose_code_part)
1119
+
1120
+ seen = set()
1121
+ for gcl in builder.code:
1122
+ for code in gcl.code_list:
1123
+ if code not in seen:
1124
+ add_code_part(code, gcl.guard)
1125
+ seen.add(code)
1126
+
1127
+ tensor_check_names = builder.tensor_check_names
1128
+ check_tensors_fn = None
1129
+ check_tensors_verbose_fn = None
1130
+ if tensor_check_names:
1131
+ assert (
1132
+ not self.output_graph.export
1133
+ ), "Illegal to set tensor_check_names in export."
1134
+ tensor_check_examples = builder.tensor_check_examples
1135
+
1136
+ dynamic_dims_sizes = [
1137
+ convert_to_concrete_values(
1138
+ self.output_graph.tensor_weakref_to_sizes_strides[t]["size"]
1139
+ )
1140
+ for t in tensor_check_examples
1141
+ ]
1142
+
1143
+ dynamic_dims_strides = [
1144
+ convert_to_concrete_values(
1145
+ self.output_graph.tensor_weakref_to_sizes_strides[t]["stride"]
1146
+ )
1147
+ for t in tensor_check_examples
1148
+ ]
1149
+
1150
+ tensor_guards = TensorGuards(
1151
+ *tensor_check_examples,
1152
+ dynamic_dims_sizes=dynamic_dims_sizes,
1153
+ dynamic_dims_strides=dynamic_dims_strides,
1154
+ )
1155
+ check_tensors_fn = tensor_guards.check
1156
+ check_tensors_verbose_fn = tensor_guards.check_verbose
1157
+ tensor_check_args = ", ".join(
1158
+ tensor_check_names + ["tensor_check_names=tensor_check_names"]
1159
+ )
1160
+ # Do this manually, to un-stagger the guards in log message
1161
+ code_parts.append(f"___check_tensors({tensor_check_args})")
1162
+ verbose_code_parts.append(f"___check_tensors({tensor_check_args})")
1163
+ tensor_check_guards = builder.tensor_check_guards
1164
+
1165
+ for i, name in enumerate(tensor_check_names):
1166
+ # This is a copy of what guards.cpp checks against
1167
+ # Keep this in sync with TensorCheck constructor
1168
+ t = tensor_check_examples[i]
1169
+ sizes = dynamic_dims_sizes[i]
1170
+ strides = dynamic_dims_strides[i]
1171
+ code_part = get_tensor_guard_code_part(t, name, sizes, strides)
1172
+ add_code_part(code_part, tensor_check_guards[i], log_only=True)
1173
+
1174
+ aotautograd_guards: List[GuardEnvExpr] = (
1175
+ self.output_graph.tracing_context.guards_context.aotautograd_guards
1176
+ if self.output_graph
1177
+ else []
1178
+ )
1179
+ for guard in aotautograd_guards:
1180
+ if isinstance(guard, DuplicateInputs):
1181
+ source_a = guard.input_source_a
1182
+ source_b = guard.input_source_b
1183
+ add_code_part(f"{source_a.name()} is {source_b.name()}", None)
1184
+ else:
1185
+ raise RuntimeError(f"Unknown GuardEnvExpr: {guard}")
1186
+
1187
+ # TODO: the "guard" here is actually just the top level SHAPE_ENV
1188
+ # which is useless. Get ShapeEnv to pass in more provenance.
1189
+ for gcl in builder.shape_env_code:
1190
+ for code in gcl.code_list:
1191
+ add_code_part(code, gcl.guard)
1192
+
1193
+ # OK, all done generating guards
1194
+ torch._logging.trace_structured(
1195
+ "dynamo_guards", payload_fn=lambda: [f() for f in structured_guard_fns]
1196
+ )
1197
+
1198
+ global_state = convert_frame.initial_global_state
1199
+ if global_state is None:
1200
+ # we should only hit this case in NopTests()
1201
+ global_state = convert_frame.GlobalStateGuard()
1202
+ closure_vars = {
1203
+ "___check_tensors": check_tensors_fn,
1204
+ "___check_tensors_verbose": check_tensors_verbose_fn,
1205
+ "___check_global_state": global_state.check,
1206
+ "___check_current_backend": torch._dynamo.eval_frame.check_current_backend,
1207
+ "tensor_check_names": tensor_check_names,
1208
+ **SYMPY_INTERP,
1209
+ **CLOSURE_VARS,
1210
+ }
1211
+
1212
+ unique_code_parts = list(unique(code_parts))
1213
+ make_guard_fn_args = ", ".join(closure_vars.keys())
1214
+ guard_body, pycode = build_guard_function(unique_code_parts, make_guard_fn_args)
1215
+
1216
+ if os.environ.get("TORCHDYNAMO_PRINT_GUARDS", None) == "1":
1217
+ print("GUARDS\n", guard_body)
1218
+
1219
+ out: Dict[str, Any] = dict()
1220
+
1221
+ # We don't put builder.scope as the globals in exec call because
1222
+ # guard_fn.__globals__ becomes equal to builder.scope. This causes
1223
+ # guard_fn to hold a referece to f_locals sitting in builder.scope["L"]
1224
+ globals_for_guard_fn = {"G": builder.scope["G"]}
1225
+ try:
1226
+ exec(pycode, globals_for_guard_fn, out)
1227
+ except SyntaxError as ex:
1228
+ log.exception("Failed to exec guard at line %s.\n%s", ex.lineno, pycode)
1229
+ raise
1230
+ guard_fn = out["___make_guard_fn"](*closure_vars.values())
1231
+ guard_fn.closure_vars = closure_vars
1232
+ # TODO(whc) maybe '.code_parts' was only kept around for the guard callback? so we don't need both
1233
+ guard_fn.args = largs
1234
+ guard_fn.code_parts = code_parts
1235
+ guard_fn.verbose_code_parts = verbose_code_parts
1236
+ # Grab only G, but preserve "G" because guards access it as "G"
1237
+ guard_fn.global_scope = globals_for_guard_fn
1238
+ guard_fn.guard_fail_fn = guard_fail_fn
1239
+ # will be populated by a non-owning reference to CacheEntry/ExtraState
1240
+ # when the CacheEntry is constructed
1241
+ guard_fn.cache_entry = None
1242
+ guard_fn.extra_state = None
1243
+ return guard_fn
1244
+
1245
+ def invalidate(self):
1246
+ # Some tests reveal that CheckFunctionManager has no attribute
1247
+ # check_fn, but this case should not be of any concern.
1248
+ # This case doesn't seem easy to repro.
1249
+ if (
1250
+ hasattr(self, "check_fn")
1251
+ and self.check_fn is not DeletedGuardFn
1252
+ and (cache_entry := self.check_fn.cache_entry) is not None
1253
+ and (extra_state := self.check_fn.extra_state) is not None
1254
+ ):
1255
+ assert isinstance(cache_entry, CacheEntry)
1256
+ assert isinstance(extra_state, ExtraState)
1257
+ extra_state.invalidate(cache_entry)
1258
+ self.check_fn.cache_entry = None
1259
+ self.check_fn.extra_state = None
1260
+ self.check_fn = DeletedGuardFn
1261
+
1262
+ def id_ref(self, obj):
1263
+ """add a weakref, return the id"""
1264
+ try:
1265
+ if id(obj) not in self._weakrefs:
1266
+ # We will clear the _weakrefs dict at the end of __init__
1267
+ # function, which will delete the callbacks as well. Therefore,
1268
+ # we are using a finalizer which is kept alive.
1269
+ self._weakrefs[id(obj)] = weakref.ref(obj)
1270
+ weakref.finalize(obj, self.invalidate)
1271
+ except TypeError:
1272
+ pass # cannot weakref bool object
1273
+ return id(obj)
1274
+
1275
+ def lookup_weakrefs(self, obj):
1276
+ """Lookup the _weakrefs created in id_ref function for ID_MATCH'd objects"""
1277
+ if id(obj) in self._weakrefs:
1278
+ return self._weakrefs[id(obj)]
1279
+ return None
1280
+
1281
+
1282
+ def build_guard_function(code_parts, closure_args) -> Tuple[str, str]:
1283
+ from torch._inductor.utils import IndentedBuffer
1284
+
1285
+ if HAS_UNPARSE_FUNCTIONS:
1286
+ csepass = PyExprCSEPass()
1287
+ csepass.count(code_parts)
1288
+
1289
+ def replace(expr: str) -> Tuple[List[str], str]:
1290
+ return csepass.replace(expr)
1291
+
1292
+ else:
1293
+
1294
+ def replace(expr: str) -> Tuple[List[str], str]:
1295
+ return [], expr
1296
+
1297
+ # Generate the inner body of the guard function.
1298
+ # i.e. if-chain of the guard expressions.
1299
+ guard_body = IndentedBuffer()
1300
+ for expr in code_parts:
1301
+ preface, expr = replace(expr)
1302
+ guard_body.writelines(preface)
1303
+ guard_body.writeline(f"if not ({expr}):")
1304
+ with guard_body.indent():
1305
+ guard_body.writeline("return False")
1306
+
1307
+ # Wrap the inner body into the actual guard function.
1308
+ guard = IndentedBuffer()
1309
+ guard.writeline("def guard(L):")
1310
+ with guard.indent():
1311
+ guard.splice(guard_body)
1312
+ guard.writeline("return True")
1313
+
1314
+ # Wrap the whole guard function into another function
1315
+ # with the closure variables.
1316
+ make_guard_fn = IndentedBuffer()
1317
+ make_guard_fn.writeline(f"def ___make_guard_fn({closure_args}):")
1318
+ with make_guard_fn.indent():
1319
+ make_guard_fn.splice(guard)
1320
+ make_guard_fn.writeline("return guard")
1321
+
1322
+ return guard_body.getvalue(), make_guard_fn.getvalue()
1323
+
1324
+
1325
+ def is_recompiles_enabled():
1326
+ return torch._logging._internal.log_state.is_artifact_enabled("recompiles")
1327
+
1328
+
1329
+ def is_recompiles_verbose_enabled():
1330
+ return torch._logging._internal.log_state.is_artifact_enabled("recompiles_verbose")
1331
+
1332
+
1333
+ def get_guard_fail_reason(
1334
+ guard_fn: GuardFn,
1335
+ code: types.CodeType,
1336
+ f_locals: Dict[str, object],
1337
+ ) -> str:
1338
+ """
1339
+ Return the reason why `guard_fn` failed.
1340
+ Updates `guard_failures` with the generated reason.
1341
+ Only the first failed check of guard_fn is reported.
1342
+ """
1343
+ scope = {"L": f_locals, "G": guard_fn.global_scope["G"]}
1344
+ scope.update(guard_fn.closure_vars)
1345
+ scope["___check_tensors"] = scope["___check_tensors_verbose"]
1346
+ reasons: List[str] = []
1347
+ for part in guard_fn.verbose_code_parts:
1348
+ global_scope = dict(guard_fn.global_scope)
1349
+ global_scope["__compile_source__"] = part
1350
+ with report_compile_source_on_error():
1351
+ try:
1352
+ fail_reason = eval(part, global_scope, scope)
1353
+ except Exception as e:
1354
+ if is_recompiles_verbose_enabled():
1355
+ continue
1356
+ else:
1357
+ raise
1358
+ # Only ___check_tensors knows how to return a fancy fail reason;
1359
+ # for everything else we just report the code that failed
1360
+
1361
+ if isinstance(fail_reason, bool) and not fail_reason:
1362
+ fail_reason = part
1363
+ if isinstance(fail_reason, str):
1364
+ reasons.append(fail_reason)
1365
+ if not is_recompiles_verbose_enabled():
1366
+ break
1367
+
1368
+ reason_str = "\n".join(reasons)
1369
+ guard_failures[orig_code_map[code]].append(reason_str)
1370
+
1371
+ try:
1372
+ if guard_fn.guard_fail_fn is not None:
1373
+ guard_fn.guard_fail_fn(
1374
+ GuardFail(reason_str or "unknown reason", orig_code_map[code])
1375
+ )
1376
+ except Exception as e:
1377
+ log.exception(
1378
+ "Failure in guard_fail_fn callback - raising here will cause a NULL Error on guard eval",
1379
+ )
1380
+
1381
+ return reason_str
1382
+
1383
+
1384
+ def get_and_maybe_log_recompilation_reason(
1385
+ cache_entry, frame: types.FrameType
1386
+ ) -> List[str]:
1387
+ """
1388
+ Return the list of guard failure reasons using cache_entry.
1389
+ Logs the recompilation reason if `recompiles` logging is enabled.
1390
+ Raises a RecompileError if `config.error_on_recompile` is enabled.
1391
+ """
1392
+ reasons = []
1393
+ while cache_entry is not None:
1394
+ reason = get_guard_fail_reason(
1395
+ cache_entry.check_fn, cache_entry.code, frame.f_locals
1396
+ )
1397
+ if reason:
1398
+ reasons.append(reason)
1399
+ cache_entry = cache_entry.next
1400
+
1401
+ code = frame.f_code
1402
+
1403
+ # at least one of "recompiles" or "recompiles_verbose" is enabled
1404
+ do_recompiles_log = is_recompiles_enabled() or is_recompiles_verbose_enabled()
1405
+
1406
+ if do_recompiles_log or config.error_on_recompile:
1407
+ if is_recompiles_verbose_enabled():
1408
+ failures = "\n\n".join(
1409
+ f"guard {i} failures:\n" + textwrap.indent(reason, "- ")
1410
+ for i, reason in enumerate(reasons)
1411
+ )
1412
+ else:
1413
+ failures = textwrap.indent("\n".join(reasons), "- ")
1414
+ guard_failure_details = (
1415
+ f"triggered by the following guard failure(s):\n{failures}"
1416
+ )
1417
+ message = (
1418
+ f"Recompiling function {code.co_name} in {code.co_filename}:{code.co_firstlineno}\n"
1419
+ f"{textwrap.indent(guard_failure_details, ' ')}"
1420
+ )
1421
+ if do_recompiles_log:
1422
+ if is_recompiles_verbose_enabled():
1423
+ recompiles_verbose_log.debug(message)
1424
+ else:
1425
+ recompiles_log.debug(message)
1426
+ if config.error_on_recompile:
1427
+ raise exc.RecompileError(message)
1428
+
1429
+ return reasons
1430
+
1431
+
1432
+ def guard_error_hook(
1433
+ guard_fn: GuardFn,
1434
+ code: types.CodeType,
1435
+ f_locals: Dict[str, object],
1436
+ index: int,
1437
+ last: bool,
1438
+ ):
1439
+ print(
1440
+ f"ERROR RUNNING GUARDS {code.co_name} {code.co_filename}:{code.co_firstlineno}"
1441
+ )
1442
+ print("lambda " + ", ".join(guard_fn.args) + ":")
1443
+ print(" ", " and\n ".join(guard_fn.code_parts))
1444
+ local_scope = {"L": f_locals, **guard_fn.closure_vars}
1445
+ for guard in guard_fn.code_parts:
1446
+ try:
1447
+ eval(guard, guard_fn.global_scope, local_scope)
1448
+ except: # noqa: B001,E722
1449
+ print(f"Malformed guard:\n{guard}")
1450
+
1451
+
1452
+ set_guard_error_hook(guard_error_hook)
1453
+
1454
+
1455
+ def unique(seq):
1456
+ seen = set()
1457
+ for x in seq:
1458
+ if x not in seen:
1459
+ yield x
1460
+ seen.add(x)
1461
+
1462
+
1463
+ def make_dupe_guard(obj_source, dupe_source):
1464
+ # Note - we may end up in a situation where we invoke something like
1465
+ # def fn(x, y)
1466
+ # with fn(x, x)
1467
+ # Prior to the addition of tracking to all relevant objects, we would handle this just fine by
1468
+ # eagerly re-entering VB and rewrapping inputs, correctly creating graphargs and placeholders. However,
1469
+ # with tracking on inputs, duplicate inputs or aliased relationships may end up getting erased here -
1470
+ # In the fn(x, x) example call above look like a graph with a single input.
1471
+ # In order to ensure that we do not reuse fn(x, x) for fn(x, y), we create a duplicate input guard.
1472
+
1473
+ # Note - we may not have a source, that is fine, it just means we had an object that is safe to have
1474
+ # leave unsourced - like a local list created and discharged entirely within a local scope.
1475
+ if dupe_source and dupe_source != obj_source:
1476
+ ser_source_is_local = is_from_local_source(dupe_source)
1477
+ source_is_local = is_from_local_source(obj_source)
1478
+ # Note - both must be local, or global, or we will run afoul of a lack of merging in how we currently
1479
+ # reconcile guards builder scopes in compile_check_fn. This technically means we miss a guard here,
1480
+ # so maybe we should do this refactor before we land this...
1481
+ # TODO(voz): Combine local and global guard builders.
1482
+ if ser_source_is_local == source_is_local:
1483
+ # Note - this is a little aggressive - these being duplicate input does not always matter.
1484
+ # However, this should always be a sound guard to add here.
1485
+ return functools.partial(GuardBuilder.DUPLICATE_INPUT, source_b=dupe_source)
1486
+ return None
1487
+
1488
+
1489
+ def install_guard(*guards, skip=0):
1490
+ """
1491
+ Add dynamo guards to the current tracing context.
1492
+
1493
+ Args:
1494
+ guards: guard(s) to add
1495
+ skip: number of stack frames to ignore for debug stack trace
1496
+ """
1497
+ from torch._guards import TracingContext
1498
+
1499
+ collect_debug_stack = guards_log.isEnabledFor(
1500
+ logging.DEBUG
1501
+ ) or verbose_guards_log.isEnabledFor(logging.DEBUG)
1502
+ add = TracingContext.get().guards_context.dynamo_guards.add
1503
+ for guard in guards:
1504
+ assert isinstance(guard, Guard)
1505
+ add(guard, collect_debug_stack=collect_debug_stack, skip=skip + 1)
llmeval-env/lib/python3.10/site-packages/torch/_dynamo/logging.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import itertools
2
+ import logging
3
+
4
+ from torch.hub import _Faketqdm, tqdm
5
+
6
+ # Disable progress bar by default, not in dynamo config because otherwise get a circular import
7
+ disable_progress = True
8
+
9
+
10
+ # Return all loggers that torchdynamo/torchinductor is responsible for
11
+ def get_loggers():
12
+ return [
13
+ logging.getLogger("torch.fx.experimental.symbolic_shapes"),
14
+ logging.getLogger("torch._dynamo"),
15
+ logging.getLogger("torch._inductor"),
16
+ ]
17
+
18
+
19
+ # Creates a logging function that logs a message with a step # prepended.
20
+ # get_step_logger should be lazily called (i.e. at runtime, not at module-load time)
21
+ # so that step numbers are initialized properly. e.g.:
22
+
23
+ # @functools.lru_cache(None)
24
+ # def _step_logger():
25
+ # return get_step_logger(logging.getLogger(...))
26
+
27
+ # def fn():
28
+ # _step_logger()(logging.INFO, "msg")
29
+
30
+ _step_counter = itertools.count(1)
31
+
32
+ # Update num_steps if more phases are added: Dynamo, AOT, Backend
33
+ # This is very inductor centric
34
+ # _inductor.utils.has_triton() gives a circular import error here
35
+
36
+ if not disable_progress:
37
+ try:
38
+ import triton # noqa: F401
39
+
40
+ num_steps = 3
41
+ except ImportError:
42
+ num_steps = 2
43
+ pbar = tqdm(total=num_steps, desc="torch.compile()", delay=0)
44
+
45
+
46
+ def get_step_logger(logger):
47
+ if not disable_progress:
48
+ pbar.update(1)
49
+ if not isinstance(pbar, _Faketqdm):
50
+ pbar.set_postfix_str(f"{logger.name}")
51
+
52
+ step = next(_step_counter)
53
+
54
+ def log(level, msg, **kwargs):
55
+ logger.log(level, "Step %s: %s", step, msg, **kwargs)
56
+
57
+ return log
llmeval-env/lib/python3.10/site-packages/torch/_dynamo/output_graph.py ADDED
@@ -0,0 +1,2063 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import collections
2
+ import contextlib
3
+ import copy
4
+ import functools
5
+ import itertools
6
+ import logging
7
+ import operator
8
+ import re
9
+ import sys
10
+ import traceback
11
+ import weakref
12
+ from dataclasses import dataclass
13
+ from typing import Any, Callable, Dict, List, NamedTuple, Optional, Set, Tuple, Union
14
+
15
+ import sympy
16
+
17
+ import torch._guards
18
+
19
+ import torch._logging
20
+
21
+ import torch.nn
22
+ import torch.utils._pytree as pytree
23
+ from torch import fx
24
+ from torch._guards import (
25
+ Checkpointable,
26
+ GlobalContextCheckpointState,
27
+ GuardsCheckpointState,
28
+ Source,
29
+ TracingContext,
30
+ )
31
+ from torch._utils_internal import signpost_event
32
+ from torch.fx._lazy_graph_module import _make_graph_module # type: ignore[attr-defined]
33
+ from torch.fx.experimental._backward_state import BackwardState
34
+ from torch.fx.experimental.sym_node import SymNode
35
+ from torch.fx.experimental.symbolic_shapes import free_symbols, is_symbolic, ShapeEnv
36
+ from torch.utils._python_dispatch import is_traceable_wrapper_subclass
37
+ from torch.utils._sympy.interp import sympy_interp
38
+ from torch.utils._sympy.reference import PythonReferenceAnalysis
39
+ from torch.utils.weak import WeakTensorKeyDictionary
40
+
41
+ from . import config, logging as torchdynamo_logging, variables
42
+ from .backends.registry import CompiledFn, CompilerFn
43
+ from .bytecode_transformation import (
44
+ create_call_function,
45
+ create_instruction,
46
+ Instruction,
47
+ unique_id,
48
+ )
49
+ from .code_context import code_context
50
+ from .codegen import PyCodegen
51
+ from .current_scope_id import enter_new_scope
52
+ from .exc import (
53
+ BackendCompilerFailed,
54
+ exceptions_allowed_to_be_fallback,
55
+ SkipFrame,
56
+ unimplemented,
57
+ unimplemented_with_warning,
58
+ )
59
+ from .guards import GuardBuilder, install_guard
60
+ from .mutation_guard import is_dynamic_nn_module
61
+ from .side_effects import SideEffects
62
+ from .source import (
63
+ AttrSource,
64
+ BackwardStateSource,
65
+ ConstantSource,
66
+ GlobalStateSource,
67
+ is_constant_source,
68
+ is_from_local_source,
69
+ LocalSource,
70
+ ParamBufferSource,
71
+ ShapeEnvSource,
72
+ TensorProperty,
73
+ TensorPropertySource,
74
+ )
75
+ from .utils import (
76
+ checkpoint_params,
77
+ CleanupHook,
78
+ clone_inputs,
79
+ count_calls,
80
+ counters,
81
+ dynamo_timed,
82
+ get_instruction_source_311,
83
+ get_static_address_type,
84
+ graph_break_reasons,
85
+ increment_op_count,
86
+ lazy_format_graph_code,
87
+ lazy_format_graph_tabular,
88
+ LazyString,
89
+ same,
90
+ )
91
+ from .variables.base import VariableTracker
92
+ from .variables.builder import (
93
+ BackwardStateGraphArg,
94
+ GraphArg,
95
+ TrackedFake,
96
+ VariableBuilder,
97
+ wrap_fx_proxy,
98
+ )
99
+ from .variables.nn_module import NNModuleVariable
100
+ from .variables.tensor import (
101
+ NumpyNdarrayVariable,
102
+ SymNodeVariable,
103
+ TensorVariable,
104
+ UnspecializedPythonVariable,
105
+ )
106
+
107
+ from .variables.torch_function import TensorWithTFOverrideVariable
108
+
109
+ log = logging.getLogger(__name__)
110
+ graph_tabular_log = torch._logging.getArtifactLogger(__name__, "graph")
111
+ graph_code_log = torch._logging.getArtifactLogger(__name__, "graph_code")
112
+ graph_sizes_log = torch._logging.getArtifactLogger(__name__, "graph_sizes")
113
+ trace_call_log = torch._logging.getArtifactLogger(__name__, "trace_call")
114
+
115
+
116
+ class OutputGraphState(NamedTuple):
117
+ input_source_to_var: Dict[Source, VariableTracker]
118
+ tracked_fakes: List[TrackedFake]
119
+ guard_state: GuardsCheckpointState
120
+ nn_modules: Optional[Dict[str, torch.nn.Module]]
121
+ register_finalizer_fns: List[Callable[[fx.GraphModule], None]]
122
+ global_state: Optional[Dict[str, bool]]
123
+ param_name_to_source: Optional[Dict[str, Source]]
124
+ side_effects: SideEffects
125
+ timestamp: int
126
+ non_compliant_ops: Set[torch._ops.OpOverload]
127
+ compliant_custom_ops: Set[torch._ops.OpOverload]
128
+
129
+ def diff(self, other: "OutputGraphState", *, prefix: str = "") -> Optional[str]:
130
+ for k in self._fields:
131
+ if k == "guard_state":
132
+ r = self.guard_state.diff(other.guard_state)
133
+ if r is not None:
134
+ return r
135
+ continue
136
+ elif k == "side_effects":
137
+ r = self.side_effects.diff(other.side_effects)
138
+ if r is not None:
139
+ return r
140
+ continue
141
+
142
+ sv = getattr(self, k)
143
+ ov = getattr(other, k)
144
+ if sv != ov:
145
+ return f"{prefix}{k} mismatch: {sv} != {ov}"
146
+ return None
147
+
148
+ # Back compat .guards api
149
+ @property
150
+ def guards(self):
151
+ return self.guard_state.dynamo_guards
152
+
153
+
154
+ @functools.lru_cache(None)
155
+ def _step_logger():
156
+ return torchdynamo_logging.get_step_logger(log)
157
+
158
+
159
+ @dataclass
160
+ class GraphCompileReason:
161
+ """Stores why a given output graph was compiled; i.e. what caused the graph break."""
162
+
163
+ reason: str
164
+ user_stack: List[traceback.FrameSummary]
165
+
166
+ # Indicates if this was a graph compile reason due to graph break.
167
+ graph_break: bool = True
168
+
169
+ def __post_init__(self):
170
+ if self.graph_break:
171
+ graph_break_reasons.append(self)
172
+
173
+
174
+ def _get_gen_rand_values_fn(random_calls):
175
+ def _gen_rand_values():
176
+ return [fn(*args, **kwargs) for fn, args, kwargs in random_calls]
177
+
178
+ return _gen_rand_values
179
+
180
+
181
+ class FakeRootModule(torch.nn.Module):
182
+ """Trick the constructor of fx.GraphModule"""
183
+
184
+ def __init__(self, nn_modules: Dict[str, torch.nn.Module]):
185
+ super().__init__()
186
+ for k, v in nn_modules.items():
187
+ setattr(self, k, v)
188
+
189
+ def __repr__(self):
190
+ return "FakeRootModule(...)"
191
+
192
+
193
+ class WrapperBackend:
194
+ def __init__(self, backend: CompilerFn):
195
+ self.backend: CompilerFn = backend
196
+
197
+ def __call__(self, gm: torch.fx.GraphModule, example_inputs: List[torch.Tensor]):
198
+ self.restore = checkpoint_params(gm)
199
+ self.gm = gm
200
+ copy_gm = copy.deepcopy(self.gm)
201
+ self.candidate = self.backend(copy_gm, example_inputs)
202
+
203
+ if self.candidate is None or self.candidate is self.gm.forward:
204
+ return self.gm.forward
205
+
206
+ if not config.verify_correctness:
207
+ return self.candidate
208
+
209
+ # if verify_correctness=True
210
+ try:
211
+ correct = self.gm.forward(*clone_inputs(example_inputs))
212
+ result = self.candidate(*clone_inputs(example_inputs))
213
+
214
+ # TODO: replace `same` function with the one in testing
215
+ if same(correct, result):
216
+ return self.candidate
217
+
218
+ raise RuntimeError(f"incorrect results of backend {self}")
219
+ return self.gm.forward
220
+
221
+ except Exception:
222
+ log.exception("error in verify_correctness")
223
+ raise
224
+ finally:
225
+ self.restore()
226
+
227
+
228
+ Scope = Dict[str, object]
229
+
230
+
231
+ class OutputGraph(Checkpointable[OutputGraphState]):
232
+ """
233
+ Wrapper class to hold outputs of InstructionTranslator. Mainly the
234
+ generated fx.Graph.
235
+
236
+ OutputGraph is 1:1 with a frame being processed. Each frame is associated
237
+ with some root InstructionTranslator. When user code calls a function,
238
+ we construct a InliningInstructionTranslator that continues to write into
239
+ the root InstructionTranslator's OutputGraph.
240
+ """
241
+
242
+ def __init__(
243
+ self,
244
+ code_options: Dict[str, Any],
245
+ compiler_fn: Optional[CompilerFn],
246
+ root_tx,
247
+ export: bool,
248
+ export_constraints,
249
+ frame_state,
250
+ local_scope: Scope,
251
+ global_scope: Scope,
252
+ f_code,
253
+ ):
254
+ super().__init__()
255
+ self.tracers = [SubgraphTracer(self, export_root=export)]
256
+ # Map from graph input's `Source` to its `VariableTracker` to
257
+ # de-duplicate graph inputs by source and reuse the tracker
258
+ self.input_source_to_var: Dict[Source, VariableTracker] = {}
259
+ self.export = export
260
+ self.export_constraints = export_constraints
261
+ self.frame_state = frame_state
262
+ self.tensor_weakref_to_sizes_strides = WeakTensorKeyDictionary()
263
+ self.cleanup_hooks: List[Callable[[], Any]] = []
264
+ # compile_id is an id number for the current torch.compile
265
+ self.compile_id: int = next(_compile_id_counter)
266
+ # Set of globals installed via install_global* APIs
267
+ self.installed_globals: Set[str] = set()
268
+
269
+ # TODO: maybe should just pass the entire f_code in here? Not
270
+ # sure...
271
+ self.co_fields = {
272
+ "co_name": f_code.co_name,
273
+ "co_filename": f_code.co_filename,
274
+ "co_firstlineno": f_code.co_firstlineno,
275
+ }
276
+
277
+ # tracked_fakes says where any tensor that was wrapped to fake came
278
+ # from. It is similar to GraphArg, in that all GraphArgs will get
279
+ # will get added to TrackedFakes, but TrackedFakes also contains
280
+ # GraphArgs that got pruned, and things like Tensor attributes which
281
+ # aren't explicit graph inputs. Used by shape guard
282
+ self.tracked_fakes: List[TrackedFake] = []
283
+
284
+ # List of symbols for which we have exact bindings in the arguments
285
+ # already
286
+ self.bound_symbols: Set[sympy.Symbol] = set()
287
+
288
+ shape_env = ShapeEnv(
289
+ # Reference Cycle!
290
+ # Share a reference to the list of TrackedFake.
291
+ #
292
+ # ShapeEnv needs this in order to be able to reproduce the call
293
+ # to produce_guards at an arbitrary time point. That is because
294
+ # TrackedFake instances may have its metadata changed throughout
295
+ # the program execution.
296
+ tracked_fakes=self.tracked_fakes,
297
+ allow_scalar_outputs=config.capture_scalar_outputs,
298
+ allow_dynamic_output_shape_ops=config.capture_dynamic_output_shape_ops,
299
+ co_fields=self.co_fields,
300
+ )
301
+
302
+ # In export mode, we force the shape_env to strictly disallow any constraining
303
+ # of the user marked dynamic dims
304
+ fake_mode = torch._subclasses.FakeTensorMode(
305
+ shape_env=shape_env,
306
+ # TODO (tmanlaibaatar) Remove this once we always lift params and buffers
307
+ allow_non_fake_inputs=True if self.export else False,
308
+ )
309
+ self.tracing_context: TracingContext = TracingContext(fake_mode)
310
+ self.init_ambient_guards()
311
+
312
+ # Map each tensor id to a list of sources. This is necessary because
313
+ # tensor ids cannot be recovered from tracked fakes (in general).
314
+ # We use this map to interpret (i.e., check for violations of) constraints,
315
+ # specifically equality constraints, which have shared tensor ids in them.
316
+ # This map should also be generally useful, e.g., for (de)serialization.
317
+ self.tracked_fakes_id_to_source: Dict[
318
+ int, List[Source]
319
+ ] = collections.defaultdict(list)
320
+ # Stores the full fqn of a param or buffer to the relevant source.
321
+ self.param_name_to_source: Optional[Dict[str, Source]] = dict()
322
+ self.side_effects = SideEffects()
323
+ self.code_options = dict(code_options)
324
+ self.output_instructions: List[Instruction] = []
325
+ # used to track nodes that are added between calls of copy_graphstate
326
+ # and restore_graphstate
327
+ self.timestamp = 0
328
+
329
+ # A list of register_finalizer_fns to apply to the output graph module
330
+ self.register_finalizer_fns: List[Callable[[fx.GraphModule], None]] = []
331
+
332
+ # Not checkpointed
333
+ self.compiler_fn: Optional[CompilerFn] = compiler_fn
334
+ self.global_scope = global_scope
335
+ self.local_scope = local_scope
336
+ self.root_tx = root_tx
337
+ from torch._dynamo.symbolic_convert import InstructionTranslatorBase
338
+
339
+ # Given a source, what are the user stacks of all locations that
340
+ # accessed it?
341
+ #
342
+ # For efficiency, we only populate this:
343
+ # - During export, and
344
+ # - If the source could potentially lead to a spurious export input
345
+ #
346
+ # Feel free to populate this more frequently if other use-cases arise,
347
+ # but be aware that we have to generate full stacks for each
348
+ # recording!
349
+ self.source_to_user_stacks: Dict[Source, List[traceback.StackSummary]] = {}
350
+
351
+ self._current_tx: List[InstructionTranslatorBase] = []
352
+ self.cleanups: List[CleanupHook] = []
353
+ self.should_exit = False
354
+ self.unspec_variable_map: Dict[str, UnspecializedPythonVariable] = {}
355
+ self.torch_function_enabled = torch._C._is_torch_function_enabled()
356
+ # Tracks if the output graph has a user defined allowed function in the
357
+ # graph. This is used later to determine if we should fallback to eager
358
+ # for certain exceptions. THe idea is that if the user has applied
359
+ # allow_in_graph, they would like to see the error instead of falling
360
+ # back for backend errors.
361
+ self.has_user_defined_allowed_in_graph = False
362
+
363
+ # Tracks a list of called ops that were not tagged with "pt2_compliant_tag".
364
+ # This information is useful for logging.
365
+ self.non_compliant_ops: Set[torch._ops.OpOverload] = set({})
366
+
367
+ # Tracks a list of called custom ops that were tagged with "pt2_compliant_tag".
368
+ # This information is useful for logging.
369
+ self.compliant_custom_ops: Set[torch._ops.OpOverload] = set({})
370
+
371
+ # We save the global torch state here to be restored in case of graph
372
+ # breaks. The relevant issue is seen here
373
+ # https://github.com/pytorch/pytorch/pull/100570#issuecomment-1543427086
374
+ # where inlining of a function changes the global state (because of the
375
+ # presence of torch.no_grad) and there is a graph break.
376
+ self.save_global_state()
377
+
378
+ # Tracks the original FQNs of the constant tensors from the original graph,
379
+ # i.e. buffers and parameters.
380
+ self.dynamo_flat_name_to_original_fqn: Dict[str, str] = {}
381
+
382
+ # All calls to random() are replaced with a single call to __gen_rand_values
383
+ # functions that returns a tuple of random values for each original call.
384
+ # random_calls tracks calls to random() and random_values_var stores the name of
385
+ # the variable that stores __gen_rand_values results.
386
+ self.random_calls: List[
387
+ Tuple[Callable[..., object], Tuple[object, ...], Dict[str, object]]
388
+ ] = []
389
+ self.random_values_var = None
390
+
391
+ # Bytecode to insert right before we call the graph
392
+ self.pregraph_bytecode: List[Instruction] = []
393
+
394
+ # Use to pass values to backward hooks when using compiled autograd
395
+ self.backward_state: Dict[str, VariableTracker] = {}
396
+ self.backward_state_proxy: Optional[torch.fx.Proxy] = None
397
+ self.backward_state_var: Optional[str] = None
398
+
399
+ def add_backward_state_hook(self, hook: VariableTracker):
400
+ name = f"hook{len(self.backward_state)}"
401
+ assert name not in self.backward_state
402
+ self.backward_state[name] = hook
403
+ return name, self.get_backward_state_proxy()
404
+
405
+ def get_backward_state_proxy(self):
406
+ if self.backward_state_proxy is None:
407
+ if self.export:
408
+ unimplemented("backward_state does not support export")
409
+ self.backward_state_proxy = self.root_tracer.create_graph_input(
410
+ "dynamo_backward_state", BackwardState, source=BackwardStateSource()
411
+ )
412
+ self.backward_state_proxy.node.meta["grapharg"] = BackwardStateGraphArg()
413
+ self.backward_state_proxy.node.meta["example_value"] = BackwardState()
414
+ self.backward_state_var = self.new_var()
415
+ return self.backward_state_proxy
416
+
417
+ # This gets its own helper function so guards DEBUG logs are more informative
418
+ def init_ambient_guards(self):
419
+ # Register a SHAPE_ENV guard to make sure we setup shape guards
420
+ # that show up in ShapeEnv
421
+ self.guards.add(ShapeEnvSource().make_guard(GuardBuilder.SHAPE_ENV))
422
+
423
+ self.guards.add(
424
+ GlobalStateSource().make_guard(GuardBuilder.DETERMINISTIC_ALGORITHMS)
425
+ )
426
+
427
+ self.guards.add(GlobalStateSource().make_guard(GuardBuilder.GRAD_MODE))
428
+
429
+ self.guards.add(GlobalStateSource().make_guard(GuardBuilder.DEFAULT_DEVICE))
430
+
431
+ self.guards.add(
432
+ GlobalStateSource().make_guard(GuardBuilder.TORCH_FUNCTION_STATE)
433
+ )
434
+
435
+ self.guards.add(GlobalStateSource().make_guard(GuardBuilder.BACKEND_MATCH))
436
+
437
+ def add_cleanup_hook(self, fn: Callable[[], Any]):
438
+ self.cleanup_hooks.append(fn)
439
+
440
+ def call_cleanup_hooks(self):
441
+ for hook in reversed(self.cleanup_hooks):
442
+ hook()
443
+ self.cleanup_hooks.clear()
444
+
445
+ @property
446
+ def root_tracer(self):
447
+ return self.tracers[0]
448
+
449
+ @property
450
+ def current_tracer(self):
451
+ return self.tracers[-1]
452
+
453
+ def is_root_tracer(self):
454
+ # Helper to tell if we are inside the higher order operator tracing.
455
+ return len(self.tracers) == 1
456
+
457
+ @property
458
+ def graph(self):
459
+ return self.current_tracer.graph
460
+
461
+ # TODO(rzou): can delete after we refactor speculate_subgraph to use nested GraphTracer.
462
+ @graph.setter
463
+ def graph(self, value):
464
+ self.current_tracer.graph = value
465
+
466
+ @property
467
+ def input_name_to_proxy(self):
468
+ return self.current_tracer.input_name_to_proxy
469
+
470
+ @property
471
+ def real_value_cache(self):
472
+ return self.current_tracer.real_value_cache
473
+
474
+ # If you are here, and you're looking for create_graph_input,
475
+ # to avoid ambiguity, please call one of the following:
476
+ # - self.current_tracer.create_graph_input
477
+ # - self.root_tracer.create_graph_input
478
+ # See NOTE [HigherOrderOperator tracing design] for more context.
479
+
480
+ def create_proxy(self, *args, **kwargs):
481
+ return self.current_tracer.create_proxy(*args, **kwargs)
482
+
483
+ def create_node(self, *args, **kwargs):
484
+ return self.current_tracer.create_node(*args, **kwargs)
485
+
486
+ def remove_node(self, *args, **kwargs):
487
+ return self.current_tracer.remove_node(*args, **kwargs)
488
+
489
+ @contextlib.contextmanager
490
+ def subtracer(self, source_target, prior_tracer):
491
+ new_scope_ctx = enter_new_scope()
492
+ try:
493
+ if prior_tracer:
494
+ # Lineage MUST stay preserved
495
+ assert prior_tracer.parent is self.current_tracer
496
+ new_scope_ctx.__enter__()
497
+ tracer = (
498
+ prior_tracer
499
+ if prior_tracer
500
+ else SubgraphTracer(
501
+ self, parent=self.current_tracer, source_target=source_target
502
+ )
503
+ )
504
+ self.tracers.append(tracer)
505
+ yield tracer
506
+ finally:
507
+ new_scope_ctx.__exit__(None, None, None)
508
+ self.tracers.pop()
509
+
510
+ @property
511
+ def output(self):
512
+ return self
513
+
514
+ @property
515
+ def fake_mode(self):
516
+ return self.tracing_context.fake_mode
517
+
518
+ @property
519
+ def shape_env(self):
520
+ return self.tracing_context.fake_mode.shape_env
521
+
522
+ @property
523
+ def guards(self) -> torch._guards.GuardsSet:
524
+ return self.tracing_context.guards_context.dynamo_guards
525
+
526
+ @property
527
+ def nn_modules(self) -> Dict[str, Any]:
528
+ return self.tracing_context.module_context.nn_modules
529
+
530
+ def save_global_state(self, out=None):
531
+ """
532
+ Saves to out if it is provided. Else saves to the tracing context's global_state.
533
+ """
534
+ global_state = (
535
+ out if out is not None else self.tracing_context.global_context.global_state
536
+ )
537
+
538
+ # TODO - Consider having a torch level API for torch_function_state. As
539
+ # of now, we create a ref cycle by passing the
540
+ # output.set_torch_function_state to
541
+ # output.tracing_context.global_context.global_state. In the interim,
542
+ # the problem can be solved by manually set
543
+ # output.tracing_context.global_context.global_state to None at cleanup.
544
+ global_state["torch_function_enabled"] = (
545
+ self.set_torch_function_state,
546
+ self.torch_function_enabled,
547
+ )
548
+ global_state["grad_enabled"] = (torch.set_grad_enabled, torch.is_grad_enabled())
549
+ global_state["autocast_enabled"] = (
550
+ torch.set_autocast_enabled,
551
+ torch.is_autocast_enabled(),
552
+ )
553
+ global_state["autocast_cpu_enabled"] = (
554
+ torch.set_autocast_cpu_enabled,
555
+ torch.is_autocast_cpu_enabled(),
556
+ )
557
+ global_state["autocast_gpu_dtype"] = (
558
+ torch.set_autocast_gpu_dtype,
559
+ torch.get_autocast_gpu_dtype(),
560
+ )
561
+ global_state["autocast_cpu_dtype"] = (
562
+ torch.set_autocast_cpu_dtype,
563
+ torch.get_autocast_cpu_dtype(),
564
+ )
565
+ global_state["autocast_cache_enabled"] = (
566
+ torch.set_autocast_cache_enabled,
567
+ torch.is_autocast_cache_enabled(),
568
+ )
569
+
570
+ def push_tx(self, tx):
571
+ self._current_tx.append(tx)
572
+
573
+ def pop_tx(self):
574
+ return self._current_tx.pop()
575
+
576
+ @property
577
+ def current_tx(self):
578
+ return self.root_tx if not self._current_tx else self._current_tx[-1]
579
+
580
+ def copy_graphstate(self) -> OutputGraphState:
581
+ """Create a checkpoint of the current state by copying everything"""
582
+ assert self.param_name_to_source is not None
583
+ guards_graph_state = self.tracing_context.guards_context.copy_graphstate()
584
+ module_state = self.tracing_context.module_context.copy_graphstate()
585
+ global_state = self.tracing_context.global_context.copy_graphstate()
586
+ state = OutputGraphState(
587
+ dict(self.input_source_to_var),
588
+ list(self.tracked_fakes),
589
+ guards_graph_state,
590
+ module_state,
591
+ list(self.register_finalizer_fns),
592
+ global_state,
593
+ dict(self.param_name_to_source),
594
+ self.side_effects.clone(),
595
+ self.timestamp,
596
+ set(self.non_compliant_ops),
597
+ set(self.compliant_custom_ops),
598
+ )
599
+ self.timestamp += 1
600
+ return state
601
+
602
+ def restore_graphstate(self, state: OutputGraphState):
603
+ """Restore a checkpoint created by self.copy_graphstate()"""
604
+ (
605
+ self.input_source_to_var,
606
+ self.tracked_fakes,
607
+ guards_state,
608
+ module_state,
609
+ self.register_finalizer_fns,
610
+ global_state,
611
+ self.param_name_to_source,
612
+ self.side_effects,
613
+ self.timestamp,
614
+ self.non_compliant_ops,
615
+ self.compliant_custom_ops,
616
+ ) = state
617
+ self.tracing_context.guards_context.restore_graphstate(guards_state)
618
+ self.tracing_context.module_context.restore_graphstate(module_state)
619
+ self.tracing_context.global_context.restore_graphstate(global_state)
620
+
621
+ # FX deepcopy doesn't work for a partially created graph, so just remove new nodes
622
+ removed_nodes = 0
623
+ for node in reversed(list(self.graph.nodes)):
624
+ if (
625
+ node.meta["creation_timestamp"] > self.timestamp
626
+ # placeholders here may have been lazily added by existing objects
627
+ and node.op != "placeholder"
628
+ ):
629
+ # Erasing node alone does not remove the meta information
630
+ # So, remove the help tensor explicitly
631
+ if "example_value" in node.meta:
632
+ del node.meta["example_value"]
633
+ self.remove_node(node)
634
+ self.real_value_cache.pop(node, None)
635
+ removed_nodes += 1
636
+ log.debug("restore_graphstate: removed %s nodes", removed_nodes)
637
+
638
+ def add_symbol_bindings(self, arg: GraphArg):
639
+ # Insert implicit size vars as necessary. With dynamic shapes, we
640
+ # maintain the invariant that every sizevar gets a direct SymInt input
641
+ # into the graph. This means downstream graph transforms can assume
642
+ # every size variable is explicitly bound and accessible, instead of
643
+ # having to pull it out implicitly from tensors.
644
+
645
+ if self.export:
646
+ return
647
+
648
+ assert arg.fake_tensor is not None
649
+
650
+ def bind_symint(s, prop):
651
+ if not (is_symbolic(s) and isinstance(s.node.expr, sympy.Symbol)):
652
+ return
653
+ s0 = s.node.expr
654
+ if s0 in self.bound_symbols:
655
+ return
656
+ self.bound_symbols.add(s0)
657
+ log.debug("bind_symint %s %s", s, prop.name())
658
+ # TODO: don't readd symint if we already have it in graph
659
+ # (this is harmless because we do remove the unused ones later)
660
+ proxy = self.root_tracer.create_graph_input(
661
+ str(s0),
662
+ torch.SymInt,
663
+ before=True,
664
+ source=prop,
665
+ )
666
+ proxy.node.meta["example_value"] = s
667
+ proxy.node.meta["grapharg"] = GraphArg(
668
+ prop,
669
+ s,
670
+ is_unspecialized=False,
671
+ fake_tensor=None,
672
+ is_tensor=False,
673
+ )
674
+
675
+ def handle_tensor(t, src):
676
+ for i, s in enumerate(t.size()):
677
+ bind_symint(s, TensorPropertySource(src, TensorProperty.SIZE, i))
678
+ for i, s in enumerate(t.stride()):
679
+ bind_symint(s, TensorPropertySource(src, TensorProperty.STRIDE, i))
680
+ bind_symint(
681
+ t.storage_offset(),
682
+ TensorPropertySource(src, TensorProperty.STORAGE_OFFSET),
683
+ )
684
+ if is_traceable_wrapper_subclass(t):
685
+ attrs, ctx = t.__tensor_flatten__()
686
+ for attr in attrs:
687
+ inner_t = getattr(t, attr)
688
+ handle_tensor(inner_t, AttrSource(src, attr))
689
+
690
+ handle_tensor(arg.fake_tensor, arg.source)
691
+
692
+ def count_calls(self):
693
+ return count_calls(self.graph)
694
+
695
+ def is_empty_graph(self):
696
+ return len(list(self.graph.nodes)) == 0
697
+
698
+ def get_submodule(self, keys):
699
+ assert keys
700
+ obj: Union[torch.nn.Module, Dict[str, torch.nn.Module]] = self.nn_modules
701
+ for k in keys.split("."):
702
+ if isinstance(obj, dict):
703
+ obj = obj[k]
704
+ else:
705
+ obj = getattr(obj, k)
706
+ return obj
707
+
708
+ def new_var(self, name="tmp"):
709
+ existing = set(self.code_options["co_varnames"])
710
+ for i in itertools.count():
711
+ var = f"{name}_{i}"
712
+ if var not in existing:
713
+ self.code_options["co_varnames"] += (var,)
714
+ return var
715
+
716
+ def update_co_names(self, name):
717
+ """Ensure self.code_options.co_names contains name"""
718
+ if name not in self.code_options["co_names"]:
719
+ self.code_options["co_names"] += (name,)
720
+
721
+ @staticmethod
722
+ def module_key_name(*names):
723
+ # create a new unique name
724
+ name = "_".join(map(str, names))
725
+ # Strip the guard lookup L/G access
726
+ name = re.sub(r"^[GL]\['?(.*?)'?\]$", r"\1", name)
727
+ # e.g. replace abc.xyz[123].qkv with abc.xyz_123.qkv
728
+ name = re.sub(r"\[(\d+)\]", r"_\g<1>", name)
729
+ # e.g. replace abc.xyz_123.qkv with abc_xyz_123_qkv
730
+ name = re.sub(r"[^a-zA-Z0-9]", "_", name)
731
+
732
+ if not name or not name[0].isalpha():
733
+ name = "sub" + name
734
+
735
+ return name
736
+
737
+ def register_attr_or_module(
738
+ self,
739
+ target: Union[torch.nn.Module, torch.Tensor, Any],
740
+ *names,
741
+ **options,
742
+ ):
743
+ if is_dynamic_nn_module(target):
744
+ return variables.UnspecializedNNModuleVariable(target, **options)
745
+
746
+ options = dict(options)
747
+ assert "source" in options
748
+ source = options["source"]
749
+ assert not isinstance(source, ParamBufferSource)
750
+
751
+ if isinstance(target, torch.Tensor):
752
+ tracer = self.current_tracer
753
+ if not self.is_root_tracer():
754
+ # For higher order ops, we don't want to insert the get_attr in
755
+ # innermost graph. Instead, we want to raise the params/buffers
756
+ # as inputs to the higher-order graph, and register them as
757
+ # get_attrs in the root tracer.
758
+
759
+ # Note that Dynamo will still call lift_tracked_freevar_to_input
760
+ # when these inputs are encountered for the inner graph. The
761
+ # only difference is what happens at the root tracer for
762
+ # nn.Parameters vs free inputs. The free inputs are registered
763
+ # as placeholders in the root graph, whereas the nn.Parameters
764
+ # are registered as get_attr nodes in the root graph.
765
+ tracer = self.root_tracer
766
+
767
+ if not is_constant_source(source):
768
+ install_guard(source.make_guard(GuardBuilder.TENSOR_MATCH))
769
+
770
+ if get_static_address_type(target) == "guarded":
771
+ install_guard(source.make_guard(GuardBuilder.DATA_PTR_MATCH))
772
+
773
+ def wrap_name(module_key):
774
+ assert self.param_name_to_source is not None
775
+ self.param_name_to_source[module_key] = source
776
+
777
+ return wrap_fx_proxy(
778
+ self.root_tx,
779
+ tracer.create_proxy("get_attr", module_key, tuple(), {}),
780
+ example_value=target,
781
+ **options,
782
+ )
783
+
784
+ elif isinstance(target, torch.nn.Module):
785
+ assert isinstance(target, torch.nn.Module)
786
+
787
+ install_guard(source.make_guard(GuardBuilder.NN_MODULE))
788
+
789
+ def wrap_name(module_key):
790
+ return NNModuleVariable(type(target), module_key, target, **options)
791
+
792
+ elif isinstance(target, (torch.SymInt, torch.SymFloat)):
793
+ # HACKY CODE REGION BEGIN
794
+ # WE ARE PIGGYBACKING ON EXISTING INFRA TO REGISTER ATTRS
795
+ # This ultimately gets written to self.nn_modules, which is unfortunate
796
+ # Attrs that are tenors and symints and such need to be migrated to have their
797
+ # own storage
798
+ # alas, this is like this for now
799
+
800
+ def wrap_name(module_key):
801
+ return SymNodeVariable.create(
802
+ self,
803
+ self.create_proxy("get_attr", module_key, tuple(), {}),
804
+ sym_num=target,
805
+ **options,
806
+ )
807
+
808
+ # HACKY CODE REGION END
809
+ else:
810
+
811
+ def wrap_name(module_key):
812
+ self.output.update_co_names(module_key)
813
+ self.global_scope[module_key] = target
814
+ return VariableBuilder(self, ConstantSource(source_name=module_key))(
815
+ target
816
+ )
817
+
818
+ for k, v in self.nn_modules.items():
819
+ if v is target:
820
+ # it already exists
821
+ return wrap_name(k)
822
+
823
+ name = OutputGraph.module_key_name(*names)
824
+
825
+ base = name
826
+ for i in itertools.count():
827
+ if name not in self.nn_modules:
828
+ self.nn_modules[name] = target
829
+ if isinstance(target, torch.nn.Module):
830
+
831
+ def register_leaf_name(leaf_name):
832
+ assert self.param_name_to_source is not None
833
+ new_source = ParamBufferSource(source, leaf_name)
834
+ new_name = f"{name}.{leaf_name}"
835
+ self.param_name_to_source[new_name] = new_source
836
+ if isinstance(source, LocalSource):
837
+ self.dynamo_flat_name_to_original_fqn[
838
+ OutputGraph.module_key_name(new_source.name())
839
+ ] = leaf_name
840
+
841
+ # annoying, but there are cases when we do not have parameters
842
+ # see test_nn_moduledict_contains
843
+ if hasattr(target, "_parameters"):
844
+ for leaf_name, _ in target.named_parameters():
845
+ register_leaf_name(leaf_name)
846
+ if hasattr(target, "_buffers"):
847
+ for leaf_name, _ in target.named_buffers():
848
+ register_leaf_name(leaf_name)
849
+
850
+ return wrap_name(name)
851
+ name = f"{base}_{i}"
852
+
853
+ raise AssertionError("unreachable")
854
+
855
+ def compile_subgraph(
856
+ self, tx, partial_convert=False, reason: Optional[GraphCompileReason] = None
857
+ ):
858
+ """
859
+ Generate a subgraph to continue execution on user code.
860
+ Automatically restore live variables.
861
+ """
862
+ assert reason is not None
863
+
864
+ from .decorators import disable
865
+
866
+ self.partial_convert = partial_convert
867
+ self.compile_subgraph_reason = reason
868
+ self.should_exit = True
869
+
870
+ log.debug("COMPILING GRAPH due to %s", reason)
871
+
872
+ if not all(block.can_restore() for block in tx.block_stack):
873
+ unimplemented("compile_subgraph with block_depth != 0")
874
+
875
+ prefix_insts: List[Instruction] = []
876
+ if sys.version_info >= (3, 11):
877
+ # prefix instructions (Python 3.11+)
878
+ for inst in tx.prefix_insts:
879
+ if inst.opname == "MAKE_CELL":
880
+ prefix_insts.append(
881
+ create_instruction("MAKE_CELL", argval=inst.argval)
882
+ )
883
+ elif inst.opname == "COPY_FREE_VARS":
884
+ prefix_insts.append(
885
+ create_instruction(
886
+ "COPY_FREE_VARS", arg=len(tx.code_options["co_freevars"])
887
+ )
888
+ )
889
+ else:
890
+ prefix_insts.append(copy.copy(inst))
891
+ assert not (
892
+ self.pregraph_bytecode and self.export
893
+ ), "export does not support pregraph_bytecode"
894
+ prefix_insts.extend(self.pregraph_bytecode)
895
+
896
+ def append_prefix_insts():
897
+ self.add_output_instructions(prefix_insts)
898
+ prefix_insts.clear()
899
+
900
+ for block in reversed(tx.block_stack):
901
+ block.exit(tx)
902
+
903
+ self.cleanup_graph()
904
+ tx.prune_dead_locals()
905
+ stack_values = list(tx.stack)
906
+ root = FakeRootModule(self.nn_modules)
907
+ # Add all the local vars to the "stack" so restore at the end
908
+ restore_vars = []
909
+ val_to_names: Dict[VariableTracker, List[str]] = {}
910
+ if stack_values:
911
+ val_to_names[stack_values[-1]] = list()
912
+ # NB: Typically (i.e., for graph compile from RETURN_VALUE),
913
+ # symbolic_locals will be empty at this point, as prune_dead_locals
914
+ # will clear out all of symbolic_locals because RETURN_VALUE is the
915
+ # last instruction and no more locals are used. The fanciness here
916
+ # is only needed for partial graphs.
917
+ for k, v in tx.symbolic_locals.items():
918
+ # Note! this explicitly uses .local_name for matching
919
+ # Failure to do so will cause spurious registrations in val_to_names.
920
+ # This will in turn result in spurious variables showing up in the graph.
921
+ # This was very tricky to debug. For an example, dump the graph at call_user_compiler
922
+ # while running test_subgraphs.py
923
+ if isinstance(v.source, LocalSource) and v.source.local_name == k:
924
+ continue # no need to restore initial state
925
+ if v not in val_to_names:
926
+ val_to_names[v] = list()
927
+ val_to_names[v].append(k)
928
+ for v in val_to_names.keys():
929
+ restore_vars.extend(val_to_names[v])
930
+ stack_values.extend([v] * len(val_to_names[v]))
931
+
932
+ # to handle random calls
933
+ if len(self.random_calls) > 0:
934
+ append_prefix_insts()
935
+ random_calls_instructions = []
936
+ self.random_values_var = self.new_var("random_values")
937
+ rand_fn = disable(_get_gen_rand_values_fn(self.random_calls))
938
+ rand_fn_name = self.install_global("__gen_rand_values", rand_fn)
939
+ codegen = PyCodegen(tx, root)
940
+ random_calls_instructions.extend(
941
+ codegen.load_function_name(rand_fn_name, True)
942
+ )
943
+ random_calls_instructions.extend(create_call_function(0, False))
944
+ random_calls_instructions.append(
945
+ codegen.create_store(tx.output.random_values_var),
946
+ )
947
+ self.add_output_instructions(random_calls_instructions)
948
+
949
+ if (
950
+ stack_values
951
+ and all(
952
+ not isinstance(
953
+ v,
954
+ (
955
+ UnspecializedPythonVariable,
956
+ NumpyNdarrayVariable,
957
+ TensorWithTFOverrideVariable,
958
+ ),
959
+ )
960
+ for v in stack_values
961
+ )
962
+ and all(isinstance(x, TensorVariable) for x in stack_values)
963
+ and len(set(stack_values)) == len(stack_values)
964
+ and self.side_effects.is_empty()
965
+ and not len(tx.debug_locals) != 0
966
+ and not self.backward_state
967
+ ):
968
+ append_prefix_insts()
969
+ # optimization to generate better code in a common case
970
+ self.add_output_instructions(
971
+ self.compile_and_call_fx_graph(tx, list(reversed(stack_values)), root)
972
+ + [create_instruction("UNPACK_SEQUENCE", arg=len(stack_values))]
973
+ )
974
+ else:
975
+ graph_output_var = self.new_var("graph_out")
976
+ pass1 = PyCodegen(tx, root, graph_output_var)
977
+ self.codegen_suffix(tx, stack_values, pass1)
978
+
979
+ # one more time now that we have established tempvars
980
+ pass2 = PyCodegen(
981
+ tx,
982
+ root,
983
+ graph_output_var,
984
+ tempvars={val: None for val, count in pass1.uses.items() if count > 1},
985
+ )
986
+ self.codegen_suffix(tx, stack_values, pass2)
987
+
988
+ output = []
989
+ if count_calls(self.graph) != 0 or len(pass2.graph_outputs) != 0:
990
+ output.extend(
991
+ self.compile_and_call_fx_graph(tx, pass2.graph_output_vars(), root)
992
+ )
993
+
994
+ if len(pass2.graph_outputs) != 0:
995
+ output.append(pass2.create_store(graph_output_var))
996
+ else:
997
+ output.append(create_instruction("POP_TOP"))
998
+ append_prefix_insts()
999
+ self.add_output_instructions(output + pass2.get_instructions())
1000
+
1001
+ # restore all the live local vars
1002
+ self.add_output_instructions(
1003
+ [PyCodegen(tx).create_store(var) for var in reversed(restore_vars)]
1004
+ )
1005
+
1006
+ def codegen_suffix(self, tx, stack_values, cg):
1007
+ if self.backward_state:
1008
+ assert not self.export
1009
+ for name, val in self.backward_state.items():
1010
+ cg(val)
1011
+ cg.append_output(cg.create_load(self.backward_state_var))
1012
+ cg.store_attr(name)
1013
+ self.side_effects.codegen_hooks(cg)
1014
+ self.side_effects.codegen_save_tempvars(cg)
1015
+
1016
+ # Return variables used for logging at the end
1017
+ for debug_var, args in tx.debug_locals:
1018
+ cg(debug_var)
1019
+ for arg in args:
1020
+ cg(arg)
1021
+ cg.extend_output(create_call_function(len(args), True))
1022
+
1023
+ cg.restore_stack(stack_values, value_from_source=not tx.export)
1024
+ self.side_effects.codegen_update_mutated(cg)
1025
+
1026
+ def cleanup_graph(self):
1027
+ """
1028
+ Remove "creation_timestamp" from node meta
1029
+
1030
+ Remove this pattern from the graph:
1031
+ torch._C._set_grad_enabled(False)
1032
+ torch._C._set_grad_enabled(True)
1033
+ """
1034
+ assert self.should_exit
1035
+ nodes = list(self.graph.nodes)
1036
+ for node in nodes:
1037
+ node.meta.pop("creation_timestamp", None)
1038
+
1039
+ grad_enabled = torch.is_grad_enabled()
1040
+ for node1, node2 in zip(nodes, nodes[1:]):
1041
+ if (
1042
+ node1.target is torch._C._set_grad_enabled
1043
+ and tuple(node1.args) == (not grad_enabled,)
1044
+ and not node1._erased
1045
+ ):
1046
+ grad_enabled = node1.args[0]
1047
+ if (
1048
+ node2.target is torch._C._set_grad_enabled
1049
+ and tuple(node2.args) == (not grad_enabled,)
1050
+ and not node2._erased
1051
+ ):
1052
+ grad_enabled = node2.args[0]
1053
+ self.graph.erase_node(node1)
1054
+ self.graph.erase_node(node2)
1055
+
1056
+ def get_graph_sizes_structured(self):
1057
+ ret = {}
1058
+ for node in self.graph.nodes:
1059
+ example_value = node.meta.get("example_value", None)
1060
+ if isinstance(example_value, torch._subclasses.FakeTensor):
1061
+ size = example_value.size()
1062
+ ret[node.name] = [s if isinstance(s, int) else repr(s) for s in size]
1063
+ return ret
1064
+
1065
+ def get_graph_sizes(self, name: str):
1066
+ graph_sizes_str = "TRACED GRAPH TENSOR SIZES\n"
1067
+ graph_sizes_str += f"===== {name} =====\n"
1068
+ for node in self.graph.nodes:
1069
+ example_value = node.meta.get("example_value", None)
1070
+ if isinstance(example_value, torch._subclasses.FakeTensor):
1071
+ size = example_value.size()
1072
+ graph_sizes_str += f"{node.name}: {tuple(size)}\n"
1073
+ concrete_size = []
1074
+ has_symint = False
1075
+ for sz in size:
1076
+ if isinstance(sz, int):
1077
+ concrete_size.append(sz)
1078
+ elif isinstance(sz, torch.SymInt):
1079
+ has_symint = True
1080
+ concrete_size.append(sz.node.hint)
1081
+ else:
1082
+ break
1083
+ else:
1084
+ if has_symint:
1085
+ graph_sizes_str += (
1086
+ f"{node.name} (concrete): {tuple(concrete_size)}\n"
1087
+ )
1088
+ return graph_sizes_str
1089
+
1090
+ @contextlib.contextmanager
1091
+ def restore_global_state(self):
1092
+ """
1093
+ Momentarily restores the global state to what it was prior to tracing the current output
1094
+ """
1095
+ prior_global_state = self.tracing_context.global_context.copy_graphstate()
1096
+ current_global_state: Dict[str, Tuple[Any, bool]] = {}
1097
+ self.save_global_state(out=current_global_state)
1098
+ try:
1099
+ # Set to state prior to tracing the graph
1100
+ self.tracing_context.global_context.restore_graphstate(prior_global_state)
1101
+ yield
1102
+ finally:
1103
+ # Reset to state at the current time (e.g. before calling the user compiler)
1104
+ self.tracing_context.global_context.restore_graphstate(
1105
+ GlobalContextCheckpointState(current_global_state)
1106
+ )
1107
+
1108
+ @torch._guards.TracingContext.clear_frame()
1109
+ def compile_and_call_fx_graph(self, tx, rv, root):
1110
+ """
1111
+ Generate code from self.graph and return the Instruction()s to
1112
+ call that generated code.
1113
+ """
1114
+ from .decorators import disable
1115
+
1116
+ assert self.should_exit
1117
+
1118
+ name = unique_id("__compiled_fn")
1119
+
1120
+ assert isinstance(rv, list)
1121
+ assert isinstance(root, FakeRootModule)
1122
+ self.create_node(
1123
+ "output",
1124
+ "output",
1125
+ (self.current_tracer.create_arg(tuple(x.as_proxy() for x in rv)),),
1126
+ {},
1127
+ )
1128
+ self.insert_deferred_runtime_asserts(root, name)
1129
+ # NB: deferred runtime asserts can keep graphargs live, so make sure
1130
+ # those are inserted before pruning
1131
+ self.remove_unused_graphargs()
1132
+ ncalls = count_calls(self.graph)
1133
+ counters["stats"]["calls_captured"] += ncalls
1134
+
1135
+ # free a bit of memory
1136
+ self.real_value_cache.clear()
1137
+
1138
+ gm = _make_graph_module(root, self.graph)
1139
+ for register_finalizer in self.register_finalizer_fns:
1140
+ register_finalizer(gm)
1141
+
1142
+ gm.compile_subgraph_reason = self.compile_subgraph_reason
1143
+ gm.meta[
1144
+ "dynamo_flat_name_to_original_fqn"
1145
+ ] = self.dynamo_flat_name_to_original_fqn.copy()
1146
+
1147
+ graph_code_log.debug("%s", lazy_format_graph_code(name, gm))
1148
+ torch._logging.trace_structured(
1149
+ "dynamo_output_graph",
1150
+ lambda: {"sizes": self.get_graph_sizes_structured()},
1151
+ payload_fn=lambda: gm.print_readable(print_output=False),
1152
+ )
1153
+ graph_tabular_log.debug("%s", lazy_format_graph_tabular(name, gm))
1154
+ graph_sizes_log.debug("%s", LazyString(lambda: self.get_graph_sizes(name)))
1155
+ self.call_cleanup_hooks()
1156
+ old_fake_mode = self.tracing_context.fake_mode
1157
+ if not self.export:
1158
+ # TODO(voz): The way export uses gm, and fake tensors, is not supported with us resetting
1159
+ backend_fake_mode = torch._subclasses.FakeTensorMode(
1160
+ shape_env=old_fake_mode.shape_env,
1161
+ )
1162
+ # TODO(voz): Ostensibily, this should be scoped and
1163
+ # restore back to old_fake_mode, but doing so currently violates
1164
+ # a lot of fake_tensor ownership assumptions and runs afoul of detect_fake_mode
1165
+ self.tracing_context.fake_mode = backend_fake_mode
1166
+
1167
+ with self.restore_global_state():
1168
+ compiled_fn = self.call_user_compiler(gm)
1169
+ compiled_fn = disable(compiled_fn)
1170
+
1171
+ counters["stats"]["unique_graphs"] += 1
1172
+ # This is safe because we pre-process name to be unique
1173
+ self.install_global_unsafe(name, compiled_fn)
1174
+
1175
+ cg = PyCodegen(tx)
1176
+ cg.make_call_generated_code(name)
1177
+ return cg.get_instructions()
1178
+
1179
+ @property
1180
+ def placeholders(self) -> List[fx.Node]:
1181
+ r = []
1182
+ for node in self.graph.nodes:
1183
+ if node.op == "placeholder":
1184
+ r.append(node)
1185
+ continue
1186
+ break
1187
+ return r
1188
+
1189
+ @property
1190
+ def graphargs(self) -> List[GraphArg]:
1191
+ return [node.meta["grapharg"] for node in self.placeholders]
1192
+
1193
+ @dynamo_timed(phase_name="backend_compile")
1194
+ def call_user_compiler(self, gm: fx.GraphModule) -> CompiledFn:
1195
+ assert self.compiler_fn is not None
1196
+ tot = 0
1197
+ placeholders = []
1198
+ for node in gm.graph.nodes:
1199
+ if node.op in ("call_function", "call_method", "call_module"):
1200
+ tot += 1
1201
+ if node.op == "placeholder":
1202
+ placeholders.append(node)
1203
+ increment_op_count(tot)
1204
+ for pl in placeholders:
1205
+ arg = pl.meta["grapharg"]
1206
+ # TODO: Why isn't this stored in meta :think:
1207
+ pl._dynamo_source = arg.source
1208
+
1209
+ gm._param_name_to_source = self.param_name_to_source # type: ignore[assignment]
1210
+ gm._source_to_user_stacks = self.source_to_user_stacks # type: ignore[assignment]
1211
+
1212
+ try:
1213
+ name = (
1214
+ self.compiler_fn.__name__
1215
+ if hasattr(self.compiler_fn, "__name__")
1216
+ else ""
1217
+ )
1218
+ _step_logger()(logging.INFO, f"calling compiler function {name}")
1219
+ compiler_fn = self.compiler_fn
1220
+ if config.verify_correctness:
1221
+ compiler_fn = WrapperBackend(compiler_fn)
1222
+ compiled_fn = compiler_fn(gm, self.example_inputs())
1223
+ _step_logger()(logging.INFO, f"done compiler function {name}")
1224
+ assert callable(compiled_fn), "compiler_fn did not return callable"
1225
+ except exceptions_allowed_to_be_fallback as e:
1226
+ if self.has_user_defined_allowed_in_graph:
1227
+ raise BackendCompilerFailed(self.compiler_fn, e).with_traceback(
1228
+ e.__traceback__
1229
+ ) from None
1230
+ msg = (
1231
+ "Backend compiler failed with a fake tensor exception at \n"
1232
+ f"{self.root_tx.format_frame_summary()}"
1233
+ "Adding a graph break."
1234
+ )
1235
+ unimplemented_with_warning(e, self.root_tx.f_code, msg)
1236
+ except SkipFrame as e:
1237
+ # The backend compiler has requested that we skip the frame, instead of
1238
+ # aborting execution.
1239
+ raise e
1240
+ except Exception as e:
1241
+ raise BackendCompilerFailed(self.compiler_fn, e).with_traceback(
1242
+ e.__traceback__
1243
+ ) from None
1244
+
1245
+ signpost_event(
1246
+ "dynamo",
1247
+ "OutputGraph.call_user_compiler",
1248
+ {
1249
+ **self.co_fields,
1250
+ "op_count": tot,
1251
+ "node_count": len(gm.graph.nodes),
1252
+ "input_count": len(placeholders),
1253
+ },
1254
+ )
1255
+
1256
+ return compiled_fn
1257
+
1258
+ def example_inputs(self) -> List[torch.Tensor]:
1259
+ result = []
1260
+ for arg in self.graphargs:
1261
+ result.append(arg.example)
1262
+ return result
1263
+
1264
+ def remove_unused_graphargs(self) -> None:
1265
+ assert self.should_exit
1266
+ # Miniature DCE pass, but only for obviously trivial operations
1267
+ for node in reversed(list(self.graph.nodes)):
1268
+ if len(list(node.users)) == 0:
1269
+ if node.op == "get_attr":
1270
+ self.remove_node(node)
1271
+ elif node.op == "call_function" and node.target is operator.getitem:
1272
+ self.remove_node(node)
1273
+
1274
+ def placeholder_binds_symbol(node):
1275
+ arg = node.meta["grapharg"]
1276
+ example = arg.example
1277
+ if isinstance(example, torch.SymInt) and isinstance(
1278
+ example.node.expr, sympy.Symbol
1279
+ ):
1280
+ return example.node.expr
1281
+ return None
1282
+
1283
+ def remove_unused(node):
1284
+ log.debug("REMOVE UNUSED GRAPHARG %s", node.meta["grapharg"].source.name())
1285
+ # I'm not really sure why you need to delete these from the
1286
+ # node since the node is going to get removed
1287
+ del node.meta["grapharg"]
1288
+ self.remove_node(node)
1289
+ self.real_value_cache.pop(node, None)
1290
+
1291
+ used_symbols = set()
1292
+ recheck_placeholders = []
1293
+ for node in self.placeholders:
1294
+ binds_symbol = placeholder_binds_symbol(node) is not None
1295
+ # Don't delete symbol bindings yet
1296
+ if binds_symbol:
1297
+ if not node.users:
1298
+ recheck_placeholders.append(node)
1299
+ else:
1300
+ if not node.users and not isinstance(
1301
+ node.meta["grapharg"], BackwardStateGraphArg
1302
+ ):
1303
+ remove_unused(node)
1304
+ else:
1305
+ # Register the free symbols as uses
1306
+ arg = node.meta["grapharg"]
1307
+ if isinstance(arg, BackwardStateGraphArg):
1308
+ continue
1309
+ fake = (
1310
+ arg.fake_tensor if arg.fake_tensor is not None else arg.example
1311
+ )
1312
+ used_symbols |= free_symbols(fake)
1313
+
1314
+ # After removing unused graphargs, prune unused binds_symbol
1315
+ for node in recheck_placeholders:
1316
+ symbol = placeholder_binds_symbol(node)
1317
+ if symbol is not None:
1318
+ if symbol not in used_symbols:
1319
+ remove_unused(node)
1320
+ else:
1321
+ # Make sure we delete later occurrences of the same symbol
1322
+ used_symbols.remove(symbol)
1323
+
1324
+ # TODO: this is a generic pass that should live outside of Dynamo
1325
+ def insert_deferred_runtime_asserts(self, root, name) -> None:
1326
+ """
1327
+ During tracing, we may have discovered that some data-dependent values
1328
+ had runtime assert on them; e.g., torch.empty(x.item()) induces a runtime
1329
+ that x.item() >= 0. This asserts can happen unpredictably during fake
1330
+ tensor propagation, so we cannot conveniently insert them into the FX graph
1331
+ when they occur. Instead, we accumulate them in the ShapeEnv, and in this
1332
+ pass insert them into the graph as proper tests.
1333
+ """
1334
+ # TODO: Request simplification on runtime asserts before emitting them
1335
+ ras_by_symbol = self.shape_env.deferred_runtime_asserts.copy()
1336
+
1337
+ if not any(ras for ras in ras_by_symbol.values()):
1338
+ return
1339
+
1340
+ gm = fx.GraphModule(root, self.graph)
1341
+ graph_code_log.debug(
1342
+ "%s",
1343
+ lazy_format_graph_code(f"pre insert_deferred_runtime_asserts {name}", gm),
1344
+ )
1345
+
1346
+ # We are going to mutate the dict
1347
+ symbol_to_proxy = {}
1348
+ placeholders = set()
1349
+ last_placeholder = None
1350
+ for node in self.graph.nodes:
1351
+ if node.op != "placeholder":
1352
+ last_placeholder = node
1353
+ break
1354
+ placeholders.add(node)
1355
+ assert last_placeholder is not None
1356
+
1357
+ # Identify what symbols we need to reify. This isn't strictly needed
1358
+ # but helps reduce churn on the graph
1359
+ needed_symbols: Set[sympy.Symbol] = set()
1360
+ for ras in ras_by_symbol.values():
1361
+ for ra in ras:
1362
+ needed_symbols.update(free_symbols(ra.expr))
1363
+
1364
+ log.debug("needed_symbols = %s", needed_symbols)
1365
+
1366
+ for node in self.graph.nodes:
1367
+ # Placeholders can match symbols, but when we destructure them
1368
+ # with size we have to make sure we insert the nodes after all
1369
+ # the placeholders
1370
+ with self.graph.inserting_before(
1371
+ node.next if node not in placeholders else last_placeholder.next
1372
+ ):
1373
+ if "example_value" not in node.meta:
1374
+ continue
1375
+
1376
+ defs = []
1377
+
1378
+ # For every new unbacked symbol, we need an fx.Node representing
1379
+ # precisely this value. There are a few places where the unbacked
1380
+ # symbol could have come from, and we will check them to setup
1381
+ # these nodes.
1382
+ #
1383
+ # For a case like item(), this is trivial (no new node is added.)
1384
+ #
1385
+ # For nonzero(), we need to add something like i0 = out.size(0)
1386
+ #
1387
+ # We could end up with duplicate nodes this way but it is not a
1388
+ # big deal.
1389
+ #
1390
+ # We also do this to setup backed SymInts, but those are all going
1391
+ # to be matched from placeholders
1392
+ def match_symbol(symint, cb):
1393
+ if (
1394
+ isinstance(symint, torch.SymInt)
1395
+ and isinstance(symint.node, SymNode)
1396
+ and isinstance(s := symint.node.expr, sympy.Symbol)
1397
+ and s not in symbol_to_proxy
1398
+ and s in needed_symbols
1399
+ ):
1400
+ symbol_to_proxy[s] = fx.Proxy(cb())
1401
+ log.debug("symbol_to_proxy[%s] = %s", s, symbol_to_proxy[s])
1402
+ defs.append(s)
1403
+
1404
+ match_symbol(node.meta["example_value"], lambda: node)
1405
+ if isinstance(t := node.meta["example_value"], torch.Tensor):
1406
+ for i, s in enumerate(t.size()):
1407
+ match_symbol(
1408
+ s, lambda: self.graph.call_method("size", (node, i))
1409
+ )
1410
+ for i, s in enumerate(t.stride()):
1411
+ match_symbol(
1412
+ s, lambda: self.graph.call_method("stride", (node, i))
1413
+ )
1414
+ match_symbol(
1415
+ t.storage_offset(),
1416
+ lambda: self.graph.call_method("storage_offset", (node,)),
1417
+ )
1418
+
1419
+ for i0 in defs:
1420
+ ras = ras_by_symbol.pop(i0, [])
1421
+ # Before we perform any asserts, first apply range
1422
+ # refinement. This is important, because if we are going
1423
+ # to retrace the graph (and we typically are if we send
1424
+ # the graph to AOTAutograd), we need to make sure we apply
1425
+ # range refinement (ala _check_is_size) first, BEFORE we
1426
+ # run any of the asserts. Otherwise, we may decide to
1427
+ # perform substitutions based on the asserts which we then
1428
+ # can't back out, because value ranges can only be applied
1429
+ # to asserts.)
1430
+ #
1431
+ # A perhaps better long term plan is to avoid this order
1432
+ # dependence by making it possible to refine ranges on
1433
+ # arbitrary expressions, not just symbols. But it is not
1434
+ # so easy to make use of this information, see
1435
+ # https://twitter.com/ezyang/status/1745801370299482492
1436
+ # We actually made an attempt at this in
1437
+ # https://github.com/pytorch/pytorch/pull/119043
1438
+ # which didn't work.
1439
+ #
1440
+ # Another ideas for how to do this:
1441
+ # - Have bound_sympy be the source of truth of the ranges of any expression
1442
+ # - Cache intermediate results for every subexpression of bound_sympy
1443
+ # - This cache should be possible to edit to refine ranges
1444
+ #
1445
+ # One issue with this proposal is that if
1446
+ # we have a bound on 2x, we are not going to be able to
1447
+ # apply it for 4x. Similarly, we may have bounds for an
1448
+ # equivalent expression that we are not applying because
1449
+ # it's not a perfect match (e.g. x < y vs y > x)".
1450
+ #
1451
+ # The first issue we already have it and it's impossible
1452
+ # to solve in general, so any implementation on a best
1453
+ # effort basis should do.
1454
+ #
1455
+ # The second issue is a preexisting one. It can be mitigated
1456
+ # with a normalisation algorithm. In general, it may also
1457
+ # be on a best effort basis, but since our grammar is not
1458
+ # terribly difficult, chances are we could even fully
1459
+ # normalise SymPy expressions... who knows.
1460
+
1461
+ if i0 in self.shape_env.size_like:
1462
+ self.graph.call_function(
1463
+ torch._check_is_size, (symbol_to_proxy[i0].node,)
1464
+ )
1465
+
1466
+ vr = self.shape_env.var_to_range[i0]
1467
+ if not self.shape_env._default_unspecified_value_range().issubset(
1468
+ vr
1469
+ ):
1470
+ # The runtime range is constrained, so add a runtime
1471
+ # assert and also explicitly refine the range
1472
+ # (refinement should not be necessary once runtime
1473
+ # asserts cause refinement, but that's NYI)
1474
+ def convert(s):
1475
+ try:
1476
+ return int(s)
1477
+ except TypeError:
1478
+ return None
1479
+
1480
+ self.graph.call_function(
1481
+ torch._constrain_as_value,
1482
+ (
1483
+ symbol_to_proxy[i0].node,
1484
+ convert(vr.lower),
1485
+ convert(vr.upper),
1486
+ ),
1487
+ )
1488
+
1489
+ for ra in ras:
1490
+ log.debug("inserting runtime assert %s", ra.expr)
1491
+ # Need to process ALL free symbols, not just unbacked ones
1492
+ fvs = free_symbols(ra.expr)
1493
+ missing = fvs - symbol_to_proxy.keys()
1494
+ if missing:
1495
+ i1 = sorted(missing)[0]
1496
+ # TODO: Remove relaxing assert on unbacked_symint https://github.com/pytorch/pytorch/issues/119689
1497
+ # assert self.shape_env.is_unbacked_symint(i1), i1
1498
+ ras_by_symbol.setdefault(i1, []).append(ra)
1499
+ else:
1500
+ # Convert the sympy expression into a sequence of FX
1501
+ # nodes
1502
+ res = sympy_interp(
1503
+ PythonReferenceAnalysis, symbol_to_proxy, ra.expr
1504
+ ).node
1505
+ self.graph.call_function(
1506
+ torch.ops.aten._assert_scalar.default,
1507
+ # TODO: use ra.msg here, but it's pretty
1508
+ # useless right now
1509
+ (
1510
+ res,
1511
+ f"Deferred runtime assertion failed {ra.expr}",
1512
+ ),
1513
+ )
1514
+
1515
+ def add_output_instructions(self, prefix: List[Instruction]) -> None:
1516
+ """
1517
+ We call this on the creation of a new compiled subgraph that is inserted
1518
+ before user code.
1519
+ """
1520
+ self.output_instructions.extend(prefix)
1521
+ self.should_exit = True
1522
+
1523
+ def install_global_unsafe(self, name, value) -> None:
1524
+ """
1525
+ WARNING: prefer the safer `install_global_by_id/install_global`.
1526
+ torch.compile instances should be independent of each other;
1527
+ one footgun is to have one instance depend on the existence of
1528
+ a global installed by another instance. This can happen if we mangle
1529
+ a global the same way across both instances.
1530
+ """
1531
+ assert name not in self.installed_globals
1532
+ self.installed_globals.add(name)
1533
+ self.cleanups.append(CleanupHook.create(self.global_scope, name, value))
1534
+
1535
+ def install_global_by_id(self, prefix, value) -> str:
1536
+ """
1537
+ Installs a global if it hasn't been installed already.
1538
+ This is determined by (prefix, id(value)) pair.
1539
+
1540
+ Returns the name of the newly installed global.
1541
+ """
1542
+ # NB: need self.compile_id to distinguish this global
1543
+ # from another global created in a different torch.compile instance
1544
+ name = f"{prefix}_{id(value)}_c{self.compile_id}"
1545
+ if name in self.installed_globals:
1546
+ return name
1547
+ self.install_global_unsafe(name, value)
1548
+ return name
1549
+
1550
+ def install_global(self, prefix, value) -> str:
1551
+ """
1552
+ Installs a global, generating a unique name for it.
1553
+
1554
+ Returns the name of the newly installed global.
1555
+ """
1556
+ # NB: unique_id is unique, even across torch.compile instances
1557
+ name = unique_id(prefix)
1558
+ self.install_global_unsafe(name, value)
1559
+ return name
1560
+
1561
+ def cleanup(self) -> None:
1562
+ # There is a reference cycle between tracer and OutputGraph, causing
1563
+ # some of the tensor objects to be held alive for longer than necessary.
1564
+ self.root_tx = None
1565
+ self.nn_modules.clear()
1566
+ self.param_name_to_source = None
1567
+
1568
+ for node in self.graph.nodes:
1569
+ if "grapharg" in node.meta:
1570
+ del node.meta["grapharg"]
1571
+ self.real_value_cache.clear()
1572
+ self.input_name_to_proxy.clear()
1573
+ self.side_effects.clear()
1574
+ self.register_finalizer_fns.clear()
1575
+ self.dynamo_flat_name_to_original_fqn.clear()
1576
+ self.tracing_context.clear()
1577
+
1578
+ def set_torch_function_state(self, enabled: bool) -> None:
1579
+ self.torch_function_enabled = enabled
1580
+
1581
+ def add_graph_finalizer(
1582
+ self, register_finalizer: Callable[[fx.GraphModule], None]
1583
+ ) -> None:
1584
+ self.register_finalizer_fns.append(register_finalizer)
1585
+
1586
+ def example_value_from_input_node(self, node: torch.fx.Node):
1587
+ """Extract the non-fake example tensor"""
1588
+ if node.op == "placeholder":
1589
+ return node.meta["grapharg"].example
1590
+ assert node.op == "get_attr"
1591
+ return self.nn_modules[node.target] # type: ignore[index]
1592
+
1593
+
1594
+ err_epilogue = (
1595
+ "With the current config, we will graph break "
1596
+ "(and fall back to eager-mode PyTorch) on all ops "
1597
+ "that have do not have the 'pt2_compliant_tag'. "
1598
+ "Please see the following doc for how to mark this op as PT2 compliant "
1599
+ "https://docs.google.com/document/d/1W--T6wz8IY8fOI0Vm8BF44PdBgs283QvpelJZWieQWQ"
1600
+ )
1601
+
1602
+
1603
+ def check_pt2_compliant_op(output_graph, kind, target, args, kwargs):
1604
+ if kind != "call_function":
1605
+ return
1606
+
1607
+ def encountered_compliant_op(target):
1608
+ if target.namespace in {"prim", "prims", "aten"}:
1609
+ return
1610
+ output_graph.compliant_custom_ops.add(target)
1611
+
1612
+ def encountered_non_compliant_op(target, msg):
1613
+ output_graph.non_compliant_ops.add(target)
1614
+ if config.only_allow_pt2_compliant_ops:
1615
+ unimplemented(msg + " " + err_epilogue)
1616
+
1617
+ if isinstance(target, torch._ops.OpOverload):
1618
+ if torch.Tag.pt2_compliant_tag in target.tags:
1619
+ encountered_compliant_op(target)
1620
+ return
1621
+ encountered_non_compliant_op(
1622
+ target,
1623
+ f"Encountered the torch.ops.OpOverload {target} "
1624
+ f"that is not PT2 compliant.",
1625
+ )
1626
+ return
1627
+
1628
+ if isinstance(target, torch._ops.OpOverloadPacket):
1629
+ overloads = tuple(target.overloads())
1630
+ # Optimization: Overload resolution is expensive.
1631
+ # If there's only one overload, we know what it will resolve to.
1632
+ if len(overloads) == 1:
1633
+ op = getattr(target, overloads[0])
1634
+ if torch.Tag.pt2_compliant_tag in op.tags:
1635
+ encountered_compliant_op(op)
1636
+ return
1637
+ encountered_non_compliant_op(
1638
+ op,
1639
+ f"Encountered the non-overloaded "
1640
+ f"torch.ops.OpOverloadPacket {target} "
1641
+ f"that is not PT2 compliant. ",
1642
+ )
1643
+ return
1644
+
1645
+ args, kwargs = torch._dynamo.utils.get_fake_values_from_nodes(
1646
+ output_graph.current_tx, (args, kwargs), False
1647
+ )
1648
+ try:
1649
+ overload = torch._C._jit_resolve_packet(
1650
+ target._qualified_op_name, *args, **kwargs
1651
+ )
1652
+ except RuntimeError as e:
1653
+ unimplemented(str(e))
1654
+
1655
+ op = getattr(target, overload)
1656
+ if torch.Tag.pt2_compliant_tag in op.tags:
1657
+ encountered_compliant_op(op)
1658
+ else:
1659
+ encountered_non_compliant_op(
1660
+ op,
1661
+ f"Encountered the torch.ops.OpOverloadPacket {target} "
1662
+ f"which resolves to the overload ({overload}) that is "
1663
+ f"not PT2 compliant.",
1664
+ )
1665
+
1666
+
1667
+ _compile_id_counter = itertools.count()
1668
+
1669
+
1670
+ class SubgraphTracer(fx.Tracer):
1671
+ """
1672
+ Holds an FX graph that is being traced. OutputGraph owns a SubgraphTracer
1673
+ and the separation of responsibilities is that SubgraphTracer is
1674
+ responsible for building the graph while OutputGraph is responsible for
1675
+ compiling and executing the graph.
1676
+ """
1677
+
1678
+ def __init__(
1679
+ self, output_graph, parent=None, export_root=False, source_target=None
1680
+ ):
1681
+ super().__init__()
1682
+ self.output_graph = weakref.proxy(output_graph)
1683
+ self.graph = torch.fx.Graph()
1684
+
1685
+ # The export is only ever set for the ROOT tracer. It controls
1686
+ # whether or not certain inputs are allowed to be added or not.
1687
+ # Look at call sites of create_graph_input to see how it is used.
1688
+ if export_root:
1689
+ assert parent is None
1690
+ self.export_root = export_root
1691
+ # Map from graph input name to its placeholder proxy object, where the
1692
+ # map's keys give all current placeholder node names and can be used to
1693
+ # create unique node names
1694
+ self.input_name_to_proxy: Dict[str, fx.Proxy] = {}
1695
+ # Node => computed real value (see utils.get_real_value)
1696
+ self.real_value_cache: Dict[fx.Node, torch.Tensor] = {}
1697
+
1698
+ # SubgraphTracers can be nested. See NOTE [HigherOrderOperator tracing design]
1699
+ self.parent = parent
1700
+ # A dict mapping previously free variables (Proxy objects)
1701
+ # to new Proxy objects that wrap inputs to this subgraph.
1702
+ #
1703
+ # This dict serves two purposes:
1704
+ # - Proxies are associated with VariableTrackers. If we see
1705
+ # the same VariableTracker twice (and it is a free variable),
1706
+ # then we want to use the same Proxy in the current subgraph to
1707
+ # record the tracing.
1708
+ # - If we are tracing a HigherOrderOperator's body_fn, then we
1709
+ # need to keep track of what free variables were lifted so we can
1710
+ # rewrite the HigherOrderOperator call using the traced body_fn.
1711
+ # Dicts maintain the order of args for the HigherOrderOperator call.
1712
+ self.lifted_freevars = {}
1713
+ self.prev_inst = None
1714
+
1715
+ self._cur_code = None
1716
+ self._orig_gm_meta = None
1717
+ self._orig_gm_lineno_map = None
1718
+ self._orig_gm_firstlineno = None
1719
+ # Each SubgraphTracer is associated with a source target, which indicates
1720
+ # which operator this subgraph is attached to. We compute a source_fn_stack
1721
+ # based on the source target. For the root tracer, it's set to [].
1722
+ # This is useful for debugging and transforming the exported graph.
1723
+ if self.parent is None:
1724
+ self.source_fn_stack = []
1725
+ else:
1726
+ self.source_fn_stack = self.parent.source_fn_stack + [
1727
+ (self.graph._target_to_str(source_target), source_target)
1728
+ ]
1729
+
1730
+ def create_proxy(
1731
+ self,
1732
+ kind,
1733
+ target,
1734
+ args,
1735
+ kwargs,
1736
+ name=None,
1737
+ type_expr=None,
1738
+ proxy_factory_fn=None,
1739
+ ):
1740
+ # NOTE: [Nested SubgraphTracer and free_variable handling]
1741
+ # --------------------------------------------------------
1742
+ # Read NOTE [HigherOrderOperator tracing design] first.
1743
+ #
1744
+ # Let's say we're in the middle of introspecting the body of a possibly
1745
+ # nested HigherOrderOperator, and we see a free variable.
1746
+ #
1747
+ # There are two cases:
1748
+ # 1. We see a free variable that is already tracked by Dynamo.
1749
+ # 2. We see a free variable that has not been tracked by Dynamo
1750
+ #
1751
+ # In case 1, we call `maybe_lift_tracked_freevar_to_input` (below)
1752
+ # which will lift the freevar to be an input of this subgraph
1753
+ # and also recursively lift it to be an input on the parent(s).
1754
+ #
1755
+ # In case 2, before the call to `create_proxy`, the InstructionTranslator
1756
+ # will see the freevar when it gets loaded by Python bytecode.
1757
+ # E.g. for Python 3.11 the bytecodes that may do this are LOAD_DEREF or
1758
+ # LOAD_GLOBAL.
1759
+ # There, the InstructionTranslator asks Dynamo to begin tracking the
1760
+ # freevar by building a new Variable.
1761
+ # Building a new Variable automatically lifts the freevar to be an
1762
+ # input of the root SubgraphTracer.
1763
+ #
1764
+ # The implications for the code below are:
1765
+ # - We will always be in Case 1 when we get to this code.
1766
+ # - Any "free variable" we encounter here is guaranteed to already be
1767
+ # bound, that is, it is either a graph input of the root graph, or
1768
+ # some local variable of the root graph or a subgraph.
1769
+ # - The additional work we need to do here is *only* that we need to
1770
+ # lift this free variable into inputs (recursively) of each nested
1771
+ # higher-order-op subgraph until we hit the subgraph where the free
1772
+ # variable is bound
1773
+ if self.parent is not None:
1774
+ flat_args, tree_spec = pytree.tree_flatten((args, kwargs))
1775
+ new_flat_args = []
1776
+ for arg in flat_args:
1777
+ maybe_new_arg = self.maybe_lift_tracked_freevar_to_input(arg)
1778
+ new_flat_args.append(maybe_new_arg)
1779
+
1780
+ args, kwargs = pytree.tree_unflatten(new_flat_args, tree_spec)
1781
+
1782
+ rv = super().create_proxy(
1783
+ kind, target, args, kwargs, name, type_expr, proxy_factory_fn
1784
+ )
1785
+
1786
+ # append stack trace to fx node
1787
+ tx = self.output_graph.current_tx
1788
+
1789
+ # log detailed location of line of code in 3.11
1790
+ if sys.version_info >= (3, 11) and kind in (
1791
+ "call_function",
1792
+ "call_method",
1793
+ "call_module",
1794
+ ):
1795
+ cur_inst = tx.current_instruction
1796
+ if (
1797
+ cur_inst is not self.prev_inst
1798
+ and cur_inst.positions is not None
1799
+ and cur_inst.positions.lineno is not None
1800
+ ):
1801
+ tx_code = tx.f_code
1802
+ header = tx.get_line_of_code_header(lineno=cur_inst.positions.lineno)
1803
+
1804
+ def get_trace_call_log_str():
1805
+ line = get_instruction_source_311(tx_code, cur_inst).rstrip()
1806
+ return f"TRACE FX call {rv.node.name} from {header}\n{line}"
1807
+
1808
+ trace_call_log.debug("%s", LazyString(get_trace_call_log_str))
1809
+ self.prev_inst = cur_inst
1810
+
1811
+ # update reference to original meta if we're tracing a new code object
1812
+ is_retracing = False
1813
+ if tx.f_code is not self._cur_code:
1814
+ orig_graphmodule_maybe = code_context.get_context(tx.f_code).get(
1815
+ "orig_graphmodule", lambda: None
1816
+ )()
1817
+ if isinstance(orig_graphmodule_maybe, torch.fx.GraphModule):
1818
+ is_retracing = True
1819
+ self._orig_gm_meta = [
1820
+ nd.meta for nd in orig_graphmodule_maybe.graph.nodes
1821
+ ]
1822
+ self._orig_gm_lineno_map = orig_graphmodule_maybe._lineno_map
1823
+ self._orig_gm_firstlineno = (
1824
+ orig_graphmodule_maybe.forward.__code__.co_firstlineno
1825
+ )
1826
+ else:
1827
+ self._orig_gm_meta = None
1828
+ self._orig_gm_lineno_map = None
1829
+ self._orig_gm_firstlineno = None
1830
+ nn_module_stack = tx.nn_module_stack
1831
+ if nn_module_stack:
1832
+ rv.node.meta["nn_module_stack"] = nn_module_stack.copy()
1833
+
1834
+ if kind in {"call_function", "call_method"}:
1835
+ rv.node.meta["source_fn_stack"] = self.source_fn_stack + [
1836
+ (rv.node.name, target)
1837
+ ]
1838
+ elif kind == "call_module":
1839
+ if self.parent is not None:
1840
+ unimplemented("Invoking an nn.Module inside HigherOrderOperator")
1841
+ # For modules we store the class
1842
+ rv.node.meta["source_fn_stack"] = self.source_fn_stack + [
1843
+ (
1844
+ rv.node.name,
1845
+ rv.node.meta["nn_module_stack"][target][1],
1846
+ )
1847
+ ]
1848
+
1849
+ # preserve original meta if it is available
1850
+ if (
1851
+ self._orig_gm_meta
1852
+ and self._orig_gm_lineno_map
1853
+ and self._orig_gm_firstlineno
1854
+ ):
1855
+ lineno = tx.current_instruction.starts_line
1856
+ node_idx = None
1857
+ if lineno is not None:
1858
+ node_idx = self._orig_gm_lineno_map.get(
1859
+ lineno - self._orig_gm_firstlineno, None
1860
+ )
1861
+ if node_idx is not None:
1862
+ meta = self._orig_gm_meta[node_idx]
1863
+ for field in fx.proxy._COPY_META_FIELDS:
1864
+ if field in meta:
1865
+ rv.node.meta[field] = meta[field]
1866
+ if "stack_trace" in meta:
1867
+ rv.node.meta["stack_trace"] = meta["stack_trace"]
1868
+
1869
+ if not is_retracing:
1870
+ if "nn_module_stack" not in rv.node.meta:
1871
+ nn_module_stack = tx.nn_module_stack
1872
+ if nn_module_stack:
1873
+ rv.node.meta["nn_module_stack"] = nn_module_stack.copy()
1874
+
1875
+ if "source_fn_stack" not in rv.node.meta:
1876
+ if kind in {"call_function", "call_method"}:
1877
+ rv.node.meta["source_fn_stack"] = self.source_fn_stack + [
1878
+ (rv.node.name, target)
1879
+ ]
1880
+ elif kind == "call_module":
1881
+ if self.parent is not None:
1882
+ unimplemented(
1883
+ "Invoking an nn.Module inside HigherOrderOperator"
1884
+ )
1885
+ # For modules we store the class
1886
+ rv.node.meta["source_fn_stack"] = self.source_fn_stack + [
1887
+ (
1888
+ rv.node.name,
1889
+ rv.node.meta["nn_module_stack"][target][1],
1890
+ )
1891
+ ]
1892
+
1893
+ if "stack_trace" not in rv.node.meta:
1894
+ frame_summaries: List[traceback.FrameSummary] = []
1895
+ while tx:
1896
+ frame_summaries.append(tx.frame_summary())
1897
+ tx = getattr(tx, "parent", None)
1898
+ # Reverse the frame_summaries, such that the innermost frame is at the last
1899
+ frame_summaries.reverse()
1900
+
1901
+ # official from_list stub doesn't have new-style type
1902
+ msgs = traceback.StackSummary.from_list(frame_summaries).format()
1903
+ rv.node.stack_trace = "".join(msgs)
1904
+
1905
+ return rv
1906
+
1907
+ def create_node(
1908
+ self, op, target, args=None, kwargs=None, name=None, type_expr=None
1909
+ ):
1910
+ check_pt2_compliant_op(self.output_graph, op, target, args, kwargs)
1911
+ if self.parent is not None:
1912
+ flat_args = pytree.arg_tree_leaves(*args, **kwargs)
1913
+ for arg in flat_args:
1914
+ if not isinstance(arg, torch.fx.Node):
1915
+ continue
1916
+ assert (
1917
+ arg.graph == self.graph
1918
+ ), "create_node using arg not from this SubgraphTracer"
1919
+
1920
+ node = super().create_node(op, target, args, kwargs, name, type_expr)
1921
+ node.meta["creation_timestamp"] = self.output_graph.timestamp
1922
+ return node
1923
+
1924
+ # Note: we did not override erase_node since
1925
+ # we call self.graph.erase_node elsewhere
1926
+ def remove_node(self, node):
1927
+ if len(node.users) > 0:
1928
+ user_graph_nodes: List[torch.fx.Node] = []
1929
+ for user in node.users.keys():
1930
+ # For the case where user.graph == self.graph, that is a real bug and will raise
1931
+ # properly.
1932
+ if user.graph != self.graph:
1933
+ # This is a nested graph, which needs to be deleted.
1934
+ # If we do not do this, we will raise on attempting to remove this.
1935
+ # As we only get here during restoration cleanup, this is sound.
1936
+ user_graph_nodes.extend(reversed(list(user.graph.nodes)))
1937
+ for other_graph_node in user_graph_nodes:
1938
+ other_graph_node.graph.erase_node(other_graph_node)
1939
+ self.graph.erase_node(node)
1940
+ self.input_name_to_proxy.pop(node.name, None)
1941
+
1942
+ # when before=True, we will insert this input before the most recent
1943
+ # inserted proxy. This is a hack to get around an ordering problem,
1944
+ # where we first insert a tensor argument, and then insert bindings
1945
+ # for SymInts that may occur in the tensor argument.
1946
+ # Remove this if https://github.com/pytorch/pytorch/issues/99007 gets
1947
+ # fixed.
1948
+ def create_graph_input(self, name, type_expr=None, before=False, source=None):
1949
+ log.debug(
1950
+ "create_graph_input %s %s",
1951
+ name,
1952
+ source.name() if source is not None else "(none)",
1953
+ )
1954
+ if source is None:
1955
+ assert (
1956
+ self.parent is not None
1957
+ ), "you are required to provide a source for inputs on the root tracer"
1958
+
1959
+ # In eager, we are generally OK with adding graph inputs whenever we
1960
+ # want, because we take care of writing the bytecode that knows how
1961
+ # to source all the inputs.
1962
+ #
1963
+ # In export, this is bad, because you want a self-contained export
1964
+ # object which only depends on the inputs you explicitly passed to it.
1965
+ # So we are a bit more strict about what sources can become inputs
1966
+ # in export
1967
+ if self.export_root:
1968
+ if not is_from_local_source(source, allow_cell_or_freevar=False):
1969
+ self.output_graph.source_to_user_stacks.setdefault(source, []).append(
1970
+ TracingContext.extract_stack()
1971
+ )
1972
+
1973
+ # unique
1974
+ if name in self.input_name_to_proxy:
1975
+ for i in itertools.count():
1976
+ candidate_name = f"{name}_{i}"
1977
+ if candidate_name not in self.input_name_to_proxy:
1978
+ name = candidate_name
1979
+ break
1980
+
1981
+ if self.input_name_to_proxy:
1982
+ prev_name = next(reversed(self.input_name_to_proxy))
1983
+ node = self.input_name_to_proxy[prev_name].node
1984
+ if before:
1985
+ ctx = self.graph.inserting_before(node)
1986
+ else:
1987
+ ctx = self.graph.inserting_after(node)
1988
+ else:
1989
+ ctx = self.graph.inserting_before(None)
1990
+ with ctx:
1991
+ proxy = self.create_proxy("placeholder", name, (), {}, type_expr=type_expr)
1992
+ if self.input_name_to_proxy and before:
1993
+ k, v = self.input_name_to_proxy.popitem()
1994
+ self.input_name_to_proxy[name] = proxy
1995
+ self.input_name_to_proxy[k] = v
1996
+ else:
1997
+ self.input_name_to_proxy[name] = proxy
1998
+ return proxy
1999
+
2000
+ # See NOTE: [Nested SubgraphTracer and free_variable handling] for more details
2001
+ def lift_tracked_freevar_to_input(self, proxy):
2002
+ # You're doing something wrong if we are the root SubgraphTracer because
2003
+ # Dynamo adds tensors to graph inputs before creating a proxy for them.
2004
+ assert (
2005
+ self.parent is not None
2006
+ ), "lift_tracked_freevar_to_input should not be called on root SubgraphTracer"
2007
+ # Proxys are associated with VariableTracker.
2008
+ # It is possible that we've already lifted the Proxy to be an input.
2009
+ # If that is the case, just return the already lifted Proxy.
2010
+ if proxy in self.lifted_freevars:
2011
+ return self.lifted_freevars[proxy]
2012
+ new_proxy = self.create_graph_input(proxy.node.name)
2013
+ new_proxy.node.meta["example_value"] = proxy.node.meta["example_value"]
2014
+ self.lifted_freevars[proxy] = new_proxy
2015
+ if self.parent is not None and proxy.tracer != self.parent:
2016
+ self.parent.lift_tracked_freevar_to_input(proxy)
2017
+ return new_proxy
2018
+
2019
+ def maybe_lift_tracked_freevar_to_input(self, arg):
2020
+ """
2021
+ If arg is a free variable, then lift it to be an input.
2022
+ Returns the new lifted arg (if arg was a freevar), else the
2023
+ original arg.
2024
+ """
2025
+ if not isinstance(arg, torch.fx.Proxy):
2026
+ return arg
2027
+ elif arg.tracer == self:
2028
+ return arg
2029
+ return self.lift_tracked_freevar_to_input(arg)
2030
+
2031
+
2032
+ # NOTE: [HigherOrderOperator tracing design]
2033
+ # Ignoring HigherOrderOperators for a moment,
2034
+ # OutputGraph represents the graph being built by Dynamo that may be compiled
2035
+ # and executed. It holds a root SubgraphTracer where the FX graph is built.
2036
+ #
2037
+ # HigherOrderOperators are operators that take functions as their arguments.
2038
+ # When Dynamo encounters a HigherOrderOperator, then it attempts to introspect
2039
+ # the function passed to it (call this the "body function"), capture it into a
2040
+ # GraphModule, and rewrite the call to the HigherOrderOperator to use the
2041
+ # GraphModule.
2042
+ #
2043
+ # The way we handle the capture of body functions is through having
2044
+ # (possibly nested) SubgraphTracers, one per body function.
2045
+ #
2046
+ # Mechanically, we do the introspection by:
2047
+ # - Creating a new SubgraphTracer via OutputGraph.subtracer
2048
+ # - Executing the body function.
2049
+ # This constructs the graph of the body function in the new SubgraphTracer
2050
+ # while modifying the state of the OutputGraph. For example:
2051
+ # - the OutputGraph can receive new GraphArgs (if we discover any new
2052
+ # untracked Tensors)
2053
+ # - side effects from the body function get accumulated into
2054
+ # OutputGraph.side_effects
2055
+ # - guards produced by the body function get accumulated into OutputGraph.guards
2056
+ #
2057
+ # The traced function has some special properties that make it easier for us
2058
+ # to transform later down the line:
2059
+ # - we lift all free variables to being inputs.
2060
+ #
2061
+ # If the introspection fails (due to the existence of graph breaks), then
2062
+ # we roll back the current OutputGraph state and graph break on the
2063
+ # HigherOrderOperator.
llmeval-env/lib/python3.10/site-packages/torch/_dynamo/polyfill.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: ignore-errors
2
+
3
+ """
4
+ Python polyfills for common builtins.
5
+ """
6
+ import math
7
+
8
+ import torch
9
+
10
+
11
+ def all(iterator):
12
+ for elem in iterator:
13
+ if not elem:
14
+ return False
15
+ return True
16
+
17
+
18
+ def any(iterator):
19
+ for elem in iterator:
20
+ if elem:
21
+ return True
22
+ return False
23
+
24
+
25
+ def index(iterator, item, start=0, end=None):
26
+ for i, elem in enumerate(list(iterator))[start:end]:
27
+ if item == elem:
28
+ return i
29
+ # This will not run in dynamo
30
+ raise ValueError(f"{item} is not in {type(iterator)}")
31
+
32
+
33
+ def repeat(item, count):
34
+ for i in range(count):
35
+ yield item
36
+
37
+
38
+ def radians(x):
39
+ return math.pi / 180.0 * x
40
+
41
+
42
+ def accumulate_grad(x, new_grad):
43
+ new_grad = torch.clone(new_grad)
44
+ if x.grad is None:
45
+ x.grad = new_grad
46
+ else:
47
+ x.grad.add_(new_grad)
llmeval-env/lib/python3.10/site-packages/torch/_dynamo/profiler.py ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import dataclasses
2
+ import os
3
+ from typing import Any, List
4
+
5
+ import torch
6
+
7
+ from .utils import print_once
8
+
9
+
10
+ @dataclasses.dataclass
11
+ class ProfileMetrics:
12
+ microseconds: float = 0.0
13
+ operators: int = 0
14
+ fusions: int = 0
15
+ graphs: int = 0
16
+
17
+ def __iadd__(self, other: "ProfileMetrics"):
18
+ self.microseconds += other.microseconds
19
+ self.operators += other.operators
20
+ self.fusions += other.fusions
21
+ return self
22
+
23
+ def __add__(self, other: "ProfileMetrics"):
24
+ assert isinstance(other, ProfileMetrics)
25
+ return ProfileMetrics(
26
+ self.microseconds + other.microseconds,
27
+ self.operators + other.operators,
28
+ self.fusions + other.fusions,
29
+ )
30
+
31
+ def __truediv__(self, other):
32
+ if isinstance(other, int):
33
+ other = ProfileMetrics(other, other, other)
34
+ return ProfileMetrics(
35
+ self.microseconds / max(1, other.microseconds),
36
+ self.operators / max(1, other.operators),
37
+ self.fusions / max(1, other.fusions),
38
+ )
39
+
40
+ def __str__(self):
41
+ return f"{self.operators:4.0%} ops {self.microseconds:4.0%} time"
42
+
43
+ def tocsv(self):
44
+ return [self.operators, self.microseconds]
45
+
46
+
47
+ class ProfileResult:
48
+ def __init__(self, captured, total, unique_graphs):
49
+ self.captured: ProfileMetrics = captured or ProfileMetrics()
50
+ self.total: ProfileMetrics = total or ProfileMetrics()
51
+ self.unique_graphs: int = unique_graphs
52
+
53
+ def __iadd__(self, other: "ProfileResult"):
54
+ self.captured += other.captured
55
+ self.total += other.total
56
+ self.unique_graphs += other.unique_graphs
57
+ return self
58
+
59
+ def percent(self):
60
+ return self.captured / self.total
61
+
62
+ def __str__(self):
63
+ return (
64
+ f"{self.unique_graphs:2} graphs {self.captured.graphs:2} graph calls "
65
+ f"{self.captured.operators:4}/{self.total.operators:4} = "
66
+ + str(self.percent())
67
+ )
68
+
69
+ def tocsv(self):
70
+ return [
71
+ self.unique_graphs,
72
+ self.captured.graphs,
73
+ self.captured.operators,
74
+ self.total.operators,
75
+ ] + self.percent().tocsv()
76
+
77
+
78
+ def should_print_missing():
79
+ return os.environ.get("TORCHDYNAMO_PRINT_MISSING") == "1"
80
+
81
+
82
+ def print_missing(stack):
83
+ if any("/torch/autograd/profiler.py" in x for x in stack):
84
+ return
85
+ stack = [
86
+ x for x in stack if ("<built-in" not in x and "site-packages/torch/" not in x)
87
+ ]
88
+ print_once("MISSING", " >> ".join(stack[-3:]))
89
+
90
+
91
+ class Profiler:
92
+ unique_graphs = 0
93
+
94
+ def __init__(self):
95
+ self.prof = torch.profiler.profile(
96
+ activities=[torch.profiler.ProfilerActivity.CPU],
97
+ with_stack=should_print_missing(),
98
+ )
99
+
100
+ def results(self):
101
+ captured_regions = 0
102
+ captured_ops = 0
103
+ captured_microseconds = 0
104
+ total_ops = 0
105
+ total_microseconds = 0
106
+
107
+ last_op_end_time = -1
108
+ captured_region_end_time = -1
109
+ events = sorted(self.prof.events(), key=lambda x: x.time_range.start)
110
+ for e in events:
111
+ if e.name == "TORCHDYNAMO":
112
+ captured_region_end_time = e.time_range.end
113
+ captured_regions += 1
114
+ # ignore `handle = torch.zeros(1)` in record_function.__init__()
115
+ total_ops -= 1
116
+ elif e.time_range.start >= last_op_end_time:
117
+ last_op_end_time = e.time_range.end
118
+ if e.time_range.end <= captured_region_end_time:
119
+ captured_ops += 1
120
+ captured_microseconds += e.time_range.elapsed_us()
121
+ elif should_print_missing():
122
+ print_missing(e.stack)
123
+ total_ops += 1
124
+ total_microseconds += e.time_range.elapsed_us()
125
+ else:
126
+ pass # ops recursively called from other ops (ignored)
127
+
128
+ unique_graphs = Profiler.unique_graphs
129
+ Profiler.unique_graphs = 0
130
+ # we counted one extra op that is part of the profiler setup code
131
+ total_ops -= 1
132
+
133
+ return ProfileResult(
134
+ captured=ProfileMetrics(
135
+ microseconds=captured_microseconds,
136
+ operators=captured_ops,
137
+ fusions=captured_ops - captured_regions,
138
+ graphs=captured_regions,
139
+ ),
140
+ total=ProfileMetrics(
141
+ microseconds=total_microseconds,
142
+ operators=total_ops,
143
+ fusions=total_ops - 1,
144
+ ),
145
+ unique_graphs=unique_graphs,
146
+ )
147
+
148
+
149
+ def fx_insert_profiling(gm: torch.fx.GraphModule, example_inputs: List[Any]):
150
+ def _wrapped(*args):
151
+ with torch.profiler.record_function("TORCHDYNAMO"):
152
+ return gm.forward(*args)
153
+
154
+ Profiler.unique_graphs += 1
155
+ return _wrapped
llmeval-env/lib/python3.10/site-packages/torch/_dynamo/resume_execution.py ADDED
@@ -0,0 +1,648 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ import dataclasses
3
+ import sys
4
+ import types
5
+ from typing import Any, cast, Dict, List, Optional, Tuple
6
+
7
+ from .bytecode_transformation import (
8
+ create_call_function,
9
+ create_call_method,
10
+ create_dup_top,
11
+ create_instruction,
12
+ create_jump_absolute,
13
+ Instruction,
14
+ InstructionExnTabEntry,
15
+ transform_code_object,
16
+ unique_id,
17
+ )
18
+ from .utils import ExactWeakKeyDictionary
19
+
20
+ # taken from code.h in cpython
21
+ CO_OPTIMIZED = 0x0001
22
+ CO_NEWLOCALS = 0x0002
23
+ CO_VARARGS = 0x0004
24
+ CO_VARKEYWORDS = 0x0008
25
+ CO_NESTED = 0x0010
26
+ CO_GENERATOR = 0x0020
27
+ CO_NOFREE = 0x0040
28
+ CO_COROUTINE = 0x0080
29
+ CO_ITERABLE_COROUTINE = 0x0100
30
+ CO_ASYNC_GENERATOR = 0x0200
31
+
32
+
33
+ @dataclasses.dataclass(frozen=True)
34
+ class ReenterWith:
35
+ stack_index: int
36
+ target_values: Optional[Tuple[Any, ...]] = None
37
+
38
+ # If we do not want to destroy the stack, we can do the same thing as a
39
+ # `SETUP_WITH` block, only that we store the context manager in a local_symbol
40
+ def try_except(self, code_options, cleanup: List[Instruction]):
41
+ """
42
+ Codegen based off of:
43
+ load args
44
+ enter context
45
+ try:
46
+ (rest)
47
+ finally:
48
+ exit context
49
+ """
50
+ load_args = []
51
+ if self.target_values:
52
+ load_args = [
53
+ create_instruction("LOAD_CONST", argval=val)
54
+ for val in self.target_values
55
+ ]
56
+ ctx_name = unique_id(f"___context_manager_{self.stack_index}")
57
+ if ctx_name not in code_options["co_varnames"]:
58
+ code_options["co_varnames"] += (ctx_name,)
59
+ for name in ["__enter__", "__exit__"]:
60
+ if name not in code_options["co_names"]:
61
+ code_options["co_names"] += (name,)
62
+
63
+ except_jump_target = create_instruction(
64
+ "NOP" if sys.version_info < (3, 11) else "PUSH_EXC_INFO"
65
+ )
66
+ cleanup_complete_jump_target = create_instruction("NOP")
67
+
68
+ setup_finally = [
69
+ *load_args,
70
+ *create_call_function(len(load_args), True),
71
+ create_instruction("STORE_FAST", argval=ctx_name),
72
+ create_instruction("LOAD_FAST", argval=ctx_name),
73
+ create_instruction("LOAD_METHOD", argval="__enter__"),
74
+ *create_call_method(0),
75
+ create_instruction("POP_TOP"),
76
+ ]
77
+
78
+ if sys.version_info < (3, 11):
79
+ setup_finally.append(
80
+ create_instruction("SETUP_FINALLY", target=except_jump_target)
81
+ )
82
+ else:
83
+ exn_tab_begin = create_instruction("NOP")
84
+ exn_tab_end = create_instruction("NOP")
85
+ exn_tab_begin.exn_tab_entry = InstructionExnTabEntry(
86
+ exn_tab_begin,
87
+ exn_tab_end,
88
+ except_jump_target,
89
+ self.stack_index + 1,
90
+ False,
91
+ )
92
+ setup_finally.append(exn_tab_begin)
93
+
94
+ def create_reset():
95
+ return [
96
+ create_instruction("LOAD_FAST", argval=ctx_name),
97
+ create_instruction("LOAD_METHOD", argval="__exit__"),
98
+ create_instruction("LOAD_CONST", argval=None),
99
+ create_dup_top(),
100
+ create_dup_top(),
101
+ *create_call_method(3),
102
+ create_instruction("POP_TOP"),
103
+ ]
104
+
105
+ if sys.version_info < (3, 9):
106
+ epilogue = [
107
+ create_instruction("POP_BLOCK"),
108
+ create_instruction("BEGIN_FINALLY"),
109
+ except_jump_target,
110
+ *create_reset(),
111
+ create_instruction("END_FINALLY"),
112
+ ]
113
+ elif sys.version_info < (3, 11):
114
+ epilogue = [
115
+ create_instruction("POP_BLOCK"),
116
+ *create_reset(),
117
+ create_instruction("JUMP_FORWARD", target=cleanup_complete_jump_target),
118
+ except_jump_target,
119
+ *create_reset(),
120
+ create_instruction("RERAISE"),
121
+ cleanup_complete_jump_target,
122
+ ]
123
+ else:
124
+ finally_exn_tab_end = create_instruction("RERAISE", arg=0)
125
+ finally_exn_tab_target = create_instruction("COPY", arg=3)
126
+ except_jump_target.exn_tab_entry = InstructionExnTabEntry(
127
+ except_jump_target,
128
+ finally_exn_tab_end,
129
+ finally_exn_tab_target,
130
+ self.stack_index + 2,
131
+ True,
132
+ )
133
+ epilogue = [
134
+ exn_tab_end,
135
+ *create_reset(),
136
+ create_instruction("JUMP_FORWARD", target=cleanup_complete_jump_target),
137
+ except_jump_target, # PUSH_EXC_INFO
138
+ *create_reset(),
139
+ finally_exn_tab_end, # RERAISE 0
140
+ finally_exn_tab_target, # COPY 3
141
+ create_instruction("POP_EXCEPT"),
142
+ create_instruction("RERAISE", arg=1),
143
+ cleanup_complete_jump_target,
144
+ ]
145
+
146
+ cleanup[:] = epilogue + cleanup
147
+ return setup_finally
148
+
149
+ def __call__(self, code_options, cleanup):
150
+ """
151
+ Codegen based off of:
152
+ with ctx(args):
153
+ (rest)
154
+ """
155
+ load_args = []
156
+ if self.target_values:
157
+ load_args = [
158
+ create_instruction("LOAD_CONST", argval=val)
159
+ for val in self.target_values
160
+ ]
161
+ if sys.version_info < (3, 9):
162
+ with_cleanup_start = create_instruction("WITH_CLEANUP_START")
163
+ begin_finally = create_instruction("BEGIN_FINALLY")
164
+ cleanup[:] = [
165
+ create_instruction("POP_BLOCK"),
166
+ begin_finally,
167
+ with_cleanup_start,
168
+ create_instruction("WITH_CLEANUP_FINISH"),
169
+ create_instruction("END_FINALLY"),
170
+ ] + cleanup
171
+
172
+ return [
173
+ *load_args,
174
+ create_instruction("CALL_FUNCTION", arg=len(load_args)),
175
+ create_instruction("SETUP_WITH", target=with_cleanup_start),
176
+ create_instruction("POP_TOP"),
177
+ ], None
178
+ elif sys.version_info < (3, 11):
179
+ with_except_start = create_instruction("WITH_EXCEPT_START")
180
+ pop_top_after_with_except_start = create_instruction("POP_TOP")
181
+
182
+ cleanup_complete_jump_target = create_instruction("NOP")
183
+
184
+ cleanup[:] = [
185
+ create_instruction("POP_BLOCK"),
186
+ create_instruction("LOAD_CONST", argval=None),
187
+ create_instruction("DUP_TOP"),
188
+ create_instruction("DUP_TOP"),
189
+ create_instruction("CALL_FUNCTION", arg=3),
190
+ create_instruction("POP_TOP"),
191
+ create_instruction("JUMP_FORWARD", target=cleanup_complete_jump_target),
192
+ with_except_start,
193
+ create_instruction(
194
+ "POP_JUMP_IF_TRUE", target=pop_top_after_with_except_start
195
+ ),
196
+ create_instruction("RERAISE"),
197
+ pop_top_after_with_except_start,
198
+ create_instruction("POP_TOP"),
199
+ create_instruction("POP_TOP"),
200
+ create_instruction("POP_EXCEPT"),
201
+ create_instruction("POP_TOP"),
202
+ cleanup_complete_jump_target,
203
+ ] + cleanup
204
+
205
+ return [
206
+ *load_args,
207
+ create_instruction("CALL_FUNCTION", arg=len(load_args)),
208
+ create_instruction("SETUP_WITH", target=with_except_start),
209
+ create_instruction("POP_TOP"),
210
+ ], None
211
+ else:
212
+ pop_top_after_with_except_start = create_instruction("POP_TOP")
213
+ cleanup_complete_jump_target = create_instruction("NOP")
214
+
215
+ def create_load_none():
216
+ return create_instruction("LOAD_CONST", argval=None)
217
+
218
+ exn_tab_1_begin = create_instruction("POP_TOP")
219
+ exn_tab_1_end = create_instruction("NOP")
220
+ exn_tab_1_target = create_instruction("PUSH_EXC_INFO")
221
+ exn_tab_2_end = create_instruction("RERAISE", arg=2)
222
+ exn_tab_2_target = create_instruction("COPY", arg=3)
223
+
224
+ exn_tab_1_begin.exn_tab_entry = InstructionExnTabEntry(
225
+ exn_tab_1_begin,
226
+ exn_tab_1_end,
227
+ exn_tab_1_target,
228
+ self.stack_index + 1,
229
+ True,
230
+ )
231
+ exn_tab_1_target.exn_tab_entry = InstructionExnTabEntry(
232
+ exn_tab_1_target,
233
+ exn_tab_2_end,
234
+ exn_tab_2_target,
235
+ self.stack_index + 3,
236
+ True,
237
+ )
238
+ pop_top_after_with_except_start.exn_tab_entry = InstructionExnTabEntry(
239
+ pop_top_after_with_except_start,
240
+ pop_top_after_with_except_start,
241
+ exn_tab_2_target,
242
+ self.stack_index + 3,
243
+ True,
244
+ )
245
+
246
+ cleanup[:] = [
247
+ exn_tab_1_end,
248
+ create_load_none(),
249
+ create_load_none(),
250
+ create_load_none(),
251
+ *create_call_function(2, False),
252
+ create_instruction("POP_TOP"),
253
+ create_instruction("JUMP_FORWARD", target=cleanup_complete_jump_target),
254
+ exn_tab_1_target, # PUSH_EXC_INFO
255
+ create_instruction("WITH_EXCEPT_START"),
256
+ create_instruction(
257
+ "POP_JUMP_FORWARD_IF_TRUE",
258
+ target=pop_top_after_with_except_start,
259
+ ),
260
+ exn_tab_2_end, # RERAISE 2
261
+ exn_tab_2_target, # COPY 3
262
+ create_instruction("POP_EXCEPT"),
263
+ create_instruction("RERAISE", arg=1),
264
+ pop_top_after_with_except_start,
265
+ create_instruction("POP_EXCEPT"),
266
+ create_instruction("POP_TOP"),
267
+ create_instruction("POP_TOP"),
268
+ cleanup_complete_jump_target,
269
+ ] + cleanup
270
+
271
+ return [
272
+ *load_args,
273
+ *create_call_function(len(load_args), True),
274
+ create_instruction("BEFORE_WITH"),
275
+ exn_tab_1_begin, # POP_TOP
276
+ ], exn_tab_1_target
277
+
278
+
279
+ @dataclasses.dataclass
280
+ class ResumeFunctionMetadata:
281
+ code: types.CodeType
282
+ instructions: List[Instruction] = dataclasses.field(default_factory=list)
283
+ # Python 3.11+ fields
284
+ # NOTE: Python 3.11 removed blocks, but for our purposes, a "block" consists
285
+ # of instructions of all exception table entries that have the same target.
286
+
287
+ # map from PUSH_EXC_INFO's in the prefix to original block target offset
288
+ prefix_block_target_offset_remap: List[int] = dataclasses.field(
289
+ default_factory=list
290
+ )
291
+ # map from new block target offsets to original block target offsets
292
+ block_target_offset_remap: Optional[Dict[int, int]] = None
293
+
294
+
295
+ def _filter_iter(l1, l2, cond):
296
+ """
297
+ Two-pointer conditional filter.
298
+ e.g. _filter_iter(insts, sorted_offsets, lambda i, o: i.offset == o)
299
+ returns the instructions with offsets in sorted_offsets
300
+ """
301
+ it = iter(l2)
302
+ res = []
303
+ try:
304
+ cur = next(it)
305
+ for val in l1:
306
+ if cond(val, cur):
307
+ res.append(val)
308
+ cur = next(it)
309
+ except StopIteration:
310
+ pass
311
+ return res
312
+
313
+
314
+ class ContinueExecutionCache:
315
+ cache = ExactWeakKeyDictionary()
316
+ generated_code_metadata = ExactWeakKeyDictionary()
317
+
318
+ @classmethod
319
+ def lookup(cls, code, lineno, *key):
320
+ if code not in cls.cache:
321
+ cls.cache[code] = dict()
322
+ key = tuple(key)
323
+ if key not in cls.cache[code]:
324
+ cls.cache[code][key] = cls.generate(code, lineno, *key)
325
+ return cls.cache[code][key]
326
+
327
+ @classmethod
328
+ def generate(
329
+ cls,
330
+ code,
331
+ lineno,
332
+ offset: int,
333
+ setup_fn_target_offsets: Tuple[int], # only used in Python 3.11+
334
+ nstack: int,
335
+ argnames: Tuple[str],
336
+ setup_fns: Tuple[ReenterWith],
337
+ null_idxes: Tuple[int],
338
+ ) -> types.CodeType:
339
+ assert offset is not None
340
+ assert not (
341
+ code.co_flags
342
+ & (CO_GENERATOR | CO_COROUTINE | CO_ITERABLE_COROUTINE | CO_ASYNC_GENERATOR)
343
+ )
344
+ assert code.co_flags & CO_OPTIMIZED
345
+ if code in ContinueExecutionCache.generated_code_metadata:
346
+ return cls.generate_based_on_original_code_object(
347
+ code,
348
+ lineno,
349
+ offset,
350
+ setup_fn_target_offsets,
351
+ nstack,
352
+ argnames,
353
+ setup_fns,
354
+ null_idxes,
355
+ )
356
+
357
+ is_py311_plus = sys.version_info >= (3, 11)
358
+ meta = ResumeFunctionMetadata(code)
359
+
360
+ def update(instructions: List[Instruction], code_options: Dict[str, Any]):
361
+ meta.instructions = copy.deepcopy(instructions)
362
+
363
+ args = [f"___stack{i}" for i in range(nstack)]
364
+ args.extend(v for v in argnames if v not in args)
365
+ freevars = tuple(code_options["co_cellvars"] or []) + tuple(
366
+ code_options["co_freevars"] or []
367
+ )
368
+ code_options[
369
+ "co_name"
370
+ ] = f"torch_dynamo_resume_in_{code_options['co_name']}_at_{lineno}"
371
+ if is_py311_plus:
372
+ qualified_path = code_options["co_qualname"].rsplit(".", maxsplit=1)
373
+ if len(qualified_path) == 1:
374
+ code_options["co_qualname"] = code_options["co_name"]
375
+ else:
376
+ assert len(qualified_path) == 2
377
+ module_name, co_name = qualified_path
378
+ code_options[
379
+ "co_qualname"
380
+ ] = f"{module_name}.torch_dynamo_resume_in_{co_name}_at_{lineno}"
381
+ code_options["co_firstlineno"] = lineno
382
+ code_options["co_cellvars"] = tuple()
383
+ code_options["co_freevars"] = freevars
384
+ code_options["co_argcount"] = len(args)
385
+ code_options["co_posonlyargcount"] = 0
386
+ code_options["co_kwonlyargcount"] = 0
387
+ code_options["co_varnames"] = tuple(
388
+ args + [v for v in code_options["co_varnames"] if v not in args]
389
+ )
390
+ code_options["co_flags"] = code_options["co_flags"] & ~(
391
+ CO_VARARGS | CO_VARKEYWORDS
392
+ )
393
+ target = next(i for i in instructions if i.offset == offset)
394
+
395
+ prefix = []
396
+ if is_py311_plus:
397
+ if freevars:
398
+ prefix.append(
399
+ create_instruction("COPY_FREE_VARS", arg=len(freevars))
400
+ )
401
+ prefix.append(create_instruction("RESUME", arg=0))
402
+
403
+ cleanup: List[Instruction] = []
404
+ hooks = {fn.stack_index: fn for fn in setup_fns}
405
+ hook_target_offsets = {
406
+ fn.stack_index: setup_fn_target_offsets[i]
407
+ for i, fn in enumerate(setup_fns)
408
+ }
409
+ offset_to_inst = {inst.offset: inst for inst in instructions}
410
+ # map old hook targets to new targets generated by the hook
411
+ old_hook_target_remap = {}
412
+ null_idxes_i = 0
413
+ for i in range(nstack):
414
+ while (
415
+ null_idxes_i < len(null_idxes)
416
+ and null_idxes[null_idxes_i] == i + null_idxes_i
417
+ ):
418
+ prefix.append(create_instruction("PUSH_NULL"))
419
+ null_idxes_i += 1
420
+ prefix.append(create_instruction("LOAD_FAST", argval=f"___stack{i}"))
421
+ if i in hooks:
422
+ hook = hooks.pop(i)
423
+ hook_insts, exn_target = hook(code_options, cleanup)
424
+ prefix.extend(hook_insts)
425
+ if is_py311_plus:
426
+ hook_target_offset = hook_target_offsets.pop(i)
427
+ old_hook_target = offset_to_inst[hook_target_offset]
428
+ meta.prefix_block_target_offset_remap.append(hook_target_offset)
429
+ old_hook_target_remap[old_hook_target] = exn_target
430
+ if is_py311_plus:
431
+ # reverse the mapping since targets of later/nested contexts are inserted
432
+ # into the mapping later, but show up earlier in the prefix.
433
+ meta.prefix_block_target_offset_remap = list(
434
+ reversed(meta.prefix_block_target_offset_remap)
435
+ )
436
+
437
+ assert not hooks
438
+
439
+ prefix.append(create_jump_absolute(target))
440
+
441
+ # because the line number table monotonically increases from co_firstlineno
442
+ # remove starts_line for any instructions before the graph break instruction
443
+ # this will ensure the instructions after the break have the correct line numbers
444
+ for inst in instructions:
445
+ if inst.offset == target.offset:
446
+ break
447
+ inst.starts_line = None
448
+ if sys.version_info >= (3, 11):
449
+ inst.positions = None
450
+
451
+ if cleanup:
452
+ prefix.extend(cleanup)
453
+ prefix.extend(cls.unreachable_codes(code_options))
454
+
455
+ # remap original instructions' exception table entries
456
+ if old_hook_target_remap:
457
+ assert is_py311_plus
458
+ for inst in instructions:
459
+ if (
460
+ inst.exn_tab_entry
461
+ and inst.exn_tab_entry.target in old_hook_target_remap
462
+ ):
463
+ inst.exn_tab_entry.target = old_hook_target_remap[
464
+ inst.exn_tab_entry.target
465
+ ]
466
+
467
+ # TODO(jansel): add dead code elimination here
468
+ instructions[:] = prefix + instructions
469
+
470
+ new_code = transform_code_object(code, update)
471
+ ContinueExecutionCache.generated_code_metadata[new_code] = meta
472
+ return new_code
473
+
474
+ @staticmethod
475
+ def unreachable_codes(code_options) -> List[Instruction]:
476
+ """Codegen a `raise None` to make analysis work for unreachable code"""
477
+ return [
478
+ create_instruction("LOAD_CONST", argval=None),
479
+ create_instruction("RAISE_VARARGS", arg=1),
480
+ ]
481
+
482
+ @classmethod
483
+ def generate_based_on_original_code_object(
484
+ cls, code, lineno, offset: int, setup_fn_target_offsets: Tuple[int, ...], *args
485
+ ):
486
+ """
487
+ This handles the case of generating a resume into code generated
488
+ to resume something else. We want to always generate starting
489
+ from the original code object so that if control flow paths
490
+ converge we only generated 1 resume function (rather than 2^n
491
+ resume functions).
492
+ """
493
+
494
+ meta: ResumeFunctionMetadata = ContinueExecutionCache.generated_code_metadata[
495
+ code
496
+ ]
497
+ new_offset = None
498
+
499
+ def find_new_offset(
500
+ instructions: List[Instruction], code_options: Dict[str, Any]
501
+ ):
502
+ nonlocal new_offset
503
+ (target,) = (i for i in instructions if i.offset == offset)
504
+ # match the functions starting at the last instruction as we have added a prefix
505
+ (new_target,) = (
506
+ i2
507
+ for i1, i2 in zip(reversed(instructions), reversed(meta.instructions))
508
+ if i1 is target
509
+ )
510
+ assert target.opcode == new_target.opcode
511
+ new_offset = new_target.offset
512
+
513
+ transform_code_object(code, find_new_offset)
514
+
515
+ if sys.version_info >= (3, 11):
516
+ # setup_fn_target_offsets currently contains the target offset of
517
+ # each setup_fn, based on `code`. When we codegen the resume function
518
+ # based on the original code object, `meta.code`, the offsets in
519
+ # setup_fn_target_offsets must be based on `meta.code` instead.
520
+ if not meta.block_target_offset_remap:
521
+ block_target_offset_remap = meta.block_target_offset_remap = {}
522
+
523
+ def remap_block_offsets(
524
+ instructions: List[Instruction], code_options: Dict[str, Any]
525
+ ):
526
+ # NOTE: each prefix block generates exactly one PUSH_EXC_INFO,
527
+ # so we can tell which block a prefix PUSH_EXC_INFO belongs to,
528
+ # by counting. Then we can use meta.prefix_block-target_offset_remap
529
+ # to determine where in the original code the PUSH_EXC_INFO offset
530
+ # replaced.
531
+ prefix_blocks: List[Instruction] = []
532
+ for inst in instructions:
533
+ if len(prefix_blocks) == len(
534
+ meta.prefix_block_target_offset_remap
535
+ ):
536
+ break
537
+ if inst.opname == "PUSH_EXC_INFO":
538
+ prefix_blocks.append(inst)
539
+
540
+ # offsets into prefix
541
+ for inst, o in zip(
542
+ prefix_blocks, meta.prefix_block_target_offset_remap
543
+ ):
544
+ block_target_offset_remap[cast(int, inst.offset)] = o
545
+
546
+ # old bytecode targets are after the prefix PUSH_EXC_INFO's
547
+ old_start_offset = (
548
+ cast(int, prefix_blocks[-1].offset) if prefix_blocks else -1
549
+ )
550
+ # offsets into old bytecode
551
+ old_inst_offsets = sorted(
552
+ n for n in setup_fn_target_offsets if n > old_start_offset
553
+ )
554
+ targets = _filter_iter(
555
+ instructions, old_inst_offsets, lambda inst, o: inst.offset == o
556
+ )
557
+ new_targets = _filter_iter(
558
+ zip(reversed(instructions), reversed(meta.instructions)),
559
+ targets,
560
+ lambda v1, v2: v1[0] is v2,
561
+ )
562
+ for new, old in zip(new_targets, targets):
563
+ block_target_offset_remap[old.offset] = new[1].offset
564
+
565
+ transform_code_object(code, remap_block_offsets)
566
+
567
+ # if offset is not in setup_fn_target_offsets, it is an error
568
+ setup_fn_target_offsets = tuple(
569
+ meta.block_target_offset_remap[n] for n in setup_fn_target_offsets
570
+ )
571
+ return ContinueExecutionCache.lookup(
572
+ meta.code, lineno, new_offset, setup_fn_target_offsets, *args
573
+ )
574
+
575
+
576
+ """
577
+ # partially finished support for with statements
578
+
579
+ def convert_locals_to_cells(
580
+ instructions: List[Instruction],
581
+ code_options: Dict[str, Any]):
582
+
583
+ code_options["co_cellvars"] = tuple(
584
+ var
585
+ for var in code_options["co_varnames"]
586
+ if var not in code_options["co_freevars"]
587
+ and not var.startswith("___stack")
588
+ )
589
+ cell_and_free = code_options["co_cellvars"] + code_options["co_freevars"]
590
+ for inst in instructions:
591
+ if str(inst.argval).startswith("___stack"):
592
+ continue
593
+ elif inst.opname == "LOAD_FAST":
594
+ inst.opname = "LOAD_DEREF"
595
+ elif inst.opname == "STORE_FAST":
596
+ inst.opname = "STORE_DEREF"
597
+ elif inst.opname == "DELETE_FAST":
598
+ inst.opname = "DELETE_DEREF"
599
+ else:
600
+ continue
601
+ inst.opcode = dis.opmap[inst.opname]
602
+ assert inst.argval in cell_and_free, inst.argval
603
+ inst.arg = cell_and_free.index(inst.argval)
604
+
605
+ def patch_setup_with(
606
+ instructions: List[Instruction],
607
+ code_options: Dict[str, Any]
608
+ ):
609
+ nonlocal need_skip
610
+ need_skip = True
611
+ target_index = next(
612
+ idx for idx, i in enumerate(instructions) if i.offset == offset
613
+ )
614
+ assert instructions[target_index].opname == "SETUP_WITH"
615
+ convert_locals_to_cells(instructions, code_options)
616
+
617
+ stack_depth_before = nstack + stack_effect(instructions[target_index].opcode,
618
+ instructions[target_index].arg)
619
+
620
+ inside_with = []
621
+ inside_with_resume_at = None
622
+ stack_depth = stack_depth_before
623
+ idx = target_index + 1
624
+ for idx in range(idx, len(instructions)):
625
+ inst = instructions[idx]
626
+ if inst.opname == "BEGIN_FINALLY":
627
+ inside_with_resume_at = inst
628
+ break
629
+ elif inst.target is not None:
630
+ unimplemented("jump from with not supported")
631
+ elif inst.opname in ("BEGIN_FINALLY", "WITH_CLEANUP_START", "WITH_CLEANUP_FINISH", "END_FINALLY",
632
+ "POP_FINALLY", "POP_EXCEPT",
633
+ "POP_BLOCK", "END_ASYNC_FOR"):
634
+ unimplemented("block ops not supported")
635
+ inside_with.append(inst)
636
+ stack_depth += stack_effect(inst.opcode, inst.arg)
637
+ assert inside_with_resume_at
638
+
639
+ instructions = [
640
+ create_instruction("LOAD_FAST", f"___stack{i}") for i in range(nstack)
641
+ ] + [
642
+ create_instruction("SETUP_WITH", target=instructions[target_index].target)
643
+ ... call the function ...
644
+ unpack_tuple
645
+ ] + [
646
+ create_instruction("JUMP_ABSOLUTE", target=inside_with_resume_at)
647
+ ]
648
+ """
llmeval-env/lib/python3.10/site-packages/torch/_dynamo/side_effects.py ADDED
@@ -0,0 +1,542 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import inspect
2
+ from typing import Any, Dict, List, Optional, Union
3
+
4
+ import torch.nn
5
+
6
+ from . import utils, variables
7
+ from .bytecode_transformation import (
8
+ create_call_function,
9
+ create_call_method,
10
+ create_instruction,
11
+ )
12
+ from .codegen import PyCodegen
13
+ from .exc import unimplemented
14
+ from .source import LocalSource, Source
15
+ from .utils import nn_module_new, object_new
16
+ from .variables.base import (
17
+ is_side_effect_safe,
18
+ MutableLocalBase,
19
+ MutableLocalSource,
20
+ VariableTracker,
21
+ )
22
+
23
+
24
+ class MutableSideEffects(MutableLocalBase):
25
+ """
26
+ VariableTracker.mutable_local marker to indicate a list passed as
27
+ an input that if we mutate we need to re-apply those mutations after
28
+ the graph runs.
29
+ """
30
+
31
+ def __init__(self, source: Source, is_modified: bool = False):
32
+ super().__init__(MutableLocalSource.Existing)
33
+ self.source = source
34
+ self.is_modified = is_modified
35
+
36
+
37
+ class AttributeMutation(MutableLocalBase):
38
+ """
39
+ VariableTracker.mutable_local marker to track changes to attributes
40
+ """
41
+
42
+ def __init__(self, typ: MutableLocalSource, source: Optional[Source]):
43
+ super().__init__(typ)
44
+ self.source = source
45
+
46
+
47
+ class AttributeMutationExisting(AttributeMutation):
48
+ def __init__(self, source: Source):
49
+ super().__init__(MutableLocalSource.Existing, source)
50
+ self.source = source
51
+
52
+
53
+ class AttributeMutationNew(AttributeMutation):
54
+ def __init__(self, source: Optional[Source], cls_source: Optional[Source]):
55
+ super().__init__(MutableLocalSource.Local, source)
56
+ self.cls_source = cls_source
57
+
58
+
59
+ class SideEffects:
60
+ """
61
+ Track side effects (list mutation, setattr, etc) that need to be
62
+ applied after an FX graph is run.
63
+ """
64
+
65
+ id_to_variable: Dict[int, VariableTracker]
66
+ store_attr_mutations: Dict[MutableLocalBase, Dict[str, VariableTracker]]
67
+ keepalive: List[Any]
68
+
69
+ def __init__(
70
+ self,
71
+ id_to_variable=None,
72
+ store_attr_mutations=None,
73
+ keepalive=None,
74
+ save_for_backward=None,
75
+ tensor_hooks=None,
76
+ ):
77
+ super().__init__()
78
+ self.id_to_variable = id_to_variable or {}
79
+ self.store_attr_mutations = store_attr_mutations or {}
80
+ self.keepalive = keepalive or []
81
+ self.save_for_backward = save_for_backward or []
82
+ self.tensor_hooks = tensor_hooks or {}
83
+
84
+ def __eq__(self, other: object) -> bool:
85
+ assert isinstance(other, SideEffects)
86
+ # NB: do NOT test keepalive
87
+ return (
88
+ self.id_to_variable == other.id_to_variable
89
+ and self.store_attr_mutations == other.store_attr_mutations
90
+ and self.save_for_backward == other.save_for_backward
91
+ and self.tensor_hooks == other.tensor_hooks
92
+ )
93
+
94
+ def diff(self, other: "SideEffects") -> Optional[str]:
95
+ if self.id_to_variable != other.id_to_variable:
96
+ sk_itv = self.id_to_variable.keys()
97
+ ok_itv = other.id_to_variable.keys()
98
+ if sk_itv != ok_itv:
99
+ return f"id_to_variable keys: {sk_itv} != {ok_itv}"
100
+ # Feel free to augment this with more fancy diffing logic
101
+ # if needed for debugging
102
+ return "id_to_variable: unknown diff"
103
+ elif self.store_attr_mutations != other.store_attr_mutations:
104
+ sk_sam = self.store_attr_mutations.keys()
105
+ ok_sam = other.store_attr_mutations.keys()
106
+ if sk_sam != ok_sam:
107
+ return f"store_attr_mutations keys: {sk_sam} != {ok_sam}"
108
+ return "store_attr_mutations: unknown diff"
109
+ elif self.save_for_backward != other.save_for_backward:
110
+ return "save_for_backward"
111
+ elif self.tensor_hooks != other.tensor_hooks:
112
+ return "tensor_hooks"
113
+ else:
114
+ return None
115
+
116
+ def clone(self):
117
+ """Create a shallow copy"""
118
+ return self.__class__(
119
+ id_to_variable=dict(self.id_to_variable),
120
+ store_attr_mutations={
121
+ k: dict(v) for k, v in self.store_attr_mutations.items()
122
+ },
123
+ keepalive=list(self.keepalive),
124
+ save_for_backward=self.save_for_backward,
125
+ tensor_hooks=self.tensor_hooks,
126
+ )
127
+
128
+ def apply(self, fn, cache=None, skip_fn=lambda _: False):
129
+ if cache is None:
130
+ cache = dict()
131
+
132
+ self.id_to_variable = {
133
+ k: VariableTracker.apply(fn, v, cache, skip_fn)
134
+ for k, v in self.id_to_variable.items()
135
+ }
136
+ self.store_attr_mutations = {
137
+ k: VariableTracker.apply(fn, v, cache, skip_fn)
138
+ for k, v in self.store_attr_mutations.items()
139
+ }
140
+ self.save_for_backward = VariableTracker.apply(
141
+ fn, self.save_for_backward, cache, skip_fn
142
+ )
143
+ self.tensor_hooks = VariableTracker.apply(fn, self.tensor_hooks, cache, skip_fn)
144
+
145
+ def __contains__(self, item):
146
+ return id(item) in self.id_to_variable
147
+
148
+ def __getitem__(self, item):
149
+ return self.id_to_variable[id(item)]
150
+
151
+ def check_allowed_side_effect(self, item):
152
+ from torch._dynamo.variables.misc import AutogradFunctionContextVariable
153
+
154
+ # People do things like self.dim = dim inside autograd.Function.
155
+ # These are benign.
156
+ if isinstance(item, AutogradFunctionContextVariable):
157
+ return True
158
+ if not is_side_effect_safe(item.mutable_local):
159
+ unimplemented(
160
+ "HigherOrderOperator: Mutating a variable not in the current scope (SideEffects)"
161
+ )
162
+
163
+ def store_attr(self, item: VariableTracker, name: str, value: VariableTracker):
164
+ assert self.is_attribute_mutation(item)
165
+ self.check_allowed_side_effect(item)
166
+ if item.mutable_local not in self.store_attr_mutations:
167
+ self.store_attr_mutations[item.mutable_local] = {}
168
+ self.store_attr_mutations[item.mutable_local][name] = value
169
+
170
+ def load_attr(self, item, name, deleted_ok=False):
171
+ assert self.is_attribute_mutation(item)
172
+ result = self.store_attr_mutations[item.mutable_local][name]
173
+ if not deleted_ok and isinstance(result, variables.DeletedVariable):
174
+ unimplemented("read deleted attribute")
175
+ return result
176
+
177
+ def store_cell(self, cellvar, value):
178
+ assert isinstance(cellvar, variables.NewCellVariable)
179
+ assert isinstance(value, variables.VariableTracker)
180
+ self.store_attr(cellvar, "cell_contents", value)
181
+
182
+ def load_cell(self, cellvar):
183
+ assert isinstance(cellvar, variables.NewCellVariable)
184
+ return self.load_attr(cellvar, "cell_contents")
185
+
186
+ def load_global(self, gvar: VariableTracker, name: str):
187
+ assert isinstance(gvar, variables.VariableTracker)
188
+ return self.load_attr(gvar, name)
189
+
190
+ def store_global(self, gvar: VariableTracker, name: str, value: VariableTracker):
191
+ assert isinstance(gvar, variables.VariableTracker)
192
+ assert isinstance(value, variables.VariableTracker)
193
+ self.store_attr(gvar, name, value)
194
+
195
+ @staticmethod
196
+ def cls_supports_mutation_side_effects(cls):
197
+ return inspect.getattr_static(cls, "__setattr__", None) in (
198
+ object.__setattr__,
199
+ torch.nn.Module.__setattr__,
200
+ )
201
+
202
+ def is_attribute_mutation(self, item):
203
+ return isinstance(item.mutable_local, AttributeMutation)
204
+
205
+ def has_pending_mutation(self, item):
206
+ return self.is_attribute_mutation(item) and bool(
207
+ self.store_attr_mutations.get(item.mutable_local)
208
+ )
209
+
210
+ def is_modified(self, item):
211
+ if isinstance(item.mutable_local, AttributeMutationNew):
212
+ return True
213
+ if self.is_attribute_mutation(item):
214
+ return item.mutable_local in self.store_attr_mutations
215
+ return item.mutable_local.is_modified
216
+
217
+ def _track_obj(
218
+ self,
219
+ item: Any,
220
+ variable: VariableTracker,
221
+ mutable_cls=MutableSideEffects,
222
+ ):
223
+ """Start tracking a new variable for mutation"""
224
+ assert variable.source is not None
225
+ variable.mutable_local = mutable_cls(variable.source)
226
+ self.id_to_variable[id(item)] = variable
227
+ self.keepalive.append(item)
228
+ return variable
229
+
230
+ track_mutable = _track_obj
231
+
232
+ def track_object_existing(
233
+ self,
234
+ item: Any,
235
+ variable: VariableTracker,
236
+ ):
237
+ return self._track_obj(item, variable, mutable_cls=AttributeMutationExisting)
238
+
239
+ def track_object_new(
240
+ self,
241
+ cls_source: Source,
242
+ user_cls: Any,
243
+ variable_cls: Any,
244
+ options,
245
+ ):
246
+ if user_cls is torch.autograd.function.FunctionCtx:
247
+ obj = torch.autograd.Function()
248
+ elif issubclass(user_cls, torch.nn.Module):
249
+ obj = nn_module_new(user_cls)
250
+ else:
251
+ obj = object_new(user_cls)
252
+ variable = variable_cls(
253
+ obj,
254
+ mutable_local=AttributeMutationNew(None, cls_source),
255
+ **options,
256
+ )
257
+ self.id_to_variable[id(obj)] = variable
258
+ self.keepalive.append(obj)
259
+ return variable
260
+
261
+ def track_cell_new(
262
+ self,
263
+ ):
264
+ obj = object()
265
+ variable = variables.NewCellVariable(
266
+ mutable_local=AttributeMutationNew(None, None),
267
+ )
268
+ self.id_to_variable[id(obj)] = variable
269
+ self.keepalive.append(obj)
270
+ return variable
271
+
272
+ def track_cell_existing(self, source: Source, item: Any):
273
+ variable = variables.NewCellVariable(
274
+ mutable_local=AttributeMutationExisting(source),
275
+ )
276
+ self.id_to_variable[id(item)] = variable
277
+ self.keepalive.append(item)
278
+ return variable
279
+
280
+ def track_global_existing(self, source: Source, item: Any):
281
+ variable = variables.NewGlobalVariable(
282
+ mutable_local=AttributeMutationExisting(source),
283
+ )
284
+ self.id_to_variable[id(item)] = variable
285
+ self.keepalive.append(item)
286
+ return variable
287
+
288
+ def track_save_for_backward(self, ctx, args):
289
+ assert isinstance(ctx, variables.AutogradFunctionContextVariable)
290
+ self.save_for_backward.append((ctx, args))
291
+
292
+ def track_tensor_variables_from_runahead_side_effects(self, other):
293
+ # In higher order ops we want to keep track of tensors seen in the
294
+ # speculate_subgraph so that we don't lift them again as a new input in
295
+ # other speculate_subgraph or in the root tracer.
296
+ for other_item in other.keepalive:
297
+ other_id = id(other_item)
298
+ other_variable = other.id_to_variable[other_id]
299
+ if other_id not in self.id_to_variable and isinstance(
300
+ other_variable, variables.TensorVariable
301
+ ):
302
+ self.track_object_existing(other_item, other_variable)
303
+
304
+ def prune_dead_object_new(self, tx):
305
+ live_new_objects = set()
306
+ skip_obj = None
307
+
308
+ def visit(var: VariableTracker):
309
+ if (
310
+ isinstance(var.mutable_local, AttributeMutationNew)
311
+ and var.mutable_local is not skip_obj
312
+ ):
313
+ live_new_objects.add(var.mutable_local)
314
+ return var
315
+
316
+ def is_live(var: Union[MutableLocalBase, VariableTracker]):
317
+ if isinstance(var, AttributeMutationNew):
318
+ return var in live_new_objects
319
+ if isinstance(var, VariableTracker):
320
+ return is_live(var.mutable_local)
321
+ return True
322
+
323
+ VariableTracker.apply(visit, (tx.stack, tx.symbolic_locals))
324
+ for var in self.id_to_variable.values():
325
+ if not isinstance(var.mutable_local, AttributeMutationNew):
326
+ VariableTracker.apply(visit, var)
327
+
328
+ for skip_obj, setattrs in self.store_attr_mutations.items():
329
+ VariableTracker.apply(visit, setattrs)
330
+
331
+ self.id_to_variable = {
332
+ k: v for k, v in self.id_to_variable.items() if is_live(v)
333
+ }
334
+ self.store_attr_mutations = {
335
+ k: v for k, v in self.store_attr_mutations.items() if is_live(k)
336
+ }
337
+
338
+ def mutation(self, var):
339
+ self.check_allowed_side_effect(var)
340
+ if isinstance(var.mutable_local, MutableSideEffects):
341
+ var.mutable_local = MutableSideEffects(var.mutable_local.source, True)
342
+
343
+ def _get_modified_vars(self):
344
+ return [var for var in self.id_to_variable.values() if self.is_modified(var)]
345
+
346
+ def codegen_save_tempvars(self, cg: PyCodegen):
347
+ for var in self._get_modified_vars():
348
+ if isinstance(
349
+ var.mutable_local, (AttributeMutationExisting, AttributeMutationNew)
350
+ ) and isinstance(var, variables.NewCellVariable):
351
+ cg.load_import_from(utils.__name__, "make_cell")
352
+ cg.extend_output(create_call_function(0, True))
353
+ cg.add_cache(var)
354
+ if isinstance(var.mutable_local, AttributeMutationNew):
355
+ var.mutable_local.source = LocalSource(cg.tempvars[var]) # type: ignore[attr-defined]
356
+ elif isinstance(var.mutable_local, AttributeMutationNew):
357
+ if isinstance(var, variables.AutogradFunctionContextVariable):
358
+ unimplemented("AutogradFunctionContextVariable escaped")
359
+ if "__call_nn_module_init" in self.store_attr_mutations.get(
360
+ var.mutable_local, {}
361
+ ):
362
+ assert isinstance(var, variables.UnspecializedNNModuleVariable)
363
+ cg.load_import_from(utils.__name__, "nn_module_new")
364
+ else:
365
+ cg.load_import_from(utils.__name__, "object_new")
366
+ cg(var.mutable_local.cls_source)
367
+ cg.extend_output(create_call_function(1, True))
368
+ cg.add_cache(var)
369
+ var.mutable_local.source = LocalSource(cg.tempvars[var])
370
+ elif var in cg.tempvars:
371
+ assert cg.tempvars.get(var) is None
372
+ # subsequent usage should point to the original variable
373
+ cg(var.mutable_local.source)
374
+ cg.add_cache(var)
375
+
376
+ for ctx, args in self.save_for_backward:
377
+ cg(ctx.source)
378
+ cg.extend_output(
379
+ [create_instruction("LOAD_METHOD", argval="save_for_backward")]
380
+ )
381
+ for arg in args:
382
+ cg(arg)
383
+ cg.extend_output(
384
+ [
385
+ *create_call_method(len(args)),
386
+ create_instruction("POP_TOP"),
387
+ ]
388
+ )
389
+
390
+ def register_hook(self, tensor, hook, handle, name):
391
+ assert isinstance(tensor, variables.TensorVariable)
392
+ assert isinstance(hook, variables.VariableTracker)
393
+ assert (
394
+ isinstance(handle, variables.RemovableHandleVariable)
395
+ and handle.mutable_local
396
+ )
397
+ assert hasattr(torch.Tensor, name)
398
+ idx = len(self.tensor_hooks.keys())
399
+ # duplicate index possible because of self.remove_hook()
400
+ while idx in self.tensor_hooks:
401
+ idx += 1
402
+ self.tensor_hooks[idx] = (tensor, hook, handle, name)
403
+ assert not handle.idx
404
+ handle.idx = idx
405
+
406
+ def remove_hook(self, idx):
407
+ del self.tensor_hooks[idx]
408
+
409
+ def codegen_hooks(self, cg):
410
+ for (
411
+ tensor,
412
+ hook,
413
+ handle,
414
+ name,
415
+ ) in self.tensor_hooks.values():
416
+ # Note: [On tensor.register_hook]
417
+ #
418
+ # register_hook on a tensor, AKA backward hooks, have slightly nuanced differences in how they are implemented
419
+ # when it comes to hooks on objects with sources (inputs, params) vs objects without sources (intermediaries).
420
+ #
421
+ # For tensors with a source, we bypass direct inclusion of register_hook calls in the graph.
422
+ # Instead, these are tracked and stashed as a global variable, enabling their association with tensors in
423
+ # the residuals. During dynamo's frame creation, these hooks are invoked seamlessly on known reconstructible/fetch-able
424
+ # tensors. Because a source indicates knowledge of this object outside the torch compile region, and
425
+ # because we are running residuals firmly before .backward() can be run, it is sound to invoke
426
+ # `register_hook` on a known tensor.
427
+ #
428
+ # For tensors without a source, we support a limited subset of hooks. Global functions only, and
429
+ # compiled_autograd must be enabled or we will graph break.
430
+ #
431
+ # Handling the Handle: When a user retains the register_hook result in a handle, we intercept the
432
+ # STORE_FAST operation to record the user-designated local variable name. This ensures the reconstructed
433
+ # bytecode retains this name. If no handle is defined, we simply pop the generated value to keep the
434
+ # stack intact.
435
+ #
436
+ # Dynamo Tensor Hooks Workflow:
437
+ # - Functions passed to register_hook are lifted globally.
438
+ # - For tensors with sources:
439
+ # - In the "side_effects" phase of codegen, we iterate over tensors with hooks to:
440
+ # - Generate the tensor.
441
+ # - Issue a register_hook call on the tensor, linking to the globally stored function.
442
+ # - Incorporate a handle if one was established in the eager phase.
443
+ # - For tensors without sources:
444
+ # - We don't generate any instructions for registering a hook.
445
+ # - Handles from intermediary hooks are NYI.
446
+ # - We produce a call function that utilizes the trace_wrapped higher order op, closing over it.
447
+ # - We then manually insert the call function above into the graph.
448
+ # - The handle's exact user-specified name, "user_code_variable_name", is discerned and associated during STORE_FAST.
449
+ assert tensor.source, "Hooks on non input tensors NYI - should not get here"
450
+ cg(tensor)
451
+ cg.extend_output([cg.create_load_attr(name)])
452
+ cg(hook)
453
+ cg.extend_output(create_call_function(1, True))
454
+
455
+ # Adding the handle to the cache means RemovableHandleVariable().reconstruct() will
456
+ # be associated with the return value of register_hook(). This consumes the top of stack.
457
+ cg.add_cache(handle)
458
+
459
+ def codegen_update_mutated(self, cg: PyCodegen):
460
+ suffixes = []
461
+ for var in self._get_modified_vars():
462
+ if isinstance(var, variables.ListVariable):
463
+ # old[:] = new
464
+ cg(var, allow_cache=False)
465
+ cg(var.mutable_local.source) # type: ignore[attr-defined]
466
+ cg.extend_output(
467
+ [
468
+ cg.create_load_const(None),
469
+ cg.create_load_const(None),
470
+ create_instruction("BUILD_SLICE", arg=2),
471
+ ]
472
+ )
473
+ suffixes.append([create_instruction("STORE_SUBSCR")])
474
+ elif isinstance(var, variables.ConstDictVariable):
475
+ cg.tx.output.update_co_names("clear")
476
+ cg.tx.output.update_co_names("update")
477
+
478
+ cg(var.mutable_local.source) # type: ignore[attr-defined]
479
+ cg.extend_output([create_instruction("LOAD_METHOD", argval="update")])
480
+ cg(var, allow_cache=False)
481
+
482
+ cg(var.mutable_local.source) # type: ignore[attr-defined]
483
+ cg.extend_output([create_instruction("LOAD_METHOD", argval="clear")])
484
+
485
+ suffixes.append(
486
+ [
487
+ *create_call_method(0), # clear
488
+ create_instruction("POP_TOP"),
489
+ *create_call_method(1), # update
490
+ create_instruction("POP_TOP"),
491
+ ]
492
+ )
493
+ elif self.is_attribute_mutation(var):
494
+ for name, value in self.store_attr_mutations.get(
495
+ var.mutable_local, {}
496
+ ).items():
497
+ if isinstance(var, variables.NewGlobalVariable):
498
+ cg.tx.output.update_co_names(name)
499
+ cg(value)
500
+ suffixes.append(
501
+ [create_instruction("STORE_GLOBAL", argval=name)]
502
+ )
503
+ elif name == "__call_nn_module_init":
504
+ pass # handled in codegen_save_tempvars
505
+ elif isinstance(value, variables.DeletedVariable):
506
+ if isinstance(
507
+ var.mutable_local, AttributeMutationExisting
508
+ ) and hasattr(getattr(var, "value", None), name):
509
+ cg.tx.output.update_co_names(name)
510
+ cg(var.mutable_local.source)
511
+ suffixes.append(
512
+ [create_instruction("DELETE_ATTR", argval=name)]
513
+ )
514
+ else:
515
+ cg.tx.output.update_co_names(name)
516
+ cg(value)
517
+ cg(var.mutable_local.source)
518
+ suffixes.append([create_instruction("STORE_ATTR", argval=name)])
519
+ elif isinstance(var, variables.TupleIteratorVariable):
520
+ for _ in range(var.index):
521
+ cg.load_import_from(utils.__name__, "iter_next")
522
+ cg(var.mutable_local.source) # type: ignore[attr-defined]
523
+ cg.extend_output(create_call_function(1, True))
524
+ cg.append_output(create_instruction("POP_TOP"))
525
+ else:
526
+ raise AssertionError(type(var))
527
+
528
+ # do all the actual mutations at the very end to handle dependencies
529
+ for suffix in reversed(suffixes):
530
+ cg.extend_output(suffix)
531
+
532
+ def is_empty(self):
533
+ return not (
534
+ any(map(self.is_modified, self.id_to_variable.values()))
535
+ or self.tensor_hooks
536
+ or self.save_for_backward
537
+ or self.tensor_hooks
538
+ )
539
+
540
+ def clear(self):
541
+ self.keepalive.clear()
542
+ self.id_to_variable.clear()
llmeval-env/lib/python3.10/site-packages/torch/_dynamo/symbolic_convert.py ADDED
@@ -0,0 +1,2603 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import collections
2
+ import contextlib
3
+ import copy
4
+ import dataclasses
5
+ import dis
6
+ import functools
7
+ import importlib
8
+ import inspect
9
+ import itertools
10
+ import linecache
11
+ import logging
12
+ import operator
13
+ import sys
14
+ import textwrap
15
+ import threading
16
+ import traceback
17
+ import types
18
+ import typing
19
+ import weakref
20
+ from typing import Any, Dict, List, NamedTuple, Optional, Set, Tuple, Type
21
+ from unittest.mock import patch
22
+
23
+ import torch
24
+ import torch._logging
25
+ from torch._guards import Checkpointable, tracing, TracingContext
26
+
27
+ from . import config, exc, logging as torchdynamo_logging, trace_rules, variables
28
+ from .bytecode_analysis import (
29
+ get_indexof,
30
+ JUMP_OPNAMES,
31
+ livevars_analysis,
32
+ propagate_line_nums,
33
+ )
34
+ from .bytecode_transformation import (
35
+ cleaned_instructions,
36
+ create_call_function,
37
+ create_instruction,
38
+ create_jump_absolute,
39
+ Instruction,
40
+ is_generator,
41
+ unique_id,
42
+ )
43
+ from .code_context import code_context
44
+ from .codegen import PyCodegen
45
+ from .current_scope_id import current_scope_id
46
+ from .exc import ArgsMismatchError, BackendCompilerFailed, unimplemented, Unsupported
47
+ from .funcname_cache import get_funcname
48
+ from .guards import GuardBuilder, install_guard
49
+ from .output_graph import GraphCompileReason, OutputGraph, OutputGraphState
50
+ from .replay_record import DummyModule, ExecutionRecorder
51
+ from .resume_execution import ContinueExecutionCache, ReenterWith
52
+ from .source import (
53
+ AttrSource,
54
+ GetItemSource,
55
+ GlobalSource,
56
+ GlobalWeakRefSource,
57
+ LocalSource,
58
+ Source,
59
+ )
60
+ from .trace_rules import is_builtin_constant, is_forbidden
61
+ from .utils import (
62
+ counters,
63
+ get_fake_value,
64
+ get_instruction_source_311,
65
+ graph_break_dup_warning_checker,
66
+ istype,
67
+ LazyString,
68
+ proxy_args_kwargs,
69
+ )
70
+ from .variables.base import (
71
+ _is_top_level_scope,
72
+ is_side_effect_safe,
73
+ MutableLocal,
74
+ typestr,
75
+ VariableTracker,
76
+ )
77
+ from .variables.builder import VariableBuilder, wrap_fx_proxy
78
+ from .variables.builtin import BuiltinVariable
79
+ from .variables.constant import ConstantVariable
80
+ from .variables.ctx_manager import (
81
+ ContextWrappingVariable,
82
+ GenericContextWrappingVariable,
83
+ WithExitFunctionVariable,
84
+ )
85
+ from .variables.dicts import ConstDictVariable, SetVariable
86
+ from .variables.functions import (
87
+ BaseUserFunctionVariable,
88
+ NestedUserFunctionVariable,
89
+ SkipFunctionVariable,
90
+ UserFunctionVariable,
91
+ UserMethodVariable,
92
+ )
93
+ from .variables.lists import (
94
+ BaseListVariable,
95
+ ListIteratorVariable,
96
+ ListVariable,
97
+ SliceVariable,
98
+ TupleVariable,
99
+ )
100
+ from .variables.misc import (
101
+ ClosureVariable,
102
+ GetAttrVariable,
103
+ InlinedClosureVariable,
104
+ NullVariable,
105
+ PythonModuleVariable,
106
+ UnknownVariable,
107
+ )
108
+ from .variables.nn_module import NNModuleVariable
109
+ from .variables.tensor import (
110
+ supported_const_comparison_ops,
111
+ supported_tensor_comparison_ops,
112
+ SymNodeVariable,
113
+ TensorVariable,
114
+ )
115
+ from .variables.user_defined import (
116
+ RemovableHandleVariable,
117
+ UserDefinedClassVariable,
118
+ UserDefinedObjectVariable,
119
+ UserDefinedVariable,
120
+ )
121
+
122
+ log = logging.getLogger(__name__)
123
+ graph_break_log = torch._logging.getArtifactLogger(__name__, "graph_breaks")
124
+ trace_call_log = torch._logging.getArtifactLogger(__name__, "trace_call")
125
+ trace_source_log = torch._logging.getArtifactLogger(__name__, "trace_source")
126
+ tls = threading.local()
127
+
128
+
129
+ @dataclasses.dataclass
130
+ class SpeculationEntry:
131
+ filename: str
132
+ lineno: int
133
+ instruction_pointer: int
134
+ failed: bool = False
135
+ reason: Optional[GraphCompileReason] = None
136
+
137
+ def fail_and_restart_analysis(self):
138
+ """
139
+ Start tracing of the current frame over again, and don't take this branch.
140
+ """
141
+ self.failed = True
142
+ raise exc.SpeculationRestartAnalysis()
143
+
144
+
145
+ @dataclasses.dataclass
146
+ class SpeculationLog:
147
+ """
148
+ SpeculationLog replaces the prior copy_graphstate/restore_graphstate
149
+ checkpointing. Rather than saving/restoring state, we restart the
150
+ dynamo conversion process over from the beginning -- but when we
151
+ hit the start of the speculation that failed, we instead generate
152
+ a graph break.
153
+ """
154
+
155
+ entries: List[SpeculationEntry] = dataclasses.field(default_factory=list)
156
+ index: int = 0
157
+
158
+ def restart(self):
159
+ self.index = 0
160
+
161
+ def clear(self):
162
+ self.entries.clear()
163
+ self.index = 0
164
+
165
+ def next(self, filename: str, lineno: int, instruction_pointer) -> SpeculationEntry:
166
+ """
167
+ Lookup or create a SpeculationEntry() that is shared across
168
+ RestartAnalysis calls. Args are used only for debug checks.
169
+ """
170
+ if len(self.entries) == self.index:
171
+ self.entries.append(SpeculationEntry(filename, lineno, instruction_pointer))
172
+ entry = self.entries[self.index]
173
+ self.index += 1
174
+ assert (
175
+ entry.instruction_pointer == instruction_pointer
176
+ and entry.filename == filename
177
+ and entry.lineno == lineno
178
+ ), textwrap.dedent(
179
+ f"""
180
+ SpecuationLog diverged at {self.index} of {len(self.entries)}:
181
+ - Run1: {entry.filename}:{entry.lineno} (ip={entry.instruction_pointer})
182
+ - Run2: {filename}:{lineno} (ip={instruction_pointer})
183
+ Please submit a bug report.
184
+ """
185
+ )
186
+ return entry
187
+
188
+
189
+ @functools.lru_cache(None)
190
+ def _step_logger():
191
+ return torchdynamo_logging.get_step_logger(log)
192
+
193
+
194
+ @dataclasses.dataclass
195
+ class BlockStackEntry:
196
+ target: Instruction
197
+ stack_index: Optional[int] = None
198
+ with_context: Optional[ContextWrappingVariable] = None
199
+
200
+ def can_restore(self):
201
+ return self.with_context is not None
202
+
203
+ def resume_fn(self):
204
+ assert self.stack_index is not None
205
+ if self.with_context and self.with_context.target_values:
206
+ return ReenterWith(self.stack_index, tuple(self.with_context.target_values))
207
+ else:
208
+ return ReenterWith(self.stack_index)
209
+
210
+ def exit(self, tx):
211
+ assert self.with_context is not None
212
+ return self.with_context.exit(tx)
213
+
214
+
215
+ class InstructionTranslatorGraphState(NamedTuple):
216
+ output: OutputGraphState
217
+ symbolic_locals: Dict[str, VariableTracker]
218
+ stack: List[VariableTracker]
219
+ block_stack: List[BlockStackEntry]
220
+ instruction_pointer: Optional[int]
221
+ current_instruction: Instruction
222
+ next_instruction: Optional[Instruction]
223
+ lineno: int
224
+
225
+ def diff(self, other: "InstructionTranslatorGraphState") -> Optional[str]:
226
+ for k in self._fields:
227
+ if k == "output":
228
+ return self.output.diff(other.output, prefix=f"{k}.")
229
+ sv = getattr(self, k)
230
+ ov = getattr(other, k)
231
+ if sv != ov:
232
+ return f"{k} mismatch: {sv} != {ov}"
233
+ return None
234
+
235
+
236
+ def stack_op(fn: typing.Callable[..., object]):
237
+ nargs = len(inspect.signature(fn).parameters)
238
+ fn_var = BuiltinVariable(fn)
239
+
240
+ @functools.wraps(fn)
241
+ def impl(self: "InstructionTranslatorBase", inst: Instruction):
242
+ self.push(fn_var.call_function(self, self.popn(nargs), {}))
243
+
244
+ return impl
245
+
246
+
247
+ def _detect_and_normalize_assert_statement(
248
+ self: "InstructionTranslatorBase",
249
+ truth_fn: typing.Callable[[object], bool],
250
+ push: bool,
251
+ ):
252
+ # Detect if this jump instruction is assert and normalize the assert
253
+ # by pushing dummy error message when nothing is given.
254
+ #
255
+ # Python 3.9 assertion is in following format:
256
+ # 18 POP_JUMP_IF_TRUE 28
257
+ # 20 LOAD_ASSERTION_ERROR
258
+ # 22 LOAD_CONST 3 ('Assert message') -> optional instruction
259
+ # 24 CALL_FUNCTION 1 -> optional instruction
260
+ # 26 RAISE_VARARGS
261
+ #
262
+ # Python 3.8 assertion is in following format:
263
+ # 18 POP_JUMP_IF_TRUE 28
264
+ # 20 LOAD_GLOBAL 0 (Assertion type)
265
+ # 22 LOAD_CONST 3 ('Assert message') -> optional instruction
266
+ # 24 CALL_FUNCTION 1 -> optional instruction
267
+ # 26 RAISE_VARARGS 1
268
+
269
+ if (truth_fn is not operator.truth) or push:
270
+ return False
271
+
272
+ assert isinstance(self.instruction_pointer, int)
273
+ current_instruction_pointer = self.instruction_pointer
274
+ inst = self.instructions[current_instruction_pointer]
275
+ # Detect LOAD_ASSERTION_ERROR or LOAD_GLOBAL 0
276
+ if sys.version_info < (3, 9):
277
+ if inst.opname != "LOAD_GLOBAL" or inst.argval != "AssertionError":
278
+ return False
279
+ else:
280
+ if inst.opname != "LOAD_ASSERTION_ERROR":
281
+ return False
282
+
283
+ current_instruction_pointer += 1
284
+
285
+ # Use dummy error message if its hard to extract
286
+ error_msg = "assertion error"
287
+
288
+ inst = self.instructions[current_instruction_pointer]
289
+ # DETECT RAISE_VARARGS or LOAD CONST
290
+ if inst.opname == "LOAD_CONST":
291
+ if not isinstance(inst.argval, str):
292
+ return False
293
+ error_msg = inst.argval
294
+
295
+ # if it is LOAD_CONSTANT, it must be followed by CALL_FUNCTION
296
+ # (PRECALL for Python 3.11+)
297
+ current_instruction_pointer += 1
298
+ inst = self.instructions[current_instruction_pointer]
299
+ if inst.opname not in ("CALL_FUNCTION", "PRECALL"):
300
+ return False
301
+
302
+ # for Python 3.11+, PRECALL should be followed by CALL, then RAISE_VARARGS
303
+ # for Python < 3.11, CALL_FUNCTION should be followed by RAISE_VARARGS
304
+ current_instruction_pointer += 1
305
+ if inst.opname == "PRECALL":
306
+ current_instruction_pointer += 1
307
+ inst = self.instructions[current_instruction_pointer]
308
+
309
+ if inst.opname != "RAISE_VARARGS":
310
+ return False
311
+
312
+ self.push(ConstantVariable.create(error_msg))
313
+
314
+ return True
315
+
316
+
317
+ def generic_jump(truth_fn: typing.Callable[[object], bool], push: bool):
318
+ def inner(self: "InstructionTranslatorBase", inst: Instruction):
319
+ value: VariableTracker = self.pop()
320
+ if (
321
+ config.rewrite_assert_with_torch_assert
322
+ and _detect_and_normalize_assert_statement(self, truth_fn, push)
323
+ ):
324
+ error_msg: VariableTracker = self.pop()
325
+ # Skip over things like `assert True`
326
+ if value.is_python_constant() and bool(value.as_python_constant()):
327
+ self.jump(inst)
328
+ return
329
+
330
+ # TODO maybe should respect DtoH sync intention of users later??
331
+ # Manually insert torch._assert_async instead of python assert and jump over
332
+ # assert related instructions as we don't need them anymore.
333
+
334
+ # if we see Tensor as assert statement, no need to call scalar_tensor
335
+ if isinstance(value, TensorVariable):
336
+ self.output.create_proxy(
337
+ "call_function",
338
+ torch._assert_async,
339
+ *proxy_args_kwargs((value, error_msg), {}),
340
+ )
341
+ self.jump(inst)
342
+ return
343
+
344
+ if isinstance(value, SymNodeVariable):
345
+ # if the assertion is normal shape expression.
346
+ # just install guard and bail out.
347
+ sym_expr = value.sym_num
348
+ if not isinstance(sym_expr, torch.SymBool):
349
+ sym_expr = sym_expr != 0
350
+
351
+ result = torch.fx.experimental.symbolic_shapes.expect_true(sym_expr)
352
+ if not result:
353
+ raise unimplemented(
354
+ "Assertion failed on symbolic shapes. Did you make sure eager mode succeeds?"
355
+ )
356
+ self.jump(inst)
357
+ return
358
+
359
+ scalar_to_tensor_proxy = self.output.create_proxy(
360
+ "call_function", torch.scalar_tensor, *proxy_args_kwargs((value,), {})
361
+ )
362
+
363
+ scalar_to_tensor = wrap_fx_proxy(
364
+ self,
365
+ scalar_to_tensor_proxy,
366
+ example_value=get_fake_value(scalar_to_tensor_proxy.node, self),
367
+ )
368
+
369
+ self.output.create_proxy(
370
+ "call_function",
371
+ torch._assert_async,
372
+ *proxy_args_kwargs((scalar_to_tensor, error_msg), {}),
373
+ )
374
+ self.jump(inst)
375
+ return
376
+
377
+ if value.is_python_constant():
378
+ if truth_fn(value.as_python_constant()):
379
+ push and self.push(value)
380
+ self.jump(inst)
381
+ elif (
382
+ isinstance(value, (TensorVariable)) and self.should_compile_partial_graph()
383
+ ):
384
+ # compile a partial subgraph prefix then jump into user code
385
+ if self.has_backedge():
386
+ msg = (
387
+ "Skipping frame because there is a graph break in a for/while loop\n"
388
+ f"{self.frame_summary()}"
389
+ )
390
+ log.info(msg)
391
+ raise exc.SkipFrame(msg)
392
+
393
+ self.push(value)
394
+ log.debug("generic_jump triggered compile")
395
+ self.output.compile_subgraph(
396
+ self,
397
+ reason=GraphCompileReason(
398
+ f"generic_jump {typestr(value)}", [self.frame_summary()]
399
+ ),
400
+ )
401
+ self.pop()
402
+
403
+ if_next = self.create_call_resume_at(self.next_instruction)
404
+ push and self.push(value)
405
+ if_jump = self.create_call_resume_at(inst.target)
406
+
407
+ self.output.add_output_instructions(
408
+ [create_instruction(inst.opname, target=if_jump[0])] + if_next + if_jump
409
+ )
410
+ elif isinstance(value, NNModuleVariable):
411
+ # Equivalent of "self.nn_module is not None"
412
+ mod = self.output.get_submodule(value.module_key)
413
+ if truth_fn(mod):
414
+ push and self.push(value)
415
+ self.jump(inst)
416
+ elif isinstance(value, UserDefinedObjectVariable):
417
+ x = value.var_getattr(self, "__bool__")
418
+ # if __bool__ is missing, trying __len__ to infer a truth value.
419
+ if isinstance(x, GetAttrVariable):
420
+ x = value.var_getattr(self, "__len__")
421
+
422
+ # __bool__ or __len__ is function
423
+ if isinstance(x, UserMethodVariable):
424
+ result = x.call_function(self, [], {})
425
+ if isinstance(result, ConstantVariable) and isinstance(
426
+ result.value, (bool, int)
427
+ ):
428
+ if truth_fn(result.value):
429
+ push and self.push(value)
430
+ self.jump(inst)
431
+ else:
432
+ unimplemented(
433
+ "generic_jump on UserDefined with __bool__ returning non-constant"
434
+ )
435
+ # __bool__ or __len__ is non-function or not existed in the user defined object
436
+ else:
437
+ if truth_fn(True):
438
+ push and self.push(value)
439
+ self.jump(inst)
440
+ elif not isinstance(value, TensorVariable) and value.has_unpack_var_sequence(
441
+ self
442
+ ):
443
+ if truth_fn(len(value.unpack_var_sequence(self))):
444
+ push and self.push(value)
445
+ self.jump(inst)
446
+ elif isinstance(value, SymNodeVariable):
447
+ eval_result = value.evaluate_expr(self.output)
448
+ if truth_fn(eval_result):
449
+ push and self.push(value)
450
+ self.jump(inst)
451
+ elif isinstance(value, variables.BackwardHookVariable):
452
+ if truth_fn(True):
453
+ push and self.push(value)
454
+ self.jump(inst)
455
+ else:
456
+ from .source import is_constant_source
457
+
458
+ if value.source is not None and is_constant_source(value.source):
459
+ if truth_fn(value.get_real_value()): # type: ignore[attr-defined]
460
+ push and self.push(value)
461
+ self.jump(inst)
462
+ else:
463
+ # TODO link the torch.cond doc later
464
+ raise exc.UserError(
465
+ exc.UserErrorType.DYNAMIC_CONTROL_FLOW,
466
+ "Dynamic control flow is not supported at the moment. Please use "
467
+ "functorch.experimental.control_flow.cond to explicitly capture the control flow.",
468
+ case_name="cond_operands",
469
+ )
470
+
471
+ return inner
472
+
473
+
474
+ explain = False
475
+
476
+
477
+ def break_graph_if_unsupported(*, push):
478
+ def decorator(inner_fn):
479
+ @functools.wraps(inner_fn)
480
+ def wrapper(self: "InstructionTranslatorBase", inst: Instruction):
481
+ speculation = self.speculate()
482
+ if speculation.failed:
483
+ assert speculation.reason is not None
484
+ return handle_graph_break(self, inst, speculation.reason)
485
+ try:
486
+ TracingContext.set_current_loc(
487
+ self.f_code.co_filename, self.lineno, self.f_code.co_name
488
+ )
489
+ return inner_fn(self, inst)
490
+ except Unsupported as excp:
491
+ if self.generic_context_manager_depth > 0:
492
+ # We don't support graph break under GenericContextWrappingVariable,
493
+ # If there is, we roll back to the checkpoint and fall back.
494
+ excp.remove_from_stats()
495
+ unimplemented("Graph break under GenericContextWrappingVariable")
496
+
497
+ if isinstance(excp, exc.UncapturedHigherOrderOpError):
498
+ raise
499
+
500
+ if not self.should_compile_partial_graph():
501
+ raise
502
+
503
+ user_stack = excp.real_stack
504
+ # TODO: Also report the traceback from the parent frame
505
+ user_stack_formatted = "".join(traceback.format_list(user_stack))
506
+ frame_loc = (user_stack[-1].filename, user_stack[-1].lineno)
507
+ # torch._dynamo.explain() formats this a little nicer, and presents a slightly
508
+ # more actionable user code pointer
509
+ if (
510
+ graph_break_log.isEnabledFor(logging.DEBUG)
511
+ and not explain
512
+ and graph_break_dup_warning_checker.add(frame_loc)
513
+ ):
514
+ # This log line is exercised from
515
+ # python test/dynamo/test_exc.py -k test_graph_break_log
516
+ graph_break_log.debug(
517
+ "Graph break: from user code at:\n%s",
518
+ user_stack_formatted,
519
+ exc_info=True,
520
+ )
521
+ else:
522
+ # This log line MUST NOT contain the string "Graph break",
523
+ # exercised by
524
+ # python test/dynamo/test_misc.py -k test_duplicate_graph_break_log
525
+ log.debug(
526
+ "Unsupported break in user code at %s:%s (details suppressed)",
527
+ *frame_loc,
528
+ )
529
+
530
+ if self.has_backedge():
531
+ msg = (
532
+ "Skipping frame because there is a graph break in a for/while loop\n"
533
+ f"{self.frame_summary()}"
534
+ )
535
+ log.info(msg)
536
+ raise exc.SkipFrame(msg) from excp
537
+
538
+ excp.remove_from_stats()
539
+ excp.add_to_stats("graph_break")
540
+ speculation.reason = GraphCompileReason(excp.msg, user_stack)
541
+ speculation.fail_and_restart_analysis()
542
+
543
+ def handle_graph_break(
544
+ self: "InstructionTranslatorBase",
545
+ inst: Instruction,
546
+ reason: GraphCompileReason,
547
+ ):
548
+ self.output.compile_subgraph(self, reason=reason)
549
+ cg = PyCodegen(self)
550
+ cleanup: List[Instruction] = []
551
+ # Reconstruct the context variables in the block stack
552
+ for b in self.block_stack:
553
+ assert b.with_context is not None
554
+ cg(b.with_context)
555
+ cg.extend_output(b.resume_fn().try_except(cg.code_options, cleanup))
556
+ self.output.add_output_instructions(cg.get_instructions())
557
+ del cg
558
+
559
+ if sys.version_info >= (3, 11) and inst.opname == "CALL":
560
+ kw_names = (
561
+ self.kw_names.as_python_constant()
562
+ if self.kw_names is not None
563
+ else ()
564
+ )
565
+ if len(kw_names) > 0:
566
+ self.output.add_output_instructions(
567
+ [create_instruction("KW_NAMES", argval=kw_names)]
568
+ )
569
+ self.output.add_output_instructions(
570
+ create_call_function(inst.arg, False)
571
+ )
572
+ else:
573
+ # copy instruction, but without exception table data
574
+ assert inst.target is None
575
+ inst_copy = copy.copy(inst)
576
+ inst_copy.exn_tab_entry = None
577
+ self.output.add_output_instructions([inst_copy])
578
+
579
+ self.output.add_output_instructions(cleanup)
580
+
581
+ if sys.version_info >= (3, 11) and inst.opname == "CALL":
582
+ # stack effect for PRECALL + CALL is split between the two instructions
583
+ stack_effect = dis.stack_effect(
584
+ dis.opmap["PRECALL"], inst.arg
585
+ ) + dis.stack_effect(dis.opmap["CALL"], inst.arg)
586
+ else:
587
+ stack_effect = dis.stack_effect(inst.opcode, inst.arg)
588
+ self.popn(push - stack_effect)
589
+
590
+ for _ in range(push):
591
+ self.push(UnknownVariable())
592
+ self.output.add_output_instructions(
593
+ self.create_call_resume_at(self.next_instruction)
594
+ )
595
+
596
+ return wrapper
597
+
598
+ return decorator
599
+
600
+
601
+ class InstructionTranslatorBase(Checkpointable[InstructionTranslatorGraphState]):
602
+ output: OutputGraph
603
+ symbolic_locals: Dict[str, VariableTracker]
604
+ symbolic_globals: Dict[str, VariableTracker]
605
+ stack: List[VariableTracker]
606
+ instruction_pointer: Optional[int]
607
+ current_instruction: Instruction
608
+ next_instruction: Optional[Instruction]
609
+ block_stack: List[BlockStackEntry]
610
+ lineno: int
611
+ kw_names: Optional[ConstantVariable]
612
+ accept_prefix_inst: bool
613
+ prefix_insts: List[Instruction]
614
+ inline_depth: int
615
+ inconsistent_side_effects: bool
616
+ current_speculation: Optional[SpeculationEntry]
617
+
618
+ def mark_inconsistent_side_effects(self):
619
+ """
620
+ InstructionTranslator has encountered instructions which may cause
621
+ dynamo to see a different version of history from eager
622
+ See: https://github.com/pytorch/pytorch/issues/110765
623
+ """
624
+ self.inconsistent_side_effects = True
625
+
626
+ def has_backedge(self):
627
+ cur_offset = self.current_instruction.offset
628
+ assert self.instruction_pointer is not None
629
+ for inst in self.instructions[self.instruction_pointer :]:
630
+ if inst.opname in JUMP_OPNAMES:
631
+ jump_offset = inst.argval
632
+ if jump_offset < cur_offset:
633
+ return True
634
+ return False
635
+
636
+ def cell_and_freevars(self):
637
+ if not hasattr(self, "_cell_and_freevars"):
638
+ self._cell_and_freevars = tuple(
639
+ self.code_options["co_cellvars"] or []
640
+ ) + tuple(self.code_options["co_freevars"] or [])
641
+ return self._cell_and_freevars
642
+
643
+ def prune_dead_locals(self):
644
+ reads = livevars_analysis(self.instructions, self.current_instruction)
645
+ # implicit use by super()
646
+ # reads = reads | {"__class__"}
647
+ # output variables?
648
+ reads = reads | set(self.cell_and_freevars())
649
+ self.symbolic_locals = {
650
+ k: v for k, v in self.symbolic_locals.items() if k in reads
651
+ }
652
+ self.output.side_effects.prune_dead_object_new(self)
653
+
654
+ def call_function(
655
+ self,
656
+ fn: VariableTracker,
657
+ args: List[VariableTracker],
658
+ kwargs: Dict[str, VariableTracker],
659
+ ):
660
+ assert isinstance(fn, VariableTracker)
661
+ assert isinstance(args, list)
662
+ assert isinstance(kwargs, dict)
663
+ assert all(
664
+ isinstance(x, VariableTracker)
665
+ for x in itertools.chain(args, kwargs.values())
666
+ )
667
+ inner_fn = None
668
+ if hasattr(fn, "value"):
669
+ inner_fn = fn.value
670
+ if hasattr(fn, "fn"):
671
+ inner_fn = fn.fn
672
+ if inner_fn and callable(inner_fn) and is_forbidden(inner_fn):
673
+ raise AssertionError(f"Attempt to trace forbidden callable {inner_fn}")
674
+ self.push(fn.call_function(self, args, kwargs))
675
+
676
+ def inline_user_function_return(self, fn, args, kwargs):
677
+ """
678
+ A call to some user defined function by inlining it.
679
+ """
680
+ return InliningInstructionTranslator.inline_call(self, fn, args, kwargs)
681
+
682
+ def get_line_of_code_header(self, lineno=None):
683
+ if lineno is None:
684
+ lineno = self.lineno
685
+ inline_depth_str = (
686
+ f" (inline depth: {self.inline_depth})" if self.inline_depth > 0 else ""
687
+ )
688
+ funcname = get_funcname(self.f_code.co_filename, lineno)
689
+ funcname_str = "" if funcname is None else f" ({funcname})"
690
+ return f"{self.f_code.co_filename}:{lineno} in {self.f_code.co_name}{funcname_str}{inline_depth_str}"
691
+
692
+ def get_log_starts_line_log_str(self):
693
+ log_str = f"TRACE starts_line {self.get_line_of_code_header()}\n"
694
+ line = linecache.getline(self.f_code.co_filename, self.lineno).rstrip()
695
+ log_str += f" {line}"
696
+ return log_str
697
+
698
+ def log_starts_line(self):
699
+ trace_source_log.debug("%s", LazyString(self.get_log_starts_line_log_str))
700
+
701
+ def step(self):
702
+ """Process exactly one instruction, return False we should exit"""
703
+ assert isinstance(self.instruction_pointer, int)
704
+ inst = self.instructions[self.instruction_pointer]
705
+ self.current_instruction = inst
706
+ self.instruction_pointer += 1
707
+ if self.instruction_pointer < len(self.instructions):
708
+ self.next_instruction = self.instructions[self.instruction_pointer]
709
+ else:
710
+ self.instruction_pointer = None
711
+ self.next_instruction = None
712
+ if inst.starts_line and self.lineno != inst.starts_line:
713
+ self.lineno = inst.starts_line
714
+ self.log_starts_line()
715
+
716
+ if (
717
+ len(self.stack) == 0
718
+ and self.should_compile_partial_graph()
719
+ and self.is_non_empty_graph()
720
+ ):
721
+ self.current_speculation = self.speculate()
722
+ if self.current_speculation.failed:
723
+ return self.step_graph_break(inst)
724
+
725
+ log.debug("TRACE %s %s %s", inst.opname, inst.argval, self.stack)
726
+
727
+ # 3.11 no longer uses a block stack, but we still keep track of one
728
+ # so that we know which contexts are currently active.
729
+ # For our purposes, all exception table entries with the same target
730
+ # are considered to be part of the same "block".
731
+ if sys.version_info >= (3, 11):
732
+ entry = inst.exn_tab_entry
733
+ if not (
734
+ # still in the same block
735
+ self.block_stack
736
+ and entry
737
+ and self.block_stack[-1].target is entry.target
738
+ ):
739
+ if not entry:
740
+ # no longer in any block
741
+ # It is possible for NOPs to be between two instructions
742
+ # in the same block, but the NOPs are not covered by an
743
+ # exception table entry. In this case, assume that we
744
+ # are still in the same block.
745
+ if self.block_stack and inst.opname != "NOP":
746
+ # If we really escape from a block and the current
747
+ # instruction is not in another block, then there
748
+ # should be no other nested blocks that we are in.
749
+ assert len(self.block_stack) == 1
750
+ self.block_stack.pop()
751
+ elif (
752
+ # current instruction is in the previous block
753
+ len(self.block_stack) > 1
754
+ and self.block_stack[-2].target is entry.target
755
+ ):
756
+ # exit the current block
757
+ self.block_stack.pop()
758
+ else:
759
+ # current instruction is in a new block
760
+ # push block to stack - note, BEFORE_WITH blocks won't
761
+ # be pushed here since BEFORE_WITH pushes the block, and
762
+ # the current instruction would be counted as being in that block.
763
+ self.block_stack.append(
764
+ BlockStackEntry(entry.target, len(self.stack))
765
+ )
766
+
767
+ try:
768
+ if not hasattr(self, inst.opname):
769
+ unimplemented(f"missing: {inst.opname}")
770
+ TracingContext.set_current_loc(
771
+ self.f_code.co_filename, self.lineno, self.f_code.co_name
772
+ )
773
+ getattr(self, inst.opname)(inst)
774
+
775
+ return inst.opname != "RETURN_VALUE"
776
+ except Unsupported:
777
+ if self.current_speculation is None:
778
+ log.debug("empty checkpoint")
779
+ raise
780
+ log.debug("step triggered compile", exc_info=True)
781
+
782
+ self.current_speculation.fail_and_restart_analysis()
783
+
784
+ def step_graph_break(self, continue_inst):
785
+ # generate code from checkpoint
786
+ assert not self.output.output_instructions
787
+ assert self.current_speculation is not None
788
+ self.output.compile_subgraph(
789
+ self,
790
+ partial_convert=True,
791
+ reason=GraphCompileReason("step_unsupported", [self.frame_summary()]),
792
+ )
793
+ self.output.add_output_instructions(
794
+ [create_jump_absolute(continue_inst)] + self.instructions
795
+ )
796
+
797
+ def run_ctx_mgr(self):
798
+ # NB: Don't push the top level frame summary; set_current_loc will
799
+ # take care of it. However, DO make sure we attach real_stack to
800
+ # exceptions
801
+ return TracingContext.current_frame(None)
802
+
803
+ def run(self):
804
+ with self.run_ctx_mgr():
805
+ try:
806
+ self.output.push_tx(self)
807
+ while (
808
+ self.instruction_pointer is not None
809
+ and not self.output.should_exit
810
+ and self.step()
811
+ ):
812
+ pass
813
+ except BackendCompilerFailed:
814
+ raise
815
+ except Exception as e:
816
+ if config.replay_record_enabled:
817
+ e.exec_record = self.exec_recorder.get_record() # type: ignore[attr-defined]
818
+ raise
819
+ finally:
820
+ self.output.pop_tx()
821
+ # Cleanup the outputGraph to delete the held tensors. We perform the
822
+ # cleanup only for InstructionTranslator and not
823
+ # InliningInstructionTranslator. The InliningInstructionTranslator
824
+ # mutates the output object and is restored to original state if
825
+ # there was an exception.
826
+ if isinstance(self, InstructionTranslator):
827
+ self.output.cleanup()
828
+
829
+ def push(self, val: Optional[VariableTracker]):
830
+ assert val is None or isinstance(
831
+ val, VariableTracker
832
+ ), f"push expects VariableTracker, got {typestr(val)}"
833
+ self.stack.append(val) # type: ignore[arg-type]
834
+
835
+ def push_many(self, vals: List[VariableTracker]):
836
+ for val in vals:
837
+ self.push(val)
838
+
839
+ def pop(self) -> VariableTracker:
840
+ return self.stack.pop()
841
+
842
+ def popn(self, n: int) -> List[VariableTracker]:
843
+ assert n >= 0
844
+ return list(reversed([self.pop() for _ in range(n)]))
845
+
846
+ def LOAD_FAST(self, inst):
847
+ name = inst.argval
848
+ if name in self.f_locals and config.replay_record_enabled:
849
+ self.exec_recorder.add_local_var(name, self.f_locals[name])
850
+
851
+ if name.startswith(".") and name not in self.symbolic_locals:
852
+ # This happens in dict/list comprehensions
853
+ name = name.replace(".", "implicit")
854
+ assert name not in self.cell_and_freevars()
855
+ if name not in self.symbolic_locals:
856
+ unimplemented("undefined LOAD_FAST")
857
+ self.push(self.symbolic_locals[name])
858
+ if name.startswith("___stack"):
859
+ self.symbolic_locals.pop(name)
860
+
861
+ def LOAD_DEREF(self, inst):
862
+ assert inst.argval in self.cell_and_freevars()
863
+
864
+ if inst.argval in self.f_locals and config.replay_record_enabled:
865
+ self.exec_recorder.add_local_var(inst.argval, self.f_locals[inst.argval])
866
+
867
+ if inst.argval not in self.symbolic_locals:
868
+ unimplemented(f"undefined LOAD_DEREF {inst.argval}")
869
+ self.push(self.symbolic_locals[inst.argval])
870
+
871
+ def STORE_FAST(self, inst):
872
+ loaded_vt = self.pop()
873
+ name = inst.argval
874
+ # Only rename at the top-level scope, this is to avoid the confusion between
875
+ # mutating a variable vs renaming it (e.g. a = b) during speculating a higher order op,
876
+ # where mutation is prohibited and it's difficult to differentiate it with renaming.
877
+ if _is_top_level_scope(current_scope_id()):
878
+ loaded_vt = loaded_vt.rename(self, name)
879
+ self.symbolic_locals[name] = loaded_vt
880
+
881
+ def DELETE_FAST(self, inst):
882
+ del self.symbolic_locals[inst.argval]
883
+
884
+ STORE_DEREF = STORE_FAST
885
+
886
+ def LOAD_CLOSURE(self, inst):
887
+ self.push(ClosureVariable(name=inst.argval))
888
+
889
+ def LOAD_CONST(self, inst):
890
+ # For empty tuples, create empty TupleVariable
891
+ if isinstance(inst.argval, tuple) and not inst.argval:
892
+ self.push(TupleVariable([]))
893
+ else:
894
+ self.push(ConstantVariable.create(value=inst.argval))
895
+
896
+ def get_global_source(self, name):
897
+ source: Source
898
+ if self.output.global_scope is self.f_globals:
899
+ source = GlobalSource(name)
900
+ else:
901
+ if "__name__" in self.f_globals:
902
+ source = AttrSource(
903
+ self.import_source(self.f_globals["__name__"]), name
904
+ )
905
+ else:
906
+ mangled_name = self.output.install_global_by_id(
907
+ "___unnamed_scope", self.f_globals
908
+ )
909
+ source = GetItemSource(GlobalSource(mangled_name), name)
910
+ return source
911
+
912
+ def LOAD_GLOBAL(self, inst):
913
+ if sys.version_info >= (3, 11):
914
+ if inst.arg % 2:
915
+ self.PUSH_NULL(inst)
916
+
917
+ name = inst.argval
918
+
919
+ if config.replay_record_enabled:
920
+ if name in self.f_globals:
921
+ self.exec_recorder.add_global_var(name, self.f_globals[name])
922
+ else:
923
+ assert name in self.f_builtins
924
+ self.exec_recorder.builtins[name] = self.f_builtins[name]
925
+
926
+ if inst.argval == "AssertionError":
927
+ unimplemented("assert with non-string message")
928
+
929
+ if name in self.symbolic_globals:
930
+ variable = self.output.side_effects[self.symbolic_globals[name]]
931
+ self.push(self.output.side_effects.load_global(variable, name))
932
+ return
933
+
934
+ try:
935
+ value = self.f_globals[name]
936
+ except KeyError:
937
+ return self.load_builtin(inst)
938
+
939
+ source = self.get_global_source(name)
940
+ self.push(VariableBuilder(self, source)(value))
941
+
942
+ def STORE_GLOBAL(self, inst):
943
+ value = self.pop()
944
+ name = inst.argval
945
+ source = self.get_global_source(name)
946
+ if name not in self.symbolic_globals:
947
+ self.symbolic_globals[name] = object() # type: ignore[assignment] # sentinel object
948
+ variable = self.output.side_effects.track_global_existing(
949
+ source, self.symbolic_globals[name]
950
+ )
951
+ if isinstance(value, RemovableHandleVariable):
952
+ unimplemented("Storing handles in globals - NYI")
953
+ self.output.side_effects.store_global(variable, name, value)
954
+
955
+ def import_source(self, module_name):
956
+ """Create an alias to a module for use in guards"""
957
+ if "torch_package" in module_name:
958
+ value = torch.package.package_importer._package_imported_modules[
959
+ module_name
960
+ ]
961
+ alias = (
962
+ module_name.replace(">", "_").replace("<", "_").replace(".", "_dot_")
963
+ )
964
+ else:
965
+ value = importlib.import_module(module_name)
966
+ alias = f"__import_{module_name.replace('.', '_dot_')}"
967
+ f_globals = self.output.global_scope
968
+ assert alias not in f_globals or f_globals[alias] is value
969
+ f_globals[alias] = value
970
+ self.output.update_co_names(alias)
971
+ return GlobalSource(alias)
972
+
973
+ def resolve_name(self, name, package, level):
974
+ """
975
+ Copied from the Cpython implementation of __import__
976
+ Resolve a relative module name to an absolute one.
977
+ https://github.com/python/cpython/blob/5a094f0255eea1db58fb2cf14c200971e64ec36e/Lib/importlib/_bootstrap.py#L902
978
+ """
979
+ bits = package.rsplit(".", level - 1)
980
+ if len(bits) < level:
981
+ raise ImportError("attempted relative import beyond top-level package")
982
+ base = bits[0]
983
+ return f"{base}.{name}" if name else base
984
+
985
+ def calc_package(self):
986
+ """
987
+ Copied from the Cpython implementation of __import__
988
+ https://github.com/python/cpython/blob/5a094f0255eea1db58fb2cf14c200971e64ec36e/Lib/importlib/_bootstrap.py#L1090
989
+ """
990
+ package = self.f_globals.get("__package__")
991
+ spec = self.f_globals.get("__spec__")
992
+ if package is not None:
993
+ if spec is not None and package != spec.parent:
994
+ log.warning(
995
+ "__package__ != __spec__.parent (%r != %r)",
996
+ package,
997
+ spec.parent,
998
+ stacklevel=3,
999
+ )
1000
+ return package
1001
+ elif spec is not None:
1002
+ return spec.parent
1003
+ else:
1004
+ log.warning(
1005
+ "can't resolve package from __spec__ or __package__, "
1006
+ "falling back on __name__ and __path__",
1007
+ stacklevel=3,
1008
+ )
1009
+ package = self.f_globals["__name__"]
1010
+ if "__path__" not in self.f_globals:
1011
+ package = package.rpartition(".")[0]
1012
+ return package
1013
+
1014
+ def IMPORT_NAME(self, inst):
1015
+ level, fromlist = self.popn(2)
1016
+ level = level.as_python_constant()
1017
+ fromlist = fromlist.as_python_constant()
1018
+ module_name = inst.argval
1019
+
1020
+ # Are we replaying? if so, load recorded module
1021
+ recorded_name = (
1022
+ f"{ExecutionRecorder.LOCAL_MOD_PREFIX}_{level}_{fromlist}_{module_name}"
1023
+ )
1024
+ if recorded_name in self.f_globals:
1025
+ value = self.f_globals[recorded_name]
1026
+ source = GlobalSource(recorded_name)
1027
+ else:
1028
+ value = __import__(
1029
+ module_name,
1030
+ fromlist=fromlist,
1031
+ level=level,
1032
+ globals=self.f_globals,
1033
+ )
1034
+
1035
+ if level != 0:
1036
+ pkg = self.calc_package()
1037
+ module_name = self.resolve_name(module_name, pkg, level)
1038
+
1039
+ # For __import__, when the name variable is of the form package.module,
1040
+ # normally, the top-level package (the name up till the first dot) is
1041
+ # returned, not the module named by module_name. However, when a
1042
+ # non-empty fromlist argument is given, the module named by name is
1043
+ # returned. Therefore, we set the source correctly here.
1044
+ if not fromlist:
1045
+ top_level_module_name = module_name.partition(".")[0]
1046
+ source = self.import_source(top_level_module_name)
1047
+ else:
1048
+ source = self.import_source(module_name)
1049
+
1050
+ if config.replay_record_enabled:
1051
+ self.exec_recorder.add_local_mod(recorded_name, value)
1052
+
1053
+ if istype(value, (types.ModuleType, DummyModule)):
1054
+ self.push(PythonModuleVariable(value, source=source))
1055
+ else:
1056
+ unimplemented(f"IMPORT_NAME {typestr(value)}")
1057
+
1058
+ def IMPORT_FROM(self, inst):
1059
+ self.DUP_TOP(inst)
1060
+ self.LOAD_ATTR(inst)
1061
+
1062
+ def load_builtin(self, inst):
1063
+ if inst.argval not in self.f_builtins:
1064
+ raise NameError(f"name '{inst.argval}' is not defined")
1065
+ val = self.f_builtins[inst.argval]
1066
+
1067
+ if callable(val):
1068
+ self.push(VariableBuilder(self, GlobalSource(inst.argval))(val))
1069
+ else:
1070
+ assert is_builtin_constant(val)
1071
+ self.push(ConstantVariable.create(value=val))
1072
+
1073
+ def jump(self, inst):
1074
+ self.instruction_pointer = self.indexof[inst.target]
1075
+
1076
+ JUMP_FORWARD = jump
1077
+ JUMP_ABSOLUTE = jump
1078
+
1079
+ POP_JUMP_IF_FALSE = generic_jump(operator.not_, False)
1080
+ POP_JUMP_IF_TRUE = generic_jump(operator.truth, False)
1081
+ JUMP_IF_FALSE_OR_POP = generic_jump(operator.not_, True)
1082
+ JUMP_IF_TRUE_OR_POP = generic_jump(operator.truth, True)
1083
+
1084
+ def SETUP_LOOP(self, inst):
1085
+ # only exists in python<=3.7
1086
+ self.block_stack.append(BlockStackEntry(inst.target))
1087
+
1088
+ def SETUP_EXCEPT(self, inst):
1089
+ # only exists in python<=3.7
1090
+ self.block_stack.append(BlockStackEntry(inst.target))
1091
+
1092
+ def POP_BLOCK(self, inst):
1093
+ self.block_stack.pop()
1094
+
1095
+ def SETUP_WITH(self, inst):
1096
+ self.setup_or_before_with(inst)
1097
+
1098
+ def SETUP_FINALLY(self, inst):
1099
+ self.block_stack.append(BlockStackEntry(inst.target))
1100
+
1101
+ def BEGIN_FINALLY(self, inst):
1102
+ self.push(None)
1103
+
1104
+ def WITH_CLEANUP_START(self, inst):
1105
+ exit, exc = self.popn(2)
1106
+ assert exc is None
1107
+ self.push(exc)
1108
+ self.push(exit.call_function(self, [ConstantVariable.create(None)] * 3, {}))
1109
+
1110
+ def WITH_CLEANUP_FINISH(self, inst):
1111
+ self.popn(2)
1112
+ self.push(None)
1113
+
1114
+ def CALL_FINALLY(self, inst):
1115
+ """
1116
+ pushes the address of the next instruction onto the stack and increments
1117
+ bytecode counter by delta
1118
+ """
1119
+ # Python 3.8 only
1120
+ assert self.next_instruction is not None
1121
+ addr = self.indexof[self.next_instruction]
1122
+ self.push(ConstantVariable.create(addr))
1123
+ self.instruction_pointer = self.indexof[inst.target]
1124
+
1125
+ def END_FINALLY(self, inst):
1126
+ # Python 3.8 only
1127
+ # https://docs.python.org/3.8/library/dis.html#opcode-END_FINALLY
1128
+ tos = self.pop()
1129
+ if isinstance(tos, ConstantVariable):
1130
+ self.instruction_pointer = tos.as_python_constant()
1131
+ else:
1132
+ pass
1133
+
1134
+ def POP_FINALLY(self, inst):
1135
+ # Python 3.8 only
1136
+ preserve_tos = inst.argval
1137
+ if preserve_tos:
1138
+ tos = self.pop()
1139
+ _ = self.pop()
1140
+ if preserve_tos:
1141
+ self.push(tos) # type: ignore[possibly-undefined]
1142
+
1143
+ def FOR_ITER(self, inst):
1144
+ it = self.pop().realize()
1145
+ if isinstance(it, (variables.ListIteratorVariable, variables.IteratorVariable)):
1146
+ try:
1147
+ val, next_iter = it.next_variables(self)
1148
+ self.push(next_iter)
1149
+ self.push(val)
1150
+ except StopIteration:
1151
+ self.jump(inst)
1152
+ else:
1153
+ unimplemented(f"FOR_ITER {typestr(it)}")
1154
+
1155
+ def COMPARE_OP(self, inst):
1156
+ left, right = self.popn(2)
1157
+ op = inst.argval
1158
+ supported_any = dict(
1159
+ itertools.chain(
1160
+ supported_tensor_comparison_ops.items(),
1161
+ supported_const_comparison_ops.items(),
1162
+ )
1163
+ )
1164
+ if (
1165
+ isinstance(
1166
+ left,
1167
+ (
1168
+ TensorVariable,
1169
+ SymNodeVariable,
1170
+ NNModuleVariable,
1171
+ BaseListVariable,
1172
+ UserDefinedVariable,
1173
+ BaseUserFunctionVariable,
1174
+ ConstDictVariable,
1175
+ ),
1176
+ )
1177
+ and isinstance(right, ConstantVariable)
1178
+ and right.value is None
1179
+ and op in supported_const_comparison_ops
1180
+ ):
1181
+ # <non-None> is None
1182
+ self.push(
1183
+ ConstantVariable.create(
1184
+ supported_const_comparison_ops[op](object(), right.value)
1185
+ )
1186
+ )
1187
+
1188
+ elif (
1189
+ left.is_python_constant()
1190
+ and right.is_python_constant()
1191
+ and op in supported_any
1192
+ ):
1193
+ # constant fold
1194
+ self.push(
1195
+ ConstantVariable.create(
1196
+ supported_any[op](
1197
+ left.as_python_constant(), right.as_python_constant()
1198
+ ),
1199
+ )
1200
+ )
1201
+ elif op in ("in", "not in"):
1202
+ self.push(right.call_method(self, "__contains__", [left], {}))
1203
+ if op == "not in":
1204
+ self.UNARY_NOT(inst)
1205
+ else:
1206
+ self.push(
1207
+ BuiltinVariable(supported_any[op]).call_function(
1208
+ self, [left, right], {}
1209
+ )
1210
+ )
1211
+
1212
+ def GET_ITER(self, inst):
1213
+ self.call_function(BuiltinVariable(iter), [self.pop()], {})
1214
+
1215
+ @break_graph_if_unsupported(push=1)
1216
+ def CALL_FUNCTION(self, inst):
1217
+ args = self.popn(inst.argval)
1218
+ fn = self.pop()
1219
+ self.call_function(fn, args, {})
1220
+
1221
+ @break_graph_if_unsupported(push=1)
1222
+ def CALL_FUNCTION_EX(self, inst):
1223
+ kwargsvars: VariableTracker
1224
+ if inst.argval == 0:
1225
+ kwargsvars = ConstDictVariable({})
1226
+ argsvars = self.pop()
1227
+ elif inst.argval == 1:
1228
+ kwargsvars = self.pop()
1229
+ argsvars = self.pop()
1230
+ else:
1231
+ unimplemented("CALL_FUNCTION_EX")
1232
+ fn = self.pop()
1233
+ if sys.version_info >= (3, 11):
1234
+ null = self.pop()
1235
+ assert isinstance(null, NullVariable)
1236
+
1237
+ if (
1238
+ isinstance(fn, GetAttrVariable)
1239
+ and isinstance(fn.obj, TensorVariable)
1240
+ and fn.name == "view"
1241
+ and isinstance(argsvars, (ConstantVariable, TensorVariable))
1242
+ ):
1243
+ # Hack to handle special case in some bert models. Converts
1244
+ # x.view(*shape) into x.view(shape), which is correct for view()
1245
+ # but not generally. See test_transpose_for_scores().
1246
+ argsvars = TupleVariable([argsvars])
1247
+
1248
+ if not isinstance(
1249
+ argsvars, BaseListVariable
1250
+ ) and argsvars.has_unpack_var_sequence(self):
1251
+ argsvars = TupleVariable(argsvars.unpack_var_sequence(self))
1252
+
1253
+ if not isinstance(argsvars, BaseListVariable) or not isinstance(
1254
+ kwargsvars, ConstDictVariable
1255
+ ):
1256
+ unimplemented(f"non-static call {typestr(argsvars)} {typestr(kwargsvars)}")
1257
+
1258
+ # Map to a dictionary of str -> VariableTracker
1259
+ kwargsvars = kwargsvars.keys_as_python_constant()
1260
+ self.call_function(fn, argsvars.items, kwargsvars)
1261
+
1262
+ @break_graph_if_unsupported(push=1)
1263
+ def CALL_FUNCTION_KW(self, inst):
1264
+ argnames = self.pop()
1265
+ args = self.popn(inst.argval)
1266
+ fn = self.pop()
1267
+ assert isinstance(argnames, TupleVariable) and argnames.is_python_constant()
1268
+ argnames = argnames.as_python_constant()
1269
+ args, kwargs_list = args[: -len(argnames)], args[-len(argnames) :]
1270
+ kwargs = dict(zip(argnames, kwargs_list))
1271
+ assert len(kwargs) == len(argnames)
1272
+ self.call_function(fn, args, kwargs)
1273
+
1274
+ def LOAD_METHOD_SUPER(self, inst):
1275
+ self.CALL_FUNCTION(dataclasses.replace(inst, argval=2))
1276
+ arg = inst.argval[0]
1277
+ argval = self.code_options["co_names"][arg]
1278
+ if sys.version_info < (3, 11):
1279
+ self.LOAD_ATTR(dataclasses.replace(inst, argval=argval))
1280
+ else:
1281
+ self.LOAD_METHOD(dataclasses.replace(inst, argval=argval))
1282
+
1283
+ def LOAD_ATTR_SUPER(self, inst):
1284
+ self.CALL_FUNCTION(dataclasses.replace(inst, argval=2))
1285
+ arg = inst.argval[0]
1286
+ argval = self.code_options["co_names"][arg]
1287
+ self.LOAD_ATTR(dataclasses.replace(inst, argval=argval))
1288
+
1289
+ def LOAD_METHOD(self, inst):
1290
+ self.LOAD_ATTR(inst)
1291
+ obj = self.pop()
1292
+ if sys.version_info >= (3, 11):
1293
+ # always follow the NULL + fn convention, since if obj
1294
+ # is actually a method, self is already bound to it, so it
1295
+ # doesn't need to be passed in as an arg.
1296
+ self.PUSH_NULL(inst)
1297
+ self.push(obj)
1298
+ else:
1299
+ self.push(obj)
1300
+ self.push(None)
1301
+
1302
+ def CALL_METHOD(self, inst):
1303
+ args = self.popn(inst.argval)
1304
+ dummy = self.pop()
1305
+ assert dummy is None
1306
+ fn = self.pop()
1307
+ self.call_function(fn, args, {})
1308
+
1309
+ def LOAD_ATTR(self, inst):
1310
+ obj = self.pop()
1311
+ result = BuiltinVariable(getattr).call_function(
1312
+ self, [obj, ConstantVariable.create(inst.argval)], {}
1313
+ )
1314
+ self.push(result)
1315
+
1316
+ def STORE_ATTR(self, inst):
1317
+ speculation = self.speculate()
1318
+ if speculation.failed:
1319
+ return self.store_attr_graph_break(inst)
1320
+ val, obj = self.popn(2)
1321
+
1322
+ if isinstance(obj, NNModuleVariable):
1323
+ # We don't allow side effects during export
1324
+ # https://github.com/pytorch/torchdynamo/issues/1475
1325
+ assert (
1326
+ not self.export
1327
+ ), f"Mutating module attribute {inst.argval} during export."
1328
+
1329
+ try:
1330
+ BuiltinVariable(setattr).call_function(
1331
+ self, [obj, ConstantVariable.create(inst.argval), val], {}
1332
+ )
1333
+ return
1334
+ except Unsupported as e:
1335
+ if not self.should_compile_partial_graph():
1336
+ raise
1337
+ log.debug("STORE_ATTR triggered compile", exc_info=True)
1338
+ e.remove_from_stats()
1339
+ e.add_to_stats("graph_break")
1340
+ speculation.fail_and_restart_analysis()
1341
+
1342
+ def store_attr_graph_break(self, inst):
1343
+ self.output.compile_subgraph(
1344
+ self, reason=GraphCompileReason("store_attr", [self.frame_summary()])
1345
+ )
1346
+ self.output.add_output_instructions([copy.copy(inst)])
1347
+ self.popn(2)
1348
+ self.output.add_output_instructions(
1349
+ self.create_call_resume_at(self.next_instruction)
1350
+ )
1351
+
1352
+ def DELETE_ATTR(self, inst):
1353
+ obj = self.pop()
1354
+ BuiltinVariable(delattr).call_function(
1355
+ self, [obj, ConstantVariable.create(inst.argval)], {}
1356
+ )
1357
+
1358
+ def create_call_resume_at(self, offset):
1359
+ raise AssertionError(
1360
+ f"create_call_resume_at not overridden by subclass {type(self)}"
1361
+ )
1362
+
1363
+ def should_compile_partial_graph(self) -> bool:
1364
+ raise AssertionError(
1365
+ f"should_compile_partial_graph not overridden by subclass {type(self)}"
1366
+ )
1367
+
1368
+ @break_graph_if_unsupported(push=0)
1369
+ def STORE_SUBSCR(self, inst):
1370
+ val, obj, key = self.popn(3)
1371
+ result = obj.call_method(self, "__setitem__", [key, val], {})
1372
+
1373
+ def BUILD_TUPLE(self, inst):
1374
+ items = self.popn(inst.argval)
1375
+ self.push(TupleVariable(items))
1376
+
1377
+ def BUILD_SLICE(self, inst):
1378
+ items = self.popn(inst.argval)
1379
+ self.push(SliceVariable(items))
1380
+
1381
+ def BUILD_LIST(self, inst):
1382
+ items = self.popn(inst.argval)
1383
+ self.push(ListVariable(items, mutable_local=MutableLocal()))
1384
+
1385
+ def BUILD_SET(self, inst):
1386
+ if config.inject_BUILD_SET_unimplemented_TESTING_ONLY:
1387
+ unimplemented("missing: BUILD_SET")
1388
+ items = self.popn(inst.argval)
1389
+ new_set = SetVariable(items, mutable_local=MutableLocal())
1390
+ self.push(new_set)
1391
+
1392
+ def BUILD_LIST_UNPACK(self, inst, cls=ListVariable):
1393
+ seqs = self.popn(inst.argval)
1394
+ items = list()
1395
+ for seq in seqs:
1396
+ try:
1397
+ items.extend(seq.unpack_var_sequence(self))
1398
+ except NotImplementedError:
1399
+ unimplemented(f"BUILD_LIST_UNPACK {seq}")
1400
+ self.push(cls(items, mutable_local=MutableLocal()))
1401
+
1402
+ def BUILD_TUPLE_UNPACK(self, inst):
1403
+ self.BUILD_LIST_UNPACK(inst, cls=TupleVariable)
1404
+
1405
+ BUILD_TUPLE_UNPACK_WITH_CALL = BUILD_TUPLE_UNPACK
1406
+
1407
+ def BUILD_MAP(self, inst):
1408
+ items = self.popn(inst.argval * 2)
1409
+ d = dict(zip(items[::2], items[1::2]))
1410
+ self.push(ConstDictVariable(d, mutable_local=MutableLocal()))
1411
+
1412
+ def BUILD_MAP_UNPACK(self, inst):
1413
+ items = self.popn(inst.argval)
1414
+ # ensure everything is a dict
1415
+ items = [BuiltinVariable(dict).call_function(self, [x], {}) for x in items]
1416
+ result = dict()
1417
+ for x in items:
1418
+ assert isinstance(x, ConstDictVariable)
1419
+ result.update(x.items)
1420
+ self.push(
1421
+ ConstDictVariable(
1422
+ result,
1423
+ mutable_local=MutableLocal(),
1424
+ )
1425
+ )
1426
+
1427
+ BUILD_MAP_UNPACK_WITH_CALL = BUILD_MAP_UNPACK
1428
+
1429
+ def BUILD_CONST_KEY_MAP(self, inst):
1430
+ keys = self.pop()
1431
+ values = self.popn(inst.argval)
1432
+ assert isinstance(keys, TupleVariable)
1433
+ assert keys.is_python_constant()
1434
+
1435
+ keys = keys.unpack_var_sequence(self)
1436
+ assert len(keys) == len(values)
1437
+
1438
+ self.push(
1439
+ ConstDictVariable(
1440
+ dict(zip(keys, values)),
1441
+ mutable_local=MutableLocal(),
1442
+ )
1443
+ )
1444
+
1445
+ def MAP_ADD(self, inst):
1446
+ k, v = self.popn(2)
1447
+ assert inst.argval > 0
1448
+ obj = self.stack[-inst.arg].realize()
1449
+ assert isinstance(obj, ConstDictVariable)
1450
+ obj.call_method(self, "__setitem__", (k, v), {}) # type: ignore[arg-type]
1451
+
1452
+ def SET_ADD(self, inst):
1453
+ v = self.pop()
1454
+ assert inst.argval > 0
1455
+ obj = self.stack[-inst.arg]
1456
+ assert isinstance(obj, SetVariable)
1457
+ assert obj.mutable_local
1458
+ return obj.call_method(self, "add", [v], {})
1459
+
1460
+ def LIST_APPEND(self, inst):
1461
+ v = self.pop()
1462
+ assert inst.argval > 0
1463
+ obj = self.stack[-inst.arg].realize()
1464
+ assert isinstance(obj, ListVariable)
1465
+ assert obj.mutable_local
1466
+ self.output.side_effects.mutation(obj)
1467
+ obj.items.append(v)
1468
+
1469
+ def MAKE_FUNCTION(self, inst):
1470
+ flags = inst.arg
1471
+ old_stack = list(self.stack)
1472
+ if sys.version_info < (3, 11):
1473
+ fn_name = self.pop()
1474
+ code = self.pop()
1475
+ if sys.version_info >= (3, 11):
1476
+ # MAKE_FUNCTION behavior actually changed in 3.11, see
1477
+ # https://github.com/python/cpython/pull/93189/
1478
+ assert hasattr(code.value, "co_qualname") # type: ignore[attr-defined]
1479
+ fn_name = ConstantVariable.create(value=code.value.co_qualname) # type: ignore[attr-defined]
1480
+ defaults = None
1481
+ closure = None
1482
+ annotations = None
1483
+ kwdefaults = None
1484
+
1485
+ if flags & 0x08:
1486
+ closure = self.pop()
1487
+ if flags & 0x04:
1488
+ annotations = self.pop()
1489
+ if flags & 0x02:
1490
+ kwdefaults = self.pop()
1491
+ if flags & 0x01:
1492
+ defaults = self.pop()
1493
+
1494
+ self.push(
1495
+ NestedUserFunctionVariable(
1496
+ fn_name,
1497
+ code,
1498
+ self.f_globals,
1499
+ defaults,
1500
+ kwdefaults,
1501
+ annotations,
1502
+ closure,
1503
+ closure_scope=self,
1504
+ )
1505
+ )
1506
+
1507
+ def UNPACK_SEQUENCE(self, inst):
1508
+ seq = self.pop()
1509
+ if isinstance(seq, TensorVariable):
1510
+ val = seq.unpack_var_sequence(self, idxes=range(inst.argval))
1511
+ elif isinstance(seq, GetAttrVariable) and isinstance(seq.obj, TensorVariable):
1512
+ # x, y = a.shape
1513
+ proxy = getattr(seq.obj.as_proxy(), seq.name)
1514
+ val = [wrap_fx_proxy(self, proxy[i]) for i in range(inst.argval)]
1515
+ elif seq.has_unpack_var_sequence(self):
1516
+ val = seq.unpack_var_sequence(self)
1517
+ else:
1518
+ unimplemented(f"UNPACK_SEQUENCE {seq}")
1519
+ if len(val) != inst.argval:
1520
+ unimplemented("UNPACK_SEQUENCE length mismatch")
1521
+ for i in reversed(val):
1522
+ self.push(i)
1523
+
1524
+ def UNPACK_EX(self, inst):
1525
+ assert 0 <= inst.argval <= 0xFFFF
1526
+ prefix = inst.argval & 0xFF # low byte
1527
+ suffix = inst.argval >> 8 # high byte
1528
+ seq = self.pop()
1529
+ if seq.has_unpack_var_sequence(self):
1530
+ vals = list(seq.unpack_var_sequence(self))
1531
+ assert len(vals) >= prefix + suffix
1532
+ vals_prefix = vals[:prefix]
1533
+ vals_list = vals[prefix : len(vals) - suffix]
1534
+ vals_suffix = vals[len(vals) - suffix :]
1535
+ for item in reversed(vals_suffix):
1536
+ self.push(item)
1537
+ self.push(TupleVariable(vals_list))
1538
+ for item in reversed(vals_prefix):
1539
+ self.push(item)
1540
+ else:
1541
+ unimplemented(f"UNPACK_EX {seq}")
1542
+
1543
+ def NOP(self, inst):
1544
+ pass
1545
+
1546
+ def POP_TOP(self, inst):
1547
+ self.pop()
1548
+
1549
+ def ROT_TWO(self, inst):
1550
+ a = self.pop()
1551
+ b = self.pop()
1552
+ self.push(a)
1553
+ self.push(b)
1554
+
1555
+ def ROT_THREE(self, inst):
1556
+ a = self.pop()
1557
+ b = self.pop()
1558
+ c = self.pop()
1559
+ self.push(a)
1560
+ self.push(c)
1561
+ self.push(b)
1562
+
1563
+ def ROT_FOUR(self, inst):
1564
+ a = self.pop()
1565
+ b = self.pop()
1566
+ c = self.pop()
1567
+ d = self.pop()
1568
+ self.push(a)
1569
+ self.push(d)
1570
+ self.push(c)
1571
+ self.push(b)
1572
+
1573
+ def DUP_TOP(self, inst):
1574
+ a = self.pop()
1575
+ self.push(a)
1576
+ self.push(a)
1577
+
1578
+ def DUP_TOP_TWO(self, inst):
1579
+ a = self.pop()
1580
+ b = self.pop()
1581
+ self.push(b)
1582
+ self.push(a)
1583
+ self.push(b)
1584
+ self.push(a)
1585
+
1586
+ def FORMAT_VALUE(self, inst):
1587
+ flags = inst.arg
1588
+ if (flags & 0x04) == 0x04:
1589
+ fmt_spec = self.pop()
1590
+ else:
1591
+ fmt_spec = ConstantVariable.create("")
1592
+
1593
+ value = self.pop()
1594
+ if isinstance(value, SymNodeVariable):
1595
+ value = ConstantVariable.create(str(value.sym_num))
1596
+ if (flags & 0x03) == 0x01:
1597
+ value = BuiltinVariable(str).call_function(self, [value], {})
1598
+ elif (flags & 0x03) == 0x02:
1599
+ value = BuiltinVariable(repr).call_function(self, [value], {})
1600
+ elif (flags & 0x03) == 0x03:
1601
+ value = BuiltinVariable(ascii).call_function(self, [value], {})
1602
+
1603
+ fmt_var = ConstantVariable.create("{:" + fmt_spec.as_python_constant() + "}")
1604
+
1605
+ self.call_function(BuiltinVariable(str.format), [fmt_var, value], {})
1606
+
1607
+ def BUILD_STRING(self, inst):
1608
+ format_string_parts: List[str] = []
1609
+ args: List[VariableTracker] = []
1610
+ kwargs: Dict[str, VariableTracker] = {}
1611
+ for part in self.popn(inst.arg):
1612
+ if isinstance(part, ConstantVariable):
1613
+ format_string_parts.append("{}")
1614
+ args.append(part)
1615
+ elif isinstance(part, variables.StringFormatVariable):
1616
+ format_string_parts.append(part.format_string)
1617
+ args.extend(part.sym_args)
1618
+ if set(kwargs.keys()) & set(part.sym_kwargs.keys()):
1619
+ unimplemented(
1620
+ f"BUILD_STRING key conflict {kwargs} & {part.sym_kwargs}"
1621
+ )
1622
+ kwargs.update(part.sym_kwargs)
1623
+ else:
1624
+ unimplemented(f"BUILD_STRING {part}")
1625
+ self.push(
1626
+ variables.StringFormatVariable.create(
1627
+ "".join(format_string_parts), args, kwargs
1628
+ )
1629
+ )
1630
+
1631
+ def IS_OP(self, inst):
1632
+ assert inst.argval == 0 or inst.argval == 1
1633
+ if inst.argval == 0:
1634
+ new_argval = "is"
1635
+ else:
1636
+ new_argval = "is not"
1637
+ new_inst = create_instruction("COMPARE_OP", argval=new_argval)
1638
+ self.COMPARE_OP(new_inst)
1639
+
1640
+ def CONTAINS_OP(self, inst):
1641
+ assert inst.argval == 0 or inst.argval == 1
1642
+ left, right = self.popn(2)
1643
+ op = inst.argval
1644
+ self.push(right.call_method(self, "__contains__", [left], {}))
1645
+ if op == 1:
1646
+ self.UNARY_NOT(inst)
1647
+
1648
+ def LIST_EXTEND(self, inst):
1649
+ v = self.pop()
1650
+ assert inst.argval > 0
1651
+ obj = self.stack[-inst.arg]
1652
+ assert isinstance(obj, ListVariable)
1653
+ assert obj.mutable_local
1654
+ obj.call_method(self, "extend", [v], {})
1655
+
1656
+ def LIST_TO_TUPLE(self, inst):
1657
+ self.push(BuiltinVariable(tuple).call_function(self, [self.pop()], {}))
1658
+
1659
+ def DICT_MERGE(self, inst):
1660
+ v = self.pop()
1661
+ assert inst.argval > 0
1662
+ obj = self.stack[-inst.arg].realize()
1663
+ assert isinstance(obj, ConstDictVariable)
1664
+ assert obj.mutable_local
1665
+ obj.call_method(self, "update", [v], {})
1666
+
1667
+ DICT_UPDATE = DICT_MERGE
1668
+
1669
+ def GEN_START(self, inst):
1670
+ self.pop()
1671
+
1672
+ def GET_LEN(self, inst):
1673
+ tos = self.stack[-1]
1674
+ if tos.is_python_constant():
1675
+ self.push(ConstantVariable.create(len(tos.as_python_constant())))
1676
+ else:
1677
+ self.push(tos.call_method(self, "__len__", [], {}))
1678
+
1679
+ def MATCH_MAPPING(self, inst):
1680
+ tos = self.stack[-1]
1681
+ assert isinstance(tos, ConstDictVariable)
1682
+ if isinstance(tos.items, collections.abc.Mapping):
1683
+ self.push(ConstantVariable.create(True))
1684
+ else:
1685
+ self.push(ConstantVariable.create(False))
1686
+
1687
+ def MATCH_SEQUENCE(self, inst):
1688
+ tos = self.stack[-1]
1689
+ assert tos.is_python_constant()
1690
+ tos_value = tos.as_python_constant()
1691
+ if isinstance(tos_value, collections.abc.Sequence) and not isinstance(
1692
+ tos_value, (str, bytes, bytearray)
1693
+ ):
1694
+ self.push(ConstantVariable.create(True))
1695
+ else:
1696
+ self.push(ConstantVariable.create(False))
1697
+
1698
+ def MATCH_KEYS(self, inst):
1699
+ tos = self.stack[-1]
1700
+ tos1 = self.stack[-2]
1701
+ assert isinstance(tos1, ConstDictVariable)
1702
+
1703
+ if all(k in tos1 for k in tos): # type: ignore[attr-defined]
1704
+ self.push(TupleVariable([tos1.getitem_const(k) for k in tos])) # type: ignore[attr-defined]
1705
+ if sys.version_info < (3, 11):
1706
+ self.push(ConstantVariable.create(True))
1707
+ else:
1708
+ self.push(ConstantVariable.create(None))
1709
+ if sys.version_info < (3, 11):
1710
+ self.push(ConstantVariable.create(False))
1711
+
1712
+ def LOAD_ASSERTION_ERROR(self, inst):
1713
+ unimplemented("assert with non-string message")
1714
+
1715
+ UNARY_POSITIVE = stack_op(operator.pos)
1716
+ UNARY_NEGATIVE = stack_op(operator.neg)
1717
+ UNARY_NOT = stack_op(operator.not_)
1718
+ UNARY_INVERT = stack_op(operator.invert)
1719
+
1720
+ BINARY_POWER = stack_op(operator.pow)
1721
+ BINARY_MULTIPLY = stack_op(operator.mul)
1722
+ BINARY_MATRIX_MULTIPLY = stack_op(operator.matmul)
1723
+ BINARY_FLOOR_DIVIDE = stack_op(operator.floordiv)
1724
+ BINARY_TRUE_DIVIDE = stack_op(operator.truediv)
1725
+ BINARY_MODULO = stack_op(operator.mod)
1726
+ BINARY_REMAINDER = stack_op(operator.mod)
1727
+ BINARY_ADD = stack_op(operator.add)
1728
+ BINARY_SUBTRACT = stack_op(operator.sub)
1729
+ BINARY_SUBSCR = break_graph_if_unsupported(push=1)(stack_op(operator.getitem))
1730
+ BINARY_LSHIFT = stack_op(operator.lshift)
1731
+ BINARY_RSHIFT = stack_op(operator.rshift)
1732
+ BINARY_AND = stack_op(operator.and_)
1733
+ BINARY_OR = stack_op(operator.or_)
1734
+ BINARY_XOR = stack_op(operator.xor)
1735
+
1736
+ INPLACE_POWER = stack_op(operator.ipow)
1737
+ INPLACE_MULTIPLY = stack_op(operator.imul)
1738
+ INPLACE_MATRIX_MULTIPLY = stack_op(operator.imatmul)
1739
+ INPLACE_FLOOR_DIVIDE = stack_op(operator.ifloordiv)
1740
+ INPLACE_TRUE_DIVIDE = stack_op(operator.itruediv)
1741
+ INPLACE_MODULO = stack_op(operator.imod)
1742
+ INPLACE_REMAINDER = stack_op(operator.imod)
1743
+ INPLACE_ADD = stack_op(operator.iadd)
1744
+ INPLACE_SUBTRACT = stack_op(operator.isub)
1745
+ INPLACE_LSHIFT = stack_op(operator.ilshift)
1746
+ INPLACE_RSHIFT = stack_op(operator.irshift)
1747
+ INPLACE_AND = stack_op(operator.iand)
1748
+ INPLACE_XOR = stack_op(operator.ixor)
1749
+ INPLACE_OR = stack_op(operator.ior)
1750
+
1751
+ # 3.11 opcodes
1752
+ def RESUME(self, inst):
1753
+ if inst.arg == 0:
1754
+ self.append_prefix_inst(inst)
1755
+ self.accept_prefix_inst = False
1756
+ else:
1757
+ assert not self.accept_prefix_inst
1758
+
1759
+ def BINARY_OP(self, inst):
1760
+ if sys.version_info >= (3, 11):
1761
+ opname = dis._nb_ops[inst.arg][0][3:] # type: ignore[attr-defined]
1762
+ if opname.startswith("INPLACE"):
1763
+ return getattr(self, "INPLACE_" + opname[8:])(inst)
1764
+ return getattr(self, "BINARY_" + opname)(inst)
1765
+ else:
1766
+ unimplemented("BINARY_OP requires Python 3.11+")
1767
+
1768
+ def PRECALL(self, inst):
1769
+ pass
1770
+
1771
+ def KW_NAMES(self, inst):
1772
+ kw_names = self.code_options["co_consts"][inst.arg]
1773
+ assert isinstance(kw_names, tuple)
1774
+ for name in kw_names:
1775
+ assert isinstance(name, str)
1776
+ assert self.kw_names is None
1777
+ self.kw_names = ConstantVariable.create(value=kw_names) # type: ignore[assignment]
1778
+
1779
+ def PUSH_NULL(self, inst):
1780
+ self.push(NullVariable())
1781
+
1782
+ @break_graph_if_unsupported(push=1)
1783
+ def CALL(self, inst):
1784
+ # see https://docs.python.org/3.11/library/dis.html#opcode-CALL
1785
+ # for convention
1786
+ contents = self.popn(inst.arg + 2)
1787
+ if isinstance(contents[0], NullVariable):
1788
+ fn = contents[1]
1789
+ args = []
1790
+ else:
1791
+ fn = contents[0]
1792
+ args = [contents[1]]
1793
+ kw_names = self.kw_names.value if self.kw_names else ()
1794
+ if kw_names:
1795
+ args = args + contents[2 : -len(kw_names)]
1796
+ kwargs_list = contents[-len(kw_names) :]
1797
+ kwargs = dict(zip(kw_names, kwargs_list))
1798
+ assert len(kwargs) == len(kw_names)
1799
+ else:
1800
+ args = args + contents[2:]
1801
+ kwargs = {}
1802
+ self.call_function(fn, args, kwargs)
1803
+ self.kw_names = None
1804
+
1805
+ def COPY(self, inst):
1806
+ self.push(self.stack[-inst.arg])
1807
+
1808
+ def SWAP(self, inst):
1809
+ self.stack[-1], self.stack[-inst.arg] = self.stack[-inst.arg], self.stack[-1]
1810
+
1811
+ JUMP_BACKWARD = jump
1812
+ JUMP_BACKWARD_NO_INTERRUPT = jump
1813
+
1814
+ POP_JUMP_FORWARD_IF_TRUE = generic_jump(operator.truth, False)
1815
+ POP_JUMP_BACKWARD_IF_TRUE = generic_jump(operator.truth, False)
1816
+ POP_JUMP_FORWARD_IF_FALSE = generic_jump(operator.not_, False)
1817
+ POP_JUMP_BACKWARD_IF_FALSE = generic_jump(operator.not_, False)
1818
+
1819
+ def CACHE(self, inst):
1820
+ pass
1821
+
1822
+ def BEFORE_WITH(self, inst):
1823
+ self.setup_or_before_with(inst)
1824
+
1825
+ def setup_or_before_with(self, inst):
1826
+ ctx = self.pop()
1827
+ if not isinstance(ctx, ContextWrappingVariable):
1828
+ unimplemented(f"{inst.opname} {ctx}")
1829
+
1830
+ if isinstance(ctx, GenericContextWrappingVariable):
1831
+ self.generic_context_manager_depth += 1
1832
+
1833
+ exit = WithExitFunctionVariable(
1834
+ ctx,
1835
+ inst.target,
1836
+ )
1837
+ if sys.version_info >= (3, 11):
1838
+ # see create_call_resume_at for block stack details
1839
+ assert self.next_instruction
1840
+ assert self.next_instruction.exn_tab_entry
1841
+ target = self.next_instruction.exn_tab_entry.target
1842
+ else:
1843
+ target = inst.target
1844
+ if isinstance(self, InstructionTranslator):
1845
+ self.block_stack.append(BlockStackEntry(target, len(self.stack), ctx))
1846
+ else:
1847
+ self.block_stack.append(BlockStackEntry(target))
1848
+
1849
+ self.push(exit)
1850
+ self.push(ctx.enter(self))
1851
+
1852
+ def append_prefix_inst(self, inst):
1853
+ assert self.accept_prefix_inst
1854
+ self.prefix_insts.append(inst)
1855
+
1856
+ def MAKE_CELL(self, inst):
1857
+ self.append_prefix_inst(inst)
1858
+
1859
+ def COPY_FREE_VARS(self, inst):
1860
+ self.append_prefix_inst(inst)
1861
+
1862
+ def RETURN_GENERATOR(self, inst):
1863
+ self.append_prefix_inst(inst)
1864
+
1865
+ def copy_graphstate(self) -> InstructionTranslatorGraphState:
1866
+ """Create a checkpoint of the current state by copying everything"""
1867
+ return InstructionTranslatorGraphState(
1868
+ self.output.copy_graphstate(),
1869
+ dict(self.symbolic_locals),
1870
+ list(self.stack),
1871
+ list(self.block_stack),
1872
+ self.instruction_pointer,
1873
+ self.current_instruction,
1874
+ self.next_instruction,
1875
+ self.lineno,
1876
+ )
1877
+
1878
+ def restore_graphstate(self, state: InstructionTranslatorGraphState):
1879
+ """Restore a checkpoint created by self.copy_graphstate()"""
1880
+ (
1881
+ output_state,
1882
+ self.symbolic_locals,
1883
+ self.stack,
1884
+ self.block_stack,
1885
+ self.instruction_pointer,
1886
+ self.current_instruction,
1887
+ self.next_instruction,
1888
+ self.lineno,
1889
+ ) = state
1890
+ self.output.restore_graphstate(output_state)
1891
+
1892
+ def is_non_empty_graph(self):
1893
+ if self.output.count_calls() > 1:
1894
+ # perf optimization only
1895
+ self.is_non_empty_graph = lambda: True # type: ignore[method-assign]
1896
+ return True
1897
+ return False
1898
+
1899
+ def format_frame_summary(self, additional_stack_frames=None):
1900
+ if additional_stack_frames is None:
1901
+ additional_stack_frames = []
1902
+ return "".join(
1903
+ traceback.format_list(
1904
+ [self.frame_summary()] + list(reversed(additional_stack_frames))
1905
+ )
1906
+ )
1907
+
1908
+ def frame_summary(self):
1909
+ return traceback.FrameSummary(
1910
+ getattr(self.f_code, "co_filename", "<unknown>"),
1911
+ self.lineno,
1912
+ getattr(self.f_code, "co_name", "<unknown>"),
1913
+ lookup_line=False,
1914
+ )
1915
+
1916
+ def store_global_weakref_by_id(self, prefix, value):
1917
+ global_name = self.output.install_global_by_id(prefix, weakref.ref(value))
1918
+ install_guard(
1919
+ GlobalWeakRefSource(global_name).make_guard(GuardBuilder.WEAKREF_ALIVE)
1920
+ )
1921
+ return global_name
1922
+
1923
+ @property
1924
+ def fake_mode(self):
1925
+ return self.output.tracing_context.fake_mode
1926
+
1927
+ def find_symbolic_locals_name(self, tensor_variable):
1928
+ for key, value in self.symbolic_locals.items():
1929
+ if value is tensor_variable:
1930
+ return key
1931
+ return None
1932
+
1933
+ @contextlib.contextmanager
1934
+ def strict_translation_mode(self):
1935
+ self.strict_checks_enabled = True
1936
+ try:
1937
+ yield
1938
+ finally:
1939
+ self.strict_checks_enabled = False
1940
+
1941
+ def speculate(self) -> SpeculationEntry:
1942
+ return self.speculation_log.next(
1943
+ self.f_code.co_filename, self.lineno, self.instruction_pointer
1944
+ )
1945
+
1946
+ def __init__(
1947
+ self,
1948
+ output: OutputGraph,
1949
+ instructions: List[Instruction],
1950
+ f_locals: Dict[str, Any],
1951
+ f_globals: Dict[str, Any],
1952
+ f_builtins: Dict[str, Any],
1953
+ code_options: Dict[str, Any],
1954
+ symbolic_locals: Dict[str, VariableTracker],
1955
+ symbolic_globals: Dict[str, VariableTracker],
1956
+ f_code: types.CodeType,
1957
+ export: bool,
1958
+ inline_depth: int,
1959
+ speculation_log: SpeculationLog,
1960
+ ):
1961
+ super().__init__()
1962
+ self.speculation_log = speculation_log
1963
+
1964
+ # Mutable state checkpointed by copy_graphstate()
1965
+ self.output = output
1966
+ self.symbolic_locals = symbolic_locals
1967
+ self.symbolic_globals = symbolic_globals
1968
+ self.stack = []
1969
+ self.instruction_pointer = 0
1970
+ self.current_instruction = create_instruction("NOP")
1971
+ self.next_instruction = None
1972
+ self.block_stack = []
1973
+ # states before SETUP_WITH for checkpointing and fallback
1974
+ self.generic_context_manager_depth = 0
1975
+ self.lineno = code_options["co_firstlineno"]
1976
+ self.kw_names = None
1977
+ self.accept_prefix_inst = True
1978
+ self.prefix_insts = []
1979
+
1980
+ # Properties of the input/output code
1981
+ self.instructions: List[Instruction] = instructions
1982
+ self.indexof: Dict[Instruction, int] = get_indexof(self.instructions)
1983
+ self.f_locals: Dict[
1984
+ str, Any
1985
+ ] = f_locals # needed for recording accessed locals for replay
1986
+ self.f_globals: Dict[str, Any] = f_globals
1987
+ self.f_builtins: Dict[str, Any] = f_builtins
1988
+ self.code_options: Dict[str, Any] = code_options
1989
+ self.f_code: types.CodeType = f_code
1990
+
1991
+ # Execution record for replaying errors
1992
+ self.exec_recorder = ExecutionRecorder(code=f_code, code_options=code_options)
1993
+ # Stack of module being parsed, current nn.module is at the end of ordered dict.
1994
+ # The first field of tuple is the fully qualified name of current module
1995
+ # in original hierarchy. The second field is the type of current nn.module
1996
+ self.nn_module_stack: Dict[str, Tuple[str, Type[Any]]] = {}
1997
+ # Flag to indicate whether tracing is used for export.
1998
+ self.export = export
1999
+
2000
+ self.current_speculation = None
2001
+
2002
+ self.strict_checks_enabled = False
2003
+
2004
+ if sys.version_info >= (3, 10):
2005
+ from .resume_execution import (
2006
+ CO_ASYNC_GENERATOR,
2007
+ CO_COROUTINE,
2008
+ CO_GENERATOR,
2009
+ CO_ITERABLE_COROUTINE,
2010
+ )
2011
+
2012
+ if f_code.co_flags & (
2013
+ CO_GENERATOR | CO_COROUTINE | CO_ITERABLE_COROUTINE | CO_ASYNC_GENERATOR
2014
+ ):
2015
+ self.push(BuiltinVariable(None))
2016
+
2017
+ self.inline_depth = inline_depth
2018
+ self.inconsistent_side_effects = False
2019
+ linecache.lazycache(f_code.co_filename, f_globals)
2020
+ self.log_starts_line()
2021
+
2022
+
2023
+ class InstructionTranslator(InstructionTranslatorBase):
2024
+ mutated_closure_cell_contents: Set[str]
2025
+
2026
+ @staticmethod
2027
+ def current_tx() -> "InstructionTranslator":
2028
+ return tls.current_tx
2029
+
2030
+ @contextlib.contextmanager
2031
+ def set_current_tx(self):
2032
+ prior = getattr(tls, "current_tx", None)
2033
+ tls.current_tx = self
2034
+ try:
2035
+ yield
2036
+ finally:
2037
+ tls.current_tx = prior
2038
+
2039
+ def __init__(
2040
+ self,
2041
+ instructions: List[Instruction],
2042
+ f_code,
2043
+ f_locals,
2044
+ f_globals,
2045
+ f_builtins,
2046
+ code_options,
2047
+ compiler_fn,
2048
+ one_graph,
2049
+ export,
2050
+ export_constraints,
2051
+ mutated_closure_cell_contents: Set[str],
2052
+ frame_state,
2053
+ speculation_log: SpeculationLog,
2054
+ ):
2055
+ _step_logger()(
2056
+ logging.INFO,
2057
+ f"torchdynamo start tracing {f_code.co_name} {code_options['co_filename']}:{code_options['co_firstlineno']}",
2058
+ )
2059
+ super().__init__(
2060
+ output=OutputGraph(
2061
+ code_options,
2062
+ compiler_fn,
2063
+ self,
2064
+ export,
2065
+ export_constraints,
2066
+ frame_state,
2067
+ local_scope=f_locals,
2068
+ global_scope=f_globals,
2069
+ f_code=f_code,
2070
+ ),
2071
+ instructions=instructions,
2072
+ f_locals=f_locals,
2073
+ f_globals=f_globals,
2074
+ f_builtins=f_builtins,
2075
+ code_options=code_options,
2076
+ symbolic_locals={}, # set below
2077
+ # A global var is inserted only after a STORE_GLOBAL happens to it
2078
+ symbolic_globals={},
2079
+ f_code=f_code,
2080
+ export=export,
2081
+ inline_depth=0,
2082
+ speculation_log=speculation_log,
2083
+ )
2084
+
2085
+ self._throw_if_in_functorch()
2086
+
2087
+ # as soon as we create the tracing context we should keep it active, so any calls
2088
+ # into dynamo apis can rely on finding it
2089
+ with tracing(self.output.tracing_context), self.set_current_tx():
2090
+ self.one_graph: bool = one_graph
2091
+ self.export = export
2092
+ self.mutated_closure_cell_contents = mutated_closure_cell_contents
2093
+ if self.export:
2094
+ assert (
2095
+ self.one_graph
2096
+ ), "Export without one graph - something has gone wrong."
2097
+
2098
+ vars = list(code_options["co_varnames"])
2099
+ cells_and_freevars = [x for x in self.cell_and_freevars() if x not in vars]
2100
+ vars.extend(cells_and_freevars)
2101
+ cells_and_freevars_set = set(cells_and_freevars)
2102
+
2103
+ self.symbolic_locals = {
2104
+ k: variables.LazyVariableTracker.create(
2105
+ f_locals[k],
2106
+ source=LocalSource(k, cell_or_freevar=k in cells_and_freevars_set),
2107
+ )
2108
+ for k in vars
2109
+ if k in f_locals
2110
+ }
2111
+ self.debug_locals: List[Tuple[VariableTracker, List[VariableTracker]]] = []
2112
+ if export:
2113
+ # export gets confused if we never realize unused inputs
2114
+ # in export mode just eagerly realize everything
2115
+ self.symbolic_locals = VariableTracker.apply(
2116
+ lambda x: x.realize(), self.symbolic_locals
2117
+ )
2118
+
2119
+ self._freevars_ids = dict()
2120
+ for name in self.code_options["co_freevars"]:
2121
+ if name in f_locals:
2122
+ self._freevars_ids[name] = id(f_locals[name])
2123
+
2124
+ def _throw_if_in_functorch(self):
2125
+ # Fallback to eager in case of a graph break inside vmap
2126
+ eager = torch._dynamo.lookup_backend("eager")
2127
+ compiler_fn = inspect.getattr_static(
2128
+ self.output.compiler_fn, "compiler_fn", self.output.compiler_fn
2129
+ )
2130
+ ci = torch._C._functorch.peek_interpreter_stack()
2131
+ forbidden_keys = (
2132
+ torch._C._functorch.TransformType.Vmap,
2133
+ torch._C._functorch.TransformType.Grad,
2134
+ )
2135
+ if ci is not None and ci.key() in forbidden_keys and compiler_fn is not eager:
2136
+ # if it reaches here, it means Dynamo failed to inline a functorch function
2137
+ name = ci.key().name.lower()
2138
+ msg = f"torch.func.{name}(fn) requires the function to be inlined by dynamo"
2139
+ unimplemented(msg)
2140
+
2141
+ def get_example_value(self, source: Source):
2142
+ if isinstance(source, LocalSource):
2143
+ return self.f_locals[source.local_name]
2144
+ if isinstance(source, GlobalSource):
2145
+ return self.f_globals[source.global_name]
2146
+ raise KeyError()
2147
+
2148
+ def run(self):
2149
+ super().run()
2150
+
2151
+ def match_nested_cell(self, name, cell):
2152
+ """Match a cell in this method to one in a function we are inlining"""
2153
+ try:
2154
+ value = cell.cell_contents
2155
+ except ValueError:
2156
+ return None
2157
+ # TODO(jansel): check the id of the cell rather than the contents
2158
+ if id(value) != self._freevars_ids.get(name):
2159
+ return None
2160
+ return self.symbolic_locals[name]
2161
+
2162
+ def should_compile_partial_graph(self):
2163
+ return (
2164
+ all(b.can_restore() for b in self.block_stack)
2165
+ and not self.one_graph
2166
+ and self.generic_context_manager_depth == 0
2167
+ )
2168
+
2169
+ def create_call_resume_at(self, inst):
2170
+ self.instruction_pointer = None
2171
+
2172
+ if inst.opname == "RETURN_VALUE":
2173
+ return [create_instruction("RETURN_VALUE")]
2174
+
2175
+ reads = livevars_analysis(self.instructions, inst)
2176
+ argnames = tuple(
2177
+ k
2178
+ for k in self.symbolic_locals.keys()
2179
+ if k in reads and k not in self.cell_and_freevars()
2180
+ )
2181
+
2182
+ cg = PyCodegen(self)
2183
+
2184
+ # Python does not allow null to be an arg to a function, so
2185
+ # we remove nulls from the stack and restore them in the
2186
+ # prologue of the resume function
2187
+
2188
+ # sorted list of indices of nulls on the stack
2189
+ null_idxes: List[int] = []
2190
+ if sys.version_info >= (3, 11):
2191
+ # find indices of NullVariables
2192
+ for i, var in enumerate(self.stack):
2193
+ if isinstance(var, NullVariable):
2194
+ null_idxes.append(i)
2195
+ # generate bytecode to pop the nulls
2196
+ null_cnt = 0
2197
+ for i, var in enumerate(reversed(self.stack)):
2198
+ if isinstance(var, NullVariable):
2199
+ for j in range(2, i + 2 - null_cnt):
2200
+ cg.append_output(create_instruction("SWAP", arg=j))
2201
+ cg.extend_output(cg.pop_null())
2202
+ null_cnt += 1
2203
+
2204
+ # we popped all nulls from the stack at runtime,
2205
+ # so we should not count NullVariables
2206
+ stack_len = len(self.stack) - len(null_idxes)
2207
+ nargs = stack_len + len(argnames)
2208
+
2209
+ name = unique_id(f"__resume_at_{inst.offset}")
2210
+
2211
+ new_code: types.CodeType = ContinueExecutionCache.lookup(
2212
+ self.f_code,
2213
+ self.lineno,
2214
+ inst.offset,
2215
+ tuple(b.target.offset for b in self.block_stack),
2216
+ stack_len,
2217
+ argnames,
2218
+ tuple(b.resume_fn() for b in self.block_stack),
2219
+ tuple(null_idxes),
2220
+ )
2221
+
2222
+ # Add original GraphModule context to the resume function to handle
2223
+ # the case of a graph break while tracing a GraphModule
2224
+ orig_graphmodule_maybe = code_context.get_context(self.f_code).get(
2225
+ "orig_graphmodule", lambda: None
2226
+ )()
2227
+ if orig_graphmodule_maybe is not None:
2228
+ code_context.get_context(new_code)["orig_graphmodule"] = weakref.ref(
2229
+ orig_graphmodule_maybe
2230
+ )
2231
+
2232
+ if new_code.co_freevars:
2233
+ cg.make_function_with_closure(name, new_code, True, stack_len)
2234
+ else:
2235
+ # This is safe: we pre-generate a unique name
2236
+ self.output.install_global_unsafe(
2237
+ name, types.FunctionType(new_code, self.f_globals, name)
2238
+ )
2239
+ cg.extend_output(cg.load_function_name(name, True, stack_len))
2240
+
2241
+ cg.extend_output([cg.create_load(k) for k in argnames])
2242
+ cg.extend_output(create_call_function(nargs, False))
2243
+ cg.append_output(create_instruction("RETURN_VALUE"))
2244
+ return cg.get_instructions()
2245
+
2246
+ def symbolic_locals_contain_module_class(self):
2247
+ for v in self.symbolic_locals.values():
2248
+ if isinstance(v, UserDefinedClassVariable) and issubclass(
2249
+ v.as_python_constant(), torch.nn.Module
2250
+ ):
2251
+ return True
2252
+ return False
2253
+
2254
+ def RETURN_VALUE(self, inst):
2255
+ if (
2256
+ self.output.count_calls() == 0
2257
+ and not self.inconsistent_side_effects
2258
+ and not self.symbolic_locals_contain_module_class()
2259
+ and not self.export
2260
+ ):
2261
+ raise exc.SkipFrame("because no content in function call")
2262
+ self.instruction_pointer = None
2263
+ _step_logger()(
2264
+ logging.INFO,
2265
+ f"torchdynamo done tracing {self.f_code.co_name} (RETURN_VALUE)",
2266
+ )
2267
+ log.debug("RETURN_VALUE triggered compile")
2268
+ self.output.compile_subgraph(
2269
+ self,
2270
+ reason=GraphCompileReason(
2271
+ "return_value", [self.frame_summary()], graph_break=False
2272
+ ),
2273
+ )
2274
+ self.output.add_output_instructions([create_instruction("RETURN_VALUE")])
2275
+
2276
+
2277
+ class InliningInstructionTranslator(InstructionTranslatorBase):
2278
+ """Trace and inline a called method"""
2279
+
2280
+ symbolic_result: Optional[TensorVariable]
2281
+
2282
+ @classmethod
2283
+ def inline_call(cls, parent, func, args, kwargs):
2284
+ with patch.dict(counters, {"unimplemented": counters["inline_call"]}):
2285
+ return cls.inline_call_(parent, func, args, kwargs)
2286
+
2287
+ @staticmethod
2288
+ def check_inlineable(func):
2289
+ if func.has_self():
2290
+ unimplemented("inline with __self__")
2291
+
2292
+ result = trace_rules.check_verbose(func, is_inlined_call=True)
2293
+ if result.skipped:
2294
+ from torch._dynamo.variables.misc import produce_trampoline_autograd_apply
2295
+
2296
+ # _origin marks this as coming from an internal dynamo known function that is safe to
2297
+ # trace through.
2298
+ if hasattr(getattr(func, "fn", None), "_origin") and func.fn._origin in [
2299
+ produce_trampoline_autograd_apply,
2300
+ ]:
2301
+ # Known sound
2302
+ return trace_rules.SkipResult(
2303
+ False, "allowlist in dynamo known function"
2304
+ )
2305
+ fn_qualname = func.fn.__qualname__ if hasattr(func, "fn") else ""
2306
+ unimplemented(
2307
+ f"'inline in skipfiles: {fn_qualname} | {func.get_name()} {func.get_filename()}, {result.reason}'"
2308
+ )
2309
+
2310
+ if isinstance(func, UserFunctionVariable) and inspect.getattr_static(
2311
+ func.get_function(), "_torchdynamo_disable", False
2312
+ ):
2313
+ unimplemented(
2314
+ f"call torch._dynamo.disable() wrapped function {func.get_function()}"
2315
+ )
2316
+ else:
2317
+ return result
2318
+
2319
+ @staticmethod
2320
+ def inline_call_(
2321
+ parent, func: VariableTracker, args: List[VariableTracker], kwargs
2322
+ ):
2323
+ if isinstance(func, SkipFunctionVariable):
2324
+ unimplemented("inline with functions in skip files")
2325
+ assert isinstance(
2326
+ func,
2327
+ (UserFunctionVariable, NestedUserFunctionVariable),
2328
+ )
2329
+ result = InliningInstructionTranslator.check_inlineable(func)
2330
+ assert result.skipped is False
2331
+ try:
2332
+ sub_locals, closure_cells = func.bind_args(parent, args, kwargs)
2333
+ except TypeError as e:
2334
+ # Wrap the general TypeError during bind_args() to the internal ArgsMismatchError with detailed info
2335
+ raise ArgsMismatchError( # noqa: TRY200
2336
+ "{reason}.\n func = {func}, args = {args}, kwargs = {kwargs}".format(
2337
+ reason=str(e),
2338
+ func=f"'{func.get_name()}' {func.get_filename()}:{func.get_code().co_firstlineno}",
2339
+ args=[arg.python_type() for arg in args],
2340
+ kwargs=kwargs,
2341
+ ),
2342
+ )
2343
+
2344
+ for v in itertools.chain(sub_locals.values(), closure_cells.values()):
2345
+ if not isinstance(v, VariableTracker):
2346
+ unimplemented(f"unconverted arg {v}")
2347
+
2348
+ code: types.CodeType = func.get_code()
2349
+ if code.co_name in ("__setitem__", "__setattr__") and not (
2350
+ args is not None
2351
+ and len(args) > 0
2352
+ and isinstance(args[0], variables.CustomizedDictVariable)
2353
+ ):
2354
+ unimplemented(f"inline {code.co_name}")
2355
+
2356
+ suffix = ""
2357
+ # TODO: mlazos, add support for enabling multiple artifact logs
2358
+ # with a single alias
2359
+ if torch._logging._internal.log_state.is_artifact_enabled("output_code"):
2360
+ suffix = f"\n{dis.Bytecode(code).dis()}"
2361
+ if sys.version_info >= (3, 11):
2362
+ cur_inst = parent.current_instruction
2363
+ parent_code = parent.f_code
2364
+ header = parent.get_line_of_code_header(lineno=cur_inst.positions.lineno)
2365
+
2366
+ def get_trace_call_log_str():
2367
+ line = get_instruction_source_311(parent_code, cur_inst).rstrip()
2368
+ return f"TRACE inlined call {code.co_name} from {header}\n{line}"
2369
+
2370
+ trace_call_log.debug("%s", LazyString(get_trace_call_log_str))
2371
+ log.debug("INLINING %s%s, %s", code, suffix, result.reason)
2372
+
2373
+ # Detect inline GraphModule calls in order to propagate node metadata,
2374
+ # by checking if the first argument (self) is a variable tracking a GraphModule.
2375
+ if args and isinstance(args[0], NNModuleVariable):
2376
+ module = parent.output.get_submodule(args[0].module_key)
2377
+ if isinstance(module, torch.fx.GraphModule):
2378
+ # The inline call might not actually be a call to `forward`,
2379
+ # but it is enough to add a context for `forward` in case it is called.
2380
+ code_context.get_context(module.forward.__code__)[
2381
+ "orig_graphmodule"
2382
+ ] = weakref.ref(module)
2383
+
2384
+ tracer: InliningInstructionTranslator
2385
+ if is_generator(code):
2386
+ tracer = InliningGeneratorInstructionTranslator(
2387
+ parent, code, sub_locals, parent.symbolic_globals, closure_cells, func
2388
+ )
2389
+ else:
2390
+ tracer = InliningInstructionTranslator(
2391
+ parent, code, sub_locals, parent.symbolic_globals, closure_cells, func
2392
+ )
2393
+
2394
+ strict_ctx: Any = contextlib.nullcontext()
2395
+ if parent.strict_checks_enabled:
2396
+ strict_ctx = tracer.strict_translation_mode()
2397
+ try:
2398
+ with strict_ctx:
2399
+ tracer.run()
2400
+ except exc.SkipFrame as e:
2401
+ msg = f"SKIPPED INLINING {code}: {e}"
2402
+ log.debug(msg)
2403
+ raise Unsupported(msg) from e
2404
+ except Exception as e:
2405
+ log.debug("FAILED INLINING %s", code)
2406
+ raise
2407
+ assert tracer.symbolic_result is not None
2408
+ func.export_freevars(parent, tracer)
2409
+
2410
+ if tracer.f_globals is parent.f_globals:
2411
+ # Merge symbolic_globals back if parent and child are in the same namespace
2412
+ parent.symbolic_globals.update(tracer.symbolic_globals)
2413
+
2414
+ parent.inconsistent_side_effects |= tracer.inconsistent_side_effects
2415
+
2416
+ log.debug("DONE INLINING %s", code)
2417
+
2418
+ if is_generator(code):
2419
+ assert isinstance(tracer, InliningGeneratorInstructionTranslator)
2420
+ assert tracer.symbolic_result.as_python_constant() is None
2421
+ return ListIteratorVariable(
2422
+ tracer.generated_items,
2423
+ mutable_local=MutableLocal(),
2424
+ )
2425
+ else:
2426
+ return tracer.symbolic_result
2427
+
2428
+ def __init__(
2429
+ self,
2430
+ parent: InstructionTranslatorBase,
2431
+ code: types.CodeType,
2432
+ symbolic_locals: Dict[str, VariableTracker],
2433
+ symbolic_globals: Dict[str, VariableTracker],
2434
+ closure_cells: Dict[str, VariableTracker],
2435
+ funcvar: BaseUserFunctionVariable,
2436
+ ):
2437
+ f_globals = funcvar.get_globals() # type: ignore[attr-defined]
2438
+ f_builtins = f_globals["__builtins__"]
2439
+ if not isinstance(f_builtins, dict):
2440
+ f_builtins = f_builtins.__dict__
2441
+ instructions = cleaned_instructions(code)
2442
+ propagate_line_nums(instructions)
2443
+ super().__init__(
2444
+ output=parent.output,
2445
+ f_locals={},
2446
+ f_globals=f_globals,
2447
+ f_builtins=f_builtins,
2448
+ symbolic_locals=symbolic_locals,
2449
+ symbolic_globals=symbolic_globals,
2450
+ instructions=instructions,
2451
+ code_options={k: getattr(code, k) for k in dir(code)},
2452
+ f_code=code,
2453
+ export=parent.export,
2454
+ inline_depth=parent.inline_depth + 1,
2455
+ speculation_log=parent.speculation_log,
2456
+ )
2457
+ self.parent = parent
2458
+ self.symbolic_result = None
2459
+ self.closure_cells = closure_cells
2460
+ self.nn_module_stack = parent.nn_module_stack.copy()
2461
+
2462
+ @property
2463
+ def fake_mode(self):
2464
+ return self.parent.fake_mode
2465
+
2466
+ def run_ctx_mgr(self):
2467
+ return TracingContext.current_frame(self.parent.frame_summary())
2468
+
2469
+ def STORE_DEREF(self, inst):
2470
+ if inst.argval in self.closure_cells:
2471
+ cell = self.closure_cells[inst.argval]
2472
+ val = self.pop()
2473
+ if isinstance(cell, ClosureVariable):
2474
+ if not self.output.is_root_tracer():
2475
+ unimplemented(
2476
+ "HigherOrderOperator: Mutating a variable not in the current scope (ClosureVariable)"
2477
+ )
2478
+ self.output.root_tx.symbolic_locals[cell.name] = val
2479
+ else:
2480
+ self.output.side_effects.store_cell(cell, val)
2481
+ else:
2482
+ maybe_cell = self.symbolic_locals.get(inst.argval)
2483
+ if isinstance(
2484
+ maybe_cell,
2485
+ variables.NewCellVariable,
2486
+ ):
2487
+ self.output.side_effects.store_cell(
2488
+ self.symbolic_locals[inst.argval], self.pop()
2489
+ )
2490
+ else:
2491
+ if (
2492
+ maybe_cell is not None
2493
+ and maybe_cell.source.name()
2494
+ not in self.output.root_tx.mutated_closure_cell_contents
2495
+ ):
2496
+ # Why is the source name here unique?
2497
+ # mutated_closure_cell_contents is a per-frame
2498
+ # concept, and sources identify, e.g., particular
2499
+ # locals from the frame. If you had two locals,
2500
+ # they'll get different source names, and therefore
2501
+ # differ here.
2502
+ self.output.root_tx.mutated_closure_cell_contents.add(
2503
+ maybe_cell.source.name()
2504
+ )
2505
+ raise exc.UnspecializeRestartAnalysis()
2506
+ unimplemented("write to __closure__ while inlining")
2507
+
2508
+ def LOAD_DEREF(self, inst):
2509
+ if inst.argval in self.closure_cells:
2510
+ cell = self.closure_cells[inst.argval]
2511
+ if isinstance(cell, ClosureVariable):
2512
+ self.push(self.output.root_tx.symbolic_locals[cell.name])
2513
+ else:
2514
+ self.push(self.output.side_effects.load_cell(cell))
2515
+ else:
2516
+ maybe_sym_local = self.symbolic_locals.get(inst.argval, None)
2517
+ if isinstance(maybe_sym_local, variables.NewCellVariable):
2518
+ self.push(self.output.side_effects.load_cell(maybe_sym_local))
2519
+ else:
2520
+ super().LOAD_DEREF(inst)
2521
+
2522
+ def LOAD_CLOSURE(self, inst):
2523
+ assert inst.argval in self.cell_and_freevars()
2524
+ if inst.argval in self.closure_cells:
2525
+ self.push(self.closure_cells[inst.argval])
2526
+ else:
2527
+ self.push(InlinedClosureVariable(name=inst.argval))
2528
+
2529
+ def check_replace_is_safe(self, oldvar):
2530
+ if not is_side_effect_safe(oldvar.mutable_local):
2531
+ unimplemented(
2532
+ "HigherOrderOperator: Mutating a variable not in the current scope (replace_all)"
2533
+ )
2534
+
2535
+ def should_compile_partial_graph(self):
2536
+ return False # inlining functions is all-or-nothing
2537
+
2538
+ def create_call_resume_at(self, offset):
2539
+ unimplemented("cant resume while inlining")
2540
+
2541
+ def RETURN_VALUE(self, inst):
2542
+ self.symbolic_result = self.pop() # type: ignore[assignment]
2543
+ self.instruction_pointer = None
2544
+
2545
+
2546
+ class InliningGeneratorInstructionTranslator(InliningInstructionTranslator):
2547
+ generated_items: List[VariableTracker]
2548
+
2549
+ def __init__(self, *args, **kwargs):
2550
+ super().__init__(*args, **kwargs)
2551
+ self.generated_items = []
2552
+
2553
+ def YIELD_VALUE(self, inst: Instruction):
2554
+ self.generated_items.append(self.pop())
2555
+ # TODO(jansel): figure out why this is needed, it isn't in the docs for YIELD_VALUE
2556
+ self.push(ConstantVariable.create(None))
2557
+
2558
+ def GET_YIELD_FROM_ITER(self, inst):
2559
+ tos = self.stack[-1]
2560
+ if not isinstance(tos, ListIteratorVariable):
2561
+ self.pop()
2562
+ res = BuiltinVariable(iter).call_function(self, [tos], {})
2563
+ self.push(res)
2564
+ return self.YIELD_FROM(inst)
2565
+
2566
+ def YIELD_FROM(self, inst):
2567
+ while True:
2568
+ tos = self.stack[-1].realize()
2569
+ if isinstance(tos, ConstantVariable) and tos.value is None:
2570
+ self.pop()
2571
+ return
2572
+ if isinstance(
2573
+ tos, (variables.ListIteratorVariable, variables.IteratorVariable)
2574
+ ):
2575
+ try:
2576
+ val, next_iter = tos.next_variables(self)
2577
+ self.push(val)
2578
+ # TODO(voz): Unclear if we need the push None in YIELD_VALUE?
2579
+ self.YIELD_VALUE(inst)
2580
+ self.pop()
2581
+ self.push(next_iter)
2582
+ except StopIteration:
2583
+ return
2584
+ else:
2585
+ unimplemented(f"YIELD_FROM {typestr(tos)}")
2586
+
2587
+ def SEND(self, inst):
2588
+ assert len(self.stack) >= 2
2589
+ val = self.pop()
2590
+ tos = self.stack[-1]
2591
+ if isinstance(tos, ListIteratorVariable):
2592
+ if isinstance(val, ConstantVariable) and val.value is None:
2593
+ self.push(val)
2594
+ self.instruction_pointer = self.indexof[inst.target]
2595
+ else:
2596
+ # invoke send
2597
+ # Unreachable code - if you hit this, you are implementing generator support and have
2598
+ # lifted the `unimplemented("generator")` in frame conversion. This codepath handles
2599
+ # subgenerator and lines up with this line in Python 3.11
2600
+ # https://github.com/python/cpython/blob/3.11/Python/ceval.c#L2597
2601
+ unimplemented("Unreachable sub-generator code")
2602
+ else:
2603
+ unimplemented(f"SEND {typestr(tos)}")
llmeval-env/lib/python3.10/site-packages/torch/_dynamo/tensor_version_op.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch._prims import _make_prim, RETURN_TYPE
3
+ from torch._subclasses import FakeTensorMode
4
+ from torch._subclasses.functional_tensor import FunctionalTensorMode
5
+
6
+ _tensor_version = _make_prim(
7
+ schema="_tensor_version(Tensor self) -> SymInt",
8
+ return_type=RETURN_TYPE.NEW,
9
+ meta=torch.ops.aten._version.default,
10
+ impl_aten=torch.ops.aten._version.default,
11
+ doc="Tracable unbacked SymInt version of torch.Tensor._version",
12
+ )
13
+
14
+
15
+ @_tensor_version.py_impl(FakeTensorMode)
16
+ def _tensor_version_fake(self):
17
+ """
18
+ The initial dynamo capture of _tensor_version + _unsafe_set_version_counter turns the
19
+ `._version` into an unbacked SymInt so that we don't need to specialize on the `._version`
20
+ of input tensors to the graph.
21
+ """
22
+ return self.fake_mode.shape_env.create_unbacked_symint()
23
+
24
+
25
+ _unsafe_set_version_counter = _make_prim(
26
+ schema="_unsafe_set_version_counter(Tensor self, SymInt version) -> ()",
27
+ return_type=RETURN_TYPE.NEW,
28
+ meta=lambda self, version: None,
29
+ impl_aten=torch._C._autograd._unsafe_set_version_counter,
30
+ doc="Tracable+SymInt version of torch._C._autograd._unsafe_set_version_counter",
31
+ )
32
+ torch.fx.node.has_side_effect(_unsafe_set_version_counter)
33
+
34
+
35
+ """
36
+ When we functionalize _tensor_version + _unsafe_set_version_counter,
37
+ the ops disappear from the traced graph. We run them eagerly on the
38
+ fake tensors used for tracing, in order to get past asserts that would
39
+ fail in autograd.
40
+
41
+ Why is this ok?
42
+ 1) Versions on functional tensors don't make any sense since you can't mutate a functional tensor.
43
+ 2) The whole point of version munging is to trick autograd into doing what we want, and after
44
+ AotAtuograd there is no longer any need for these ops.
45
+
46
+ Note this is similar to how no_grad is handled.
47
+ """
48
+
49
+
50
+ @_tensor_version.py_impl(FunctionalTensorMode)
51
+ def _tensor_version_functional(self):
52
+ return self._version
53
+
54
+
55
+ @_unsafe_set_version_counter.py_impl(FunctionalTensorMode)
56
+ def _unsafe_set_version_counter_functional(self, version):
57
+ torch._C._autograd._unsafe_set_version_counter(self, version)
llmeval-env/lib/python3.10/site-packages/torch/_dynamo/test_minifier_common.py ADDED
@@ -0,0 +1,244 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import dataclasses
2
+ import io
3
+ import logging
4
+ import os
5
+ import re
6
+ import shutil
7
+ import subprocess
8
+ import sys
9
+ import tempfile
10
+ import traceback
11
+ from typing import Optional
12
+ from unittest.mock import patch
13
+
14
+ import torch
15
+ import torch._dynamo
16
+ import torch._dynamo.test_case
17
+ from torch.utils._traceback import report_compile_source_on_error
18
+
19
+
20
+ @dataclasses.dataclass
21
+ class MinifierTestResult:
22
+ minifier_code: str
23
+ repro_code: str
24
+
25
+ def _get_module(self, t):
26
+ match = re.search(r"class Repro\(torch\.nn\.Module\):\s+([ ].*\n| *\n)+", t)
27
+ assert match is not None, "failed to find module"
28
+ r = match.group(0)
29
+ r = re.sub(r"\s+$", "\n", r, flags=re.MULTILINE)
30
+ r = re.sub(r"\n{3,}", "\n\n", r)
31
+ return r.strip()
32
+
33
+ def minifier_module(self):
34
+ return self._get_module(self.minifier_code)
35
+
36
+ def repro_module(self):
37
+ return self._get_module(self.repro_code)
38
+
39
+
40
+ class MinifierTestBase(torch._dynamo.test_case.TestCase):
41
+ DEBUG_DIR = tempfile.mkdtemp()
42
+
43
+ @classmethod
44
+ def setUpClass(cls):
45
+ super().setUpClass()
46
+ cls._exit_stack.enter_context( # type: ignore[attr-defined]
47
+ torch._dynamo.config.patch(debug_dir_root=cls.DEBUG_DIR)
48
+ )
49
+ # These configurations make new process startup slower. Disable them
50
+ # for the minification tests to speed them up.
51
+ cls._exit_stack.enter_context( # type: ignore[attr-defined]
52
+ torch._inductor.config.patch(
53
+ {
54
+ # https://github.com/pytorch/pytorch/issues/100376
55
+ "pattern_matcher": False,
56
+ # multiprocess compilation takes a long time to warmup
57
+ "compile_threads": 1,
58
+ # https://github.com/pytorch/pytorch/issues/100378
59
+ "cpp.vec_isa_ok": False,
60
+ }
61
+ )
62
+ )
63
+
64
+ @classmethod
65
+ def tearDownClass(cls):
66
+ if os.getenv("PYTORCH_KEEP_TMPDIR", "0") != "1":
67
+ shutil.rmtree(cls.DEBUG_DIR)
68
+ else:
69
+ print(f"test_minifier_common tmpdir kept at: {cls.DEBUG_DIR}")
70
+ cls._exit_stack.close() # type: ignore[attr-defined]
71
+
72
+ def _gen_codegen_fn_patch_code(self, device, bug_type):
73
+ assert bug_type in ("compile_error", "runtime_error", "accuracy")
74
+ return f"""\
75
+ {torch._dynamo.config.codegen_config()}
76
+ {torch._inductor.config.codegen_config()}
77
+ torch._inductor.config.{"cpp" if device == "cpu" else "triton"}.inject_relu_bug_TESTING_ONLY = {bug_type!r}
78
+ """
79
+
80
+ def _maybe_subprocess_run(self, args, *, isolate, cwd=None):
81
+ if not isolate:
82
+ assert len(args) >= 2, args
83
+ assert args[0] == "python3", args
84
+ if args[1] == "-c":
85
+ assert len(args) == 3, args
86
+ code = args[2]
87
+ args = ["-c"]
88
+ else:
89
+ assert len(args) >= 2, args
90
+ with open(args[1]) as f:
91
+ code = f.read()
92
+ args = args[1:]
93
+
94
+ # WARNING: This is not a perfect simulation of running
95
+ # the program out of tree. We only interpose on things we KNOW we
96
+ # need to handle for tests. If you need more stuff, you will
97
+ # need to augment this appropriately.
98
+
99
+ # NB: Can't use save_config because that will omit some fields,
100
+ # but we must save and reset ALL fields
101
+ dynamo_config = torch._dynamo.config.shallow_copy_dict()
102
+ inductor_config = torch._inductor.config.shallow_copy_dict()
103
+ try:
104
+ stderr = io.StringIO()
105
+ log_handler = logging.StreamHandler(stderr)
106
+ log = logging.getLogger("torch._dynamo")
107
+ log.addHandler(log_handler)
108
+ try:
109
+ prev_cwd = os.getcwd()
110
+ if cwd is not None:
111
+ os.chdir(cwd)
112
+ with patch("sys.argv", args), report_compile_source_on_error():
113
+ exec(code, {"__name__": "__main__", "__compile_source__": code})
114
+ rc = 0
115
+ except Exception:
116
+ rc = 1
117
+ traceback.print_exc(file=stderr)
118
+ finally:
119
+ log.removeHandler(log_handler)
120
+ if cwd is not None:
121
+ os.chdir(prev_cwd) # type: ignore[possibly-undefined]
122
+ # Make sure we don't leave buggy compiled frames lying
123
+ # around
124
+ torch._dynamo.reset()
125
+ finally:
126
+ torch._dynamo.config.load_config(dynamo_config)
127
+ torch._inductor.config.load_config(inductor_config)
128
+
129
+ # TODO: return a more appropriate data structure here
130
+ return subprocess.CompletedProcess(
131
+ args,
132
+ rc,
133
+ b"",
134
+ stderr.getvalue().encode("utf-8"),
135
+ )
136
+ else:
137
+ return subprocess.run(args, capture_output=True, cwd=cwd, check=False)
138
+
139
+ # Run `code` in a separate python process.
140
+ # Returns the completed process state and the directory containing the
141
+ # minifier launcher script, if `code` outputted it.
142
+ def _run_test_code(self, code, *, isolate):
143
+ proc = self._maybe_subprocess_run(
144
+ ["python3", "-c", code], isolate=isolate, cwd=self.DEBUG_DIR
145
+ )
146
+
147
+ print("test stdout:", proc.stdout.decode("utf-8"))
148
+ print("test stderr:", proc.stderr.decode("utf-8"))
149
+ repro_dir_match = re.search(
150
+ r"(\S+)minifier_launcher.py", proc.stderr.decode("utf-8")
151
+ )
152
+ if repro_dir_match is not None:
153
+ return proc, repro_dir_match.group(1)
154
+ return proc, None
155
+
156
+ # Runs the minifier launcher script in `repro_dir`
157
+ def _run_minifier_launcher(self, repro_dir, isolate, *, minifier_args=()):
158
+ self.assertIsNotNone(repro_dir)
159
+ launch_file = os.path.join(repro_dir, "minifier_launcher.py")
160
+ with open(launch_file) as f:
161
+ launch_code = f.read()
162
+ self.assertTrue(os.path.exists(launch_file))
163
+
164
+ args = ["python3", launch_file, "minify", *minifier_args]
165
+ if not isolate:
166
+ args.append("--no-isolate")
167
+ launch_proc = self._maybe_subprocess_run(args, isolate=isolate, cwd=repro_dir)
168
+ print("minifier stdout:", launch_proc.stdout.decode("utf-8"))
169
+ stderr = launch_proc.stderr.decode("utf-8")
170
+ print("minifier stderr:", stderr)
171
+ self.assertNotIn("Input graph did not fail the tester", stderr)
172
+
173
+ return launch_proc, launch_code
174
+
175
+ # Runs the repro script in `repro_dir`
176
+ def _run_repro(self, repro_dir, *, isolate=True):
177
+ self.assertIsNotNone(repro_dir)
178
+ repro_file = os.path.join(repro_dir, "repro.py")
179
+ with open(repro_file) as f:
180
+ repro_code = f.read()
181
+ self.assertTrue(os.path.exists(repro_file))
182
+
183
+ repro_proc = self._maybe_subprocess_run(
184
+ ["python3", repro_file], isolate=isolate, cwd=repro_dir
185
+ )
186
+ print("repro stdout:", repro_proc.stdout.decode("utf-8"))
187
+ print("repro stderr:", repro_proc.stderr.decode("utf-8"))
188
+ return repro_proc, repro_code
189
+
190
+ # Template for testing code.
191
+ # `run_code` is the code to run for the test case.
192
+ # `patch_code` is the code to be patched in every generated file; usually
193
+ # just use this to turn on bugs via the config
194
+ def _gen_test_code(self, run_code, repro_after, repro_level):
195
+ return f"""\
196
+ import torch
197
+ import torch._dynamo
198
+ {torch._dynamo.config.codegen_config()}
199
+ {torch._inductor.config.codegen_config()}
200
+ torch._dynamo.config.repro_after = "{repro_after}"
201
+ torch._dynamo.config.repro_level = {repro_level}
202
+ torch._dynamo.config.debug_dir_root = "{self.DEBUG_DIR}"
203
+ {run_code}
204
+ """
205
+
206
+ # Runs a full minifier test.
207
+ # Minifier tests generally consist of 3 stages:
208
+ # 1. Run the problematic code
209
+ # 2. Run the generated minifier launcher script
210
+ # 3. Run the generated repro script
211
+ #
212
+ # If possible, you should run the test with isolate=False; use
213
+ # isolate=True only if the bug you're testing would otherwise
214
+ # crash the process
215
+ def _run_full_test(
216
+ self, run_code, repro_after, expected_error, *, isolate, minifier_args=()
217
+ ) -> Optional[MinifierTestResult]:
218
+ if isolate:
219
+ repro_level = 3
220
+ elif expected_error is None or expected_error == "AccuracyError":
221
+ repro_level = 4
222
+ else:
223
+ repro_level = 2
224
+ test_code = self._gen_test_code(run_code, repro_after, repro_level)
225
+ print("running test", file=sys.stderr)
226
+ test_proc, repro_dir = self._run_test_code(test_code, isolate=isolate)
227
+ if expected_error is None:
228
+ # Just check that there was no error
229
+ self.assertEqual(test_proc.returncode, 0)
230
+ self.assertIsNone(repro_dir)
231
+ return None
232
+ # NB: Intentionally do not test return code; we only care about
233
+ # actually generating the repro, we don't have to crash
234
+ self.assertIn(expected_error, test_proc.stderr.decode("utf-8"))
235
+ self.assertIsNotNone(repro_dir)
236
+ print("running minifier", file=sys.stderr)
237
+ minifier_proc, minifier_code = self._run_minifier_launcher(
238
+ repro_dir, isolate=isolate, minifier_args=minifier_args
239
+ )
240
+ print("running repro", file=sys.stderr)
241
+ repro_proc, repro_code = self._run_repro(repro_dir, isolate=isolate)
242
+ self.assertIn(expected_error, repro_proc.stderr.decode("utf-8"))
243
+ self.assertNotEqual(repro_proc.returncode, 0)
244
+ return MinifierTestResult(minifier_code=minifier_code, repro_code=repro_code)
llmeval-env/lib/python3.10/site-packages/torch/_dynamo/testing.py ADDED
@@ -0,0 +1,378 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import contextlib
2
+ import dis
3
+ import functools
4
+ import logging
5
+ import os.path
6
+ import random
7
+ import re
8
+ import sys
9
+ import types
10
+ import unittest
11
+ from typing import List, Optional, Sequence, Union
12
+ from unittest.mock import patch
13
+
14
+ np: Optional[types.ModuleType] = None
15
+ try:
16
+ import numpy as np
17
+ except ModuleNotFoundError:
18
+ np = None
19
+
20
+ import torch
21
+ from torch import fx
22
+ from torch._dynamo.output_graph import OutputGraph
23
+
24
+ from . import config, eval_frame, optimize_assert, reset
25
+ from .bytecode_transformation import (
26
+ create_instruction,
27
+ debug_checks,
28
+ is_generator,
29
+ transform_code_object,
30
+ )
31
+ from .guards import CheckFunctionManager, GuardedCode
32
+ from .utils import same
33
+
34
+ unsupported = eval_frame.unsupported
35
+ three = 3
36
+
37
+ log = logging.getLogger(__name__)
38
+
39
+
40
+ def clone_me(x):
41
+ if x is None:
42
+ return None
43
+ return x.detach().clone().requires_grad_(x.requires_grad)
44
+
45
+
46
+ def named_parameters_for_optimized_module(mod):
47
+ assert isinstance(mod, eval_frame.OptimizedModule)
48
+ return mod._orig_mod.named_parameters
49
+
50
+
51
+ def named_buffers_for_optimized_module(mod):
52
+ assert isinstance(mod, eval_frame.OptimizedModule)
53
+ return mod._orig_mod.named_buffers
54
+
55
+
56
+ def remove_optimized_module_prefix(name) -> str:
57
+ return re.sub(r"^_orig_mod[.]", "", name)
58
+
59
+
60
+ def collect_results(model, prediction, loss, example_inputs):
61
+ results = []
62
+ results.append(prediction)
63
+ results.append(loss)
64
+ # if isinstance(loss, torch.Tensor) and loss.item() > 1:
65
+ # log.warning(
66
+ # f"High loss value alert - {loss:.2f}. Can result in unstable gradients."
67
+ # )
68
+
69
+ grads = dict()
70
+ params = dict()
71
+ for name, param in model.named_parameters():
72
+ if isinstance(model, eval_frame.OptimizedModule):
73
+ name = remove_optimized_module_prefix(name)
74
+ param_copy = param
75
+ grad = param.grad
76
+ # Treat None and zero grad as same
77
+ if param.grad is None:
78
+ grad = torch.zeros_like(param)
79
+ grads[name + ".grad"] = grad
80
+ params[name] = param_copy
81
+ results.append(grads)
82
+ results.append(params)
83
+ buffers = dict()
84
+ for name, buffer in model.named_buffers():
85
+ if isinstance(model, eval_frame.OptimizedModule):
86
+ name = remove_optimized_module_prefix(name)
87
+ buffers[name] = buffer
88
+ results.append(buffers)
89
+ for example in example_inputs:
90
+ if isinstance(example, (tuple, list)):
91
+ for inp in example:
92
+ if isinstance(inp, torch.Tensor):
93
+ results.append(inp.grad)
94
+ else:
95
+ if isinstance(example, torch.Tensor):
96
+ results.append(example.grad)
97
+ return results
98
+
99
+
100
+ def requires_bwd_pass(out):
101
+ if isinstance(out, torch.Tensor):
102
+ return out.requires_grad
103
+ elif isinstance(out, (list, tuple)):
104
+ return any(requires_bwd_pass(x) for x in out)
105
+ elif out is None:
106
+ return False
107
+ elif isinstance(out, int):
108
+ return False
109
+ raise NotImplementedError("Don't know how to reduce", type(out))
110
+
111
+
112
+ def reduce_to_scalar_loss(out):
113
+ """Reduce the output of a model to get scalar loss"""
114
+ if isinstance(out, torch.Tensor):
115
+ # Mean does not work on integer tensors
116
+ return out.sum() / out.numel()
117
+ elif isinstance(out, (list, tuple)):
118
+ return sum([reduce_to_scalar_loss(x) for x in out]) / len(out)
119
+ elif type(out).__name__ in (
120
+ "MaskedLMOutput",
121
+ "Seq2SeqLMOutput",
122
+ "CausalLMOutputWithCrossAttentions",
123
+ ):
124
+ return reduce_to_scalar_loss(out.logits)
125
+ elif type(out).__name__ == "SquashedNormal":
126
+ return out.mean.sum()
127
+ elif isinstance(out, dict):
128
+ return sum([reduce_to_scalar_loss(value) for value in out.values()]) / len(
129
+ out.keys()
130
+ )
131
+ raise NotImplementedError("Don't know how to reduce", type(out))
132
+
133
+
134
+ def debug_dir() -> str:
135
+ path = os.path.join(os.path.dirname(__file__), "../debug")
136
+ if not os.path.exists(path):
137
+ os.mkdir(path)
138
+ return path
139
+
140
+
141
+ def debug_dump(name, code: types.CodeType, extra="") -> None:
142
+ with open(os.path.join(debug_dir(), name), "w") as fd:
143
+ fd.write(
144
+ f"{dis.Bytecode(code).info()}\n\n{dis.Bytecode(code).dis()}\n\n{extra}\n"
145
+ )
146
+
147
+
148
+ def debug_insert_nops(
149
+ frame, cache_size, hooks, _, *, skip: int = 0
150
+ ) -> Optional[GuardedCode]:
151
+ """used to debug jump updates"""
152
+
153
+ def insert_nops(instructions, code_options):
154
+ instructions.insert(0, create_instruction("NOP"))
155
+ instructions.insert(0, create_instruction("NOP"))
156
+
157
+ if is_generator(frame.f_code):
158
+ return None
159
+
160
+ debug_checks(frame.f_code)
161
+ code = transform_code_object(frame.f_code, insert_nops)
162
+ graph = OutputGraph(
163
+ code_options={},
164
+ compiler_fn=None,
165
+ root_tx=None,
166
+ export=False,
167
+ export_constraints=None,
168
+ frame_state={"_id": 0},
169
+ # TODO: shouldn't this be f_locals/f_globals from frame?
170
+ local_scope=locals(),
171
+ global_scope=globals(),
172
+ f_code=frame.f_code,
173
+ )
174
+
175
+ return GuardedCode(code, CheckFunctionManager(graph).check_fn)
176
+
177
+
178
+ class CompileCounter:
179
+ def __init__(self):
180
+ self.frame_count = 0
181
+ self.op_count = 0
182
+
183
+ def __call__(self, gm: torch.fx.GraphModule, example_inputs: List[torch.Tensor]):
184
+ self.frame_count += 1
185
+ for node in gm.graph.nodes:
186
+ if "call" in node.op:
187
+ self.op_count += 1
188
+ return gm.forward
189
+
190
+ def clear(self):
191
+ self.frame_count = 0
192
+ self.op_count = 0
193
+
194
+
195
+ class CompileCounterWithBackend:
196
+ def __init__(self, backend):
197
+ self.frame_count = 0
198
+ self.op_count = 0
199
+ self.backend = backend
200
+ self.graphs = []
201
+
202
+ def __call__(self, gm: torch.fx.GraphModule, example_inputs: List[torch.Tensor]):
203
+ from .backends.registry import lookup_backend
204
+
205
+ self.frame_count += 1
206
+ for node in gm.graph.nodes:
207
+ if "call" in node.op:
208
+ self.op_count += 1
209
+ self.graphs.append(gm)
210
+ return lookup_backend(self.backend)(gm, example_inputs)
211
+
212
+
213
+ # Equivalent to backend="eager", but also records graphs that
214
+ # we can assert on
215
+ class EagerAndRecordGraphs:
216
+ def __init__(self):
217
+ self.graphs = []
218
+
219
+ def __call__(self, gm: torch.fx.GraphModule, example_inputs: List[torch.Tensor]):
220
+ self.graphs.append(gm)
221
+ return gm
222
+
223
+
224
+ def strip_comment(code) -> str:
225
+ code = str(code)
226
+ return re.sub(r"(?m)^ *#.*\n?", "", code)
227
+
228
+
229
+ def remove_trailing_space(code) -> str:
230
+ return "\n".join([line.rstrip() for line in code.split("\n")])
231
+
232
+
233
+ def normalize_gm(gm_str) -> str:
234
+ # strip comments as comments have path to files which may differ from
235
+ # system to system.
236
+ return remove_trailing_space(strip_comment(gm_str))
237
+
238
+
239
+ def standard_test(
240
+ self,
241
+ fn,
242
+ nargs,
243
+ expected_ops=None,
244
+ expected_ops_dynamic=None,
245
+ expected_frame_count=1,
246
+ ):
247
+ if not config.assume_static_by_default and expected_ops_dynamic is not None:
248
+ expected_ops = expected_ops_dynamic
249
+
250
+ actual = CompileCounter()
251
+
252
+ args1 = [torch.randn(10, 10) for _ in range(nargs)]
253
+ args2 = [torch.randn(10, 10) for _ in range(nargs)]
254
+ correct1 = fn(*args1)
255
+ correct2 = fn(*args2)
256
+ reset()
257
+ opt_fn = optimize_assert(actual)(fn)
258
+ val1a = opt_fn(*args1)
259
+ val2a = opt_fn(*args2)
260
+ val1b = opt_fn(*args1)
261
+ val2b = opt_fn(*args2)
262
+ reset()
263
+ self.assertTrue(same(val1a, correct1))
264
+ self.assertTrue(same(val1b, correct1))
265
+ self.assertTrue(same(val2a, correct2))
266
+ self.assertTrue(same(val2b, correct2))
267
+ self.assertEqual(actual.frame_count, expected_frame_count)
268
+ if expected_ops is not None:
269
+ self.assertEqual(actual.op_count, expected_ops)
270
+
271
+
272
+ def dummy_fx_compile(gm: fx.GraphModule, example_inputs):
273
+ return gm.forward
274
+
275
+
276
+ def format_speedup(speedup, pvalue, is_correct=True, pvalue_threshold=0.1):
277
+ if not is_correct:
278
+ return "ERROR"
279
+ if pvalue > pvalue_threshold:
280
+ return f"{speedup:.3f}x SAME"
281
+ return f"{speedup:.3f}x p={pvalue:.2f}"
282
+
283
+
284
+ def rand_strided(
285
+ size: Sequence[int],
286
+ stride: Sequence[int],
287
+ dtype: torch.dtype = torch.float32,
288
+ device: Union[str, torch.device] = "cpu",
289
+ extra_size: int = 0,
290
+ ):
291
+ needed_size = (
292
+ sum((shape - 1) * stride for shape, stride in zip(size, stride))
293
+ + 1
294
+ + extra_size
295
+ )
296
+ if dtype.is_floating_point:
297
+ buffer = torch.randn(needed_size, dtype=dtype, device=device)
298
+ else:
299
+ buffer = torch.zeros(size=[needed_size], dtype=dtype, device=device)
300
+ return torch.as_strided(buffer, size, stride)
301
+
302
+
303
+ def _make_fn_with_patches(fn, *patches):
304
+ @functools.wraps(fn)
305
+ def _fn(*args, **kwargs):
306
+ with contextlib.ExitStack() as stack:
307
+ for module, attr, val in patches:
308
+ stack.enter_context(patch.object(module, attr, val))
309
+
310
+ return fn(*args, **kwargs)
311
+
312
+ return _fn
313
+
314
+
315
+ def make_test_cls_with_patches(cls, cls_prefix, fn_suffix, *patches, xfail_prop=None):
316
+ DummyTestClass = type(f"{cls_prefix}{cls.__name__}", cls.__bases__, {})
317
+ DummyTestClass.__qualname__ = DummyTestClass.__name__
318
+
319
+ for name in dir(cls):
320
+ if name.startswith("test_"):
321
+ fn = getattr(cls, name)
322
+ if not callable(fn):
323
+ setattr(DummyTestClass, name, getattr(cls, name))
324
+ continue
325
+ new_name = f"{name}{fn_suffix}"
326
+ new_fn = _make_fn_with_patches(fn, *patches)
327
+ new_fn.__name__ = new_name
328
+ if xfail_prop is not None and hasattr(fn, xfail_prop):
329
+ new_fn = unittest.expectedFailure(new_fn)
330
+ setattr(DummyTestClass, new_name, new_fn)
331
+ # NB: Doesn't handle slots correctly, but whatever
332
+ elif not hasattr(DummyTestClass, name):
333
+ setattr(DummyTestClass, name, getattr(cls, name))
334
+
335
+ return DummyTestClass
336
+
337
+
338
+ # test Python 3.11+ specific features
339
+ def skipIfNotPy311(fn):
340
+ if sys.version_info >= (3, 11):
341
+ return fn
342
+ return unittest.skip(fn)
343
+
344
+
345
+ def xfailIfPy311(fn):
346
+ if sys.version_info >= (3, 11):
347
+ return unittest.expectedFailure(fn)
348
+ return fn
349
+
350
+
351
+ # Controls tests generated in test/inductor/test_torchinductor_dynamic_shapes.py
352
+ # and test/dynamo/test_dynamic_shapes.py
353
+ def expectedFailureDynamic(fn):
354
+ fn._expected_failure_dynamic = True
355
+ return fn
356
+
357
+
358
+ # Controls tests generated in test/inductor/test_torchinductor_codegen_dynamic_shapes.py
359
+ def expectedFailureCodegenDynamic(fn):
360
+ fn._expected_failure_codegen_dynamic = True
361
+ return fn
362
+
363
+
364
+ # Controls test generated in test/inductor/test_cpp_wrapper.py
365
+ def expectedFailureDynamicWrapper(fn):
366
+ fn._expected_failure_dynamic_wrapper = True
367
+ return fn
368
+
369
+
370
+ def reset_rng_state(use_xla=False):
371
+ torch.manual_seed(1337)
372
+ random.seed(1337)
373
+ if np:
374
+ np.random.seed(1337)
375
+ if use_xla:
376
+ import torch_xla.core.xla_model as xm
377
+
378
+ xm.set_rng_state(1337, str(xm.xla_device()))
llmeval-env/lib/python3.10/site-packages/torch/_dynamo/trace_rules.py ADDED
The diff for this file is too large to render. See raw diff
 
llmeval-env/lib/python3.10/site-packages/torch/_dynamo/utils.py ADDED
@@ -0,0 +1,2548 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import atexit
2
+ import collections
3
+ import contextlib
4
+ import copy
5
+ import cProfile
6
+ import dataclasses
7
+ import datetime
8
+ import dis
9
+ import enum
10
+ import functools
11
+ import gc
12
+ import inspect
13
+ import itertools
14
+ import linecache
15
+ import logging
16
+ import math
17
+ import operator
18
+ import os
19
+ import pstats
20
+ import re
21
+ import subprocess
22
+ import sys
23
+ import textwrap
24
+ import threading
25
+ import time
26
+ import types
27
+ import typing
28
+ import weakref
29
+ from contextlib import contextmanager
30
+ from functools import lru_cache, wraps
31
+ from pathlib import Path
32
+ from types import MethodWrapperType
33
+ from typing import (
34
+ Any,
35
+ Callable,
36
+ cast,
37
+ ClassVar,
38
+ Counter,
39
+ DefaultDict,
40
+ Deque,
41
+ Dict,
42
+ Iterator,
43
+ KeysView,
44
+ List,
45
+ Optional,
46
+ Set,
47
+ Tuple,
48
+ Type,
49
+ Union,
50
+ ValuesView,
51
+ )
52
+
53
+ from ..utils.hooks import RemovableHandle
54
+
55
+ try:
56
+ import numpy as np
57
+ except ModuleNotFoundError:
58
+ np = None # type: ignore[assignment]
59
+
60
+ try:
61
+ import torch._logging
62
+ import torch._numpy as tnp
63
+ from torch._guards import detect_fake_mode # noqa: F401n
64
+ from torch._logging import LazyString
65
+ from . import config
66
+
67
+ # NOTE: Make sure `NP_SUPPORTED_MODULES` and `NP_TO_TNP_MODULE` are in sync.
68
+ if np:
69
+ NP_SUPPORTED_MODULES: Tuple[types.ModuleType, ...] = (
70
+ np,
71
+ np.fft,
72
+ np.linalg,
73
+ np.random,
74
+ )
75
+
76
+ NP_TO_TNP_MODULE = {
77
+ np: tnp,
78
+ np.fft: tnp.fft,
79
+ np.linalg: tnp.linalg,
80
+ np.random: tnp.random,
81
+ }
82
+ else:
83
+ NP_SUPPORTED_MODULES = tuple()
84
+
85
+ NP_TO_TNP_MODULE = {}
86
+ from torch._subclasses.fake_tensor import FakeTensor, is_fake, maybe_get_fake_mode
87
+ except ImportError:
88
+ pass
89
+
90
+ import importlib
91
+
92
+ import torch
93
+ import torch._functorch.config
94
+ import torch.fx.experimental.symbolic_shapes
95
+ from torch import fx
96
+ from torch._dispatch.python import enable_python_dispatcher
97
+ from torch._utils_internal import log_compilation_event
98
+
99
+ from torch.nn.modules.lazy import LazyModuleMixin
100
+ from torch.utils._pytree import tree_map_only
101
+
102
+
103
+ counters: DefaultDict[str, Counter[str]] = collections.defaultdict(collections.Counter)
104
+ optimus_scuba_log: Dict[str, Any] = {}
105
+ troubleshooting_url = "https://pytorch.org/docs/master/compile/troubleshooting.html"
106
+ nnmodule_doc_url = "https://pytorch.org/docs/master/compile/nn-module.html"
107
+ nnmodule_doc_url_msg = f"See {nnmodule_doc_url} for more information and limitations."
108
+ log = logging.getLogger(__name__)
109
+
110
+ # profiling compilation time by function
111
+ compilation_time_metrics: Dict[str, List[float]] = {}
112
+
113
+ # profiling compilation time by frame phase
114
+ frame_phase_timing: Dict[str, Dict[str, float]] = {}
115
+
116
+ timer_counter = itertools.count()
117
+
118
+
119
+ def tabulate(rows, headers):
120
+ try:
121
+ import tabulate
122
+
123
+ return tabulate.tabulate(rows, headers=headers)
124
+ except ImportError:
125
+ return "\n".join(
126
+ ", ".join(map(str, row)) for row in itertools.chain([headers], rows)
127
+ )
128
+
129
+
130
+ def maybe_cprofile(func):
131
+ if config.cprofile:
132
+ return cprofile_wrapper(func)
133
+ return func
134
+
135
+
136
+ def cprofile_wrapper(func):
137
+ @wraps(func)
138
+ def profile_wrapper(*args, **kwargs):
139
+ global timer_counter
140
+ profile_cnt = next(timer_counter)
141
+ profile_path = Path(func.__name__ + f"{profile_cnt}.profile")
142
+ prof = cProfile.Profile()
143
+ prof.enable()
144
+ start_ts = time.time()
145
+ retval = prof.runcall(func, *args, **kwargs)
146
+ profile_latency = time.time() - start_ts
147
+ prof.disable()
148
+ print(
149
+ f"### Cprofile for {func.__name__} iter {profile_cnt} took {profile_latency:.3f} seconds ###"
150
+ )
151
+ ps = pstats.Stats(prof)
152
+ prof.dump_stats(profile_path)
153
+ svg_path = profile_path.with_suffix(".svg")
154
+ try:
155
+ gprof2dot_process = subprocess.Popen(
156
+ [
157
+ "gprof2dot",
158
+ "-f",
159
+ "pstats",
160
+ "--node-label=total-time-percentage",
161
+ "--node-label=self-time-percentage",
162
+ "--node-label=total-time",
163
+ str(profile_path),
164
+ ],
165
+ stdout=subprocess.PIPE,
166
+ )
167
+ subprocess.check_call(
168
+ ["dot", "-Tsvg", "-o", str(svg_path)],
169
+ stdin=gprof2dot_process.stdout,
170
+ )
171
+ print(f"Generated SVG from profile at {str(svg_path)}")
172
+ except FileNotFoundError:
173
+ print(
174
+ "Failed to generate SVG from profile -- dumping stats instead."
175
+ "Try installing gprof2dot and dot for a better visualization"
176
+ )
177
+ ps.sort_stats(pstats.SortKey.TIME).print_stats(20)
178
+ ps.sort_stats(pstats.SortKey.CUMULATIVE).print_stats(20)
179
+ return retval
180
+
181
+ return profile_wrapper
182
+
183
+
184
+ curr_frame = 0
185
+
186
+
187
+ # Note: Called for you by dynamo - you almost never ever want to invoke this yourself.
188
+ def increment_frame():
189
+ global curr_frame
190
+ curr_frame = curr_frame + 1
191
+
192
+
193
+ # Note: Called for you by dynamo - you almost never ever want to invoke this yourself.
194
+ def reset_frame_count():
195
+ global curr_frame
196
+ frame_phase_timing.clear()
197
+ compilation_time_metrics.clear()
198
+ curr_frame = 0
199
+
200
+
201
+ op_count = 0
202
+
203
+
204
+ def increment_op_count(cnt):
205
+ global op_count
206
+ op_count += cnt
207
+
208
+
209
+ # Print a report of time spent so far
210
+ # Ex:
211
+ # TIMING:
212
+ # entire_frame_compile:8.574629999999999
213
+ # backend_compile:5.26806
214
+ def print_time_report():
215
+ total = 0.0
216
+ total_by_key = {}
217
+ for timings in frame_phase_timing.values():
218
+ for key, timing in timings.items():
219
+ total += timing
220
+ if key not in total_by_key:
221
+ total_by_key[key] = timing
222
+ else:
223
+ total_by_key[key] += timing
224
+
225
+ out = "TIMING:"
226
+ for key, value in total_by_key.items():
227
+ out = f"{out} {key}:{round(value, 5)}"
228
+
229
+ print(out)
230
+
231
+
232
+ # dynamo_timed API works as a function decorator
233
+ # By wrapping a function in dynamo_timed, we can store a record in compilation_time_metrics
234
+ # where the key is the functions name.
235
+ # For example:
236
+ #
237
+ # @dynamo_timed
238
+ # def _foo(...):
239
+ #
240
+ # Would show up as an entry in our timing dict:
241
+ # OrderedDict([('bar.<locals>._foo', [0.083690, 0.23949, 3.1425e-05])])
242
+ # This is extremely useful for granular debugging.
243
+ #
244
+ # For a higher-level mode, pass a phase_name into dynamo_timed
245
+ # phase_names record an extra record into a separate compilation timing structure,
246
+ # one keyed on frame+name rather than function.
247
+ # The frame is incremented outside of this function, in def increment_frame() above.
248
+
249
+
250
+ def dynamo_timed(original_function=None, phase_name=None):
251
+ def dynamo_timed_inner(func):
252
+ if config.cprofile:
253
+ return func
254
+
255
+ @wraps(func)
256
+ def time_wrapper(*args, **kwargs):
257
+ key = func.__qualname__
258
+ if key not in compilation_time_metrics:
259
+ compilation_time_metrics[key] = []
260
+ with torch.profiler.record_function(f"{key} (dynamo_timed)"):
261
+ t0 = time.time()
262
+ r = func(*args, **kwargs)
263
+ time_spent = time.time() - t0
264
+ compilation_time_metrics[key].append(time_spent)
265
+ if phase_name:
266
+ frame_key = str(curr_frame)
267
+ if frame_key not in frame_phase_timing:
268
+ frame_phase_timing[frame_key] = {}
269
+ if phase_name not in frame_phase_timing[frame_key]:
270
+ frame_phase_timing[frame_key][phase_name] = time_spent
271
+ else:
272
+ frame_phase_timing[frame_key][phase_name] += time_spent
273
+ return r
274
+
275
+ return time_wrapper
276
+
277
+ if original_function:
278
+ return dynamo_timed_inner(original_function)
279
+ return dynamo_timed_inner
280
+
281
+
282
+ def compile_times(repr="str", aggregate=False):
283
+ """
284
+ Get metrics about torchdynamo frontend/backend compilation times.
285
+
286
+ Accumulates information from functions tagged with `@dynamo_timed`.
287
+
288
+ repr='str' returns a printable string for user interaction, and 'csv'
289
+ returns headers, rows which can be logged for output
290
+
291
+ aggregate causes values from multiple compilations (e.g. split graphs)
292
+ to be accumulated into one value. If false, expect more than one value
293
+ per metric.
294
+ """
295
+
296
+ def fmt_fn(values, item_fn=lambda x: x):
297
+ if aggregate:
298
+ return item_fn(sum(values))
299
+ return ", ".join(map(item_fn, values))
300
+
301
+ if repr == "str":
302
+ rows = [
303
+ (k, fmt_fn(compilation_time_metrics[k], item_fn=lambda x: f"{x:.4f}"))
304
+ for k in compilation_time_metrics
305
+ ]
306
+ out = "TorchDynamo compilation metrics:\n"
307
+ out += tabulate(rows, headers=("Function", "Runtimes (s)"))
308
+ return out
309
+ elif repr == "csv":
310
+ values = [
311
+ fmt_fn(v, item_fn=lambda x: f"{x:.6f}")
312
+ for v in compilation_time_metrics.values()
313
+ ]
314
+ headers = list(compilation_time_metrics.keys())
315
+ return headers, values
316
+
317
+
318
+ @atexit.register
319
+ def dump_compile_times():
320
+ log.info(compile_times(repr="str", aggregate=True))
321
+
322
+
323
+ tensortype_to_dtype = {
324
+ torch.FloatTensor: (torch.float32, torch.float),
325
+ torch.DoubleTensor: (torch.float64, torch.double),
326
+ torch.HalfTensor: (torch.float16, torch.half),
327
+ torch.BFloat16Tensor: (torch.bfloat16,),
328
+ torch.ByteTensor: (torch.uint8,),
329
+ torch.CharTensor: (torch.int8,),
330
+ torch.LongTensor: (torch.int64, torch.long),
331
+ torch.IntTensor: (torch.int32, torch.int),
332
+ torch.ShortTensor: (torch.int16, torch.short),
333
+ torch.BoolTensor: (torch.bool,),
334
+ }
335
+
336
+
337
+ class DuplicateWarningChecker:
338
+ def __init__(self, maxsize=4096):
339
+ self.maxsize = maxsize
340
+ self.reset()
341
+
342
+ def reset(self):
343
+ self.set = collections.OrderedDict()
344
+
345
+ def add(self, key):
346
+ if key in self.set:
347
+ self.set.move_to_end(key, last=True)
348
+ if not config.verbose:
349
+ return False
350
+ else:
351
+ self.set[key] = None
352
+ while len(self.set) > self.maxsize:
353
+ self.set.popitem(last=False)
354
+ return True
355
+
356
+
357
+ graph_break_dup_warning_checker = DuplicateWarningChecker()
358
+
359
+
360
+ def setup_compile_debug():
361
+ compile_debug = os.environ.get("TORCH_COMPILE_DEBUG", "0") == "1"
362
+
363
+ if compile_debug:
364
+ torch._logging.set_logs(
365
+ dynamo=logging.DEBUG,
366
+ aot=logging.DEBUG,
367
+ inductor=logging.DEBUG,
368
+ output_code=True, # this is off by default
369
+ )
370
+ return add_file_handler()
371
+
372
+ return contextlib.ExitStack()
373
+
374
+
375
+ def reset_graph_break_dup_checker():
376
+ graph_break_dup_warning_checker.reset()
377
+
378
+
379
+ def add_file_handler():
380
+ log_path = os.path.join(get_debug_dir(), "torchdynamo")
381
+ os.makedirs(log_path, exist_ok=True)
382
+
383
+ log_file_handler = logging.FileHandler(os.path.join(log_path, "debug.log"))
384
+ logger = logging.getLogger("torch._dynamo")
385
+ logger.addHandler(log_file_handler)
386
+
387
+ exitstack = contextlib.ExitStack()
388
+ exitstack.callback(lambda: logger.removeHandler(log_file_handler))
389
+ return exitstack
390
+
391
+
392
+ def setup_log_file():
393
+ exitstack = contextlib.ExitStack()
394
+ if config.log_file_name is not None:
395
+ log_file_handler = logging.FileHandler(config.log_file_name)
396
+ for logger in torch._logging._internal.get_loggers():
397
+ logger.addHandler(log_file_handler)
398
+ exitstack.callback(lambda: logger.removeHandler(log_file_handler))
399
+ return exitstack
400
+
401
+ return exitstack
402
+
403
+
404
+ def gen_record_file_name(exc, code):
405
+ return f"{get_debug_dir()}/error_recordings/\
406
+ {code.co_name}_{type(exc).__name__}_{code.co_firstlineno}.rec"
407
+
408
+
409
+ def write_record_to_file(filename, exec_record):
410
+ try:
411
+ if os.path.exists(filename):
412
+ log.warning(
413
+ "Unable to write execution record %s; file already exists.", filename
414
+ )
415
+ else:
416
+ os.makedirs(os.path.dirname(filename), exist_ok=True)
417
+ with open(filename, "wb") as f:
418
+ exec_record.dump(f)
419
+ except Exception:
420
+ log.exception("Unable to write execution record %s", filename)
421
+
422
+
423
+ def count_calls(g: fx.Graph):
424
+ c = 0
425
+ for n in g.nodes:
426
+ if "call" in n.op:
427
+ c += 1
428
+ return c
429
+
430
+
431
+ def identity(x):
432
+ return x
433
+
434
+
435
+ def hashable(x):
436
+ try:
437
+ hash(x)
438
+ return True
439
+ except TypeError:
440
+ return False
441
+ # cannot hash writable memoryview object
442
+ except ValueError:
443
+ return False
444
+
445
+
446
+ def nothing(*args, **kwargs):
447
+ pass
448
+
449
+
450
+ class ExactWeakKeyDictionary:
451
+ """Similar to weakref.WeakKeyDictionary, but use `is`/`id` rather than `==` to compare equality"""
452
+
453
+ def __init__(self):
454
+ self.values = dict()
455
+ self.refs = dict()
456
+
457
+ def __getitem__(self, key):
458
+ return self.values[id(key)]
459
+
460
+ def get(self, key, default=None):
461
+ return self.values.get(id(key), default)
462
+
463
+ def __contains__(self, key):
464
+ return id(key) in self.values
465
+
466
+ def __setitem__(self, key, value):
467
+ idx = id(key)
468
+ if idx not in self.refs:
469
+ self.refs[idx] = weakref.ref(key, lambda ref: self._remove_id(idx))
470
+ self.values[idx] = value
471
+
472
+ def _remove_id(self, idx):
473
+ if idx in self.values:
474
+ del self.values[idx]
475
+ if idx in self.refs:
476
+ del self.refs[idx]
477
+
478
+ def clear(self):
479
+ self.refs.clear()
480
+ self.values.clear()
481
+
482
+
483
+ def istype(obj, allowed_types):
484
+ """isinstance() without subclasses"""
485
+ if isinstance(allowed_types, (tuple, list, set)):
486
+ return type(obj) in allowed_types
487
+ return type(obj) is allowed_types
488
+
489
+
490
+ def is_typing(value):
491
+ # _Final catches most of typing classes:
492
+ # - Any
493
+ # - Callable
494
+ # - Union
495
+ # ...
496
+ #
497
+ # NB: we intentionally ignore classes that inherit from Generic, since they
498
+ # can be used as both TypingVariable as well as UserDefinedClassVariable.
499
+ return isinstance(value, typing._Final) or value is typing.Generic # type: ignore[attr-defined]
500
+
501
+
502
+ def is_numpy_int_type(value):
503
+ if not np:
504
+ return False
505
+
506
+ return istype(
507
+ value,
508
+ (
509
+ np.int8,
510
+ np.int16,
511
+ np.int32,
512
+ np.int64,
513
+ np.uint8,
514
+ np.uint16,
515
+ np.uint32,
516
+ np.uint64,
517
+ ),
518
+ )
519
+
520
+
521
+ def is_numpy_float_type(value):
522
+ if not np:
523
+ return False
524
+
525
+ return istype(
526
+ value,
527
+ (
528
+ np.float16,
529
+ np.float32,
530
+ np.float64,
531
+ ),
532
+ )
533
+
534
+
535
+ def is_function_or_wrapper(value):
536
+ return (
537
+ is_function(value)
538
+ or isinstance(value, functools._lru_cache_wrapper)
539
+ and is_function(inspect.getattr_static(value, "__wrapped__"))
540
+ or isinstance(value, (torch._ops.OpOverloadPacket, torch._ops.OpOverload))
541
+ )
542
+
543
+
544
+ def is_function(value):
545
+ return isinstance(
546
+ value,
547
+ (
548
+ types.FunctionType,
549
+ types.BuiltinFunctionType,
550
+ types.MethodDescriptorType,
551
+ types.WrapperDescriptorType,
552
+ torch.jit.ScriptFunction,
553
+ ),
554
+ )
555
+
556
+
557
+ def unwrap_if_wrapper(fn):
558
+ return unwrap_with_attr_name_if_wrapper(fn)[0]
559
+
560
+
561
+ def unwrap_with_attr_name_if_wrapper(fn):
562
+ # unpack @functools.lru_cache wrapped function
563
+ if isinstance(fn, functools._lru_cache_wrapper):
564
+ fn = inspect.getattr_static(fn, "__wrapped__")
565
+ attr_name = "__wrapped__"
566
+ # unpack @torch._dynamo.optimize()(fn) wrapped function
567
+ elif is_function(fn) and inspect.getattr_static(fn, "_torchdynamo_inline", False):
568
+ fn = inspect.getattr_static(fn, "_torchdynamo_inline", fn)
569
+ attr_name = "_torchdynamo_inline"
570
+ # unpack torch.jit.script_if_tracing
571
+ elif is_function(fn) and inspect.getattr_static(
572
+ fn, "__script_if_tracing_wrapper", False
573
+ ):
574
+ fn = inspect.getattr_static(fn, "__original_fn", fn)
575
+ attr_name = "__original_fn"
576
+ else:
577
+ attr_name = None
578
+ return fn, attr_name
579
+
580
+
581
+ def is_numpy_ndarray(value):
582
+ if not np:
583
+ return False
584
+
585
+ return istype(value, np.ndarray)
586
+
587
+
588
+ def istensor(obj):
589
+ """Check of obj is a tensor"""
590
+ tensor_list = (
591
+ torch.Tensor,
592
+ torch.nn.Parameter,
593
+ *config.traceable_tensor_subclasses,
594
+ )
595
+ tensor_list = tensor_list + (torch._subclasses.FakeTensor,)
596
+ return istype(obj, tensor_list)
597
+
598
+
599
+ def is_lazy_module(mod):
600
+ return isinstance(mod, LazyModuleMixin)
601
+
602
+
603
+ @functools.lru_cache(4096)
604
+ def print_once(*args):
605
+ print(*args)
606
+
607
+
608
+ def make_cell(val=None):
609
+ """Some black magic to create a cell object that usually only exists in a closure"""
610
+ x = val
611
+
612
+ def f():
613
+ return x
614
+
615
+ assert f.__closure__ is not None and len(f.__closure__) == 1
616
+ return f.__closure__[0]
617
+
618
+
619
+ def proxy_args_kwargs(args, kwargs):
620
+ try:
621
+ proxy_args = tuple(arg.as_proxy() for arg in args)
622
+ proxy_kwargs = {key: arg.as_proxy() for key, arg in kwargs.items()}
623
+ return proxy_args, proxy_kwargs
624
+ except NotImplementedError as e:
625
+ from .exc import unimplemented
626
+ from .variables.base import typestr
627
+
628
+ raise unimplemented(
629
+ f"call_function args: {typestr(*args)} {typestr(*list(kwargs.values()))}"
630
+ ) from e
631
+
632
+
633
+ @dataclasses.dataclass
634
+ class CompilationMetrics:
635
+ frame_key: str
636
+ co_name: str
637
+ co_filename: str
638
+ co_firstlineno: int
639
+ cache_size: int
640
+ accumulated_cache_size: int
641
+ guard_count: Optional[int]
642
+ shape_env_guard_count: Optional[int]
643
+ graph_op_count: Optional[int]
644
+ graph_node_count: Optional[int]
645
+ graph_input_count: Optional[int]
646
+ start_time: float
647
+ entire_frame_compile_time_s: Optional[float]
648
+ backend_compile_time_s: Optional[float]
649
+ inductor_compile_time_s: Optional[float]
650
+ code_gen_time_s: Optional[float]
651
+ fail_type: Optional[str]
652
+ fail_reason: Optional[str]
653
+ fail_user_frame_filename: Optional[str]
654
+ fail_user_frame_lineno: Optional[int]
655
+ non_compliant_ops: Set[str]
656
+ compliant_custom_ops: Set[str]
657
+
658
+
659
+ DEFAULT_COMPILATION_METRICS_LIMIT = 64
660
+
661
+
662
+ _compilation_metrics: Deque[CompilationMetrics] = collections.deque(
663
+ maxlen=DEFAULT_COMPILATION_METRICS_LIMIT
664
+ )
665
+
666
+
667
+ def record_compilation_metrics(compilation_metrics: CompilationMetrics):
668
+ global _compilation_metrics
669
+ _compilation_metrics.append(compilation_metrics)
670
+ if config.log_compilation_metrics:
671
+ log_compilation_event(compilation_metrics)
672
+
673
+
674
+ def set_compilation_metrics_limit(new_size: int) -> None:
675
+ global _compilation_metrics
676
+ while len(_compilation_metrics) > new_size:
677
+ _compilation_metrics.popleft()
678
+ new_deque = collections.deque(_compilation_metrics, maxlen=new_size)
679
+ _compilation_metrics = new_deque
680
+
681
+
682
+ def clear_compilation_metrics() -> None:
683
+ global _compilation_metrics
684
+ _compilation_metrics.clear()
685
+
686
+
687
+ def get_compilation_metrics() -> List[CompilationMetrics]:
688
+ return list(_compilation_metrics)
689
+
690
+
691
+ @dataclasses.dataclass
692
+ class CleanupHook:
693
+ """Remove a global variable when hook is called"""
694
+
695
+ scope: Dict[str, Any]
696
+ name: str
697
+
698
+ def __call__(self, *args):
699
+ CleanupManager.count -= 1
700
+ del self.scope[self.name]
701
+
702
+ @staticmethod
703
+ def create(scope, name, val):
704
+ assert name not in scope
705
+ CleanupManager.count += 1
706
+ scope[name] = val
707
+ return CleanupHook(scope, name)
708
+
709
+
710
+ class CleanupManager(ExactWeakKeyDictionary):
711
+ count = 0
712
+ instance: ClassVar["CleanupManager"]
713
+
714
+ def _remove_id(self, idx):
715
+ for hook in self.values[idx]:
716
+ hook()
717
+ super()._remove_id(idx)
718
+
719
+
720
+ CleanupManager.instance = CleanupManager()
721
+
722
+
723
+ def clone_tensor(x):
724
+ """Clone the tensor and its gradient"""
725
+ y = x.clone().requires_grad_(x.requires_grad)
726
+ if x.is_leaf and x.grad is not None:
727
+ y.grad = x.grad.clone()
728
+ return y
729
+
730
+
731
+ def clone_input(x, *, dtype=None):
732
+ """copy while preserving strides"""
733
+ # TODO: this is questionable
734
+ if is_fake(x):
735
+ # this func fails on fake tensors in __torch_dispatch__
736
+ return x
737
+
738
+ def torch_clone(x):
739
+ y = torch.clone(x)
740
+ if x.is_leaf:
741
+ y.requires_grad_(x.requires_grad)
742
+ if x.is_leaf and x.grad is not None:
743
+ y.grad = clone_input(x.grad, dtype=dtype)
744
+ if hasattr(x, "_dynamo_dynamic_indices"):
745
+ y._dynamo_dynamic_indices = x._dynamo_dynamic_indices.copy() # type: ignore[attr-defined]
746
+ return y
747
+
748
+ with torch.no_grad():
749
+ if x.device.type == "xla":
750
+ # Access data_ptr() for a xla tensor will cause crash
751
+ return torch_clone(x)
752
+
753
+ needed_size = sum(
754
+ (shape - 1) * stride for shape, stride in zip(x.size(), x.stride())
755
+ )
756
+ if x.is_quantized:
757
+ result = torch.empty_quantized((needed_size + 32,), x)
758
+ else:
759
+ result = torch.empty(
760
+ needed_size + 32, dtype=dtype or x.dtype, device=x.device
761
+ )
762
+ cache_line_offset = (
763
+ (x.data_ptr() - result.data_ptr()) % 32
764
+ ) // x.element_size()
765
+ result.as_strided_(x.size(), x.stride(), cache_line_offset)
766
+ try:
767
+ result.copy_(x.clone())
768
+ if x.is_leaf:
769
+ result.requires_grad_(x.requires_grad)
770
+ if x.is_leaf and x.grad is not None:
771
+ result.grad = clone_input(x.grad, dtype=dtype)
772
+ except RuntimeError:
773
+ # RuntimeError: unsupported operation: more than one element of the written-to
774
+ # tensor refers to a single memory location. Please clone() the tensor before
775
+ # performing the operation.
776
+ return torch_clone(x)
777
+ if hasattr(x, "_dynamo_dynamic_indices"):
778
+ result._dynamo_dynamic_indices = x._dynamo_dynamic_indices.copy() # type: ignore[attr-defined]
779
+ return result
780
+
781
+
782
+ def clone_inputs(example_inputs):
783
+ res: Union[Dict[Any, Any], List[Any]]
784
+ if type(example_inputs) is dict:
785
+ res = dict(example_inputs)
786
+ for key, value in res.items():
787
+ if isinstance(value, tuple):
788
+ res[key] = clone_inputs(value)
789
+ else:
790
+ assert isinstance(value, torch.Tensor), type(value)
791
+ res[key] = clone_input(value)
792
+ return res
793
+
794
+ res = list(example_inputs)
795
+ for i in range(len(res)):
796
+ if isinstance(res[i], torch.Tensor):
797
+ res[i] = clone_input(res[i])
798
+ return res
799
+
800
+
801
+ def skip_frame_if_in_functorch_mode(val: torch.Tensor):
802
+ try:
803
+ val.data_ptr() # will throw for functorch tensors
804
+ except RuntimeError as e:
805
+ from .exc import SkipFrame
806
+
807
+ # This will be GradTrackingTensor/BatchedTensor/etc
808
+ functorch_subclass_name = re.sub(r"\(.*", "", repr(val))
809
+ raise SkipFrame(
810
+ f"torch.compile cannot be run in context: {functorch_subclass_name}"
811
+ ) from e
812
+
813
+
814
+ @contextmanager
815
+ def preserve_rng_state():
816
+ disable_functorch = torch._C._DisableFuncTorch
817
+ disable_current_modes = torch.utils._python_dispatch._disable_current_modes
818
+ with disable_current_modes(), disable_functorch():
819
+ rng_state = torch.clone(torch.random.get_rng_state())
820
+ skip_frame_if_in_functorch_mode(rng_state)
821
+ if torch.cuda.is_available():
822
+ cuda_rng_state = torch.clone(torch.cuda.get_rng_state())
823
+ try:
824
+ yield
825
+ finally:
826
+ with torch.utils._python_dispatch._disable_current_modes():
827
+ torch.random.set_rng_state(rng_state)
828
+ if torch.cuda.is_available():
829
+ torch.cuda.set_rng_state(cuda_rng_state) # type: ignore[possibly-undefined]
830
+
831
+
832
+ def is_jit_model(model0):
833
+ return isinstance(
834
+ model0,
835
+ (
836
+ torch.jit._trace.TopLevelTracedModule,
837
+ torch.jit._script.RecursiveScriptModule,
838
+ torch.jit.ScriptFunction,
839
+ torch.jit.ScriptModule,
840
+ ),
841
+ )
842
+
843
+
844
+ def torchscript(model, example_inputs, verbose=False):
845
+ if is_jit_model(model):
846
+ # already done?
847
+ return model
848
+
849
+ try:
850
+ return torch.jit.trace(model, example_inputs)
851
+ except Exception:
852
+ try:
853
+ return torch.jit.script(model)
854
+ except Exception:
855
+ if verbose:
856
+ log.exception("jit error")
857
+ else:
858
+ log.error("Both torch.jit.trace and torch.jit.script failed")
859
+ return None
860
+
861
+
862
+ def getfile(obj):
863
+ try:
864
+ return inspect.getfile(obj)
865
+ except (TypeError, OSError):
866
+ return None
867
+
868
+
869
+ def is_namedtuple(obj):
870
+ """Test if an object is a namedtuple or a torch.return_types.* quasi-namedtuple"""
871
+ return is_namedtuple_cls(type(obj))
872
+
873
+
874
+ def is_namedtuple_cls(cls):
875
+ """Test if an object is a namedtuple or a torch.return_types.* quasi-namedtuple"""
876
+ try:
877
+ if issubclass(cls, tuple):
878
+ bases = getattr(cls, "__bases__", []) or [None]
879
+ module = getattr(cls, "__module__", None)
880
+ return module == "torch.return_types" or (
881
+ bases[0] is tuple and hasattr(cls, "_make") and hasattr(cls, "_fields")
882
+ )
883
+ except TypeError:
884
+ pass
885
+ return False
886
+
887
+
888
+ @functools.lru_cache(1)
889
+ def namedtuple_fields(cls):
890
+ """Get the fields of a namedtuple or a torch.return_types.* quasi-namedtuple"""
891
+ if cls is slice:
892
+ return ["start", "stop", "step"]
893
+
894
+ assert issubclass(cls, tuple)
895
+ if hasattr(cls, "_fields"):
896
+ # normal namedtuples
897
+ return cls._fields
898
+
899
+ @dataclasses.dataclass
900
+ class Marker:
901
+ index: int
902
+
903
+ # frustrating ones e.g. torch.return_types.max
904
+ assert cls.__module__ == "torch.return_types"
905
+ obj = cls(map(Marker, range(cls.n_fields)))
906
+ fields: List[Optional[str]] = [None] * cls.n_fields
907
+ for name in dir(obj):
908
+ if name[0] != "_" and isinstance(getattr(obj, name), Marker):
909
+ fields[getattr(obj, name).index] = name
910
+ return fields
911
+
912
+
913
+ def checkpoint_params(gm):
914
+ with torch.no_grad():
915
+ rng_state = torch.clone(torch.random.get_rng_state())
916
+ if torch.cuda.is_available():
917
+ cuda_rng_state = torch.clone(torch.cuda.get_rng_state())
918
+ saved_state = []
919
+ for param in itertools.chain(gm.parameters(), gm.buffers()):
920
+ saved_state.append((param, param._version, torch.clone(param)))
921
+
922
+ def restore():
923
+ with torch.no_grad():
924
+ torch.random.set_rng_state(rng_state)
925
+ if torch.cuda.is_available():
926
+ torch.cuda.set_rng_state(cuda_rng_state)
927
+ for param, version, original_value in saved_state:
928
+ if param._version != version:
929
+ param.copy_(original_value)
930
+
931
+ return restore
932
+
933
+
934
+ def timed(model, example_inputs, times=1):
935
+ if torch.cuda.is_available():
936
+ synchronize = torch.cuda.synchronize
937
+ else:
938
+ synchronize = nothing
939
+
940
+ synchronize()
941
+ gc.collect()
942
+ torch.manual_seed(1337)
943
+ t0 = time.perf_counter()
944
+ for _ in range(times):
945
+ result = model(*example_inputs)
946
+ synchronize()
947
+ t1 = time.perf_counter()
948
+ return result, t1 - t0 # type: ignore[possibly-undefined]
949
+
950
+
951
+ def check_is_cuda(gm, example_inputs):
952
+ return all(x.is_cuda for x in itertools.chain(example_inputs, gm.parameters(True)))
953
+
954
+
955
+ @lru_cache(32)
956
+ def rot_n_helper(n):
957
+ assert n > 1
958
+ vars = [f"v{i}" for i in range(n)]
959
+ rotated = reversed(vars[-1:] + vars[:-1])
960
+ fn = eval(f"lambda {','.join(vars)}: ({','.join(rotated)})")
961
+ fn.__name__ = f"rot_{n}_helper"
962
+ return fn
963
+
964
+
965
+ common_constant_types = {
966
+ int,
967
+ float,
968
+ complex,
969
+ bool,
970
+ str,
971
+ bytes,
972
+ type(None),
973
+ Ellipsis.__class__,
974
+ types.CodeType,
975
+ torch.device,
976
+ torch.dtype,
977
+ torch.memory_format,
978
+ torch.layout,
979
+ }
980
+
981
+
982
+ def is_safe_constant(v):
983
+ if istype(v, (tuple, frozenset)):
984
+ return all(map(is_safe_constant, v))
985
+ return isinstance(v, (enum.Enum, type)) or istype(
986
+ v,
987
+ common_constant_types | {slice},
988
+ )
989
+
990
+
991
+ def specialize_symnode(arg):
992
+ from .variables import ConstantVariable, SymNodeVariable
993
+
994
+ # Guard and specialize
995
+ if isinstance(arg, SymNodeVariable):
996
+ return ConstantVariable.create(arg.evaluate_expr())
997
+
998
+ return arg
999
+
1000
+
1001
+ def guard_if_dyn(arg):
1002
+ from .variables import ConstantVariable
1003
+
1004
+ arg = specialize_symnode(arg)
1005
+
1006
+ if isinstance(arg, ConstantVariable):
1007
+ return arg.as_python_constant()
1008
+
1009
+ return arg
1010
+
1011
+
1012
+ def check_constant_args(args, kwargs):
1013
+ return all(x.is_python_constant() for x in itertools.chain(args, kwargs.values()))
1014
+
1015
+
1016
+ def check_unspec_python_args(args, kwargs):
1017
+ from .variables.constant import ConstantVariable
1018
+ from .variables.tensor import UnspecializedPythonVariable
1019
+
1020
+ unspec_count = 0
1021
+ for x in itertools.chain(args, kwargs.values()):
1022
+ if isinstance(x, UnspecializedPythonVariable):
1023
+ unspec_count += 1
1024
+ elif not isinstance(x, (UnspecializedPythonVariable, ConstantVariable)):
1025
+ return False
1026
+ else:
1027
+ pass
1028
+
1029
+ return unspec_count > 0
1030
+
1031
+
1032
+ def check_numpy_ndarray_args(args, kwargs):
1033
+ from .variables.tensor import NumpyNdarrayVariable
1034
+
1035
+ return any(
1036
+ isinstance(x, NumpyNdarrayVariable)
1037
+ for x in itertools.chain(args, kwargs.values())
1038
+ )
1039
+
1040
+
1041
+ dict_keys: Type[KeysView[Any]] = type(dict().keys())
1042
+ dict_values: Type[ValuesView[Any]] = type(dict().values())
1043
+ odict_values: Type[ValuesView[Any]] = type(collections.OrderedDict().values())
1044
+ tuple_iterator: Type[Iterator[Any]] = type(iter(tuple()))
1045
+ tuple_iterator_len = tuple_iterator.__length_hint__ # type: ignore[attr-defined]
1046
+ object_new = object.__new__
1047
+
1048
+
1049
+ def nn_module_new(cls):
1050
+ obj = object_new(cls)
1051
+ torch.nn.Module.__init__(obj)
1052
+ return obj
1053
+
1054
+
1055
+ def product(it):
1056
+ return functools.reduce(operator.mul, it, 1)
1057
+
1058
+
1059
+ def tuple_iterator_getitem(it, index):
1060
+ _, (obj,), start = it.__reduce__()
1061
+ return obj[start + index]
1062
+
1063
+
1064
+ iter_next = next
1065
+
1066
+
1067
+ def to_subclass(t, cls):
1068
+ return t.as_subclass(cls)
1069
+
1070
+
1071
+ def dict_keys_getitem(d, n):
1072
+ return next(itertools.islice(iter(d), n, n + 1))
1073
+
1074
+
1075
+ def enum_repr(value, local):
1076
+ # enum class can override __str__ method. Use __class__ and name attribute
1077
+ # to extract the class name and key name.
1078
+ name = value.__class__.__name__
1079
+ val = value.name
1080
+ scope = "L" if local else "G"
1081
+ local_name = f'{scope}["{name}"].{val}'
1082
+ return local_name
1083
+
1084
+
1085
+ def _get_fake_tensor(vt):
1086
+ fake_tensor = vt.as_proxy().node.meta.get("example_value")
1087
+ if not is_fake(fake_tensor):
1088
+ from .exc import unimplemented
1089
+
1090
+ unimplemented("Cannot check Tensor object identity without its fake value")
1091
+ return fake_tensor
1092
+
1093
+
1094
+ def iter_contains(items, search, tx, check_tensor_identity=False):
1095
+ from .variables import (
1096
+ BuiltinVariable,
1097
+ ConstantVariable,
1098
+ TensorVariable,
1099
+ VariableTracker,
1100
+ )
1101
+
1102
+ if search.is_python_constant():
1103
+ found_const = any(
1104
+ x.is_python_constant()
1105
+ and x.as_python_constant() == search.as_python_constant()
1106
+ for x in items
1107
+ )
1108
+ return ConstantVariable.create(found_const)
1109
+
1110
+ must_check_tensor_id = False
1111
+ if check_tensor_identity and isinstance(search, TensorVariable):
1112
+ must_check_tensor_id = True
1113
+ # Match of Tensor means match of FakeTensor
1114
+ search = _get_fake_tensor(search)
1115
+
1116
+ found: Optional[VariableTracker] = None
1117
+ for x in items:
1118
+ if must_check_tensor_id:
1119
+ if isinstance(x, TensorVariable):
1120
+ if search is _get_fake_tensor(x): # Object equivalence
1121
+ return ConstantVariable.create(True)
1122
+ else:
1123
+ check = BuiltinVariable(operator.eq).call_function(tx, [x, search], {})
1124
+ if found is None:
1125
+ found = check
1126
+ else:
1127
+ found = BuiltinVariable(operator.or_).call_function(
1128
+ tx, [check, found], {}
1129
+ )
1130
+ if found is None:
1131
+ found = ConstantVariable.create(False)
1132
+ return found
1133
+
1134
+
1135
+ def key_is_id(k):
1136
+ """Returns whether it indexes dictionaries using its id"""
1137
+ return isinstance(k, (torch.Tensor, torch.nn.Module, MethodWrapperType))
1138
+
1139
+
1140
+ def key_to_id(value):
1141
+ return [id(k) if key_is_id(k) else k for k in value.keys()]
1142
+
1143
+
1144
+ def const_repr(x, *, local) -> str:
1145
+ from .trace_rules import is_builtin_callable
1146
+
1147
+ if isinstance(x, (list, tuple)):
1148
+ elems_repr = ",".join(const_repr(s, local=local) for s in x)
1149
+ if isinstance(x, list):
1150
+ return f"[{elems_repr}]"
1151
+ else:
1152
+ assert isinstance(x, tuple)
1153
+ if len(x) == 1:
1154
+ return f"({elems_repr},)"
1155
+ else:
1156
+ return f"({elems_repr})"
1157
+ elif isinstance(x, enum.Enum):
1158
+ # To workaround repr(Enum) returning invalid global reference before python 3.11
1159
+ # by calling enum_repr and removing quotes to render enum in guard code.
1160
+ return enum_repr(x, local=local).replace("'", "")
1161
+ elif is_builtin_callable(x):
1162
+ return x.__name__
1163
+ elif isinstance(x, type):
1164
+
1165
+ def fullname(o):
1166
+ klass = o.__class__
1167
+ module = klass.__module__
1168
+ if module == "builtins":
1169
+ return klass.__qualname__ # avoid outputs like 'builtins.str'
1170
+ return module + "." + klass.__qualname__
1171
+
1172
+ return fullname(x)
1173
+ else:
1174
+ return f"{x!r}"
1175
+
1176
+
1177
+ def dict_keys_repr(const_keys, *, local) -> str:
1178
+ keys_str = ",".join(const_repr(s, local=local) for s in const_keys)
1179
+ return "[" + keys_str + "]"
1180
+
1181
+
1182
+ GLOBAL_KEY_PREFIX = "__dict_key"
1183
+
1184
+
1185
+ from torch._subclasses import UnsupportedFakeTensorException # noqa: F401
1186
+
1187
+
1188
+ def wrap_fake_exception(fn):
1189
+ try:
1190
+ return fn()
1191
+ except UnsupportedFakeTensorException as e:
1192
+ from .exc import unimplemented
1193
+
1194
+ msg = f"Unsupported: {e.reason} with fake tensor propagation."
1195
+ log.warning(msg)
1196
+ raise unimplemented(msg) from e
1197
+
1198
+
1199
+ def deepcopy_to_fake_tensor(obj, fake_mode):
1200
+ with torch._subclasses.fake_tensor.FakeCopyMode(fake_mode):
1201
+ return wrap_fake_exception(lambda: copy.deepcopy(obj))
1202
+
1203
+
1204
+ def rmse(ref, res):
1205
+ """
1206
+ Calculate root mean squared error
1207
+ """
1208
+ return torch.sqrt(torch.mean(torch.square(ref - res)))
1209
+
1210
+
1211
+ def same(
1212
+ ref,
1213
+ res,
1214
+ fp64_ref=None,
1215
+ cos_similarity=False,
1216
+ tol=1e-4,
1217
+ equal_nan=False,
1218
+ exact_dtype=True,
1219
+ relax_numpy_equality=False,
1220
+ ignore_non_fp=False,
1221
+ log_error=log.error,
1222
+ ):
1223
+ """Check correctness to see if ref and res match"""
1224
+ if fp64_ref is None:
1225
+ fp64_ref = ref
1226
+ if isinstance(ref, (list, tuple, torch.nn.ParameterList, torch.Size)):
1227
+ assert isinstance(res, (list, tuple)), f"type mismatch {type(ref)} {type(res)}"
1228
+ if len(ref) != len(res):
1229
+ log_error("Length mismatch")
1230
+ return False
1231
+ return len(ref) == len(res) and all(
1232
+ same(
1233
+ ai,
1234
+ bi,
1235
+ fp64_refi,
1236
+ cos_similarity,
1237
+ tol,
1238
+ equal_nan,
1239
+ exact_dtype,
1240
+ relax_numpy_equality,
1241
+ ignore_non_fp,
1242
+ log_error=log_error,
1243
+ )
1244
+ for ai, bi, fp64_refi in zip(ref, res, fp64_ref)
1245
+ )
1246
+ elif isinstance(ref, dict):
1247
+ assert isinstance(res, dict)
1248
+ assert set(ref.keys()) == set(
1249
+ res.keys()
1250
+ ), f"keys mismatch {set(ref.keys())} == {set(res.keys())}"
1251
+ for k in sorted(ref.keys()):
1252
+ if not (
1253
+ same(
1254
+ ref[k],
1255
+ res[k],
1256
+ fp64_ref[k],
1257
+ cos_similarity=cos_similarity,
1258
+ tol=tol,
1259
+ equal_nan=equal_nan,
1260
+ exact_dtype=exact_dtype,
1261
+ relax_numpy_equality=relax_numpy_equality,
1262
+ ignore_non_fp=ignore_non_fp,
1263
+ log_error=log_error,
1264
+ )
1265
+ ):
1266
+ log_error("Accuracy failed for key name %s", k)
1267
+ return False
1268
+ return True
1269
+ elif isinstance(ref, (torch.Tensor, float)):
1270
+ assert not isinstance(ref, torch._subclasses.FakeTensor)
1271
+ assert not isinstance(res, torch._subclasses.FakeTensor)
1272
+
1273
+ def to_tensor(t):
1274
+ return t if isinstance(t, torch.Tensor) else torch.tensor(t)
1275
+
1276
+ ref, res, fp64_ref = (to_tensor(val) for val in (ref, res, fp64_ref))
1277
+
1278
+ if ref.is_sparse:
1279
+ assert res.is_sparse
1280
+ ref = ref.to_dense()
1281
+ res = res.to_dense()
1282
+ assert isinstance(res, torch.Tensor), f"type mismatch {type(ref)} {type(res)}"
1283
+ if exact_dtype:
1284
+ if ref.dtype != res.dtype:
1285
+ log_error("dtype mismatch %s, %s", ref.dtype, res.dtype)
1286
+ return False
1287
+ if ref.dtype == torch.bool:
1288
+ if ignore_non_fp:
1289
+ return True
1290
+ # triton stores bool as int8, so add this for more accurate checking
1291
+ r = torch.allclose(
1292
+ ref.to(dtype=torch.uint8),
1293
+ res.to(dtype=torch.uint8),
1294
+ atol=tol,
1295
+ rtol=tol,
1296
+ equal_nan=equal_nan,
1297
+ )
1298
+ if not r:
1299
+ log_error("Accuracy failed: uint8 tensor did not match")
1300
+ return r
1301
+
1302
+ if cos_similarity:
1303
+ ref = ref.flatten().to(torch.float32)
1304
+ res = res.flatten().to(torch.float32)
1305
+ if torch.allclose(ref, res, atol=tol, rtol=tol, equal_nan=True):
1306
+ # early exit that handles zero/nan better
1307
+ # cosine_similarity(zeros(10), zeros(10), dim=0) is 0
1308
+ return True
1309
+ score = torch.nn.functional.cosine_similarity(ref, res, dim=0, eps=1e-6)
1310
+ if score < 0.99:
1311
+ log.warning("Similarity score=%s", score.cpu().detach().item())
1312
+ return score >= 0.99
1313
+ else:
1314
+ if not exact_dtype:
1315
+ ref = ref.to(res.dtype)
1316
+
1317
+ # First try usual allclose
1318
+ if torch.allclose(ref, res, atol=tol, rtol=tol, equal_nan=equal_nan):
1319
+ return True
1320
+
1321
+ # Check error from fp64 version
1322
+ if fp64_ref.dtype == torch.float64:
1323
+ ref_error = rmse(fp64_ref, ref).item()
1324
+ # ref unable to produce this with stable numerics in this precision, ignore
1325
+ if math.isnan(ref_error):
1326
+ log.warning(
1327
+ "Found nan in reference. Consider running in higher precision."
1328
+ )
1329
+
1330
+ res_error = rmse(fp64_ref, res).item()
1331
+
1332
+ # In the case of using AMP (Automatic Mixed Precision), certain models have
1333
+ # failed the benchmark's correctness check. However, the end-to-end model's
1334
+ # accuracy when comparing AMP with FP32 is within a difference of less than 0.1%.
1335
+ # Thus, it's possible that the correctness check failures for these models are
1336
+ # false alarms. We use multiplier of 3 instead of 2 to avoid these false alarms.
1337
+ multiplier = 3.0 if res.dtype == torch.bfloat16 else 2.0
1338
+
1339
+ if (
1340
+ fp64_ref.numel() < 1000
1341
+ or (ref.ndim == 4 and ref.shape[-1] == ref.shape[-2] == 1)
1342
+ # large tol means a benchmark has been specified as REQUIRE_HIGHER_TOLERANCE
1343
+ or tol >= 2 * 1e-2
1344
+ ):
1345
+ # In the presence of noise, noise might dominate our error
1346
+ # metric for smaller tensors.
1347
+ # Similary, for 1x1 kernels, there seems to be high noise with amp.
1348
+ multiplier = 3.0
1349
+
1350
+ passes_test = res_error <= (multiplier * ref_error + tol / 10.0)
1351
+ if not passes_test:
1352
+ log_error(
1353
+ "RMSE (res-fp64): %.5f, (ref-fp64): %.5f and shape=%s",
1354
+ res_error,
1355
+ ref_error,
1356
+ res.size(),
1357
+ )
1358
+ # import pdb; pdb.set_trace()
1359
+ return passes_test
1360
+
1361
+ if ignore_non_fp:
1362
+ return True
1363
+
1364
+ log_error("Accuracy failed: allclose not within tol=%s", tol)
1365
+ return False
1366
+ elif isinstance(ref, (str, int, type(None), bool, torch.device)):
1367
+ if ignore_non_fp:
1368
+ return True
1369
+ r = ref == res
1370
+ if not r:
1371
+ log_error("Accuracy failed (%s): %s != %s", type(ref), ref, res)
1372
+ return r
1373
+ elif is_numpy_int_type(ref) or is_numpy_float_type(ref):
1374
+ if relax_numpy_equality and not (
1375
+ is_numpy_int_type(res) or is_numpy_float_type(res)
1376
+ ):
1377
+ ref = ref.item()
1378
+ r = (type(ref) is type(res)) and (ref == res)
1379
+ if not r:
1380
+ log_error("Accuracy failed (numpy): %s != %s", ref, res)
1381
+ return r
1382
+ elif is_numpy_ndarray(ref):
1383
+ return (type(ref) is type(res)) and same(
1384
+ torch.as_tensor(ref),
1385
+ torch.as_tensor(res),
1386
+ fp64_ref,
1387
+ cos_similarity=cos_similarity,
1388
+ tol=tol,
1389
+ equal_nan=equal_nan,
1390
+ exact_dtype=exact_dtype,
1391
+ relax_numpy_equality=relax_numpy_equality,
1392
+ ignore_non_fp=ignore_non_fp,
1393
+ log_error=log_error,
1394
+ )
1395
+ elif type(ref).__name__ in (
1396
+ "MaskedLMOutput",
1397
+ "Seq2SeqLMOutput",
1398
+ "CausalLMOutputWithCrossAttentions",
1399
+ "LongformerMaskedLMOutput",
1400
+ "Instances",
1401
+ "SquashedNormal",
1402
+ "Boxes",
1403
+ "Normal",
1404
+ "TanhTransform",
1405
+ "Foo",
1406
+ "Variable",
1407
+ ):
1408
+ assert type(ref) is type(res)
1409
+ return all(
1410
+ same(
1411
+ getattr(ref, key),
1412
+ getattr(res, key),
1413
+ getattr(fp64_ref, key),
1414
+ cos_similarity=cos_similarity,
1415
+ tol=tol,
1416
+ equal_nan=equal_nan,
1417
+ exact_dtype=exact_dtype,
1418
+ relax_numpy_equality=relax_numpy_equality,
1419
+ ignore_non_fp=ignore_non_fp,
1420
+ log_error=log_error,
1421
+ )
1422
+ for key in ref.__dict__.keys()
1423
+ )
1424
+ else:
1425
+ raise RuntimeError(f"unsupported type: {type(ref).__name__}")
1426
+
1427
+
1428
+ def format_func_info(code):
1429
+ short_filename = code.co_filename.split("/")[-1]
1430
+ return f"'{code.co_name}' ({short_filename}:{code.co_firstlineno})"
1431
+
1432
+
1433
+ @contextlib.contextmanager
1434
+ def disable_cache_limit():
1435
+ prior = config.cache_size_limit
1436
+ config.cache_size_limit = sys.maxsize
1437
+ prior_acc_limit = config.accumulated_cache_size_limit
1438
+ config.accumulated_cache_size_limit = sys.maxsize
1439
+
1440
+ try:
1441
+ yield
1442
+ finally:
1443
+ config.cache_size_limit = prior
1444
+ config.accumulated_cache_size_limit = prior_acc_limit
1445
+
1446
+
1447
+ # map from transformed code back to original user code
1448
+ orig_code_map = ExactWeakKeyDictionary()
1449
+
1450
+ # keep a record of code_obj -> list of guard failure reasons for logging
1451
+ guard_failures: DefaultDict[Any, List[Any]] = collections.defaultdict(list)
1452
+
1453
+ # Keep a record of graph break reasons for logging
1454
+ graph_break_reasons: List["torch._dynamo.output_graph.GraphCompileReason"] = list()
1455
+
1456
+ # keep record of compiled code, if we are in "error if recompile"
1457
+ # to track code that dynamo has compiled previously
1458
+ seen_code_map = ExactWeakKeyDictionary()
1459
+
1460
+
1461
+ class CompileProfiler:
1462
+ """Utility for profiling how and what dynamo would compile.
1463
+
1464
+ Can be used for
1465
+ * diagnosing recompilation issues
1466
+ * determining an appropriate compile cache limit
1467
+ * (TODO)confirming which functions got compiled/skipped
1468
+ """
1469
+
1470
+ def __init__(self):
1471
+ self.frame_count = 0
1472
+ self.op_count = 0
1473
+ self.backend_ctx_ctor = disable_cache_limit
1474
+
1475
+ def __call__(self, gm: torch.fx.GraphModule, example_inputs):
1476
+ self.frame_count += 1
1477
+ for node in gm.graph.nodes:
1478
+ if "call" in node.op:
1479
+ self.op_count += 1
1480
+ return gm.forward
1481
+
1482
+ # no-op __enter__ and __exit__ to preserve BC
1483
+ def __enter__(self):
1484
+ return self
1485
+
1486
+ def __exit__(self, typ, val, traceback):
1487
+ pass
1488
+
1489
+ def get_metrics(self):
1490
+ return {"guard_failures": guard_failures}
1491
+
1492
+ def report(self):
1493
+ metrics = self.get_metrics()
1494
+ gf = metrics["guard_failures"]
1495
+
1496
+ def num_recompiles(code):
1497
+ return len(gf[code])
1498
+
1499
+ def recompile_reasons(code):
1500
+ return "\n".join([str(x) for x in gf[code]])
1501
+
1502
+ summarized_gf = [
1503
+ [format_func_info(code), num_recompiles(code), recompile_reasons(code)]
1504
+ for code in gf
1505
+ ]
1506
+
1507
+ def graph_break_report():
1508
+ if "graph_break" in counters:
1509
+ graph_breaks = counters["graph_break"]
1510
+ return tabulate(
1511
+ [[msg, graph_breaks[msg]] for msg in graph_breaks],
1512
+ headers=["Graph Break Reason", "Count"],
1513
+ )
1514
+
1515
+ def recompilation_report():
1516
+ if len(gf):
1517
+ max_recompiles = max([num_recompiles(code) for code in gf])
1518
+ recomp_table = tabulate(
1519
+ summarized_gf,
1520
+ headers=["Function", "Recompiles", "Recompile Reasons"],
1521
+ )
1522
+ return recomp_table + textwrap.dedent(
1523
+ f"""
1524
+
1525
+ Set torch._dynamo.config.cache_size_limit to {max_recompiles} to avoid being cache limited.
1526
+ """
1527
+ )
1528
+
1529
+ report = textwrap.dedent(
1530
+ """
1531
+ Torchdynamo Profiler Report
1532
+ ===========================
1533
+
1534
+ Graph Breaks
1535
+ ------------
1536
+ Graph breaks happen when torchdynamo encounters code it can't safely trace.
1537
+ If you want to find out why breaks are happening, check below for each break reason
1538
+ You may gain additional insight by passing `fullgraph=True` to torch.compile,
1539
+ to stop at the first break.
1540
+
1541
+ """
1542
+ )
1543
+ report += graph_break_report() or "No graph breaks detected."
1544
+ report += textwrap.dedent(
1545
+ """
1546
+
1547
+ Recompilation
1548
+ -------------
1549
+ These subgraphs were recompiled more than once due to guard failures
1550
+ Guard failures indicate some condition assumed to be static by the tracer changed,
1551
+ making it unsafe to reuse the compiled program.
1552
+
1553
+ """
1554
+ )
1555
+ report += recompilation_report() or "No recompilation detected.\n"
1556
+ return report
1557
+
1558
+
1559
+ # return same dir unless user changes config between calls
1560
+ @functools.lru_cache(None)
1561
+ def _get_debug_dir(root_dir):
1562
+ dir_name = (
1563
+ "run_"
1564
+ + datetime.datetime.now().strftime("%Y_%m_%d_%H_%M_%S_%f")
1565
+ # use pid to avoid conflicts among ranks
1566
+ + "-pid_"
1567
+ + str(os.getpid())
1568
+ )
1569
+ return os.path.join(root_dir, dir_name)
1570
+
1571
+
1572
+ def get_debug_dir():
1573
+ debug_root = config.debug_dir_root
1574
+ return _get_debug_dir(debug_root)
1575
+
1576
+
1577
+ def extract_fake_example_value(node, required=True):
1578
+ if "example_value" in node.meta and is_fake(node.meta["example_value"]):
1579
+ return node.meta["example_value"]
1580
+ elif required:
1581
+ from torch._dynamo.exc import unimplemented
1582
+
1583
+ unimplemented("`FakeTensor` example value was required but not available")
1584
+ else:
1585
+ return None
1586
+
1587
+
1588
+ def ensure_graph_fake(e, tx):
1589
+ assert maybe_get_fake_mode(e) is tx.fake_mode
1590
+ return e
1591
+
1592
+
1593
+ def get_fake_values_from_nodes(tx, nodes, allow_non_graph_fake):
1594
+ def visit(n: torch.fx.Node):
1595
+ if n.op == "call_function" and "example_value" not in n.meta:
1596
+ # fake tensor validity is checked inside get_fake_value using
1597
+ # ensure_graph_fake
1598
+ return get_fake_value(n, tx, allow_non_graph_fake)
1599
+
1600
+ out = n.meta["example_value"]
1601
+ if not allow_non_graph_fake and isinstance(out, torch.Tensor):
1602
+ return ensure_graph_fake(out, tx)
1603
+ return out
1604
+
1605
+ return torch.fx.node.map_arg(nodes, visit)
1606
+
1607
+
1608
+ def get_fake_value(node, tx, allow_non_graph_fake=False):
1609
+ """
1610
+ Run the computation represented by `node` using fake tensors and return the result.
1611
+
1612
+ allow_non_graph_fake: whether to allow the return result to be:
1613
+ 1. non-fake or 2. fake that is not created by this instance of Dynamo.
1614
+ If `True`, you must be prepared to deal with such return values, ideally
1615
+ by further wrapping them as this graph's fakes.
1616
+ """
1617
+ from torch.utils._sympy.value_ranges import ValueRangeError
1618
+ from .exc import (
1619
+ TorchRuntimeError,
1620
+ unimplemented,
1621
+ Unsupported,
1622
+ UserError,
1623
+ UserErrorType,
1624
+ )
1625
+
1626
+ op = node.op
1627
+
1628
+ # FX Node should always return the same fake value
1629
+ if "example_value" in node.meta and is_fake(node.meta["example_value"]):
1630
+ return node.meta["example_value"]
1631
+
1632
+ args, kwargs = get_fake_values_from_nodes(
1633
+ tx, (node.args, node.kwargs), allow_non_graph_fake
1634
+ )
1635
+
1636
+ nnmodule = None
1637
+ if op == "call_method" and len(args) > 0 and isinstance(args[0], torch.nn.Module):
1638
+ # If the first argument is nn.Module, should copy to fake mode.
1639
+ args = (deepcopy_to_fake_tensor(args[0], tx.fake_mode),) + tuple(args[1:])
1640
+
1641
+ if op == "call_module":
1642
+ nnmodule = tx.output.nn_modules[node.target]
1643
+
1644
+ if is_lazy_module(nnmodule) and hasattr(nnmodule, "_initialize_hook"):
1645
+ # In the case of a lazy module, we want to run
1646
+ # the pre-hooks which initialize it.
1647
+ # Afterwards, lazy module deletes its pre-hooks
1648
+ # to avoid treating it as lazy on subsequent recompile.
1649
+ nnmodule._infer_parameters(nnmodule, args)
1650
+
1651
+ # no matter it's lazy module or not, we should copy to fake mode.
1652
+ nnmodule = deepcopy_to_fake_tensor(nnmodule, tx.fake_mode)
1653
+
1654
+ try:
1655
+ with tx.fake_mode, enable_python_dispatcher():
1656
+ ret_val = wrap_fake_exception(
1657
+ lambda: run_node(tx.output, node, args, kwargs, nnmodule)
1658
+ )
1659
+ except Unsupported:
1660
+ raise
1661
+ except RuntimeError as e:
1662
+ cause: BaseException = e
1663
+ if e.__cause__ is not None:
1664
+ cause = e.__cause__
1665
+
1666
+ if isinstance(
1667
+ cause, torch._subclasses.fake_tensor.DataDependentOutputException
1668
+ ):
1669
+ unimplemented(
1670
+ f"data dependent operator: {cause.func}; "
1671
+ "to enable, set torch._dynamo.config.capture_scalar_outputs = True"
1672
+ )
1673
+ elif isinstance(
1674
+ cause, torch._subclasses.fake_tensor.DynamicOutputShapeException
1675
+ ):
1676
+ unimplemented(
1677
+ f"dynamic shape operator: {cause.func}; "
1678
+ "to enable, set torch._dynamo.config.capture_dynamic_output_shape_ops = True"
1679
+ )
1680
+ elif isinstance(
1681
+ cause, torch._subclasses.fake_tensor.UnsupportedOperatorException
1682
+ ):
1683
+ op = cause.func
1684
+ import_suggestion = ""
1685
+ if isinstance(op, torch._ops.OpOverload):
1686
+ maybe_pystub = torch._C._dispatch_pystub(
1687
+ op._schema.name, op._schema.overload_name
1688
+ )
1689
+ if maybe_pystub is not None:
1690
+ module, ctx = maybe_pystub
1691
+ import_suggestion = (
1692
+ f"It's possible that the support was implemented in "
1693
+ f"module `{module}` and you may need to `import {module}`"
1694
+ f"({ctx}), otherwise "
1695
+ )
1696
+ unimplemented(
1697
+ f"unsupported operator: {cause.func} ({import_suggestion}see "
1698
+ "https://docs.google.com/document/d/1GgvOe7C8_NVOMLOCwDaYV1mXXyHMXY7ExoewHqooxrs/edit#heading=h.64r4npvq0w0"
1699
+ " for how to fix)"
1700
+ )
1701
+ elif isinstance(
1702
+ cause, torch.fx.experimental.symbolic_shapes.GuardOnDataDependentSymNode
1703
+ ):
1704
+ raise UserError( # noqa: TRY200
1705
+ UserErrorType.CONSTRAINT_VIOLATION,
1706
+ "Tried to use data-dependent value in the subsequent computation. "
1707
+ "This can happen when we encounter unbounded dynamic value that is unknown during tracing time. "
1708
+ "You will need to explicitly give hint to the compiler. Please take a look at "
1709
+ f"constrain_as_value OR constrain_as_size APIs. {cause}",
1710
+ case_name="constrain_as_size_example",
1711
+ )
1712
+ elif isinstance(cause, ValueRangeError):
1713
+ raise UserError(UserErrorType.CONSTRAINT_VIOLATION, e.args[0]) from e
1714
+ raise TorchRuntimeError(str(e)).with_traceback(e.__traceback__) from None
1715
+
1716
+ if not allow_non_graph_fake:
1717
+ _ = tree_map_only(
1718
+ torch.Tensor, functools.partial(ensure_graph_fake, tx=tx), ret_val
1719
+ )
1720
+ return ret_val
1721
+
1722
+
1723
+ _current_node = threading.local()
1724
+
1725
+
1726
+ def get_current_node():
1727
+ return getattr(_current_node, "value", None)
1728
+
1729
+
1730
+ @contextmanager
1731
+ def set_current_node(node):
1732
+ old = get_current_node()
1733
+ _current_node.value = node
1734
+ try:
1735
+ yield
1736
+ finally:
1737
+ _current_node.value = old
1738
+
1739
+
1740
+ def run_node(tracer, node, args, kwargs, nnmodule):
1741
+ """
1742
+ Runs a given node, with the given args and kwargs.
1743
+
1744
+ Behavior is dictated by a node's op.
1745
+
1746
+ run_node is useful for extracting real values out of nodes.
1747
+ See get_real_value for more info on common usage.
1748
+
1749
+ Note: The tracer arg is only used for 'get_attr' ops
1750
+ Note: The nnmodule arg is only used for 'call_module' ops
1751
+
1752
+ Nodes that are not call_function, call_method, call_module, or get_attr will
1753
+ raise an AssertionError.
1754
+ """
1755
+ op = node.op
1756
+
1757
+ with set_current_node(node):
1758
+
1759
+ def make_error_message(e):
1760
+ return f"Failed running {op} {node.target}(*{args}, **{kwargs}):\n" + str(e)
1761
+
1762
+ try:
1763
+ if op == "call_function":
1764
+ return node.target(*args, **kwargs)
1765
+ elif op == "call_method":
1766
+ return getattr(args[0], node.target)(*args[1:], **kwargs)
1767
+ elif op == "call_module":
1768
+ assert nnmodule is not None
1769
+ return nnmodule(*args, **kwargs)
1770
+ elif op == "get_attr":
1771
+ return tracer.get_submodule(node.target)
1772
+ elif op == "placeholder":
1773
+ assert "example_value" in node.meta
1774
+ return node.meta["example_value"]
1775
+
1776
+ except (NotImplementedError, UnsupportedFakeTensorException) as e:
1777
+ # NB: mimic how wrap_fake_exception does it
1778
+ from .exc import unimplemented
1779
+
1780
+ raise unimplemented(make_error_message(e)) from e
1781
+ except Exception as e:
1782
+ raise RuntimeError(make_error_message(e)).with_traceback(
1783
+ e.__traceback__
1784
+ ) from e
1785
+
1786
+ raise AssertionError(op)
1787
+
1788
+
1789
+ def get_real_value(node, tracer):
1790
+ """
1791
+ Run the actual computation represented by `node` and return the result.
1792
+ This will execute any dependent nodes in the graph as well.
1793
+ """
1794
+ from .exc import TorchRuntimeError
1795
+
1796
+ cache = tracer.real_value_cache
1797
+ if node in cache:
1798
+ return cache[node]
1799
+
1800
+ op = node.op
1801
+ args, kwargs = torch.fx.node.map_arg(
1802
+ (node.args, node.kwargs),
1803
+ lambda n: get_real_value(n, tracer),
1804
+ )
1805
+
1806
+ if op == "call_module":
1807
+ nn_module = tracer.output_graph.nn_modules[node.target]
1808
+ if not is_lazy_module(nn_module):
1809
+ nn_module = copy.deepcopy(nn_module)
1810
+ else:
1811
+ # In the case of a lazy module, we want to run
1812
+ # the pre-hooks which initialize it
1813
+ nn_module(*args, **kwargs)
1814
+ else:
1815
+ nn_module = None
1816
+
1817
+ try:
1818
+ real_value = run_node(tracer, node, args, kwargs, nn_module)
1819
+ cache[node] = real_value
1820
+ except RuntimeError as e:
1821
+ raise TorchRuntimeError(str(e)).with_traceback(e.__traceback__) from None
1822
+ return real_value
1823
+
1824
+
1825
+ def assert_no_fake_params_or_buffers(gm):
1826
+ from torch._subclasses.fake_tensor import FakeTensorConfig
1827
+
1828
+ def stack_or_hint(t):
1829
+ if FakeTensorConfig.debug:
1830
+ import traceback
1831
+
1832
+ return f"FAKE TENSOR CREATION TRACEBACK: \n {traceback.format_list(t._debug_trace)}"
1833
+ else:
1834
+ return "Enable TORCH_FAKE_TENSOR_DEBUG=1 to get creation stack traces on fake tensors."
1835
+
1836
+ for name, buffer in gm.named_buffers():
1837
+ assert not isinstance(
1838
+ buffer, torch._subclasses.FakeTensor
1839
+ ), f"Unexpected fake buffer {name} {stack_or_hint(buffer)}"
1840
+ for name, param in gm.named_parameters():
1841
+ assert not isinstance(
1842
+ param, torch._subclasses.FakeTensor
1843
+ ), f"Unexpected fake param {name} {stack_or_hint(param)}"
1844
+
1845
+
1846
+ def fqn(obj: Any):
1847
+ """
1848
+ Returns the fully qualified name of the object.
1849
+ """
1850
+ return f"{obj.__module__}.{obj.__qualname__}"
1851
+
1852
+
1853
+ def ifdynstaticdefault(count1, count2):
1854
+ if torch._dynamo.config.assume_static_by_default:
1855
+ return count1
1856
+ else:
1857
+ return count2
1858
+
1859
+
1860
+ def import_submodule(mod: types.ModuleType):
1861
+ """
1862
+ Ensure all the files in a given submodule are imported
1863
+ """
1864
+ for filename in sorted(os.listdir(os.path.dirname(cast(str, mod.__file__)))):
1865
+ if filename.endswith(".py") and filename[0] != "_":
1866
+ importlib.import_module(f"{mod.__name__}.{filename[:-3]}")
1867
+
1868
+
1869
+ def object_has_getattribute(value: Any):
1870
+ try:
1871
+ if isinstance(
1872
+ inspect.getattr_static(type(value), "__getattribute__"),
1873
+ types.FunctionType,
1874
+ ):
1875
+ return True
1876
+ except AttributeError:
1877
+ pass
1878
+ return False
1879
+
1880
+
1881
+ def get_custom_getattr(value: Any):
1882
+ try:
1883
+ getattr_fn = inspect.getattr_static(type(value), "__getattr__")
1884
+ except AttributeError:
1885
+ getattr_fn = None
1886
+ if getattr_fn is torch.nn.Module.__getattr__:
1887
+ # ignore this case of getattr
1888
+ getattr_fn = None
1889
+ return getattr_fn
1890
+
1891
+
1892
+ class TensorStaticReason(enum.Enum):
1893
+ PARAMETER = 2
1894
+ NOT_TENSOR = 4
1895
+ NN_MODULE_PROPERTY = 5
1896
+
1897
+
1898
+ def tensor_static_reason_to_message(reason: TensorStaticReason):
1899
+ if reason == TensorStaticReason.PARAMETER:
1900
+ return "mark_dynamic on parameter, parameters are always static today."
1901
+ if reason == TensorStaticReason.NOT_TENSOR:
1902
+ return "mark_dynamic on a non tensor, how did this happen?"
1903
+ if reason == TensorStaticReason.NN_MODULE_PROPERTY:
1904
+ return "tensor is static because it is nn module associated."
1905
+ raise AssertionError(f"Illegal reason {reason}")
1906
+
1907
+
1908
+ def tensor_always_has_static_shape(
1909
+ tensor: Union[torch.Tensor, Any],
1910
+ is_tensor: bool,
1911
+ guard_source: "torch._guards.GuardSource",
1912
+ ) -> Tuple[bool, Optional[TensorStaticReason]]:
1913
+ """
1914
+ Given a tensor, source, and is_tensor flag, determine if a shape should be static.
1915
+
1916
+ Args:
1917
+ tensor - the real tensor to evaluate, parameters force a static shape.
1918
+ is_tensor - internal dynamo check, essentially "is_tensor": target_cls is TensorVariable,
1919
+ tensors not in a TensorVariable for whatever reason are forced static.
1920
+
1921
+ Returns a tuple, where the first element is the bool of whether or not this tensor should have a static shape.
1922
+ The second element is a TensorStaticReason, useful for passing to tensor_static_reason_to_message if needed.
1923
+ """
1924
+ if guard_source.is_nn_module() and config.force_nn_module_property_static_shapes:
1925
+ return True, TensorStaticReason.NN_MODULE_PROPERTY
1926
+ if type(tensor) is torch.nn.Parameter and config.force_parameter_static_shapes:
1927
+ return True, TensorStaticReason.PARAMETER
1928
+ if not is_tensor:
1929
+ return True, TensorStaticReason.NOT_TENSOR
1930
+ return False, None
1931
+
1932
+
1933
+ def lazy_format_graph_code(name, gm, maybe_id=None):
1934
+ def format_name():
1935
+ if maybe_id is not None:
1936
+ return f"{name} {maybe_id}"
1937
+ else:
1938
+ return name
1939
+
1940
+ return LazyString(
1941
+ lambda: _format_graph_code(
1942
+ f"===== {format_name()} =====\n",
1943
+ gm.forward.__code__.co_filename,
1944
+ gm.print_readable(print_output=False),
1945
+ )
1946
+ )
1947
+
1948
+
1949
+ def _format_graph_code(name, filename, graph_str):
1950
+ return f"TRACED GRAPH\n {name} {filename} {graph_str}\n"
1951
+
1952
+
1953
+ def lazy_format_graph_tabular(fn_name, gm):
1954
+ def inner():
1955
+ try:
1956
+ from tabulate import tabulate # TODO: Check that this is installed
1957
+ except ImportError:
1958
+ return (
1959
+ "Tabulate module missing, please install tabulate to log the graph in tabular format, logging code instead:\n"
1960
+ + str(lazy_format_graph_code(fn_name, gm))
1961
+ )
1962
+
1963
+ node_specs = [
1964
+ [n.op, n.name, n.target, n.args, n.kwargs] for n in gm.graph.nodes
1965
+ ]
1966
+ graph_str = tabulate(
1967
+ node_specs, headers=["opcode", "name", "target", "args", "kwargs"]
1968
+ )
1969
+ return _format_graph_code(fn_name, gm.forward.__code__.co_filename, graph_str)
1970
+
1971
+ return LazyString(inner)
1972
+
1973
+
1974
+ def format_bytecode(prefix, name, filename, line_no, code):
1975
+ return f"{prefix} {name} {filename} line {line_no} \n{dis.Bytecode(code).dis()}\n"
1976
+
1977
+
1978
+ forward_hook_names = ["_forward_pre_hooks", "_forward_hooks"]
1979
+ backward_hook_names = ["_backward_pre_hooks", "_backward_hooks"]
1980
+ state_dict_hook_names = [
1981
+ "_state_dict_pre_hooks",
1982
+ "_state_dict_hooks",
1983
+ "_load_state_dict_pre_hooks",
1984
+ "_load_state_dict_post_hooks",
1985
+ ]
1986
+ all_hook_names = forward_hook_names + backward_hook_names + state_dict_hook_names
1987
+
1988
+
1989
+ def nn_module_get_all_hooks(
1990
+ mod,
1991
+ check_forward_hooks=False,
1992
+ check_backward_hooks=False,
1993
+ check_state_dict_hooks=False,
1994
+ ):
1995
+ reset_code = torch._C._dynamo.eval_frame.reset_code
1996
+ """
1997
+ Sometimes its useful to differentiate between types of hooks such as forward/backward/pre
1998
+ hooks executed during module.__call__, and state_dict hooks which are executed separately.
1999
+ """
2000
+ hook_dicts_to_check = []
2001
+ check_all_hooks = (
2002
+ not check_forward_hooks
2003
+ and not check_backward_hooks
2004
+ and not check_state_dict_hooks
2005
+ )
2006
+ if check_forward_hooks or check_all_hooks:
2007
+ hook_dicts_to_check.extend(forward_hook_names)
2008
+ if check_backward_hooks or check_all_hooks:
2009
+ hook_dicts_to_check.extend(backward_hook_names)
2010
+ if check_state_dict_hooks:
2011
+ hook_dicts_to_check.extend(state_dict_hook_names)
2012
+
2013
+ all_hooks = []
2014
+ for hook_dict_name in hook_dicts_to_check:
2015
+ hooks = getattr(mod, hook_dict_name, [])
2016
+ for hook_name in hooks:
2017
+ hook = hooks[hook_name]
2018
+
2019
+ all_hooks.append(hook)
2020
+ return all_hooks
2021
+
2022
+
2023
+ def nnmodule_has_hooks(
2024
+ mod,
2025
+ check_forward_hooks=False,
2026
+ check_backward_hooks=False,
2027
+ check_state_dict_hooks=False,
2028
+ ):
2029
+ """
2030
+ Helper function to check if a module has any hooks attached to it.
2031
+ """
2032
+ hooks = nn_module_get_all_hooks(
2033
+ mod,
2034
+ check_forward_hooks=check_forward_hooks,
2035
+ check_backward_hooks=check_backward_hooks,
2036
+ check_state_dict_hooks=check_state_dict_hooks,
2037
+ )
2038
+ return bool(hooks)
2039
+
2040
+
2041
+ def to_numpy_helper(value):
2042
+ """Convert tensor and tnp.ndarray to numpy.ndarray."""
2043
+ if is_fake(value):
2044
+ return value
2045
+ if isinstance(value, tnp.ndarray):
2046
+ return to_numpy_helper(value.tensor)
2047
+ elif isinstance(value, torch.Tensor):
2048
+ return value.numpy(force=True)
2049
+ elif isinstance(value, (tuple, list)):
2050
+ return type(value)(to_numpy_helper(obj) for obj in value)
2051
+ else:
2052
+ return value
2053
+
2054
+
2055
+ def numpy_to_tensor(value):
2056
+ """Convert tnp.ndarray to tensor, leave other types intact. If a list/tuple, loop through it to convert."""
2057
+ assert np is not None
2058
+ if isinstance(value, np.ndarray):
2059
+ return torch.as_tensor(value)
2060
+ if isinstance(value, tnp.ndarray):
2061
+ return value.tensor
2062
+ elif isinstance(value, (tuple, list)):
2063
+ return type(value)(numpy_to_tensor(obj) for obj in value)
2064
+ else:
2065
+ return value
2066
+
2067
+
2068
+ class numpy_to_tensor_wrapper:
2069
+ def __init__(self, f):
2070
+ self.f = f
2071
+ self.__name__ = "wrapped_" + self.f.__name__
2072
+
2073
+ def __repr__(self):
2074
+ return f"<Wrapped function <original {self.f.__name__}>>"
2075
+
2076
+ def __call__(self, *args, **kwargs):
2077
+ out = self.f(*args, **kwargs)
2078
+ return numpy_to_tensor(out)
2079
+
2080
+
2081
+ def numpy_attr_wrapper(obj, name):
2082
+ if isinstance(obj, tnp.ndarray):
2083
+ out = getattr(obj, name)
2084
+ return numpy_to_tensor(out)
2085
+ elif isinstance(obj, torch.Tensor):
2086
+ out = getattr(tnp.ndarray(obj), name)
2087
+ return numpy_to_tensor(out)
2088
+
2089
+
2090
+ class numpy_method_wrapper:
2091
+ """Convert obj from torch.Tensor to tnp.ndarray and call method. Then convert result back to torch.Tensor."""
2092
+
2093
+ def __init__(self, method: str):
2094
+ self.method = method
2095
+ self.__name__ = "wrapped_" + self.method
2096
+
2097
+ def __repr__(self):
2098
+ return f"<Wrapped method <original {self.method}>>"
2099
+
2100
+ def __call__(self, *args, **kwargs):
2101
+ obj = args[0]
2102
+ if isinstance(obj, torch.Tensor):
2103
+ obj = tnp.ndarray(obj)
2104
+ method_callable = getattr(obj, self.method)
2105
+ out = method_callable(*args[1:], **kwargs)
2106
+ return numpy_to_tensor(out)
2107
+
2108
+
2109
+ class numpy_operator_wrapper:
2110
+ """Implements dunder methods for tnp.ndarray via functions from the operator library"""
2111
+
2112
+ def __init__(self, op: Callable[..., Any]):
2113
+ self.op = op
2114
+ self.__name__ = f"wrapped_{op.__name__}"
2115
+
2116
+ def __repr__(self):
2117
+ return f"<Wrapped operator <original {self.__name__}>>"
2118
+
2119
+ def __call__(self, *args, **kwargs):
2120
+ assert not kwargs
2121
+
2122
+ args = (
2123
+ tnp.ndarray(arg) if isinstance(arg, torch.Tensor) else arg for arg in args
2124
+ )
2125
+ out = self.op(*args)
2126
+ return numpy_to_tensor(out)
2127
+
2128
+
2129
+ def defake(x):
2130
+ if not isinstance(x, FakeTensor):
2131
+ return x
2132
+ size: "torch._prims_common.ShapeType"
2133
+ stride: "torch._prims_common.StrideType"
2134
+ if x._has_symbolic_sizes_strides:
2135
+ size = []
2136
+ for s in x.size():
2137
+ if isinstance(s, torch.SymInt):
2138
+ size.append(s.node.shape_env.size_hint(s.node.expr))
2139
+ else:
2140
+ size.append(s)
2141
+ stride = []
2142
+ for s in x.stride():
2143
+ if isinstance(s, torch.SymInt):
2144
+ stride.append(s.node.shape_env.size_hint(s.node.expr))
2145
+ else:
2146
+ stride.append(s)
2147
+ else:
2148
+ size = x.size()
2149
+ stride = x.stride()
2150
+ y = torch.empty_strided(
2151
+ size,
2152
+ stride,
2153
+ dtype=x.dtype,
2154
+ device=x.device,
2155
+ requires_grad=x.requires_grad,
2156
+ )
2157
+ y.zero_()
2158
+ return y
2159
+
2160
+
2161
+ def is_utils_checkpoint(obj):
2162
+ # Lazy import to avoid circular dependencies
2163
+ import torch.utils.checkpoint
2164
+
2165
+ return obj is torch.utils.checkpoint.checkpoint
2166
+
2167
+
2168
+ def build_checkpoint_variable(**options):
2169
+ import torch._higher_order_ops.wrap as higher_order_ops
2170
+ from .variables.higher_order_ops import TorchHigherOrderOperatorVariable
2171
+
2172
+ # TODO - This is a temporary situation where we have two versions of
2173
+ # checkpointing implementation. We will converge on one and remove the other.
2174
+ activation_checkpoint_op: "torch._ops.HigherOrderOperator" = (
2175
+ higher_order_ops.tag_activation_checkpoint
2176
+ )
2177
+ if torch._functorch.config.functionalize_rng_ops:
2178
+ activation_checkpoint_op = higher_order_ops.wrap_activation_checkpoint
2179
+
2180
+ return TorchHigherOrderOperatorVariable.make(
2181
+ activation_checkpoint_op,
2182
+ **options,
2183
+ )
2184
+
2185
+
2186
+ def is_compile_supported(device_type):
2187
+ from .eval_frame import is_dynamo_supported
2188
+
2189
+ compile_supported = is_dynamo_supported()
2190
+ if device_type == "cpu":
2191
+ pass
2192
+ elif device_type == "cuda" and compile_supported:
2193
+ from torch.utils._triton import has_triton
2194
+
2195
+ compile_supported = has_triton()
2196
+ else:
2197
+ compile_supported = False
2198
+ return compile_supported
2199
+
2200
+
2201
+ # The following 3.11 source code functions are adapted from
2202
+ # https://github.com/python/cpython/blob/v3.11.4/Lib/traceback.py
2203
+ # in order to output source code corresponding to bytecode in 3.11+.
2204
+ # We need our own versions since we want to support multiline expressions.
2205
+ def _fix_offset(str: str, offset: int) -> int:
2206
+ """
2207
+ Convert byte offset `offset` of `str` into character offset.
2208
+ Byte offset is used for 3.11+ instruction column data.
2209
+ Takes things like unicode characters into consideration.
2210
+
2211
+ Unchanged from CPython implementation.
2212
+ """
2213
+ as_utf8 = str.encode("utf-8")
2214
+ return len(as_utf8[:offset].decode("utf-8", errors="replace"))
2215
+
2216
+
2217
+ @dataclasses.dataclass
2218
+ class _Anchors:
2219
+ # inclusive
2220
+ left_end_lineno: int
2221
+ left_end_offset: int
2222
+ right_start_lineno: int
2223
+ # exclusive
2224
+ right_start_offset: int
2225
+
2226
+
2227
+ def _extract_anchors_from_expr(segment: str) -> Optional[_Anchors]:
2228
+ """
2229
+ Given source code `segment` corresponding to a bytecode
2230
+ instruction, determine:
2231
+ - for binary ops, the location of the binary op
2232
+ - for indexing, the location of the brackets.
2233
+ `segment` is expected to be a valid Python expression
2234
+ """
2235
+ assert sys.version_info >= (3, 11)
2236
+
2237
+ import ast
2238
+
2239
+ try:
2240
+ # Without brackets, `segment` is parsed as a statement.
2241
+ # We expect an expression, so wrap `segment` in
2242
+ # brackets to handle multi-line expressions.
2243
+ tree = ast.parse("(\n" + segment + "\n)")
2244
+ except SyntaxError:
2245
+ return None
2246
+
2247
+ if len(tree.body) != 1:
2248
+ return None
2249
+
2250
+ lines = segment.split("\n")
2251
+
2252
+ # get character index given byte offset
2253
+ def normalize(lineno, offset):
2254
+ return _fix_offset(lines[lineno], offset)
2255
+
2256
+ # Gets the next valid character index in `lines`, if
2257
+ # the current location is not valid. Handles empty lines.
2258
+ def next_valid_char(lineno, col):
2259
+ while lineno < len(lines) and col >= len(lines[lineno]):
2260
+ col = 0
2261
+ lineno += 1
2262
+ assert lineno < len(lines) and col < len(lines[lineno])
2263
+ return lineno, col
2264
+
2265
+ # Get the next valid character index in `lines`.
2266
+ def increment(lineno, col):
2267
+ col += 1
2268
+ lineno, col = next_valid_char(lineno, col)
2269
+ assert lineno < len(lines) and col < len(lines[lineno])
2270
+ return lineno, col
2271
+
2272
+ # Get the next valid character at least on the next line
2273
+ def nextline(lineno, col):
2274
+ col = 0
2275
+ lineno += 1
2276
+ lineno, col = next_valid_char(lineno, col)
2277
+ assert lineno < len(lines) and col < len(lines[lineno])
2278
+ return lineno, col
2279
+
2280
+ statement = tree.body[0]
2281
+ if isinstance(statement, ast.Expr):
2282
+ expr = statement.value
2283
+ if isinstance(expr, ast.BinOp):
2284
+ # ast gives locations for BinOp subexpressions, e.g.
2285
+ # ( left_expr ) + ( right_expr )
2286
+ # left^^^^^ right^^^^^
2287
+ # -2 since end_lineno is 1-indexed and because we added an extra
2288
+ # bracket to `segment` when calling ast.parse
2289
+ cur_lineno = cast(int, expr.left.end_lineno) - 2
2290
+ cur_col = normalize(cur_lineno, expr.left.end_col_offset)
2291
+ cur_lineno, cur_col = next_valid_char(cur_lineno, cur_col)
2292
+
2293
+ # Heuristic to find the operator character.
2294
+ # The original CPython implementation did not look for ), \, or #,
2295
+ # leading to incorrect anchor location, e.g.
2296
+ # (x) + (y)
2297
+ # ~~^~~~~~~
2298
+ while (ch := lines[cur_lineno][cur_col]).isspace() or ch in ")\\#":
2299
+ if ch in "\\#":
2300
+ cur_lineno, cur_col = nextline(cur_lineno, cur_col)
2301
+ else:
2302
+ cur_lineno, cur_col = increment(cur_lineno, cur_col)
2303
+
2304
+ # binary op is 1 or 2 characters long, on the same line
2305
+ right_col = cur_col + 1
2306
+ if (
2307
+ right_col < len(lines[cur_lineno])
2308
+ and not (ch := lines[cur_lineno][right_col]).isspace()
2309
+ and ch not in "\\#"
2310
+ ):
2311
+ right_col += 1
2312
+ # right_col can be invalid since it is exclusive
2313
+
2314
+ return _Anchors(cur_lineno, cur_col, cur_lineno, right_col)
2315
+ elif isinstance(expr, ast.Subscript):
2316
+ # ast gives locations for value and slice subexpressions, e.g.
2317
+ # ( value_expr ) [ slice_expr ]
2318
+ # value^^^^^ slice^^^^^
2319
+ # subscript^^^^^^^^^^^^^^^^^^^^
2320
+ # find left bracket (first '[' after value)
2321
+ left_lineno = cast(int, expr.value.end_lineno) - 2
2322
+ left_col = normalize(left_lineno, expr.value.end_col_offset)
2323
+ left_lineno, left_col = next_valid_char(left_lineno, left_col)
2324
+ while lines[left_lineno][left_col] != "[":
2325
+ left_lineno, left_col = increment(left_lineno, left_col)
2326
+ # find right bracket (final character of expression)
2327
+ right_lineno = cast(int, expr.end_lineno) - 2
2328
+ right_col = normalize(right_lineno, expr.end_col_offset)
2329
+ return _Anchors(left_lineno, left_col, right_lineno, right_col)
2330
+ elif isinstance(expr, ast.Call):
2331
+ # ( func_expr ) (args, kwargs)
2332
+ # func^^^^^
2333
+ # call^^^^^^^^^^^^^^^^^^^^^^^^
2334
+ # find left bracket (first '(' after func)
2335
+ left_lineno = cast(int, expr.func.end_lineno) - 2
2336
+ left_col = normalize(left_lineno, expr.func.end_col_offset)
2337
+ left_lineno, left_col = next_valid_char(left_lineno, left_col)
2338
+ while lines[left_lineno][left_col] != "(":
2339
+ left_lineno, left_col = increment(left_lineno, left_col)
2340
+ # find right bracket (final character of expression)
2341
+ right_lineno = cast(int, expr.end_lineno) - 2
2342
+ right_col = normalize(right_lineno, expr.end_col_offset)
2343
+ return _Anchors(left_lineno, left_col, right_lineno, right_col)
2344
+
2345
+ return None
2346
+
2347
+
2348
+ def get_instruction_source_311(code: types.CodeType, inst: dis.Instruction) -> str:
2349
+ """
2350
+ Python 3.11+ only. Returns lines of source code (from code object `code`)
2351
+ corresponding to `inst`'s location data, and underlines relevant code to `inst`.
2352
+
2353
+ Example: CALL on `g`:
2354
+ f(g(
2355
+ ^^
2356
+ h(x)))
2357
+ ^^^^^
2358
+
2359
+ We need our own implementation since `format_frame_summary` in
2360
+ Python's `traceback` module doesn't handle multi-line expressions
2361
+ (and their anchor extraction code is not completely correct).
2362
+ """
2363
+ assert inst.positions is not None
2364
+ if inst.positions.lineno is None:
2365
+ return ""
2366
+ # The rstrip + "\n" pattern is used throughout this function to handle
2367
+ # linecache.getline errors. Error lines are treated as empty strings "", but we want
2368
+ # to treat them as blank lines "\n".
2369
+ first_line = linecache.getline(code.co_filename, inst.positions.lineno).rstrip()
2370
+ if inst.positions.end_lineno is None:
2371
+ return first_line
2372
+ if inst.positions.col_offset is None or inst.positions.end_col_offset is None:
2373
+ return first_line
2374
+
2375
+ # character index of the start of the instruction
2376
+ start_offset = _fix_offset(first_line, inst.positions.col_offset)
2377
+ # character index of the end of the instruction
2378
+ # compute later since end may be a different line
2379
+ end_offset = None
2380
+ # expression corresponding to the instruction so we can get anchors
2381
+ segment = ""
2382
+ # underline markers to be printed - start with `~` marker and replace with `^` later
2383
+ markers = []
2384
+
2385
+ # Compute segment and initial markers
2386
+ if inst.positions.end_lineno == inst.positions.lineno:
2387
+ end_offset = _fix_offset(first_line, inst.positions.end_col_offset)
2388
+ segment = first_line[start_offset:end_offset]
2389
+ markers.append(" " * start_offset + "~" * (end_offset - start_offset))
2390
+ else:
2391
+ segment = first_line[start_offset:] + "\n"
2392
+ markers.append(" " * start_offset + "~" * (len(first_line) - start_offset))
2393
+ last_line = linecache.getline(
2394
+ code.co_filename, inst.positions.end_lineno
2395
+ ).rstrip()
2396
+ end_offset = _fix_offset(last_line, inst.positions.end_col_offset)
2397
+ for lineno in range(inst.positions.lineno + 1, inst.positions.end_lineno):
2398
+ line = linecache.getline(code.co_filename, lineno).rstrip()
2399
+ segment += line + "\n"
2400
+ # don't underline leading spaces
2401
+ num_spaces = len(line) - len(line.lstrip())
2402
+ markers.append(" " * num_spaces + "~" * (len(line) - num_spaces))
2403
+ segment += last_line[:end_offset]
2404
+ num_spaces = len(last_line) - len(last_line.lstrip())
2405
+ markers.append(" " * num_spaces + "~" * (end_offset - num_spaces))
2406
+
2407
+ anchors: Optional[_Anchors] = None
2408
+ try:
2409
+ anchors = _extract_anchors_from_expr(segment)
2410
+ except AssertionError:
2411
+ pass
2412
+
2413
+ # replace `~` markers with `^` where necessary
2414
+ if anchors is None:
2415
+ markers = [marker.replace("~", "^") for marker in markers]
2416
+ else:
2417
+ # make markers mutable
2418
+ mutable_markers: List[List[str]] = [list(marker) for marker in markers]
2419
+
2420
+ # anchor positions do not take start_offset into account
2421
+ if anchors.left_end_lineno == 0:
2422
+ anchors.left_end_offset += start_offset
2423
+ if anchors.right_start_lineno == 0:
2424
+ anchors.right_start_offset += start_offset
2425
+
2426
+ # Turn `~`` markers between anchors to `^`
2427
+ for lineno in range(len(markers)):
2428
+ for col in range(len(mutable_markers[lineno])):
2429
+ if lineno < anchors.left_end_lineno:
2430
+ continue
2431
+ if lineno == anchors.left_end_lineno and col < anchors.left_end_offset:
2432
+ continue
2433
+ if (
2434
+ lineno == anchors.right_start_lineno
2435
+ and col >= anchors.right_start_offset
2436
+ ):
2437
+ continue
2438
+ if lineno > anchors.right_start_lineno:
2439
+ continue
2440
+ if mutable_markers[lineno][col] == "~":
2441
+ mutable_markers[lineno][col] = "^"
2442
+
2443
+ # make markers into strings again
2444
+ markers = ["".join(marker) for marker in mutable_markers]
2445
+
2446
+ result = ""
2447
+ for i in range(len(markers)):
2448
+ result += (
2449
+ linecache.getline(code.co_filename, inst.positions.lineno + i).rstrip()
2450
+ + "\n"
2451
+ )
2452
+ result += markers[i] + "\n"
2453
+ return result
2454
+
2455
+
2456
+ def get_static_address_type(t):
2457
+ if isinstance(t, torch.Tensor):
2458
+ return getattr(t, "_dynamo_static_input_type", None)
2459
+
2460
+ return None
2461
+
2462
+
2463
+ def is_rng_state_getter_or_setter(value):
2464
+ getters = (
2465
+ # The following two functions are not identical, so don't remove anyone!
2466
+ torch._C.Generator.get_state,
2467
+ torch.default_generator.get_state,
2468
+ torch.get_rng_state,
2469
+ torch.cuda.get_rng_state,
2470
+ )
2471
+ setters = (
2472
+ torch._C.Generator.set_state,
2473
+ torch.default_generator.set_state,
2474
+ torch.set_rng_state,
2475
+ torch.cuda.set_rng_state,
2476
+ )
2477
+ return value in (*setters, *getters)
2478
+
2479
+
2480
+ def is_tensor_base_attr_getter(value):
2481
+ return (
2482
+ isinstance(value, types.MethodWrapperType)
2483
+ and value.__name__ == "__get__"
2484
+ and value.__self__.__objclass__ is torch._C._TensorBase # type: ignore[attr-defined]
2485
+ )
2486
+
2487
+
2488
+ def is_torch_function_object(value):
2489
+ return hasattr(value, "__torch_function__")
2490
+
2491
+
2492
+ def has_torch_function(vt: "torch._dynamo.variables.base.VariableTracker") -> bool:
2493
+ from torch._dynamo.variables import UserDefinedObjectVariable
2494
+ from torch._dynamo.variables.torch_function import TensorWithTFOverrideVariable
2495
+
2496
+ return isinstance(vt, TensorWithTFOverrideVariable) or (
2497
+ isinstance(vt, UserDefinedObjectVariable)
2498
+ and hasattr(vt.value, "__torch_function__")
2499
+ )
2500
+
2501
+
2502
+ # see note [Tensor Fakification and Symbol Caching]
2503
+ def to_fake_tensor(t, fake_mode):
2504
+ symbolic_context = None
2505
+ source = None
2506
+ if tracing_context := torch._guards.TracingContext.try_get():
2507
+ if t in tracing_context.tensor_to_context:
2508
+ symbolic_context = tracing_context.tensor_to_context[t]
2509
+ source = symbolic_context.tensor_source
2510
+
2511
+ return fake_mode.from_tensor(
2512
+ t, static_shapes=False, symbolic_context=symbolic_context, source=source
2513
+ )
2514
+
2515
+
2516
+ def get_first_attr(obj, *attrs):
2517
+ """
2518
+ Return the first available attribute or throw an exception if none is present.
2519
+ """
2520
+ for attr in attrs:
2521
+ if hasattr(obj, attr):
2522
+ return getattr(obj, attr)
2523
+
2524
+ raise AssertionError(f"{obj} does not has any of the attributes: {attrs}")
2525
+
2526
+
2527
+ @contextlib.contextmanager
2528
+ def maybe_enable_compiled_autograd(should_enable):
2529
+ def compiler_fn(gm):
2530
+ def inner_compiler(gm_, example_inputs_):
2531
+ torch._dynamo.utils.counters["compiled_autograd"]["compiles"] += 1
2532
+ return torch._inductor.compile(gm_, example_inputs_)
2533
+
2534
+ return torch.compile(gm, backend=inner_compiler, fullgraph=True, dynamic=True)
2535
+
2536
+ if should_enable:
2537
+ with torch._dynamo.compiled_autograd.enable(compiler_fn) as ctx:
2538
+ yield ctx
2539
+ else:
2540
+ yield
2541
+
2542
+
2543
+ def invalid_removeable_handle():
2544
+ # need a subclass so weakref works
2545
+ class Invalid(dict): # type: ignore[type-arg]
2546
+ pass
2547
+
2548
+ return RemovableHandle(Invalid())
llmeval-env/lib/python3.10/site-packages/torch/utils/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (2.17 kB). View file
 
llmeval-env/lib/python3.10/site-packages/torch/utils/__pycache__/_config_module.cpython-310.pyc ADDED
Binary file (11.7 kB). View file
 
llmeval-env/lib/python3.10/site-packages/torch/utils/__pycache__/_contextlib.cpython-310.pyc ADDED
Binary file (5.34 kB). View file
 
llmeval-env/lib/python3.10/site-packages/torch/utils/__pycache__/_cxx_pytree.cpython-310.pyc ADDED
Binary file (31.6 kB). View file
 
llmeval-env/lib/python3.10/site-packages/torch/utils/__pycache__/_freeze.cpython-310.pyc ADDED
Binary file (8.24 kB). View file
 
llmeval-env/lib/python3.10/site-packages/torch/utils/__pycache__/_import_utils.cpython-310.pyc ADDED
Binary file (1.21 kB). View file
 
llmeval-env/lib/python3.10/site-packages/torch/utils/__pycache__/_stats.cpython-310.pyc ADDED
Binary file (849 Bytes). View file
 
llmeval-env/lib/python3.10/site-packages/torch/utils/__pycache__/_traceback.cpython-310.pyc ADDED
Binary file (5.92 kB). View file
 
llmeval-env/lib/python3.10/site-packages/torch/utils/__pycache__/_triton.cpython-310.pyc ADDED
Binary file (2.89 kB). View file
 
llmeval-env/lib/python3.10/site-packages/torch/utils/__pycache__/_typing_utils.cpython-310.pyc ADDED
Binary file (545 Bytes). View file
 
llmeval-env/lib/python3.10/site-packages/torch/utils/__pycache__/bundled_inputs.cpython-310.pyc ADDED
Binary file (17.1 kB). View file
 
llmeval-env/lib/python3.10/site-packages/torch/utils/__pycache__/collect_env.cpython-310.pyc ADDED
Binary file (15.4 kB). View file
 
llmeval-env/lib/python3.10/site-packages/torch/utils/__pycache__/cpp_backtrace.cpython-310.pyc ADDED
Binary file (690 Bytes). View file
 
llmeval-env/lib/python3.10/site-packages/torch/utils/__pycache__/cpp_extension.cpython-310.pyc ADDED
Binary file (71.6 kB). View file
 
llmeval-env/lib/python3.10/site-packages/torch/utils/__pycache__/dlpack.cpython-310.pyc ADDED
Binary file (3.86 kB). View file
 
llmeval-env/lib/python3.10/site-packages/torch/utils/__pycache__/weak.cpython-310.pyc ADDED
Binary file (9.14 kB). View file
 
llmeval-env/lib/python3.10/site-packages/torch/utils/_sympy/__init__.py ADDED
File without changes
llmeval-env/lib/python3.10/site-packages/torch/utils/_sympy/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (191 Bytes). View file
 
llmeval-env/lib/python3.10/site-packages/torch/utils/_sympy/__pycache__/functions.cpython-310.pyc ADDED
Binary file (9.69 kB). View file
 
llmeval-env/lib/python3.10/site-packages/torch/utils/_sympy/__pycache__/interp.cpython-310.pyc ADDED
Binary file (3 kB). View file
 
llmeval-env/lib/python3.10/site-packages/torch/utils/_sympy/__pycache__/reference.cpython-310.pyc ADDED
Binary file (6.59 kB). View file
 
llmeval-env/lib/python3.10/site-packages/torch/utils/_sympy/__pycache__/singleton_int.cpython-310.pyc ADDED
Binary file (2.82 kB). View file
 
llmeval-env/lib/python3.10/site-packages/torch/utils/_sympy/__pycache__/solve.cpython-310.pyc ADDED
Binary file (2.89 kB). View file