Sumitwarrior7 commited on
Commit
de81d48
·
verified ·
1 Parent(s): c71ee4b

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. .venv/lib/python3.10/site-packages/torch/_higher_order_ops/__init__.py +84 -0
  2. .venv/lib/python3.10/site-packages/torch/_higher_order_ops/_invoke_quant.py +62 -0
  3. .venv/lib/python3.10/site-packages/torch/_higher_order_ops/aoti_call_delegate.py +165 -0
  4. .venv/lib/python3.10/site-packages/torch/_higher_order_ops/associative_scan.py +923 -0
  5. .venv/lib/python3.10/site-packages/torch/_higher_order_ops/auto_functionalize.py +1069 -0
  6. .venv/lib/python3.10/site-packages/torch/_higher_order_ops/base_hop.py +281 -0
  7. .venv/lib/python3.10/site-packages/torch/_higher_order_ops/cond.py +757 -0
  8. .venv/lib/python3.10/site-packages/torch/_higher_order_ops/effects.py +340 -0
  9. .venv/lib/python3.10/site-packages/torch/_higher_order_ops/executorch_call_delegate.py +182 -0
  10. .venv/lib/python3.10/site-packages/torch/_higher_order_ops/flat_apply.py +178 -0
  11. .venv/lib/python3.10/site-packages/torch/_higher_order_ops/flex_attention.py +1461 -0
  12. .venv/lib/python3.10/site-packages/torch/_higher_order_ops/foreach_map.py +24 -0
  13. .venv/lib/python3.10/site-packages/torch/_higher_order_ops/hints_wrap.py +142 -0
  14. .venv/lib/python3.10/site-packages/torch/_higher_order_ops/invoke_leaf_function.py +608 -0
  15. .venv/lib/python3.10/site-packages/torch/_higher_order_ops/invoke_subgraph.py +1063 -0
  16. .venv/lib/python3.10/site-packages/torch/_higher_order_ops/local_map.py +641 -0
  17. .venv/lib/python3.10/site-packages/torch/_higher_order_ops/map.py +338 -0
  18. .venv/lib/python3.10/site-packages/torch/_higher_order_ops/out_dtype.py +164 -0
  19. .venv/lib/python3.10/site-packages/torch/_higher_order_ops/partitioner.py +381 -0
  20. .venv/lib/python3.10/site-packages/torch/_higher_order_ops/print.py +116 -0
  21. .venv/lib/python3.10/site-packages/torch/_higher_order_ops/run_const_graph.py +85 -0
  22. .venv/lib/python3.10/site-packages/torch/_higher_order_ops/scan.py +990 -0
  23. .venv/lib/python3.10/site-packages/torch/_higher_order_ops/schema.py +323 -0
  24. .venv/lib/python3.10/site-packages/torch/_higher_order_ops/strict_mode.py +98 -0
  25. .venv/lib/python3.10/site-packages/torch/_higher_order_ops/torchbind.py +168 -0
  26. .venv/lib/python3.10/site-packages/torch/_higher_order_ops/triton_kernel_wrap.py +2207 -0
  27. .venv/lib/python3.10/site-packages/torch/_higher_order_ops/utils.py +1339 -0
  28. .venv/lib/python3.10/site-packages/torch/_higher_order_ops/while_loop.py +954 -0
  29. .venv/lib/python3.10/site-packages/torch/_higher_order_ops/wrap.py +394 -0
  30. .venv/lib/python3.10/site-packages/torch/_inductor/analysis/__init__.py +0 -0
  31. .venv/lib/python3.10/site-packages/torch/_inductor/analysis/device_info.py +216 -0
  32. .venv/lib/python3.10/site-packages/torch/_inductor/analysis/profile_analysis.py +823 -0
  33. .venv/lib/python3.10/site-packages/torch/_inductor/compile_worker/__init__.py +0 -0
  34. .venv/lib/python3.10/site-packages/torch/_inductor/compile_worker/__main__.py +80 -0
  35. .venv/lib/python3.10/site-packages/torch/_inductor/compile_worker/subproc_pool.py +496 -0
  36. .venv/lib/python3.10/site-packages/torch/_inductor/compile_worker/timer.py +55 -0
  37. .venv/lib/python3.10/site-packages/torch/_inductor/compile_worker/tracked_process_pool.py +113 -0
  38. .venv/lib/python3.10/site-packages/torch/_inductor/compile_worker/utils.py +54 -0
  39. .venv/lib/python3.10/site-packages/torch/_inductor/fx_passes/serialized_patterns/__init__.py +0 -0
  40. .venv/lib/python3.10/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_1.py +174 -0
  41. .venv/lib/python3.10/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_10.py +205 -0
  42. .venv/lib/python3.10/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_11.py +204 -0
  43. .venv/lib/python3.10/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_13.py +130 -0
  44. .venv/lib/python3.10/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_14.py +210 -0
  45. .venv/lib/python3.10/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_15.py +230 -0
  46. .venv/lib/python3.10/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_16.py +599 -0
  47. .venv/lib/python3.10/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_18.py +453 -0
  48. .venv/lib/python3.10/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_19.py +209 -0
  49. .venv/lib/python3.10/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_2.py +174 -0
  50. .venv/lib/python3.10/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_20.py +244 -0
.venv/lib/python3.10/site-packages/torch/_higher_order_ops/__init__.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from torch._higher_order_ops._invoke_quant import (
2
+ invoke_quant,
3
+ invoke_quant_packed,
4
+ InvokeQuant,
5
+ )
6
+ from torch._higher_order_ops.aoti_call_delegate import aoti_call_delegate
7
+ from torch._higher_order_ops.associative_scan import associative_scan
8
+ from torch._higher_order_ops.auto_functionalize import (
9
+ auto_functionalized,
10
+ auto_functionalized_v2,
11
+ )
12
+ from torch._higher_order_ops.base_hop import BaseHOP
13
+ from torch._higher_order_ops.cond import cond
14
+ from torch._higher_order_ops.effects import with_effects
15
+ from torch._higher_order_ops.executorch_call_delegate import executorch_call_delegate
16
+ from torch._higher_order_ops.flat_apply import flat_apply
17
+ from torch._higher_order_ops.flex_attention import (
18
+ flex_attention,
19
+ flex_attention_backward,
20
+ )
21
+ from torch._higher_order_ops.foreach_map import _foreach_map, foreach_map
22
+ from torch._higher_order_ops.hints_wrap import hints_wrapper
23
+ from torch._higher_order_ops.invoke_leaf_function import invoke_leaf_function
24
+ from torch._higher_order_ops.invoke_subgraph import invoke_subgraph
25
+ from torch._higher_order_ops.local_map import local_map_hop
26
+ from torch._higher_order_ops.map import map
27
+ from torch._higher_order_ops.out_dtype import out_dtype
28
+ from torch._higher_order_ops.print import print
29
+ from torch._higher_order_ops.run_const_graph import run_const_graph
30
+ from torch._higher_order_ops.scan import scan
31
+ from torch._higher_order_ops.strict_mode import strict_mode
32
+ from torch._higher_order_ops.torchbind import call_torchbind
33
+ from torch._higher_order_ops.while_loop import (
34
+ while_loop,
35
+ while_loop_stack_output_op as while_loop_stack_output,
36
+ )
37
+ from torch._higher_order_ops.wrap import (
38
+ dynamo_bypassing_wrapper,
39
+ inductor_compiled_code,
40
+ tag_activation_checkpoint,
41
+ wrap_activation_checkpoint,
42
+ wrap_with_autocast,
43
+ wrap_with_set_grad_enabled,
44
+ )
45
+
46
+
47
+ __all__ = [
48
+ "cond",
49
+ "while_loop",
50
+ "invoke_subgraph",
51
+ "scan",
52
+ "map",
53
+ "flex_attention",
54
+ "flex_attention_backward",
55
+ "hints_wrapper",
56
+ "BaseHOP",
57
+ "flat_apply",
58
+ "foreach_map",
59
+ "_foreach_map",
60
+ "with_effects",
61
+ "tag_activation_checkpoint",
62
+ "auto_functionalized",
63
+ "auto_functionalized_v2",
64
+ "associative_scan",
65
+ "out_dtype",
66
+ "executorch_call_delegate",
67
+ "call_torchbind",
68
+ "run_const_graph",
69
+ "InvokeQuant",
70
+ "invoke_leaf_function",
71
+ "invoke_quant",
72
+ "invoke_quant_packed",
73
+ "wrap_with_set_grad_enabled",
74
+ "wrap_with_autocast",
75
+ "wrap_activation_checkpoint",
76
+ "dynamo_bypassing_wrapper",
77
+ "strict_mode",
78
+ "aoti_call_delegate",
79
+ "map",
80
+ "while_loop_stack_output",
81
+ "local_map_hop",
82
+ "print",
83
+ "inductor_compiled_code",
84
+ ]
.venv/lib/python3.10/site-packages/torch/_higher_order_ops/_invoke_quant.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ # need to fix prim_hop_base type annotations first
3
+
4
+ import dataclasses
5
+ from typing import Optional
6
+
7
+ import torch
8
+ from torch._higher_order_ops.base_hop import BaseHOP, FunctionWithNoFreeVars
9
+
10
+
11
+ class InvokeQuantTracer(BaseHOP):
12
+ def __init__(self) -> None:
13
+ super().__init__("invoke_quant_packed")
14
+
15
+ def __call__(self, subgraph, *operands, scheme=None, quant_options=None):
16
+ subgraph = FunctionWithNoFreeVars(subgraph)
17
+ return super().__call__(
18
+ subgraph, *operands, scheme=scheme, quant_options=quant_options
19
+ )
20
+
21
+
22
+ invoke_quant_packed = InvokeQuantTracer()
23
+
24
+
25
+ class InvokeQuantUnpacked(BaseHOP):
26
+ def __init__(self) -> None:
27
+ super().__init__("invoke_quant")
28
+
29
+
30
+ invoke_quant = InvokeQuantUnpacked()
31
+
32
+
33
+ @dataclasses.dataclass(frozen=True, repr=True)
34
+ class InvokeQuant:
35
+ """
36
+ Invoke a quantization function that will be preserved as a single operator. Preservation
37
+ as a single operator aids in pattern matching and custom lowerings.
38
+
39
+ The operation appears as:
40
+ torch.ops.higher_order.invoke_quant(subgraph, *args, scheme=scheme)
41
+
42
+ Args:
43
+ codegen_low_precision: Use observed subgraph dtypes for codegen instead of
44
+ upcasting to fp32. Can improve performance for prologue fusion but
45
+ requires careful testing of numerics.
46
+ """
47
+
48
+ codegen_low_precision: bool = True
49
+
50
+ def __call__(
51
+ self,
52
+ *args,
53
+ scheme: Optional[str] = None,
54
+ **kwargs,
55
+ ):
56
+ if not torch.compiler.is_compiling():
57
+ return args[0](*args[1:], **kwargs)
58
+
59
+ if scheme is not None:
60
+ kwargs["scheme"] = scheme
61
+
62
+ return invoke_quant_packed(*args, **kwargs, quant_options=self) # type: ignore[call-arg]
.venv/lib/python3.10/site-packages/torch/_higher_order_ops/aoti_call_delegate.py ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+
3
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
4
+ # All rights reserved.
5
+ #
6
+ # This source code is licensed under the BSD-style license found in the
7
+ # LICENSE file in the root directory of this source tree.
8
+
9
+ from __future__ import annotations
10
+
11
+ import torch
12
+ import torch.utils._pytree as pytree
13
+ from torch._ops import HigherOrderOperator
14
+ from torch._subclasses.fake_tensor import FakeTensor, FakeTensorMode
15
+ from torch.fx.experimental.proxy_tensor import (
16
+ disable_proxy_modes_tracing,
17
+ ProxyTorchDispatchMode,
18
+ track_tensor_tree,
19
+ )
20
+
21
+
22
+ AOTI_LOWERED_MODULE = "AOTInductorEPModule/AOTInductorRunnerWrapper"
23
+
24
+
25
+ class AOTICallDelegate(HigherOrderOperator):
26
+ """aoti_call_delegate is a HOP for calling AOTInductor lowered submodule in ExportedProgram.
27
+
28
+ It has the following signature:
29
+ aoti_call_delegate(
30
+ lowered_module: Union[AOTInductorEPModule, AOTInductorRunnerWrapper]
31
+ original_gm:fx.GraphModule,
32
+ weight_args: List[Tensor],
33
+ input_args: List[Tensor],
34
+ ) -> outputs: List[Tensor]
35
+
36
+ where,
37
+ - lowered_module is the AOTInductor lowered submodule, backed by compiled .so file, supporting real tensor inputs
38
+ - original_gm is the stateless version of the original GraphModule before lowering, allowing FakeTensor propagation
39
+ - weight_args is the list of weights in original GraphModule, including parameters and buffers
40
+ - input_args is the list of flatten inputs
41
+ """
42
+
43
+ def __init__(self) -> None:
44
+ super().__init__("aoti_call_delegate")
45
+
46
+ def __call__(
47
+ self,
48
+ lowered_module: AOTI_LOWERED_MODULE, # type: ignore[valid-type]
49
+ original_gm: torch.fx.GraphModule,
50
+ weight_args: list[torch.Tensor],
51
+ input_args: list[torch.Tensor],
52
+ ) -> list[torch.Tensor]:
53
+ # pyrefly: ignore [missing-attribute]
54
+ return super().__call__(lowered_module, original_gm, weight_args, input_args)
55
+
56
+
57
+ aoti_call_delegate = AOTICallDelegate()
58
+ aoti_call_delegate.fallthrough(torch._C.DispatchKey.PythonDispatcher)
59
+ aoti_call_delegate.fallthrough(torch._C.DispatchKey.PythonTLSSnapshot)
60
+ aoti_call_delegate.fallthrough(torch._C.DispatchKey.ADInplaceOrView)
61
+ aoti_call_delegate.fallthrough(torch._C.DispatchKey.AutocastCPU)
62
+
63
+
64
+ @aoti_call_delegate.py_impl(torch._C.DispatchKey.CompositeExplicitAutograd)
65
+ def call_delegate_cpu(
66
+ lowered_module: AOTI_LOWERED_MODULE, # type: ignore[valid-type]
67
+ original_gm: torch.fx.GraphModule,
68
+ weight_args: list[torch.Tensor],
69
+ input_args: list[torch.Tensor],
70
+ ) -> list[torch.Tensor]:
71
+ # FX creates this immutable_dict/list concept. Get rid of this.
72
+ map_types: dict[type, type] = {
73
+ torch.fx.immutable_collections.immutable_dict: dict,
74
+ torch.fx.immutable_collections.immutable_list: list,
75
+ }
76
+ new_args = pytree.tree_map_only(
77
+ tuple(map_types.keys()),
78
+ lambda a: map_types[type(a)](a),
79
+ weight_args + input_args,
80
+ lambda a: isinstance(a, tuple(map_types.keys())),
81
+ )
82
+ has_fake_args = any(isinstance(arg, FakeTensor) for arg in new_args)
83
+ if has_fake_args:
84
+ # use stateless original_gm for tracing with fake tensors
85
+ fake_out = original_gm(*new_args)
86
+ return fake_out
87
+ else:
88
+ # use AOTI Runner for real tensors
89
+ new_input_args = new_args[len(weight_args) :]
90
+ if type(lowered_module).__name__ == "AOTInductorRunnerWrapper":
91
+ return lowered_module(*new_input_args) # type: ignore[misc]
92
+ elif type(lowered_module).__name__ == "AOTInductorEPModule":
93
+ return lowered_module(new_input_args) # type: ignore[misc]
94
+ else:
95
+ raise RuntimeError(
96
+ f"Unexpected lowered_module type: {type(lowered_module)}."
97
+ )
98
+
99
+
100
+ def trace_aoti_call_delegate(
101
+ proxy_mode, func_overload, lowered_module, original_gm, weight_args, input_args
102
+ ):
103
+ proxy_mode.tracer.root.register_module("lowered_module", lowered_module)
104
+ proxy_mode.tracer.root.register_module("original_gm", original_gm)
105
+
106
+ node_args = (lowered_module, original_gm, weight_args, input_args)
107
+ proxy_args = pytree.tree_map(proxy_mode.tracer.unwrap_proxy, node_args)
108
+
109
+ out_proxy = proxy_mode.tracer.create_proxy(
110
+ "call_function", func_overload, proxy_args, {}, name="aoti_call_delegate"
111
+ )
112
+ with disable_proxy_modes_tracing():
113
+ out = call_delegate_cpu(lowered_module, original_gm, weight_args, input_args)
114
+
115
+ return track_tensor_tree(out, out_proxy, constant=None, tracer=proxy_mode.tracer)
116
+
117
+
118
+ @aoti_call_delegate.py_impl(ProxyTorchDispatchMode)
119
+ def call_delegate_proxy_torch_dispatch_mode(
120
+ mode: ProxyTorchDispatchMode,
121
+ lowered_module: AOTI_LOWERED_MODULE, # type: ignore[valid-type]
122
+ original_gm: torch.fx.GraphModule,
123
+ weight_args: list[torch.Tensor],
124
+ input_args: list[torch.Tensor],
125
+ ):
126
+ res = trace_aoti_call_delegate(
127
+ mode, aoti_call_delegate, lowered_module, original_gm, weight_args, input_args
128
+ )
129
+ return res
130
+
131
+
132
+ @aoti_call_delegate.py_impl(FakeTensorMode)
133
+ def call_delegate_fake_tensor_mode(
134
+ mode: FakeTensorMode,
135
+ lowered_module: AOTI_LOWERED_MODULE, # type: ignore[valid-type]
136
+ original_gm: torch.fx.GraphModule,
137
+ weight_args: list[torch.Tensor],
138
+ input_args: list[torch.Tensor],
139
+ ) -> list[torch.Tensor]:
140
+ with mode:
141
+ return call_delegate_cpu(lowered_module, original_gm, weight_args, input_args)
142
+
143
+
144
+ @aoti_call_delegate.py_functionalize_impl
145
+ def call_delegate_functionalize(
146
+ ctx,
147
+ lowered_module: AOTI_LOWERED_MODULE, # type: ignore[valid-type]
148
+ original_gm: torch.fx.GraphModule,
149
+ weight_args: list[torch.Tensor],
150
+ input_args: list[torch.Tensor],
151
+ ):
152
+ unwrapped_weight_args = tuple(
153
+ ctx.unwrap_tensors(weight_arg) for weight_arg in weight_args
154
+ )
155
+ unwrapped_input_args = tuple(
156
+ ctx.unwrap_tensors(input_arg) for input_arg in input_args
157
+ )
158
+ with ctx.redispatch_to_next():
159
+ res = aoti_call_delegate(
160
+ lowered_module,
161
+ original_gm,
162
+ unwrapped_weight_args, # type: ignore[arg-type]
163
+ unwrapped_input_args, # type: ignore[arg-type]
164
+ )
165
+ return ctx.wrap_tensors(res)
.venv/lib/python3.10/site-packages/torch/_higher_order_ops/associative_scan.py ADDED
@@ -0,0 +1,923 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import functools
3
+ import itertools
4
+ from collections.abc import Callable
5
+ from typing import Any
6
+
7
+ import torch
8
+ import torch._prims_common as utils
9
+ import torch.utils._pytree as pytree
10
+ from torch._C import DispatchKey
11
+ from torch._higher_order_ops.utils import (
12
+ _maybe_compile_and_run_fn,
13
+ _maybe_run_with_interpreter,
14
+ check_input_alias_and_mutation_return_outputs,
15
+ check_meta_consistency,
16
+ create_bw_fn,
17
+ first_slice_copy,
18
+ first_slice_copy_with_grad,
19
+ materialize_as_graph,
20
+ reenter_make_fx,
21
+ save_values_for_backward,
22
+ saved_values,
23
+ split_into_chunks,
24
+ unique_graph_id,
25
+ validate_subgraph_args_types,
26
+ )
27
+ from torch._ops import HigherOrderOperator
28
+ from torch._subclasses.fake_tensor import FakeTensorMode
29
+ from torch.fx.experimental.proxy_tensor import (
30
+ disable_proxy_modes_tracing,
31
+ ProxyTorchDispatchMode,
32
+ track_tensor_tree,
33
+ )
34
+
35
+
36
+ aten = torch._ops.ops.aten
37
+
38
+
39
+ def wrap_combine_fn_flat(*args, combine_fn, spec, num_leaves):
40
+ if len(args) != 2 * num_leaves:
41
+ raise AssertionError(
42
+ f"Combine_fn received wrong number of arguments, expected {2 * num_leaves}, but got {len(args)}"
43
+ )
44
+ lhs = pytree.tree_unflatten(args[:num_leaves], spec)
45
+ rhs = pytree.tree_unflatten(args[num_leaves:], spec)
46
+ return combine_fn(lhs, rhs)
47
+
48
+
49
+ def _interleave(a, b, dim=0):
50
+ # https://stackoverflow.com/questions/60869537/how-can-i-interleave-5-pytorch-tensors
51
+ if b_trunc := (a.shape[dim] == b.shape[dim] + 1):
52
+ pad = (
53
+ [0] * ((b.ndim - dim - 1) * 2 + 1)
54
+ + [1]
55
+ + [0] * (b.ndim * 2 - ((b.ndim - dim - 1) * 2 + 2))
56
+ )
57
+ b = torch.nn.functional.pad(b, pad)
58
+
59
+ stacked = torch.stack([a, b], dim=dim + 1)
60
+ interleaved = torch.flatten(stacked, start_dim=dim, end_dim=dim + 1)
61
+ # pyrefly: ignore [unbound-name]
62
+ if b_trunc:
63
+ # TODO: find torch alternative for slice_along dim for torch.jit.script to work
64
+ interleaved = aten.slice(interleaved, dim, 0, b.shape[dim] + a.shape[dim] - 1)
65
+ return interleaved
66
+
67
+
68
+ def safe_map(f, *args):
69
+ args = list(map(list, args))
70
+ n = len(args[0])
71
+ for arg in args[1:]:
72
+ if len(arg) != n:
73
+ raise ValueError("length mismatch: {list(map(len, args))}")
74
+
75
+ def nf(a):
76
+ return f(*a)
77
+
78
+ return list(map(nf, zip(*args)))
79
+
80
+
81
+ class AssociativeScanOp(HigherOrderOperator):
82
+ def __init__(self):
83
+ super().__init__("associative_scan")
84
+
85
+ def __call__(self, combine_fn, xs, additional_inputs):
86
+ # There is currently an issue that the ScanOp is sometimes called with
87
+ # the additional_inputs being a list. See https://github.com/pytorch/pytorch/issues/145785
88
+ # Once this issue is resolved, the assertion should only allow tuples
89
+ # and the tuple cast should be removed
90
+ if not isinstance(additional_inputs, (tuple, list)):
91
+ raise AssertionError(
92
+ f"additional_inputs must be a tuple or list, got {type(additional_inputs)}"
93
+ )
94
+ additional_inputs = (
95
+ tuple(additional_inputs)
96
+ if isinstance(additional_inputs, list)
97
+ else additional_inputs
98
+ )
99
+ validate_subgraph_args_types(additional_inputs)
100
+ # pyrefly: ignore [missing-attribute]
101
+ return super().__call__(combine_fn, xs, additional_inputs)
102
+
103
+ # pyrefly: ignore [bad-override]
104
+ def gen_schema(self, combine_fn, xs, additional_inputs):
105
+ from torch._higher_order_ops.schema import HopSchemaGenerator
106
+ from torch._higher_order_ops.utils import materialize_as_graph
107
+
108
+ # For associative scan, we need two copies of xs for the combine function
109
+ # The combine function takes two elements and returns one element
110
+ xs_slice1 = [first_slice_copy(x) for x in xs]
111
+ xs_slice2 = [first_slice_copy(x) for x in xs]
112
+ all_inputs = tuple(xs_slice1 + xs_slice2 + list(additional_inputs))
113
+
114
+ combine_gm: torch.fx.GraphModule = materialize_as_graph(combine_fn, all_inputs)
115
+ (
116
+ _,
117
+ _,
118
+ _,
119
+ mutated_inputs,
120
+ outputs,
121
+ ) = check_input_alias_and_mutation_return_outputs(combine_gm)
122
+ if len(mutated_inputs) > 0:
123
+ raise RuntimeError(
124
+ "For associative_scan, combine_fn cannot have in-place mutations but found "
125
+ f"{mutated_inputs}-th inputs are mutated."
126
+ )
127
+
128
+ schema_gen = HopSchemaGenerator(self)
129
+ schema_gen.add_arg("combine_fn", combine_gm)
130
+
131
+ for idx, x in enumerate(xs):
132
+ schema_gen.add_arg(f"xs{idx}", x)
133
+
134
+ for idx, arg in enumerate(additional_inputs):
135
+ schema_gen.add_arg(
136
+ f"additional_input{idx}",
137
+ arg,
138
+ )
139
+
140
+ for out in outputs:
141
+ schema_gen.add_output(out)
142
+
143
+ schema_gen.add_schema_tree_spec(combine_fn, xs, additional_inputs)
144
+ return schema_gen.gen_schema()
145
+
146
+
147
+ associative_scan_op = AssociativeScanOp()
148
+
149
+
150
+ def associative_scan(
151
+ combine_fn: Callable[[pytree.PyTree, pytree.PyTree], pytree.PyTree],
152
+ xs: pytree.PyTree,
153
+ dim: int,
154
+ reverse: bool = False,
155
+ combine_mode: str = "pointwise",
156
+ ) -> torch.Tensor:
157
+ r"""
158
+ Performs an inclusive scan with an associative combine function.
159
+
160
+ .. warning::
161
+
162
+ ``torch.associative_scan`` is a prototype feature in PyTorch. It currently
163
+ does not support autograd and you may run into miscompiles.
164
+ Read more about feature classification at:
165
+ https://pytorch.org/blog/pytorch-feature-classification-changes/#prototype
166
+
167
+ This operator requires runtime code generation and so requires support for
168
+ ``torch.compile``. Further, only CUDA device codegen is supported at the moment.
169
+
170
+ Args:
171
+ combine_fn (Callable): A binary callable with type ``(Tensor, Tensor) -> Tensor``,
172
+ or if input is a pytree ``(pytree, pytree) -> pytree``.
173
+ This function must be pure, i.e., no lifted arguments are supported at the moment,
174
+ satisfy the associative property and have no side-effects.
175
+ xs (torch.Tensor): The input tensor, or nested pytree of tensors.
176
+ All inputs are expected to have the same shape.
177
+ dim (int): the dimension to scan over
178
+ reverse (bool): A boolean stating if the scan should be reversed with respect to ``dim``, default ``False``.
179
+ combine_mode (str): A string indicating whether the ``combine_fn`` is ``pointwise`` or ``generic``, default ``pointwise``.
180
+ If ``combine_mode=pointwise``, ``combine_fn`` must be pure, may only contain pointwise operations
181
+ and ``xs`` must be CUDA tensors.
182
+ In all other cases ``combine_mode=generic`` should be used.
183
+ Note: ``combine_mode=pointwise`` is more efficient than ``combine_mode=generic``.
184
+
185
+
186
+ Example::
187
+
188
+ def add(x: torch.Tensor, y: torch.Tensor):
189
+ return x + y
190
+
191
+
192
+ cumsum = associative_scan(add, x, dim)
193
+
194
+ """
195
+ # TODO: Support lifted arguments in inductor for associative_scan
196
+ # TODO: Support autograd for cases with lifted arguments for combine_mode=pointwise
197
+
198
+ # The reason we flatten xs before calling into dynamo is that
199
+ # we want to create a consistent input ordering for combine_fn
200
+ # and we also want to the input ordering matches the output ordering.
201
+ leaves_xs_orig, spec_xs = pytree.tree_flatten(xs)
202
+
203
+ def _validate_input(cfn, lxs, d, r, cm):
204
+ # Basic arguments check
205
+ if not callable(cfn):
206
+ raise ValueError(f"Combine_fn must be a callable, but got {cfn}")
207
+ if not isinstance(d, int):
208
+ raise ValueError("Dim must be an int, but got " + str(type(d)))
209
+ if not isinstance(r, bool):
210
+ raise RuntimeError("Reverse must be a bool, but got " + str(type(r)))
211
+ if cm not in ["pointwise", "generic"]:
212
+ raise ValueError(
213
+ f"Combine_mode must either 'pointwise' or 'generic', but got {cm}"
214
+ )
215
+ if cm == "pointwise" and not all(l.device.type in ("cuda", "xpu") for l in lxs):
216
+ raise ValueError(
217
+ "For combine_mode='pointwise', all input tensors need to be on CUDA or XPU"
218
+ )
219
+
220
+ # Checks for xs
221
+ if len(lxs) == 0:
222
+ raise ValueError("Expected at least 1 xs leaf")
223
+ if any(not isinstance(x, torch.Tensor) for x in lxs):
224
+ raise ValueError("xs leaves must be a Tensor")
225
+ if any(x.is_sparse for x in lxs):
226
+ raise ValueError(
227
+ "xs leaves must dense Tensors, consider using `to_dense()`"
228
+ )
229
+ if any(x.ndim <= d for x in lxs):
230
+ raise ValueError(
231
+ "All xs leaves must at least have 'dim' number of dimensions and scan dimension > 0"
232
+ )
233
+ if any(x.shape[d] == 0 for x in lxs):
234
+ raise ValueError(
235
+ "All xs leaves must at least have 'dim' number of dimensions and scan dimension > 0"
236
+ )
237
+
238
+ ndim = leaves_xs_orig[0].ndim
239
+ dim = utils.canonicalize_dim(ndim, dim)
240
+
241
+ _validate_input(combine_fn, leaves_xs_orig, dim, reverse, combine_mode)
242
+
243
+ # Move scan dim to 0 and always perform scan on dim 0
244
+ leaves_xs = [torch.movedim(elem, dim, 0) for elem in leaves_xs_orig]
245
+
246
+ if reverse:
247
+ leaves_xs = [torch.flip(elem, [0]) for elem in leaves_xs]
248
+
249
+ if combine_mode == "generic":
250
+ # The generic_associative_scan implementation calls the combine_fn with a `batch` along the scan dimension
251
+ # For example, consider:
252
+ # def add(x: torch.Tensor, y: torch.Tensor):
253
+ # return x + y
254
+ # leaves = torch.tensor([[0.0, 1.0, 2.0, 3.0]
255
+ # [0.0, 1.0, 2.0, 3.0]])
256
+ # which has shape 2 x 4;
257
+ # dim = 1;
258
+ # In the first iteration of `_scan` the combine_fn gets invoked with
259
+ # combine_fn([torch.tensor([[0.0, 2.0],
260
+ # [0.0, 2.0]])],
261
+ # [torch.tensor([[1.0, 3.0],
262
+ # [1.0, 3.0]])])
263
+ # The arguments are of shape 2 x 2, but can be evaluated in parallel along the scan dimension.
264
+ combine_fn = functools.partial(
265
+ wrap_combine_fn_flat,
266
+ combine_fn=torch.vmap(
267
+ combine_fn,
268
+ in_dims=(
269
+ pytree.tree_unflatten([0] * len(leaves_xs), spec_xs),
270
+ pytree.tree_unflatten([0] * len(leaves_xs), spec_xs),
271
+ ),
272
+ out_dims=0,
273
+ ),
274
+ spec=spec_xs,
275
+ num_leaves=len(leaves_xs),
276
+ )
277
+ out = generic_associative_scan(combine_fn, leaves_xs, additional_inputs=())
278
+ out = pytree.tree_unflatten(out, spec_xs)
279
+ else:
280
+ combine_fn = functools.partial(
281
+ wrap_combine_fn_flat,
282
+ combine_fn=combine_fn,
283
+ spec=spec_xs,
284
+ num_leaves=len(leaves_xs),
285
+ )
286
+
287
+ def run_flattened_associative_scan(combine_fn, leaves_xs):
288
+ return associative_scan_op(combine_fn, leaves_xs, additional_inputs=())
289
+
290
+ out = _maybe_compile_and_run_fn(
291
+ run_flattened_associative_scan,
292
+ combine_fn,
293
+ leaves_xs,
294
+ )
295
+
296
+ if reverse:
297
+ out = pytree.tree_map(lambda elem: elem.flip([0]), out)
298
+
299
+ out = pytree.tree_map(lambda elem: torch.movedim(elem, 0, dim), out)
300
+
301
+ return out
302
+
303
+
304
+ def generic_associative_scan(operator, leaves, dim=0, additional_inputs=()):
305
+ r"""
306
+ This function performs the associative_scan operation.
307
+ The algorithm works by recursively collecting neighbours of ``leaves`` and subsequently
308
+ applying the ``operator`` on all pairs in parallel along ``dim``.
309
+ The results of the recursive calls are later combined.
310
+
311
+ Args:
312
+ operator (Callable): A binary callable with type ``(Tensor, Tensor) -> Tensor``,
313
+ or if input is a pytree ``(pytree, pytree) -> pytree``.
314
+ This function must be pure, pointwise, and satisfy the associative property.
315
+ leaves (torch.Tensor): A list of torch.Tensors converted from the pytree of
316
+ ``xs`` provided to ``associative_scan``.
317
+ All inputs are expected to have the same shape.
318
+ dim (int): the dimension to scan over
319
+ additional_inputs (Tuple of tensors): A tuple of lifted parameters from the global scope.
320
+ This parameter will be populated internally.
321
+
322
+ Example::
323
+
324
+ def add(x: torch.Tensor, y: torch.Tensor):
325
+ return x + y
326
+
327
+ leaves = torch.tensor([0.0, 1.0, 2.0, 3.0])
328
+
329
+ First iteration of _scan ->
330
+ # odd_elems -> apply operator on all neighbours
331
+ # odd_elems = operator([torch.tensor([0.0, 2.0])],
332
+ # [torch.tensor([1.0, 3.0])])
333
+ odd_elems = torch.tensor([1.0, 5.0])
334
+ Second iteration of _scan ->
335
+ # odd_elems = operator([torch.tensor([1.0])],
336
+ # [torch.tensor([5.0])])
337
+ odd_elems = torch.tensor([6.0])
338
+ # even_elems -> apply operator on all odd_elems and
339
+ # every second element of ``elems``, starting from the second element.
340
+ # even_elems is expanded with the first element of ``elems``
341
+ even_elems = [1.0]
342
+ # Merges odd_elems and even_elems
343
+ res = torch.tensor([1.0, 6.0])
344
+ # even_elems -> apply operator on all odd_elems and
345
+ # every second element of ``elems``, starting from the second element.
346
+ # even_elems is expanded with the first element of ``elems``
347
+ even_elems = [0.0, 3.0]
348
+ # Merges odd_elems and even_elems
349
+ res = torch.tensor([0.0, 1.0, 3.0, 6.0])
350
+
351
+ """
352
+
353
+ def call_operator(*args):
354
+ return pytree.tree_leaves(operator(*args))
355
+
356
+ def _scan(elems):
357
+ """Perform the actual recursive scan on ``elems``."""
358
+ num_elems = elems[0].shape[dim]
359
+
360
+ if num_elems < 2:
361
+ return elems
362
+
363
+ reduced_elems = call_operator(
364
+ *[aten.slice(elem, dim, 0, -1, 2) for elem in elems],
365
+ *[aten.slice(elem, dim, 1, None, 2) for elem in elems],
366
+ *additional_inputs,
367
+ )
368
+
369
+ # Recursively compute scan for partially reduced tensors.
370
+ odd_elems = _scan(reduced_elems)
371
+
372
+ if num_elems % 2 == 0:
373
+ even_elems = call_operator(
374
+ *[aten.slice(e, dim, 0, -1) for e in odd_elems],
375
+ *[aten.slice(e, dim, 2, None, 2) for e in elems],
376
+ *additional_inputs,
377
+ )
378
+ else:
379
+ even_elems = call_operator(
380
+ *odd_elems,
381
+ *[aten.slice(e, dim, 2, None, 2) for e in elems],
382
+ *additional_inputs,
383
+ )
384
+
385
+ # The first element of a scan is the same as the first element
386
+ # of the original `elems`.
387
+ even_elems = [
388
+ torch.cat([aten.slice(elem, dim, 0, 1), result], dim=dim)
389
+ if result.shape.numel() > 0 and elem.shape[dim] > 0
390
+ else result
391
+ if result.shape.numel() > 0
392
+ else aten.slice(
393
+ elem, dim, 0, 1
394
+ ) # Jax allows/ignores concat with 0-dim, Pytorch does not
395
+ for (elem, result) in zip(elems, even_elems)
396
+ ]
397
+
398
+ return list(
399
+ safe_map(functools.partial(_interleave, dim=dim), even_elems, odd_elems)
400
+ )
401
+
402
+ scans = _scan(leaves)
403
+
404
+ return scans
405
+
406
+
407
+ def trace_associative_scan(
408
+ proxy_mode,
409
+ func_overload,
410
+ combine_fn: Callable,
411
+ xs: list[torch.Tensor],
412
+ additional_inputs: tuple[torch.Tensor],
413
+ ):
414
+ from torch._dynamo.utils import clone_input
415
+
416
+ with disable_proxy_modes_tracing():
417
+ sample_xs = [first_slice_copy(x) for x in itertools.chain(xs, xs)]
418
+ sample_additional_inputs = [
419
+ clone_input(x) if isinstance(x, torch.Tensor) else x
420
+ for x in additional_inputs
421
+ ]
422
+ combine_graph = reenter_make_fx(combine_fn)(
423
+ *sample_xs, *sample_additional_inputs
424
+ )
425
+
426
+ outputs = None
427
+ for node in combine_graph.graph.nodes:
428
+ if node.op == "output":
429
+ if outputs is not None:
430
+ raise AssertionError("found multiple output nodes in combine_graph")
431
+ if len(node.args) != 1:
432
+ raise AssertionError(
433
+ f"expected output node to have 1 arg, got {len(node.args)}"
434
+ )
435
+ outputs = node.args[0]
436
+
437
+ if outputs is None:
438
+ raise AssertionError("no output node found in combine_graph")
439
+ outputs = pytree.tree_leaves(outputs)
440
+ if len(outputs) != len(xs):
441
+ raise AssertionError(
442
+ f"expected combine_fn to return {len(xs)} results but got {len(outputs)}"
443
+ )
444
+
445
+ xs_fake_tensors: list[torch.Tensor | torch.SymInt | int] = [
446
+ first_slice_copy(x) for x in xs
447
+ ]
448
+ output_fake_tensors: list[torch.Tensor | torch.SymInt | int] = [
449
+ c.meta["val"] for c in outputs
450
+ ]
451
+ check_meta_consistency(
452
+ xs_fake_tensors, output_fake_tensors, "init", "carry", include_contiguity=False
453
+ )
454
+
455
+ _, combine_graph_name = unique_graph_id(
456
+ proxy_mode, prefix="associative_scan_combine_graph"
457
+ )
458
+
459
+ proxy_mode.tracer.root.register_module(combine_graph_name, combine_graph)
460
+
461
+ args = (combine_graph, xs, additional_inputs)
462
+ proxy_args = pytree.tree_map(proxy_mode.tracer.unwrap_proxy, args)
463
+ out_proxy = proxy_mode.tracer.create_proxy(
464
+ "call_function", func_overload, proxy_args, {}, name="associative_scan"
465
+ )
466
+
467
+ with disable_proxy_modes_tracing():
468
+ out = tuple(aten.clone(x) for x in xs)
469
+
470
+ return track_tensor_tree(out, out_proxy, constant=None, tracer=proxy_mode.tracer)
471
+
472
+
473
+ @associative_scan_op.py_impl(DispatchKey.CompositeExplicitAutograd)
474
+ def associative_scan_op_dense(combine_fn, xs, additional_inputs):
475
+ return generic_associative_scan(combine_fn, xs, additional_inputs=additional_inputs)
476
+
477
+
478
+ class AssociativeScanAutogradOp(torch.autograd.Function):
479
+ r""" associative_scan
480
+ Example::
481
+ xs = torch.arange(1, 5) = [1, 2, 3, 4]
482
+
483
+ def combine_fn(a: torch.Tensor, b: torch.Tensor):
484
+ return a * b
485
+
486
+ ys = associative_scan(comine_fn, xs),
487
+ which can be unpacked as:
488
+ ys0 = xs0 = 1
489
+ ys1 = combine_fn(ys0, xs1) = combine_fn(1, 2) = 2
490
+ ...
491
+ ysT = combine_fn(ys(T-1), xsT) = combine_fn(6, 4) = 24
492
+ ys = [1, 2, 6, 24]
493
+
494
+ This creates a recursive data dependency structure where each output yst
495
+ depends on all prior inputs xs0 through xst. The dependency can be visualized as:
496
+
497
+ Level 0 (Input): xs0 xs1 xs2 xs3 xs4
498
+ \ / | | |
499
+ \ / | | |
500
+ Level 1: ys1 ───────┘ | |
501
+ \ / |
502
+ \ / |
503
+ Level 2: ys2 ────────┘ |
504
+ \ /
505
+ \ /
506
+ Level 3: ys3 ────────────┘
507
+ \
508
+ \
509
+ Level 4: ys4
510
+
511
+
512
+ We could get the following backward gradient graph:
513
+
514
+
515
+ Level 0 (output): g_xs0 g_xs1 g_xs2 g_xs3 g_xs4
516
+ \ / | | |
517
+ \ / | | |
518
+ Level 1: gl_ys1 ─> g_ys1 ──────┘ | |
519
+ \ / |
520
+ \ / |
521
+ Level 2: gl_ys2 ─> g_ys2 ────────┘ |
522
+ \ /
523
+ \ /
524
+ Level 3: gl_ys3 ─> g_ys3 ────────────┘
525
+ \
526
+ \
527
+ Level 4: gl_ys4 ─> g_ys4,
528
+
529
+ where gl_y1 is the gradient of the loss with respect to ys1 and the input of backward.
530
+
531
+ To calculate the gradients of the inputs, the chain rule suggests:
532
+
533
+ g_xs0 = g_ys1
534
+ g_xs1 = g_ys1 * bw(ys0, xs1) = g_ys1 * bwxs01
535
+ g_xs2 = g_ys2 * bw(ys1, xs2) = g_ys2 * bwxs12
536
+ g_xs3 = g_ys3 * bw(ys2, xs3) = g_ys3 * bwxs23
537
+ g_xs4 = g_ys4 * bw(ys3, xs4) = g_ys4 * bwxs34
538
+
539
+ Notice the bw(...) is just the single step bw (instantaneous gradients), whose formula can be computed from combine_fn.
540
+ For example bw(ys3, xs4) (also abbreviated with bwxs34) computes the gradients ∂/∂xs4 combine_fn(ys3, xs4).
541
+ Similarly, bw(ys4, ys3) (also abbreviated with bwys43) computes the gradients ∂/∂ys3 combine_fn(ys3, xs4).
542
+
543
+ Let's break down how to calculate g_ys by recursively substituting the unknowns:
544
+
545
+ g_ys1 = gl_ys1 + g_ys2 * bw(ys2, ys1)
546
+ = gl_ys1 + (gl_ys2 + g_ys3 * bw(ys3, ys2)) * bw(ys2, ys1)
547
+ = gl_ys1 + gl_ys2 * bw(ys2, ys1) + g_ys3 * bw(ys3, ys2) * bw(y2, y1)
548
+ = gl_ys1 + gl_ys2 * bw(ys2, ys1) + gl_ys3 * bw(ys3, ys2) * bw(y2, y1) \
549
+ + g_ys4 * bw(ys4, ys3) * bw(ys3, ys2) * bw(ys2, ys1)
550
+ = gl_ys1 + gl_ys2 * bw(ys2, ys1) + gl_ys3 * bw(ys3, ys2) * bw(y2, y1) \
551
+ + gl_ys4 * bw(ys4, ys3) * bw(ys3, ys2) * bw(ys2, ys1)
552
+
553
+ Let's do the same for all the g_ys:
554
+ g_ys2 = gl_ys2 + gl_ys3 * bw(ys3, ys2) + gl_y4 * bw(ys4, ys3) * bw(ys3, ys2)
555
+ g_ys3 = gl_ys3 + gl_ys4 * bw(ys4, ys3)
556
+ g_ys4 = gl_ys4
557
+
558
+ Notice that the above can be re-written as columnwise multiplication of y_mat and gl_ys:
559
+
560
+ g_ys1 1, bwys21, bwys321, bwys4321 gl_ys1
561
+ g_ys2 = 0, 1 , bwys321, bwys4321 . gl_ys2
562
+ g_ys3 0, 0 , 1 , bwys4321 gl_ys3
563
+ g_ys4 0, 0 , 0 , 1 gl_ys4,
564
+
565
+ where bwys21 is an abbreviation for bw(ys2, ys1),
566
+ bwys321 is an abbreviation for bw(ys3, ys2) * bw(ys2, ys1) so on and so forth.
567
+
568
+ We could effectively compute the upper triangular matrix y_mat with:
569
+ cumprod([1, bwys21, bwys32, bwys43]) then masking out the values as needed.
570
+ Thus, only [1, bwys21, bwys32, bwys43] are required to compute the y_mat.
571
+
572
+
573
+ References: https://justintchiu.com/blog/pscan_diff/
574
+
575
+ NOTE: [associative_scan autograd implementation]
576
+
577
+ The forward of associative_scan can be computed with the following steps:
578
+
579
+ 1.) Compute the forward output of the associative_scan
580
+ ys = associative_scan(combine_fn, xs, additional_inputs)
581
+
582
+ The backward of associative_scan can be computed with the following steps:
583
+
584
+ 2.) Prepare the backward graph
585
+ We prepare the backward graph to be used in the backward function.
586
+ We utilize ``create_bw_fn`` to generate the joint function:
587
+ combine_fn_bw = create_bw_fn(combine_fn, operands)
588
+ where operands = [ys{t-1}, xst, additional_inputs]
589
+
590
+ 3.) Materialize the ``combine_fn_bw``
591
+ This is required because torch.compile and torch.autograd.grad
592
+ cannot trace through the joint backward function dynamically.
593
+
594
+ 4.) Compute the single step bw (instantaneous gradients) at every step t
595
+ bwys{t-1}, bwxst = combine_fn_bw(ys{t-1}, xst, 1.)
596
+ Here we pass 1 as the upstream gradient to obtain the local partial derivatives.
597
+
598
+ This gives:
599
+ bwys = [bw(ys1, ys0), bw(ys2, ys1), ..., bw(ysT, ys{T-1})]
600
+ bwxs = [bw(ys1, xs0), bw(ys2, xs1), ..., bw(ys{T-1}, xsT)]
601
+
602
+ 5.) Compute the gradient transition matrix y_mat
603
+
604
+ As shown in the example above, each input xst affects all later outputs ysi for i ≥ t.
605
+ According to the chain rule, each such path contributes a product of local gradients g_ysk.
606
+
607
+ For example:
608
+ ∂ysT/∂xst = ∂ysT/∂ys{T-1} * ∂ys{T-1}/∂ys{T-2} * ... * ∂ys{t+1}/∂yst * ∂yst/∂xst
609
+ = bw(ysT, ys{T-1}) * bw(ys{T-1}, ys{T-2}) * ... * bw(ys{t+1}, yst) * bw(ys{t-1}, xst)
610
+
611
+ This motivates the use of a cumulative product over bwys to compute all such paths efficiently.
612
+
613
+ We now construct the matrix of gradient transition paths:
614
+
615
+ 5.1 Repeat g_y values to form the base matrix
616
+ y_mat = [[1, bwys21, bwys32, bwys43],
617
+ [1, bwys21, bwys32, bwys43],
618
+ [1, bwys21, bwys32, bwys43],
619
+ [1, bwys21, bwys32, bwys43]]
620
+
621
+ 5.2 Mask the lower triangle (inclusive) with 1s
622
+ y_mat = [[1, bwys21, bwys32, bwys43],
623
+ [1, 1 , bwys32, bwys43],
624
+ [1, 1 , 1 , bwys43],
625
+ [1, 1 , 1 , 1 ]]
626
+
627
+ 5.3 Apply cumulative product row-wise
628
+ y_mat = cumprod(y_mat, dim=1)
629
+ Resulting in:
630
+ y_mat = [[1, bwys21, bwys32 * bwys21, bwys43 * bwys32 * bwys21],
631
+ [1, 1 , bwys32 , bwys43 * bwys32 ],
632
+ [1, 1 , 1 , bwys43 ],
633
+ [1, 1 , 1 , 1 ]]
634
+
635
+ 5.4 Zero out the lower triangle (exclusive)
636
+ Final y_mat:
637
+ y_mat = [[1, bwys21, bwys32 * bwys21, bwys43 * bwys32 * bwys21],
638
+ [0, 1 , bwys32 , bwys43 * bwys32 ],
639
+ [0, 0 , 1 , bwys43 ],
640
+ [0, 0 , 0 , 1 ]]
641
+
642
+ 6.) Scale the y_mat with the upstream gradients gl_ys
643
+ scaled_y_mat = y_mat * gl_ys
644
+ Each entry now holds the full contribution of ∂L/∂ysj to ∂L/∂xsi via the path through ysj.
645
+
646
+ 7.) Reduce the scaled_y_mat with a row-wise sum
647
+ summed_y_mat = scaled_y_mat.sum(dim=1)
648
+ This accumulates all downstream contributions for each xst.
649
+
650
+ 8.) Scale with the instantaneous input gradients bwxs
651
+ g_xs = summed_y_mat * bwxs
652
+
653
+ This gives the final input gradients:
654
+ g_xs = [∂L/∂xs0, ∂L/∂xs1, ..., ∂L/∂xsT]
655
+
656
+ NOTE: [scan partial grad handling]
657
+ If any element of xs or of the outputs does not require gradients
658
+ (i.e., requires_grad=False), then the corresponding gradients will be returned
659
+ as tensors of zeros with the same shape as the element.
660
+ """
661
+
662
+ @staticmethod
663
+ # pyrefly: ignore [bad-override]
664
+ def forward(
665
+ ctx,
666
+ combine_fn,
667
+ num_xs,
668
+ num_additional_inputs,
669
+ *operands,
670
+ ):
671
+ ctx._num_xs = num_xs
672
+ ctx._num_additional_inputs = num_additional_inputs
673
+ ctx._combine_fn = combine_fn
674
+ xs, additional_inputs = split_into_chunks(
675
+ operands, [num_xs, num_additional_inputs]
676
+ )
677
+
678
+ scan_length = xs[0].shape[0]
679
+ ctx._scan_length = scan_length
680
+
681
+ # We snapshot the dispatch keys in forward for materializing the
682
+ # the bw_graph in backward.
683
+ ctx._fw_include_key_set = torch._C._dispatch_tls_local_include_set()
684
+ ctx._fw_exclude_key_set = torch._C._dispatch_tls_local_exclude_set()
685
+
686
+ with torch._C._AutoDispatchBelowAutograd():
687
+ # 1.) Compute the forward output of the associative_scan
688
+ ys = associative_scan_op(combine_fn, xs, additional_inputs)
689
+ save_values_for_backward(ctx, list(operands) + list(ys))
690
+
691
+ return (*ys,)
692
+
693
+ @staticmethod
694
+ def backward(ctx, *gl_ys):
695
+ r"""
696
+ This function computes the gradients of the scan operation.
697
+ For a detailed description see the document above.
698
+
699
+ Args:
700
+ flat_grads (torch.Tensor): The tensor of upstream gradients, or a nested pytree of tensors.
701
+ E.g.: Gradient of the loss with respect to the forward output ys
702
+ """
703
+
704
+ # The backward of associative_scan is always performed on the first dimension
705
+ dim = 0
706
+ scan_length = ctx._scan_length
707
+ num_xs = ctx._num_xs
708
+ num_additional_inputs = ctx._num_additional_inputs
709
+
710
+ # Extract the inputs to the forward path and outputs from the forward path
711
+ flat_args = saved_values(ctx)
712
+ xs, additional_inputs, outs = split_into_chunks(
713
+ flat_args, [num_xs, num_additional_inputs, num_xs]
714
+ )
715
+ ndim = outs[0].ndim
716
+
717
+ # First_slice_copy does not keep the original requires_grad flag,
718
+ # but we need it here in order to compute the correcte gradients
719
+ xs_slices = first_slice_copy_with_grad(itertools.chain(xs, xs))
720
+
721
+ # Construct the operands from the forward, fw_operands
722
+ # and the operands for a single event t of the forward, fw_operands_slice
723
+ fw_operands = (*xs, *additional_inputs)
724
+ fw_operands_slice = (*xs_slices, *additional_inputs)
725
+
726
+ # 2.) Prepare the backward graph
727
+ combine_fn_bw = create_bw_fn(ctx._combine_fn, fw_operands_slice)
728
+
729
+ # 3.) Materialize the ``combine_fn_bw``
730
+ # TODO: we need to materialize the bw graphs because dynamo is unable to
731
+ # trace through the joint function when torch.compile torch.autograd.grad.
732
+ combine_fn_bw_gm = materialize_as_graph(
733
+ combine_fn_bw,
734
+ (
735
+ *fw_operands_slice,
736
+ *[first_slice_copy(o) for o in outs],
737
+ ),
738
+ ctx._fw_include_key_set,
739
+ ctx._fw_exclude_key_set,
740
+ force_enable_grad=True,
741
+ )
742
+
743
+ # vmap joint graph over scan dimension to compute the individual
744
+ # gradients for each time slice ``t`` in parallel.
745
+ # This computation can be parallelized, as these are just the instantaneous gradients and not the full chain-rule
746
+ # pyrefly: ignore [bad-argument-type]
747
+ mapped_combine_fn_bw_gm = torch.vmap(combine_fn_bw_gm, 0, 0)
748
+
749
+ # 4.) Compute the single step bw (instantaneous gradients) at every step ``t``
750
+ # Use a ones_like tensor in order not to scale the bwyst and bwxst,
751
+ # with the upstream gradients yet.
752
+ # Note: All bwyst and bwxst are computed in parallel, thus the tensors bwys and bwxs are the result.
753
+ dummy_upstream_grad = (torch.ones_like(x) for x in gl_ys)
754
+ grads = mapped_combine_fn_bw_gm(
755
+ *(o.roll(1, dim) for o in outs), *fw_operands, *dummy_upstream_grad
756
+ )
757
+ bwys, bwxs = split_into_chunks(grads, [num_xs, num_xs])
758
+
759
+ def compute_y_mat(bwys: torch.Tensor) -> torch.Tensor:
760
+ # Prepare a ones and a zeros helper mask in order to easily compute the y_mat
761
+ def compute_helper_tril_mask(diagonal):
762
+ def expand_masks(mask):
763
+ for _ in range(ndim - 1):
764
+ mask = mask.unsqueeze(-1)
765
+ return mask
766
+
767
+ tril_mask = torch.tril(
768
+ torch.ones(
769
+ scan_length, scan_length, device=bwys.device, dtype=torch.bool
770
+ ),
771
+ diagonal=diagonal,
772
+ )
773
+ tril_mask = expand_masks(tril_mask)
774
+ tril_mask = tril_mask.expand(-1, -1, *bwys.shape[1:])
775
+ return tril_mask
776
+
777
+ # The ones mask is used to fill the main diagonal and all elements below it with 1s
778
+ ones_mask = compute_helper_tril_mask(0)
779
+
780
+ # The zero mask is used to set all elements below the main diagonal to 0
781
+ zeros_mask = compute_helper_tril_mask(-1)
782
+
783
+ # 5.1) Repeat the elements of bwys to form the square matrix
784
+ y_mat = bwys.unsqueeze(dim).repeat_interleave(scan_length, dim)
785
+
786
+ # 5.2) Fill the lower triangular part, including the diagonal,
787
+ # of the h_mat with 1s. I.e., use the ones_mask to fill with 1s.
788
+ y_mat.masked_fill_(ones_mask, 1.0)
789
+
790
+ # 5.3) Compute the cumulative products across dim + 1
791
+ y_mat = y_mat.cumprod(dim=dim + 1)
792
+
793
+ # 5.4) Replace the elements we filled with 1s before with 0s
794
+ y_mat.masked_fill_(zeros_mask, 0.0)
795
+
796
+ return y_mat
797
+
798
+ def compute_grad(bwxs, bwys, gl_ys):
799
+ # Set the first gradient component of bwxs to 1.0, per definition.
800
+ torch.select(bwxs, dim, 0).fill_(1.0)
801
+
802
+ # 5.) Compute the gradient transition matrix
803
+ y_mat = compute_y_mat(bwys)
804
+
805
+ # 6.) scale the y_mat with the upstream gradients gl_ys
806
+ scaled_y_mat = y_mat * gl_ys
807
+
808
+ # 7.) Reduce the y_mat with sum along the columns to get the total contributions for xs_t
809
+ summed_y_mat = scaled_y_mat.sum(dim + 1)
810
+
811
+ # 8.) Scale with the bwxs to obtain the final gradients g_xs
812
+ g_xs = summed_y_mat * bwxs
813
+
814
+ return g_xs
815
+
816
+ # Stack all leaves of the gradients along the first dimension.
817
+ # This is useful as later the gradients of those leaves can be computed in parallel.
818
+ bwxs_stacked_leaves = torch.stack(bwxs)
819
+ bwys_stacked_leaves = torch.stack(bwys)
820
+ gl_ys_stacked_leaves = torch.stack(gl_ys)
821
+
822
+ # The compute_grad function is parallelized across all individual leaves of xs
823
+ # as these gradients can be computed independently from each other
824
+ # TODO: torch.vmap may create composability issues
825
+ compute_grad_mapped = torch.vmap(compute_grad, 0, 0)
826
+
827
+ g_xs = compute_grad_mapped(
828
+ bwxs_stacked_leaves, bwys_stacked_leaves, gl_ys_stacked_leaves
829
+ )
830
+
831
+ # TODO: Currently the gradients for the additional_inputs are not computed properly
832
+ return *[None] * 3, *g_xs, *[None] * num_additional_inputs
833
+
834
+
835
+ @associative_scan_op.py_autograd_impl
836
+ def associative_scan_autograd(combine_fn, xs, additional_inputs):
837
+ num_xs = len(xs)
838
+ num_additional_inputs = len(additional_inputs)
839
+
840
+ if num_additional_inputs > 0:
841
+ raise RuntimeError(
842
+ "Associative_scan does currently not support gradients for lifted parameters!"
843
+ )
844
+
845
+ flat_out = AssociativeScanAutogradOp.apply(
846
+ combine_fn,
847
+ num_xs,
848
+ num_additional_inputs,
849
+ *(tuple(xs) + tuple(additional_inputs)),
850
+ )
851
+ return (*flat_out,)
852
+
853
+
854
+ @associative_scan_op.py_impl(ProxyTorchDispatchMode)
855
+ def associative_scan_proxy_mode(mode, combine_fn, xs, additional_inputs):
856
+ return trace_associative_scan(
857
+ mode, associative_scan_op, combine_fn, xs, additional_inputs
858
+ )
859
+
860
+
861
+ @associative_scan_op.py_impl(FakeTensorMode)
862
+ def assoiciative_scan_fake_tensor_mode(mode, combine_fn, xs, additional_inputs):
863
+ with mode:
864
+ return tuple(x.clone() for x in xs)
865
+
866
+
867
+ @associative_scan_op.py_functionalize_impl
868
+ def associative_scan_functionalize(ctx, combine_fn, xs, additional_inputs):
869
+ from torch._higher_order_ops.utils import _check_alias_and_mutation
870
+
871
+ unwrapped_xs = ctx.unwrap_tensors(xs)
872
+ unwrapped_additional_inputs = ctx.unwrap_tensors(additional_inputs)
873
+ with ctx.redispatch_to_next():
874
+ functional_combine_fn = ctx.functionalize(
875
+ _maybe_run_with_interpreter(combine_fn)
876
+ )
877
+ pre_dispatch = hasattr(ctx, "mode") and ctx.mode.pre_dispatch
878
+ sample_unwrapped_xs_sliced = [
879
+ first_slice_copy(inp) for inp in itertools.chain(unwrapped_xs, unwrapped_xs)
880
+ ]
881
+ sample_inputs = list(
882
+ itertools.chain(
883
+ sample_unwrapped_xs_sliced,
884
+ unwrapped_additional_inputs,
885
+ )
886
+ )
887
+ _check_alias_and_mutation(
888
+ combine_fn, sample_inputs, "associative_scan", pre_dispatch
889
+ )
890
+ ret = associative_scan_op(
891
+ functional_combine_fn,
892
+ unwrapped_xs,
893
+ unwrapped_additional_inputs,
894
+ )
895
+ return ctx.wrap_tensors(ret)
896
+
897
+
898
+ def _fake_associative_scan(combine_fn, xs, dim, reverse=False):
899
+ inp_leaves, spec = pytree.tree_flatten(xs)
900
+ result_flat: list[Any] = []
901
+ num_leaves = len(inp_leaves)
902
+ op = reversed if reverse else lambda x: x
903
+
904
+ for ind in op(range(inp_leaves[0].size(dim))):
905
+ r = [
906
+ inp_leaves[leave_ind][(slice(None),) * dim + (ind,)]
907
+ for leave_ind in range(num_leaves)
908
+ ]
909
+ if (ind > 0 and not reverse) or (
910
+ ind < (inp_leaves[0].size(dim) - 1) and reverse
911
+ ):
912
+ r = combine_fn(
913
+ pytree.tree_unflatten(result_flat[-1], spec),
914
+ pytree.tree_unflatten(r, spec),
915
+ )
916
+ r_flat, _ = pytree.tree_flatten(r)
917
+ result_flat.append(r_flat)
918
+
919
+ results = [
920
+ torch.stack([e[leave_ind] for e in op(result_flat)], dim)
921
+ for leave_ind in range(num_leaves)
922
+ ]
923
+ return pytree.tree_unflatten(results, spec)
.venv/lib/python3.10/site-packages/torch/_higher_order_ops/auto_functionalize.py ADDED
@@ -0,0 +1,1069 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import warnings
3
+ from abc import ABC, abstractmethod
4
+ from collections.abc import Callable, Sequence
5
+ from dataclasses import dataclass
6
+ from typing import Any, get_args, Optional, Union
7
+
8
+ import torch
9
+ import torch._library.utils as library_utils
10
+ import torch.utils._pytree as pytree
11
+ from torch import Tensor
12
+ from torch._C import DispatchKey
13
+ from torch._higher_order_ops.utils import (
14
+ _has_gen_schema,
15
+ call_op,
16
+ HopInstance,
17
+ HopSchema,
18
+ materialize_callable_in_args,
19
+ unique_graph_id,
20
+ )
21
+ from torch._ops import HigherOrderOperator, OperatorBase, OpOverload
22
+ from torch._prims_common import clone_preserve_strides
23
+ from torch._subclasses.fake_tensor import FakeTensorMode
24
+ from torch.fx.experimental.proxy_tensor import (
25
+ disable_proxy_modes_tracing,
26
+ ProxyTorchDispatchMode,
27
+ track_tensor_tree,
28
+ )
29
+
30
+
31
+ class SchemaHolder:
32
+ def __init__(self, schema: torch.FunctionSchema):
33
+ self.schema = schema
34
+
35
+ def __eq__(self, other):
36
+ return self.schema == other.schema
37
+
38
+ def __hash__(self) -> int:
39
+ return hash(self.schema)
40
+
41
+ @classmethod
42
+ def from_tree_spec(cls, tree_spec: pytree.TreeSpec):
43
+ if tree_spec is None:
44
+ raise AssertionError("tree_spec cannot be None")
45
+ return cls(pytree.tree_unflatten([], tree_spec).schema)
46
+
47
+
48
+ # register_constant allows us to get a tree_spec from pytree.tree_flatten(SchemaHolder(FunctionSchema)).
49
+ # The tree_spec is proxable in the graph and we can get back the schema via
50
+ # schema = pytree.tree_unflatten([], tree_spec).schema
51
+ pytree.register_constant(SchemaHolder)
52
+
53
+
54
+ def get_base(tensor):
55
+ if torch.is_inference_mode_enabled():
56
+ return tensor._inference_mode_base
57
+ else:
58
+ return tensor._base
59
+
60
+
61
+ class ViewInfo(ABC):
62
+ base_index: int
63
+
64
+ def __init__(self, base_index):
65
+ self.base_index = base_index
66
+
67
+ @abstractmethod
68
+ def regenerate_view(self, bases_list: list[Tensor]):
69
+ pass
70
+
71
+
72
+ @dataclass
73
+ class AsStridedViewInfo(ViewInfo):
74
+ size: Sequence[Union[int, torch.SymInt]]
75
+ stride: Sequence[Union[int, torch.SymInt]]
76
+ storage_offset: int
77
+
78
+ def __init__(self, base_index, size, stride, storage_offset):
79
+ super().__init__(base_index)
80
+ self.size = size
81
+ self.stride = stride
82
+ self.storage_offset = storage_offset
83
+
84
+ def regenerate_view(self, bases_list: list[Tensor]):
85
+ return torch.as_strided(
86
+ bases_list[self.base_index],
87
+ self.size,
88
+ self.stride,
89
+ self.storage_offset,
90
+ )
91
+
92
+
93
+ @dataclass
94
+ class SliceViewInfo(ViewInfo):
95
+ dim: Union[int, torch.SymInt]
96
+ start: Union[int, torch.SymInt]
97
+ end: Union[int, torch.SymInt]
98
+
99
+ def __init__(self, base_index, dim, start, end):
100
+ super().__init__(base_index)
101
+ self.dim = dim
102
+ self.start = start
103
+ self.end = end
104
+
105
+ def regenerate_view(self, bases_list: list[Tensor]):
106
+ return torch.ops.aten.slice.Tensor(
107
+ bases_list[self.base_index], self.dim, self.start, self.end
108
+ )
109
+
110
+
111
+ @dataclass
112
+ class AliasViewInfo(ViewInfo):
113
+ def __init__(self, base_index):
114
+ super().__init__(base_index)
115
+
116
+ def regenerate_view(self, bases_list: list[Tensor]):
117
+ return torch.ops.aten.alias.default(bases_list[self.base_index])
118
+
119
+
120
+ @dataclass
121
+ class NotView(ViewInfo):
122
+ def __init__(self, base_index):
123
+ super().__init__(base_index)
124
+
125
+ def regenerate_view(self, bases_list: list[Tensor]):
126
+ return bases_list[self.base_index]
127
+
128
+
129
+ def is_alias(base, tensor):
130
+ from torch.fx.experimental.symbolic_shapes import statically_known_true, sym_eq
131
+
132
+ return all(
133
+ statically_known_true(a)
134
+ for a in [
135
+ sym_eq(base.storage_offset(), tensor.storage_offset()),
136
+ sym_eq(base.stride(), tensor.stride()),
137
+ sym_eq(base.size(), tensor.size()),
138
+ ]
139
+ )
140
+
141
+
142
+ # return None or (dim, start, end)
143
+ def try_use_slice(base, tensor):
144
+ from torch.fx.experimental.symbolic_shapes import statically_known_true, sym_eq
145
+
146
+ # This condition should never be triggered.
147
+ if is_alias(base, tensor):
148
+ return (0, 0, base.size()[0])
149
+
150
+ # TODO is there cases can we use slice even if stride or len(sizes) are not equal?
151
+ if not statically_known_true(sym_eq(tensor.stride(), base.stride())):
152
+ return None
153
+ if not statically_known_true(sym_eq(len(tensor.size()), len(base.size()))):
154
+ return None
155
+
156
+ dim = None
157
+ count = 0
158
+ for i in range(len(tensor.size())):
159
+ if base.size()[i] != tensor.size()[i]:
160
+ dim = i
161
+ count = count + 1
162
+ if count != 1:
163
+ return None
164
+
165
+ if tensor.storage_offset() % tensor.stride()[dim] != 0:
166
+ return None
167
+ start = tensor.storage_offset() // tensor.stride()[dim]
168
+ end = start + tensor.size()[dim]
169
+ return (dim, start, end)
170
+
171
+
172
+ def write_view_information_to_args(
173
+ mutable_arg_names: list[str],
174
+ mutable_arg_types: list[torch.Type],
175
+ kwargs: dict[str, Any],
176
+ arg_to_base_index: dict[str, Any],
177
+ ):
178
+ """
179
+ This function writes the view information into kwargs. It reads mutable_args from kwargs.
180
+ and uses arg_to_base_index and tensor information to write ViewInfo into kwargs.
181
+ mutable_arg_names: mutable custom operator arg names.
182
+ mutable_arg_types: mutable custom operator arg types.
183
+ kwargs: the original custom operator args.
184
+ arg_to_base_index: maps mutable_arg_name to int | [int] that refers to the base tensor that
185
+ corresponds to the input tensor
186
+ """
187
+
188
+ def write_single_view(prefix: str, tensor: Tensor, base_index: int):
189
+ if f"{prefix}_base_index" in kwargs:
190
+ raise AssertionError(f"{prefix}_base_index already in kwargs")
191
+ if f"{prefix}_size" in kwargs:
192
+ raise AssertionError(f"{prefix}_size already in kwargs")
193
+ if f"{prefix}_stride" in kwargs:
194
+ raise AssertionError(f"{prefix}_stride already in kwargs")
195
+ if f"{prefix}_storage_offset" in kwargs:
196
+ raise AssertionError(f"{prefix}_storage_offset already in kwargs")
197
+
198
+ if f"{prefix}_slice_dim" in kwargs:
199
+ raise AssertionError(f"{prefix}_slice_dim already in kwargs")
200
+ if f"{prefix}_slice_start" in kwargs:
201
+ raise AssertionError(f"{prefix}_slice_start already in kwargs")
202
+ if f"{prefix}_slice_end" in kwargs:
203
+ raise AssertionError(f"{prefix}_slice_end already in kwargs")
204
+
205
+ def use_as_strided(tensor):
206
+ kwargs[f"{prefix}_size"] = tensor.size()
207
+ kwargs[f"{prefix}_stride"] = tensor.stride()
208
+ kwargs[f"{prefix}_storage_offset"] = tensor.storage_offset()
209
+
210
+ def use_slice(dim, start, end):
211
+ kwargs[f"{prefix}_slice_dim"] = dim
212
+ kwargs[f"{prefix}_slice_start"] = start
213
+ kwargs[f"{prefix}_slice_end"] = end
214
+
215
+ def use_alias():
216
+ kwargs[f"{prefix}_alias"] = True
217
+
218
+ # The start if the function
219
+ if tensor is None:
220
+ kwargs[f"{prefix}_base_index"] = None
221
+ else:
222
+ base = get_base(tensor)
223
+ kwargs[f"{prefix}_base_index"] = base_index
224
+ if base is None:
225
+ # no need to add anything else other than _base_index
226
+ return
227
+ elif is_alias(base, tensor):
228
+ use_alias()
229
+ elif (slice_info := try_use_slice(base, tensor)) is not None:
230
+ use_slice(*slice_info)
231
+ else:
232
+ use_as_strided(tensor)
233
+
234
+ for arg_name, arg_type in zip(mutable_arg_names, mutable_arg_types):
235
+ arg = kwargs[arg_name]
236
+ if library_utils.is_tensorlist_like_type(arg_type):
237
+ if arg is None:
238
+ kwargs[f"_{arg_name}_length"] = None
239
+ else:
240
+ kwargs[f"_{arg_name}_length"] = len(arg)
241
+ for i, elem in enumerate(arg):
242
+ write_single_view(
243
+ f"_{arg_name}_{i}", elem, arg_to_base_index[arg_name][i]
244
+ )
245
+
246
+ elif library_utils.is_tensor_like_type(arg_type):
247
+ write_single_view(
248
+ f"_{arg_name}",
249
+ kwargs[arg_name],
250
+ arg_to_base_index.get(arg_name), # type: ignore[arg-type]
251
+ )
252
+ else:
253
+ raise RuntimeError(f"Unsupported type {arg_type}")
254
+
255
+
256
+ # Returns a dict of arg_name -> ViewInfo | [ViewInfo]
257
+ def read_view_information_from_args(
258
+ mutable_arg_names: list[str],
259
+ mutable_arg_types: list[torch.Type],
260
+ kwargs: dict[str, Any],
261
+ all_bases: list[Tensor],
262
+ ):
263
+ """
264
+ This reads the view information added by `write_view_information_to_args` from kwargs, pop them,
265
+ and returns a dict arg_name -> ViewInfo | [ViewInfo](if the input is list). that maps each mutable arg
266
+ to its view information.
267
+ mutable_arg_names: mutable custom operator arg names.
268
+ mutable_arg_types: mutable custom operator arg types.
269
+ kwargs : args of auto_functionalize(custom_op, kwargs)
270
+ """
271
+
272
+ def get_arg(name):
273
+ return kwargs.pop(name)
274
+
275
+ def read_single_view(prefix):
276
+ base_index = get_arg(f"{prefix}_base_index")
277
+ if base_index is None:
278
+ return None
279
+ elif f"{prefix}_alias" in kwargs:
280
+ get_arg(f"{prefix}_alias")
281
+ return AliasViewInfo(base_index)
282
+ elif f"{prefix}_storage_offset" in kwargs:
283
+ # The view is regenerated using as_strided.
284
+ size = get_arg(f"{prefix}_size")
285
+ stride = get_arg(f"{prefix}_stride")
286
+ storage_offset = get_arg(f"{prefix}_storage_offset")
287
+ return AsStridedViewInfo(base_index, size, stride, storage_offset)
288
+ elif f"{prefix}_slice_dim" in kwargs:
289
+ dim = get_arg(f"{prefix}_slice_dim")
290
+ start = get_arg(f"{prefix}_slice_start")
291
+ end = get_arg(f"{prefix}_slice_end")
292
+ return SliceViewInfo(base_index, dim, start, end)
293
+ else:
294
+ # This means that the argument is the base tensor
295
+ return NotView(base_index)
296
+
297
+ args_view_info: dict[str, Any] = {}
298
+ for arg_name, arg_type in zip(mutable_arg_names, mutable_arg_types):
299
+ if library_utils.is_tensorlist_like_type(arg_type):
300
+ length = get_arg(f"_{arg_name}_length")
301
+ if length is None:
302
+ # The whole list is None.
303
+ args_view_info[arg_name] = None
304
+ else:
305
+ args_view_info[arg_name] = [
306
+ read_single_view(f"_{arg_name}_{i}") for i in range(length)
307
+ ]
308
+
309
+ elif library_utils.is_tensor_like_type(arg_type):
310
+ args_view_info[arg_name] = read_single_view(f"_{arg_name}")
311
+ else:
312
+ raise RuntimeError(f"Unsupported type {arg_type}")
313
+ return args_view_info
314
+
315
+
316
+ # NOTE: [auto-functionalizing custom ops]
317
+ # Users may wish to torch.compile custom ops that mutate their inputs.
318
+ # torch.compile will automatically support this op without anyone needing
319
+ # to provide a functionalization kernel for it. Here's how.
320
+ #
321
+ # Let's say we have a hypothetical mylib::sin_(Tensor(a!) x) -> ()
322
+ # op. First, when FakeTensor sees this op:
323
+ # - If the schema says it returns nothing, we can generate a trivial
324
+ # FakeTensor rule for it (that returns nothing).
325
+ # - Otherwise, the user needs to provide a FakeTensor impl (fake impl)
326
+ #
327
+ # Next, when Python FunctionalTensor sees the op, it will functionalize
328
+ # it by emitting a call to an auto_functionalize(op, ["x"], {"x": ...})
329
+ # HOP and replacing the mutated inputs with corresponding outputs of this HOP.
330
+ # This HOP effectively runs the functional version of the op when
331
+ # called: it clones inputs that will be mutated, runs the op, and
332
+ # then returns (output, Tensors with the new values)
333
+ #
334
+ # auto_functionalize_v2 is an improved version of auto_functionalize that better handle
335
+ # re-inplacing views.
336
+
337
+
338
+ class AutoFunctionalized(HigherOrderOperator):
339
+ """auto_functionalized(_mutable_op, **kwargs)
340
+
341
+ This HOP runs a "functional" version of _mutable_op.
342
+
343
+ Concretely, it looks at all the arguments that are mutable through
344
+ _mutable_op's operator schema, clones those kwargs, runs
345
+ `out = _mutable_op(**kwargs)` with the cloned values, and then returns the
346
+ operator output concatenated with the cloned values that were mutated.
347
+
348
+ We have some restrictions on `_mutable_op`.
349
+ See `can_auto_functionalize` for the restrictions. We can likely lift
350
+ many of these if users request it.
351
+
352
+ The reason why _mutable_op is prefixed with an
353
+ underscore is to prevent collisions with kwarg names in **kwargs.
354
+ """
355
+
356
+ def __init__(self) -> None:
357
+ super().__init__("auto_functionalized", cacheable=True)
358
+
359
+ def __call__(
360
+ self,
361
+ /,
362
+ _mutable_op: OpOverload,
363
+ **kwargs: Any,
364
+ ) -> tuple[Any, tuple[Tensor, ...]]:
365
+ if not can_auto_functionalize(_mutable_op):
366
+ raise AssertionError(f"Cannot auto-functionalize op {_mutable_op}")
367
+ if not isinstance(kwargs, dict):
368
+ raise AssertionError(f"kwargs must be a dict, got {type(kwargs)}")
369
+ # pyrefly: ignore [missing-attribute]
370
+ return super().__call__(_mutable_op, **kwargs)
371
+
372
+
373
+ auto_functionalized = AutoFunctionalized()
374
+ auto_functionalized.__module__ = "torch.ops.higher_order"
375
+
376
+ auto_functionalized.fallthrough(DispatchKey.AutogradCPU)
377
+ auto_functionalized.fallthrough(DispatchKey.AutogradCUDA)
378
+
379
+
380
+ _MutableOpType = Union[OpOverload, HigherOrderOperator]
381
+
382
+
383
+ class AutoFunctionalizedV2(HigherOrderOperator):
384
+ """auto_functionalized_v2(_mutable_op, **kwargs)
385
+
386
+ This HOP runs a "functional" version of _mutable_op.
387
+ Unlike AutoFunctionalized, this version is improved to better handle
388
+ view tensors. This version is only used in non export mode.
389
+ """
390
+
391
+ def __init__(self) -> None:
392
+ super().__init__("auto_functionalized_v2", cacheable=True)
393
+
394
+ def __call__(
395
+ self,
396
+ /,
397
+ _mutable_op: _MutableOpType,
398
+ **kwargs: Any,
399
+ ) -> tuple[Any, tuple[Tensor, ...]]:
400
+ _op_to_check: Optional[Union[OpOverload, HopInstance]] = None
401
+ if isinstance(_mutable_op, HigherOrderOperator):
402
+ _op_to_check = HopInstance(
403
+ _mutable_op,
404
+ SchemaHolder.from_tree_spec(kwargs.get("_op_schema")).schema, # type: ignore[arg-type]
405
+ )
406
+ else:
407
+ _op_to_check = _mutable_op
408
+
409
+ if _op_to_check is None:
410
+ raise AssertionError("_op_to_check cannot be None")
411
+ if not can_auto_functionalize(_op_to_check):
412
+ raise AssertionError(f"Cannot auto-functionalize op {_op_to_check}")
413
+ if not isinstance(kwargs, dict):
414
+ raise AssertionError(f"kwargs must be a dict, got {type(kwargs)}")
415
+ # pyrefly: ignore [missing-attribute]
416
+ return super().__call__(_mutable_op, **kwargs)
417
+
418
+
419
+ auto_functionalized_v2 = AutoFunctionalizedV2()
420
+ auto_functionalized_v2.__module__ = "torch.ops.higher_order"
421
+
422
+ auto_functionalized_v2.fallthrough(DispatchKey.AutogradCPU)
423
+ auto_functionalized_v2.fallthrough(DispatchKey.AutogradCUDA)
424
+
425
+
426
+ def can_auto_functionalize(
427
+ op: Union[OperatorBase, HopInstance],
428
+ ) -> bool:
429
+ if isinstance(op, HopInstance):
430
+ # HOPs that implement gen_schema and schema is not functional are auto_functionalizable.
431
+ if not _has_gen_schema(op._op):
432
+ return False
433
+
434
+ else:
435
+ if not isinstance(op, OpOverload):
436
+ return False
437
+
438
+ if torch._library.utils.is_builtin(op):
439
+ # We control the built-ins. These may (in rare cases)
440
+ # do input metadata mutation (which we have banned on custom ops)
441
+ return False
442
+
443
+ schema = op._schema
444
+ if not schema.is_mutable:
445
+ return False
446
+ schema = op._schema
447
+
448
+ for arg in schema.arguments:
449
+ if arg.alias_info is None:
450
+ continue
451
+ if not arg.alias_info.is_write:
452
+ continue
453
+ if torch._library.utils.is_tensor_like_type(arg.type):
454
+ continue
455
+ if torch._library.utils.is_tensorlist_like_type(arg.type):
456
+ continue
457
+ return False
458
+
459
+ if len(schema.returns) == 1 and isinstance(schema.returns[0].type, torch.NoneType):
460
+ # Skip schema returns -> None
461
+ return True
462
+ if isinstance(op, OpOverload):
463
+ # The returns of OpOverload must not alias anything
464
+ for ret in schema.returns:
465
+ if ret.alias_info is None and type(ret.type) is torch.TensorType:
466
+ continue
467
+ # Not yet supported: List[Tensor] return.
468
+ return False
469
+ if torch._C._dispatch_has_kernel_for_dispatch_key(op.name(), "Functionalize"):
470
+ return False
471
+ return True
472
+
473
+
474
+ def get_mutable_args_from_schema(
475
+ schema: torch.FunctionSchema,
476
+ ) -> tuple[list[str], list[torch.Type]]:
477
+ """
478
+ Returns the list of argument names that get mutated according to the
479
+ schema and their types.
480
+ """
481
+ mutable_args_names = [
482
+ arg.name
483
+ for arg in schema.arguments
484
+ if arg.alias_info is not None and arg.alias_info.is_write
485
+ ]
486
+
487
+ mutable_args_types = [
488
+ arg.type
489
+ for arg in schema.arguments
490
+ if arg.alias_info is not None and arg.alias_info.is_write
491
+ ]
492
+ return mutable_args_names, mutable_args_types # type: ignore[return-value]
493
+
494
+
495
+ def get_mutable_args(op: OpOverload) -> tuple[list[str], list[torch.Type]]:
496
+ return get_mutable_args_from_schema(op._schema)
497
+
498
+
499
+ def do_auto_functionalize(
500
+ mode: "torch._subclasses.functional_tensor.FunctionalTensorMode",
501
+ op: OpOverload,
502
+ args: tuple[Any, ...],
503
+ kwargs: dict[str, Any],
504
+ ) -> Any:
505
+ """Functionalizes a call to op(*args, **kwargs) by emitting a call to
506
+ `outs = auto_functionalized(op, normalized_kwargs)`
507
+ and replacing the mutated (args, kwargs) with the corresponding outputs.
508
+
509
+ The normalized_kwargs are just the (args, kwargs), but all in kwarg form.
510
+ This makes handling easier for the auto_functionalized HOP.
511
+ """
512
+ from torch._subclasses.functional_tensor import PythonFunctionalizeAPI
513
+
514
+ ctx = PythonFunctionalizeAPI(mode=mode)
515
+
516
+ # All of the (args, kwargs), but all as kwargs. The names for the
517
+ # args come from the schema. This makes it easier for us to work with them.
518
+ normalized_kwargs = {}
519
+ schema = op._schema
520
+ for idx, arg in enumerate(schema.arguments):
521
+ # NB: torch_dispatch kwargs are the args defined as kwarg-only in the schema
522
+ if arg.name in kwargs:
523
+ normalized_kwargs[arg.name] = kwargs[arg.name]
524
+ elif idx < len(args):
525
+ # if its out of bounds we don't need to do anything
526
+ # as it means the optional arg was passed with its default
527
+ # value
528
+ normalized_kwargs[arg.name] = args[idx]
529
+ else:
530
+ normalized_kwargs[arg.name] = arg.default_value
531
+
532
+ unwrapped_kwargs = ctx.unwrap_tensors(normalized_kwargs) # type: ignore[arg-type]
533
+ if "self" in unwrapped_kwargs or "self_" in unwrapped_kwargs:
534
+ warnings.warn(
535
+ "Using `self` or `self_` as an argument in the definition of custom ops may lead to ambiguous parsing. "
536
+ "Please consider using a different name for this argument to avoid potential issues.",
537
+ stacklevel=2,
538
+ )
539
+ with ctx.redispatch_to_next():
540
+ unwrapped_outs = auto_functionalized(
541
+ op,
542
+ **unwrapped_kwargs, # type: ignore[arg-type]
543
+ )
544
+
545
+ # List of the name of args that get mutated (according to the schema)
546
+ mutable_args_names, _ = get_mutable_args(op)
547
+
548
+ unwrapped_actual_out: Union[Any, tuple[Any]] = unwrapped_outs[
549
+ : -len(mutable_args_names)
550
+ ]
551
+ unwrapped_mutable_out = unwrapped_outs[-len(mutable_args_names) :]
552
+
553
+ if len(op._schema.returns) == 0:
554
+ if unwrapped_actual_out[0] is not None:
555
+ raise AssertionError(
556
+ f"Expected None for op with no returns, got {unwrapped_actual_out[0]}"
557
+ )
558
+ unwrapped_actual_out = None
559
+ elif len(op._schema.returns) == 1:
560
+ if len(unwrapped_actual_out) != 1:
561
+ raise AssertionError(f"Expected 1 output, got {len(unwrapped_actual_out)}")
562
+ unwrapped_actual_out = unwrapped_actual_out[0]
563
+ else:
564
+ if len(unwrapped_actual_out) != len(op._schema.returns):
565
+ raise AssertionError(
566
+ f"Expected {len(op._schema.returns)} outputs, got {len(unwrapped_actual_out)}"
567
+ )
568
+
569
+ for name, unwrapped_out in zip(mutable_args_names, unwrapped_mutable_out):
570
+ # Can be None if input was `Tensor(a!)?`
571
+ if unwrapped_out is None:
572
+ continue
573
+
574
+ # We only handle Tensor or List[Tensor] here for now.
575
+ def sync_update(o, orig_arg):
576
+ ctx.replace(orig_arg, o)
577
+ ctx.commit_update(orig_arg)
578
+ ctx.sync(orig_arg)
579
+
580
+ orig_arg = normalized_kwargs[name]
581
+
582
+ if isinstance(unwrapped_out, torch.Tensor):
583
+ sync_update(unwrapped_out, orig_arg)
584
+ elif isinstance(unwrapped_out, list) and all(
585
+ isinstance(o, torch.Tensor) for o in unwrapped_out
586
+ ):
587
+ if len(orig_arg) != len(unwrapped_out):
588
+ raise AssertionError(
589
+ f"orig_arg length ({len(orig_arg)}) != unwrapped_out length ({len(unwrapped_out)})"
590
+ )
591
+ for orig_a, o in zip(orig_arg, unwrapped_out):
592
+ sync_update(o, orig_a)
593
+ else:
594
+ raise RuntimeError(
595
+ f"unsupported type for auto-functionalization: {unwrapped_out}"
596
+ )
597
+
598
+ return ctx.wrap_tensors(unwrapped_actual_out) # type: ignore[arg-type]
599
+
600
+
601
+ # Wrapper for GraphModule that applies functionalization during execution to enable
602
+ # epilogue graph inlining and better fusion opportunities in subgraphs
603
+ # When tracing this wrapper, we'll get a graph module with epilogue.
604
+ #
605
+ # We want to hash it according to the original graph module, so that when we go
606
+ # from Functional mode -> fake mode for multiple invoke_subgraph calls that share,
607
+ # the same inner graph module, we can hit the cache.
608
+ class FunctionalCallableWithEpilogue:
609
+ def __init__(self, orig_callable: Callable):
610
+ self.orig_callable = orig_callable
611
+
612
+ def __call__(self, *args, **kwargs):
613
+ # We call torch.func.functionalize. This allows us to inline the epilogue graph.
614
+ # Inlining has the benefit of allowing easiser fusion inside subgraph.
615
+ # Though the epilogue graph contains copy_, it is OK because inductor can handle it
616
+ # and this is also how we have been supporting top-level graph input mutation.
617
+ return tuple(torch.func.functionalize(self.orig_callable)(*args, **kwargs))
618
+
619
+ def __hash__(self):
620
+ return id(self.orig_callable)
621
+
622
+
623
+ def do_auto_functionalize_v2(
624
+ mode: "torch._subclasses.functional_tensor.FunctionalTensorMode",
625
+ op: Union[OpOverload, HopInstance],
626
+ args: tuple[Any, ...],
627
+ kwargs: dict[str, Any],
628
+ ) -> Any:
629
+ from torch._subclasses.functional_tensor import PythonFunctionalizeAPI
630
+
631
+ ctx = PythonFunctionalizeAPI(mode=mode)
632
+
633
+ # All of the (args, kwargs), but all as kwargs. The names for the
634
+ # args come from the schema. This makes it easier for us to work with them.
635
+ normalized_kwargs = {}
636
+
637
+ schema = op._schema
638
+ # pyrefly: ignore [bad-assignment]
639
+ op = op._op if isinstance(op, HopInstance) else op
640
+ if not isinstance(op, get_args(_MutableOpType)):
641
+ raise AssertionError(f"Expected _MutableOpType, got {type(op)}")
642
+
643
+ def _functionalize_callable(arg: Any):
644
+ if callable(arg):
645
+ return FunctionalCallableWithEpilogue(arg)
646
+ return arg
647
+
648
+ args, kwargs = pytree.tree_map(_functionalize_callable, (args, kwargs))
649
+
650
+ for idx, arg in enumerate(schema.arguments):
651
+ # NB: torch_dispatch kwargs are the args defined as kwarg-only in the schema
652
+ if arg.name in kwargs:
653
+ normalized_kwargs[arg.name] = kwargs[arg.name]
654
+ elif idx < len(args):
655
+ # if its out of bounds we don't need to do anything
656
+ # as it means the optional arg was passed with its default
657
+ # value
658
+ normalized_kwargs[arg.name] = args[idx]
659
+ else:
660
+ normalized_kwargs[arg.name] = arg.default_value
661
+
662
+ # List of the name of args that get mutated (according to the schema)
663
+ mutable_args_names, mutable_args_types = get_mutable_args_from_schema(schema)
664
+
665
+ # A list of all bases of mutable args without duplication
666
+ all_bases = []
667
+ all_bases_addresses: list[int] = []
668
+
669
+ # Map arg_name to the index of its base in all_bases.
670
+ arg_to_base_index: dict[str, Any] = {}
671
+
672
+ def update_dict(tensor, arg_name, index=None):
673
+ base = tensor if get_base(tensor) is None else get_base(tensor)
674
+
675
+ def set_result(base_index):
676
+ if index is None:
677
+ arg_to_base_index[arg_name] = base_index
678
+ else:
679
+ arg_to_base_index[arg_name][index] = base_index
680
+
681
+ if not all_bases_addresses.__contains__(base._cdata):
682
+ all_bases_addresses.append(base._cdata)
683
+ all_bases.append(base)
684
+ set_result(len(all_bases) - 1)
685
+ else:
686
+ set_result(all_bases_addresses.index(base._cdata))
687
+
688
+ for arg_name in mutable_args_names:
689
+ arg = normalized_kwargs[arg_name]
690
+ if arg is None:
691
+ continue
692
+
693
+ if isinstance(arg, list):
694
+ arg_to_base_index[arg_name] = {}
695
+ for i, tensor in enumerate(arg):
696
+ if tensor is None:
697
+ arg_to_base_index[arg_name].append(None)
698
+ continue
699
+
700
+ update_dict(tensor, arg_name, i)
701
+
702
+ else:
703
+ update_dict(arg, arg_name)
704
+
705
+ # add view_meta for each args into unwrapped_kwargs.
706
+ write_view_information_to_args(
707
+ mutable_args_names,
708
+ mutable_args_types,
709
+ normalized_kwargs,
710
+ arg_to_base_index,
711
+ )
712
+
713
+ # remove mutated args from the kwargs (its a function of _all_bases now)
714
+ for arg_name in mutable_args_names:
715
+ del normalized_kwargs[arg_name] # type: ignore[arg-type]
716
+
717
+ unwrapped_kwargs = ctx.unwrap_tensors(normalized_kwargs) # type: ignore[arg-type]
718
+ if "self" in unwrapped_kwargs or "self_" in unwrapped_kwargs:
719
+ warnings.warn(
720
+ "Using `self` or `self_` as an argument in the definition of custom ops may lead to ambiguous parsing. "
721
+ "Please consider using a different name for this argument to avoid potential issues.",
722
+ stacklevel=2,
723
+ )
724
+ all_basis_unwrapped = ctx.unwrap_tensors(all_bases)
725
+
726
+ if "_all_bases" in unwrapped_kwargs:
727
+ raise AssertionError(f"_all_bases already in unwrapped_kwargs for {op}")
728
+ auto_func_kwargs = dict(unwrapped_kwargs, _all_bases=all_basis_unwrapped)
729
+ if isinstance(op, HigherOrderOperator):
730
+ if "_ops_schema" in unwrapped_kwargs:
731
+ raise AssertionError(f"_ops_schema already in unwrapped_kwargs for {op}")
732
+ # We pass in the tree_spec of tree_flatten(SchemaHolder) to make it proxable
733
+ auto_func_kwargs.update(
734
+ {"_op_schema": pytree.tree_flatten(SchemaHolder(schema))[1]}
735
+ )
736
+
737
+ with ctx.redispatch_to_next():
738
+ unwrapped_outs = auto_functionalized_v2(
739
+ op,
740
+ **auto_func_kwargs, # type: ignore[arg-type]
741
+ )
742
+
743
+ unwrapped_actual_out: Union[Any, tuple[Any]] = (
744
+ unwrapped_outs if len(all_bases) == 0 else unwrapped_outs[: -len(all_bases)]
745
+ )
746
+
747
+ unwrapped_mutable_out = (
748
+ [] if len(all_bases) == 0 else unwrapped_outs[-len(all_bases) :]
749
+ )
750
+
751
+ if isinstance(op, HigherOrderOperator):
752
+ if len(schema.returns) <= 0:
753
+ raise AssertionError(
754
+ f"hop is expected to return at least one output {schema}."
755
+ )
756
+ if len(unwrapped_actual_out) != len(schema.returns):
757
+ raise AssertionError(
758
+ f"Expected {len(schema.returns)} outputs, got {len(unwrapped_actual_out)}"
759
+ )
760
+ else:
761
+ if len(schema.returns) == 0:
762
+ if unwrapped_actual_out[0] is not None:
763
+ raise AssertionError(
764
+ f"Expected None for op with no returns, got {unwrapped_actual_out[0]}"
765
+ )
766
+ unwrapped_actual_out = None
767
+ elif len(schema.returns) == 1:
768
+ if len(unwrapped_actual_out) != 1:
769
+ raise AssertionError(
770
+ f"Expected 1 output, got {len(unwrapped_actual_out)}"
771
+ )
772
+ unwrapped_actual_out = unwrapped_actual_out[0]
773
+ else:
774
+ if len(unwrapped_actual_out) != len(schema.returns):
775
+ raise AssertionError(
776
+ f"Expected {len(schema.returns)} outputs, got {len(unwrapped_actual_out)}"
777
+ )
778
+
779
+ for orig_arg, unwrapped_out in zip(all_bases, unwrapped_mutable_out):
780
+ # Can be None if input was `Tensor(a!)?`
781
+ if unwrapped_out is None:
782
+ continue
783
+
784
+ # We only handle Tensor or List[Tensor] here for now.
785
+ def sync_update(o, orig_arg):
786
+ ctx.replace(orig_arg, o)
787
+ ctx.commit_update(orig_arg)
788
+ ctx.sync(orig_arg)
789
+
790
+ if isinstance(unwrapped_out, torch.Tensor):
791
+ sync_update(unwrapped_out, orig_arg)
792
+ elif isinstance(unwrapped_out, list) and all(
793
+ isinstance(o, torch.Tensor) for o in unwrapped_out
794
+ ):
795
+ if len(orig_arg) != len(unwrapped_out):
796
+ raise AssertionError(
797
+ f"orig_arg length ({len(orig_arg)}) != unwrapped_out length ({len(unwrapped_out)})"
798
+ )
799
+ for orig_a, o in zip(orig_arg, unwrapped_out):
800
+ sync_update(o, orig_a)
801
+ else:
802
+ raise RuntimeError(
803
+ f"unsupported type for auto-functionalization: {unwrapped_out}"
804
+ )
805
+
806
+ return ctx.wrap_tensors(unwrapped_actual_out) # type: ignore[arg-type]
807
+
808
+
809
+ # auto_functionalize functions
810
+ @auto_functionalized.py_impl(DispatchKey.CompositeExplicitAutograd)
811
+ def auto_functionalized_dense(
812
+ _mutable_op: OpOverload,
813
+ _only_clone_these_tensors: Optional[tuple[str, ...]] = None,
814
+ **kwargs: Any,
815
+ ) -> tuple[Any, tuple[Tensor, ...]]:
816
+ new_kwargs = dict(**kwargs)
817
+ result = []
818
+
819
+ _mutable_args_names, _ = get_mutable_args(_mutable_op)
820
+ for name in _mutable_args_names:
821
+ if (
822
+ _only_clone_these_tensors is not None
823
+ and name not in _only_clone_these_tensors
824
+ ):
825
+ new_kwargs[name] = kwargs[name]
826
+ else:
827
+ new_kwargs[name] = (
828
+ [clone_preserve_strides(x) for x in kwargs[name]]
829
+ if kwargs[name] is not None and isinstance(kwargs[name], list)
830
+ else (
831
+ clone_preserve_strides(kwargs[name])
832
+ if kwargs[name] is not None
833
+ else None
834
+ )
835
+ )
836
+ result.append(new_kwargs[name])
837
+ out = _mutable_op(**new_kwargs)
838
+
839
+ if isinstance(out, tuple):
840
+ return (*out, *result) # type: ignore[return-value]
841
+ else:
842
+ return (out, *result) # type: ignore[return-value]
843
+
844
+
845
+ @auto_functionalized.py_impl(FakeTensorMode)
846
+ def auto_functionalized_fake(
847
+ mode,
848
+ _mutable_op: OpOverload,
849
+ **kwargs: Any,
850
+ ) -> tuple[Any, tuple[Tensor, ...]]:
851
+ with mode:
852
+ result = auto_functionalized_dense(
853
+ _mutable_op, _only_clone_these_tensors=None, **kwargs
854
+ )
855
+ return result
856
+
857
+
858
+ @auto_functionalized.py_impl(ProxyTorchDispatchMode)
859
+ def auto_functionalized_proxy(
860
+ mode,
861
+ _mutable_op: OpOverload,
862
+ **kwargs: Any,
863
+ ) -> tuple[Any, tuple[Tensor, ...]]:
864
+ with disable_proxy_modes_tracing():
865
+ out = auto_functionalized(_mutable_op, **kwargs)
866
+
867
+ proxy_kwargs = pytree.tree_map(mode.tracer.unwrap_proxy, kwargs)
868
+ out_proxy = mode.tracer.create_proxy(
869
+ "call_function",
870
+ auto_functionalized,
871
+ (_mutable_op,),
872
+ proxy_kwargs,
873
+ )
874
+ result = track_tensor_tree(out, out_proxy, constant=None, tracer=mode.tracer)
875
+ return result
876
+
877
+
878
+ @auto_functionalized.py_functionalize_impl
879
+ def auto_functionalized_func(ctx, _mutable_op, **kwargs):
880
+ unwrapped_kwargs = ctx.unwrap_tensors(kwargs)
881
+ with ctx.redispatch_to_next():
882
+ result = auto_functionalized(_mutable_op, **unwrapped_kwargs)
883
+ return ctx.wrap_tensors(result)
884
+
885
+
886
+ # auto_functionalized_v2 functions
887
+ @auto_functionalized_v2.py_impl(DispatchKey.CompositeExplicitAutograd)
888
+ def auto_functionalized_v2_dense(
889
+ _mutable_op: _MutableOpType,
890
+ _only_clone_these_bases: Optional[tuple[int, ...]] = None,
891
+ **kwargs: Any,
892
+ ) -> tuple[Any, tuple[Tensor, ...]]:
893
+ _all_bases: list[Tensor] = kwargs.pop("_all_bases", [])
894
+ if _only_clone_these_bases is None:
895
+ _only_clone_these_bases = tuple(range(len(_all_bases)))
896
+
897
+ if isinstance(_mutable_op, OpOverload):
898
+ schema: torch._C.FunctionSchema = _mutable_op._schema
899
+ else:
900
+ schema = pytree.tree_unflatten([], kwargs.pop("_op_schema")).schema
901
+
902
+ if isinstance(_mutable_op, OpOverload):
903
+ _callable_op: Union[HopInstance, OpOverload] = _mutable_op
904
+ else:
905
+ if not isinstance(schema, HopSchema):
906
+ raise AssertionError(f"Expected HopSchema, got {type(schema)}")
907
+ _callable_op = HopInstance(_mutable_op, schema)
908
+
909
+ op_kwargs_new, all_bases_new = _generate_new_op_kwargs_from_bases(
910
+ schema,
911
+ kwargs,
912
+ _all_bases,
913
+ _only_clone_these_bases,
914
+ )
915
+
916
+ out = call_op(
917
+ _callable_op,
918
+ tuple(),
919
+ op_kwargs_new,
920
+ )
921
+
922
+ if isinstance(out, tuple):
923
+ return (*out, *all_bases_new) # type: ignore[return-value]
924
+ else:
925
+ return (out, *all_bases_new) # type: ignore[return-value]
926
+
927
+
928
+ def _generate_new_op_kwargs_from_bases(
929
+ schema, kwargs, all_bases, _only_clone_these_bases
930
+ ):
931
+ mutable_args_names, mutable_args_types = get_mutable_args_from_schema(schema)
932
+ args_view_info = read_view_information_from_args(
933
+ mutable_args_names, mutable_args_types, kwargs, all_bases
934
+ )
935
+
936
+ def maybe_copy(i, t):
937
+ if t is None:
938
+ return None
939
+ if i in _only_clone_these_bases:
940
+ return clone_preserve_strides(t)
941
+ else:
942
+ return t
943
+
944
+ all_bases_new = [maybe_copy(i, t) for i, t in enumerate(all_bases)]
945
+
946
+ # create new args
947
+ new_kwargs = dict(**kwargs)
948
+
949
+ # re-generate all inputs from all_bases_new using args_view_info and add them to new_kwargs.
950
+ for arg_name in mutable_args_names:
951
+ if args_view_info[arg_name] is None:
952
+ new_kwargs[arg_name] = None
953
+ elif isinstance(args_view_info[arg_name], list):
954
+ new_kwargs[arg_name] = []
955
+ for i, elem in enumerate(args_view_info[arg_name]):
956
+ if elem is None:
957
+ new_kwargs[arg_name].append(None)
958
+ else:
959
+ view_info = args_view_info[arg_name][i]
960
+ new_kwargs[arg_name].append(
961
+ view_info.regenerate_view(all_bases_new)
962
+ )
963
+ else:
964
+ new_kwargs[arg_name] = args_view_info[arg_name].regenerate_view(
965
+ all_bases_new
966
+ )
967
+
968
+ return new_kwargs, all_bases_new
969
+
970
+
971
+ @auto_functionalized_v2.py_impl(FakeTensorMode)
972
+ def auto_functionalized_v2_fake(
973
+ mode,
974
+ _mutable_op: _MutableOpType,
975
+ **kwargs: dict[str, Any],
976
+ ) -> tuple[Any, tuple[Tensor, ...]]:
977
+ with mode:
978
+ result = auto_functionalized_v2_dense(
979
+ _mutable_op, _only_clone_these_bases=None, **kwargs
980
+ )
981
+ return result
982
+
983
+
984
+ @auto_functionalized_v2.py_impl(ProxyTorchDispatchMode)
985
+ def auto_functionalized_v2_proxy(
986
+ mode,
987
+ _mutable_op: _MutableOpType,
988
+ **kwargs: Any,
989
+ ) -> tuple[Any, tuple[Tensor, ...]]:
990
+ if isinstance(_mutable_op, HigherOrderOperator):
991
+ # Note [materialize callable inputs as graph]
992
+ # Below code materializes the callable inputs to the hop as graph modules.
993
+ # kwargs may contain general callables, that are not proxable e.g. FunctionWithNoFreeVars
994
+ # this could happen when we auto_functionalize the backward of the hop,
995
+ # where backward fn is a callablle that wraps forward graph module.
996
+ # This function materialize the callable args according to the schema of the hop.
997
+
998
+ # We cannot materialize the callables in kwargs directly because the inputs to callable
999
+ # vary from hops to hop. To make the materialiation process generic to all hops,
1000
+ # we trace a function that wraps the hop and let each hop itself figure out how to trace
1001
+ # its callable inputs. Then we look at the schema of the traced hop node and replace the
1002
+ # callable in original kwarg with the traced subgraphs.
1003
+ #
1004
+ # Specifically, we first trace a wrapped_fn that calls into the hop. Then we look for the
1005
+ # hop node in the traced graph and graph module inputs to the hop. Finally, we replace the
1006
+ # original kwarg's callable with the graph module.
1007
+ all_bases = kwargs.get("_all_bases", [])
1008
+ _only_clone_these_bases = kwargs.get("_only_clone_these_bases")
1009
+ if _only_clone_these_bases is None:
1010
+ _only_clone_these_bases = tuple(range(len(all_bases)))
1011
+
1012
+ schema = pytree.tree_unflatten([], kwargs.get("_op_schema")).schema # type: ignore[arg-type]
1013
+ new_kwargs, _ = _generate_new_op_kwargs_from_bases(
1014
+ schema,
1015
+ {k: v for k, v in kwargs.items() if k not in ("_all_bases", "_op_schema")},
1016
+ all_bases,
1017
+ _only_clone_these_bases,
1018
+ )
1019
+
1020
+ _, materialized_kwargs = materialize_callable_in_args(
1021
+ HopInstance(_mutable_op, schema), tuple(), new_kwargs
1022
+ )
1023
+
1024
+ # Only replace the callabes in kwargs with the materialized subgraphs.
1025
+ # The rest of the kwargs are kept unchanged.
1026
+ for k, v in kwargs.items():
1027
+ if callable(v):
1028
+ if k not in materialized_kwargs or not isinstance(
1029
+ materialized_kwargs[k], torch.fx.GraphModule
1030
+ ):
1031
+ raise AssertionError(
1032
+ f"Expected {k} to be in materialized_kwargs as a GraphModule"
1033
+ )
1034
+ kwargs[k] = materialized_kwargs[k]
1035
+
1036
+ with disable_proxy_modes_tracing():
1037
+ out = auto_functionalized_v2(_mutable_op, **kwargs)
1038
+
1039
+ proxy_kwargs = pytree.tree_map(mode.tracer.unwrap_proxy, kwargs)
1040
+
1041
+ if isinstance(_mutable_op, HigherOrderOperator):
1042
+
1043
+ def _maybe_register_subgraph(val: Any):
1044
+ if isinstance(val, torch.fx.GraphModule):
1045
+ _, graph_name = unique_graph_id(
1046
+ mode, prefix="auto_functionalized_subgraph"
1047
+ )
1048
+ mode.tracer.root.register_module(graph_name, val)
1049
+ return val
1050
+ return val
1051
+
1052
+ proxy_kwargs = pytree.tree_map(_maybe_register_subgraph, proxy_kwargs)
1053
+
1054
+ out_proxy = mode.tracer.create_proxy(
1055
+ "call_function",
1056
+ auto_functionalized_v2,
1057
+ (_mutable_op,),
1058
+ proxy_kwargs,
1059
+ )
1060
+ result = track_tensor_tree(out, out_proxy, constant=None, tracer=mode.tracer)
1061
+ return result
1062
+
1063
+
1064
+ @auto_functionalized_v2.py_functionalize_impl
1065
+ def auto_functionalized_v2_func(ctx, _mutable_op, **kwargs):
1066
+ unwrapped_kwargs = ctx.unwrap_tensors(kwargs)
1067
+ with ctx.redispatch_to_next():
1068
+ result = auto_functionalized_v2(_mutable_op, **unwrapped_kwargs)
1069
+ return ctx.wrap_tensors(result)
.venv/lib/python3.10/site-packages/torch/_higher_order_ops/base_hop.py ADDED
@@ -0,0 +1,281 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+
3
+ import abc
4
+
5
+ import torch
6
+ import torch.utils._pytree as pytree
7
+ from torch._C import DispatchKey
8
+ from torch._dispatch.python import suspend_functionalization
9
+ from torch._higher_order_ops.auto_functionalize import FunctionalCallableWithEpilogue
10
+ from torch._higher_order_ops.utils import (
11
+ check_input_alias_and_mutation_return_outputs,
12
+ HopInstance,
13
+ materialize_as_graph,
14
+ reenter_make_fx,
15
+ )
16
+ from torch._ops import HigherOrderOperator
17
+ from torch._subclasses import FakeTensorMode
18
+ from torch._subclasses.functional_tensor import disable_functional_mode
19
+ from torch.fx.experimental.proxy_tensor import (
20
+ disable_proxy_modes_tracing,
21
+ ProxyTorchDispatchMode,
22
+ track_tensor_tree,
23
+ )
24
+
25
+
26
+ class BaseHOP(HigherOrderOperator, abc.ABC):
27
+ """
28
+ This is the "Base" HOP implementation for a HOP that looks like:
29
+
30
+ call_subgraph_hop(subgraph, *operands, **kwargs)
31
+
32
+ That is:
33
+ 1) the HOP stays alive until Inductor
34
+ 2) the HOP's semantics are subgraph(*operands)
35
+ 3) kwargs may be some config options but aren't passed directly to the subgraph.
36
+
37
+ To use this, please subclass this class and override methods as necessary:
38
+ ```
39
+ class InvokeQuant(BaseHOP):
40
+ def __init__(self):
41
+ return super().__init__("invoke_quant")
42
+
43
+
44
+ invoke_quant = InvokeQuant()
45
+
46
+
47
+ def g(x):
48
+ return x.sin().cos()
49
+
50
+
51
+ @torch.compile(backend="aot_eager")
52
+ def f(x):
53
+ return invoke_quant(g, x, scheme="nf4")
54
+ ```
55
+
56
+ NOTE: don't subclass BaseHOP out of tree! That is not allowed. All
57
+ usages must be in tree.
58
+ """
59
+
60
+ def __init__(self, hop_name) -> None:
61
+ super().__init__(hop_name)
62
+
63
+ # Set up the registrations
64
+ # If you want to override any of these, override them in your subclass.
65
+ self.py_autograd_impl(self._call_Autograd)
66
+ self.py_functionalize_impl(self._call_Functionalize)
67
+ self.py_impl(ProxyTorchDispatchMode)(self._call_ProxyTorchDispatchMode)
68
+ self.py_impl(FakeTensorMode)(self._call_FakeTensorMode)
69
+ self.py_impl(DispatchKey.CompositeExplicitAutograd)(
70
+ self._call_CompositeExplicitAutograd
71
+ )
72
+
73
+ def __call__(self, subgraph, *operands, **kwargs):
74
+ if not isinstance(
75
+ subgraph,
76
+ (
77
+ torch.fx.GraphModule,
78
+ FunctionWithNoFreeVars,
79
+ FunctionalCallableWithEpilogue,
80
+ ),
81
+ ):
82
+ raise RuntimeError(
83
+ f"{self._name}: when calling this API without torch.compile, "
84
+ f"we require that the subgraph be a torch.fx.GraphModule (or "
85
+ f"a function we know doesn't have free variables)."
86
+ )
87
+ # pyrefly: ignore [missing-attribute]
88
+ return super().__call__(subgraph, *operands, **kwargs)
89
+
90
+ def _call_Autograd(self, subgraph, *operands, **kwargs):
91
+ if isinstance(subgraph, torch.fx.GraphModule):
92
+ pass
93
+
94
+ # We assume the subgraph doesn't mutate inputs and there is no aliasing.
95
+ # In the PT2 stack, this is Dynamo's responsibility to figure out.
96
+ return BaseHOPFunction.apply(self, subgraph, kwargs, *operands)
97
+
98
+ def _call_CompositeExplicitAutograd(self, subgraph, *operands, **kwargs):
99
+ from torch.utils._python_dispatch import _get_current_dispatch_mode
100
+
101
+ mode = _get_current_dispatch_mode()
102
+ if mode is not None:
103
+ raise AssertionError("Mode should never be enabled for CPU/CUDA key")
104
+ return subgraph(*operands)
105
+
106
+ def _call_ProxyTorchDispatchMode(self, proxy_mode, subgraph, *operands, **kwargs):
107
+ traced_graph = reenter_make_fx(subgraph)(*operands)
108
+ if not isinstance(proxy_mode.tracer, torch.fx.Tracer):
109
+ raise AssertionError(
110
+ f"expected proxy_mode.tracer to be torch.fx.Tracer, got {type(proxy_mode.tracer)}"
111
+ )
112
+ qualname = proxy_mode.tracer.get_fresh_qualname("subgraph")
113
+ proxy_mode.tracer.root.register_module(qualname, traced_graph)
114
+
115
+ node_args = (traced_graph, *operands)
116
+ proxy_args = pytree.tree_map(proxy_mode.tracer.unwrap_proxy, node_args) # type: ignore[attr-defined]
117
+ proxy_kwargs = pytree.tree_map(proxy_mode.tracer.unwrap_proxy, kwargs) # type: ignore[attr-defined]
118
+ out_proxy = proxy_mode.tracer.create_proxy(
119
+ "call_function", self, proxy_args, proxy_kwargs
120
+ )
121
+
122
+ out = self(subgraph, *operands, **kwargs)
123
+ return track_tensor_tree(
124
+ out,
125
+ out_proxy,
126
+ constant=None,
127
+ tracer=proxy_mode.tracer, # type: ignore[arg-type]
128
+ )
129
+
130
+ def _call_FakeTensorMode(self, mode, subgraph, *operands, **kwargs):
131
+ # TODO: this should probably route through FakeTensorMode to reuse caching
132
+ with mode:
133
+ return subgraph(*operands)
134
+
135
+ # NOTE [Support input mutation of hops]
136
+ # To support input mutation, hop's subgraph must be functionalized because many inductor passes are
137
+ # applied to subgraph recursively and only work on functional graph. However, we could inline an
138
+ # epilogue graph (i.e. the copy_) into the subgraph because this is how input mutation
139
+ # is implemented in the top-level graph when no hop is presented. All passes must have been and will be
140
+ # aware of the epilogue graph.
141
+ #
142
+ # Since we've supported input mutation for custom op with auto_functionalized, we share the infra for hops
143
+ # The plan is:
144
+ # 1. In hop's Functionalization key, it calls do_auto_functionalize_v2 if subgraph mutates input
145
+ # 2. In do_auto_functionalize_v2:
146
+ # a. we functionalize the callables in hop's argument. This is to make the subgraphs functional so we
147
+ # could recursively run passes on them. Also the epilogue graph is inlined at the end.
148
+ # b. we call auto_functionalized_v2 and pass in an additional schema in order to properly invoke
149
+ # the hop with normalized kwargs.
150
+ # 3. In inductor, we decompose the auto_functionalized hop by callilng into the dense implementation, which
151
+ # copies the mutated inputs to the hop if necessary and call the hop.
152
+ # After these steps, the rest of the inductor stack knows how to fuse the copy_ in subgraph with other ops.
153
+ def _call_Functionalize(self, ctx, subgraph, *operands, **kwargs):
154
+ from torch._higher_order_ops.auto_functionalize import (
155
+ can_auto_functionalize,
156
+ do_auto_functionalize_v2,
157
+ )
158
+
159
+ # invoke_quant has non-proxable argument of type InvokeQuant that
160
+ # we cannot generate schema for.
161
+ if self is not torch.ops.higher_order.invoke_quant_packed:
162
+ hop_instance = HopInstance.create(self, subgraph, *operands, **kwargs)
163
+ if can_auto_functionalize(hop_instance):
164
+ return do_auto_functionalize_v2(
165
+ ctx.mode, hop_instance, (subgraph, *operands), kwargs
166
+ )
167
+
168
+ unwrapped_operands = ctx.unwrap_tensors(operands)
169
+ with ctx.redispatch_to_next():
170
+ # We assume the subgraph doesn't mutate inputs and there is no aliasing.
171
+ # In the PT2 stack, this is Dynamo's responsibility to figure out.
172
+ functionalized_subgraph = FunctionWithNoFreeVars(
173
+ ctx.functionalize(subgraph)
174
+ )
175
+ out = self(functionalized_subgraph, *unwrapped_operands, **kwargs)
176
+ return ctx.wrap_tensors(out)
177
+
178
+ # pyrefly: ignore [bad-override]
179
+ def gen_schema(self, subgraph, *operands, **kwargs):
180
+ from .schema import HopSchemaGenerator
181
+
182
+ subgraph = materialize_as_graph(subgraph, operands)
183
+ (
184
+ inp_inp_alias,
185
+ inp_out_alias,
186
+ out_out_alias,
187
+ mutated_inp_idx,
188
+ output,
189
+ ) = check_input_alias_and_mutation_return_outputs(subgraph)
190
+
191
+ if not (
192
+ len(inp_inp_alias) == 0
193
+ and len(inp_out_alias) == 0
194
+ and len(out_out_alias) == 0
195
+ ):
196
+ # TODO: turn this into an error.
197
+ # test_foreach_map_backward_binary_foreach_map_addrecip_op fails the alias test.
198
+ import warnings
199
+
200
+ warnings.warn(
201
+ "Aliasing is not supported for HOP subgraph.\n"
202
+ f"{subgraph.print_readable(print_output=False)}\n"
203
+ f"Alias info: inp-inp alias: {inp_inp_alias}, inp-out alias: {inp_out_alias}, out-out alias{out_out_alias}"
204
+ f"This may lead to silent incorrectness.",
205
+ stacklevel=2,
206
+ )
207
+
208
+ schema_gen = HopSchemaGenerator(self)
209
+ schema_gen.add_arg("subgraph", subgraph)
210
+ for idx, arg in enumerate(operands):
211
+ schema_gen.add_arg(f"arg{idx}", arg, is_mutated=idx in mutated_inp_idx)
212
+
213
+ for name, arg in kwargs.items():
214
+ schema_gen.add_arg(name, arg, default_value=arg, kw_only=True)
215
+
216
+ for out in output:
217
+ schema_gen.add_output(out)
218
+
219
+ return schema_gen.gen_schema()
220
+
221
+
222
+ class BaseHOPFunction(torch.autograd.Function):
223
+ @staticmethod
224
+ # pyrefly: ignore [bad-override]
225
+ def forward(ctx, hop, subgraph, kwargs, *operands):
226
+ ctx.hop = hop
227
+ ctx.operands = operands
228
+ ctx.subgraph = subgraph
229
+ ctx.kwargs = kwargs
230
+
231
+ with torch._C._AutoDispatchBelowAutograd():
232
+ return hop(subgraph, *operands, **kwargs)
233
+
234
+ @staticmethod
235
+ def backward(ctx, *grad_outputs):
236
+ subgraph = ctx.subgraph
237
+ operands = ctx.operands
238
+ kwargs = ctx.kwargs
239
+
240
+ # TODO: Something special needs to happen with min cut partitioner
241
+ with (
242
+ suspend_functionalization(),
243
+ disable_functional_mode(),
244
+ torch.enable_grad(),
245
+ ):
246
+ with disable_proxy_modes_tracing():
247
+ from .invoke_subgraph import create_fw_bw_graph
248
+ from .utils import _from_fun
249
+
250
+ fw_inputs = pytree.tree_map(_from_fun, operands)
251
+ (
252
+ _,
253
+ joint_graph,
254
+ _,
255
+ ) = create_fw_bw_graph(subgraph, fw_inputs, grad_outputs)
256
+
257
+ # The joint graph returns (*grad_inputs, *fwd_outputs).
258
+ # We only need the grad_inputs.
259
+ def bwd_fn(*args):
260
+ operands = args[: -len(grad_outputs)]
261
+ grad_outs = args[-len(grad_outputs) :]
262
+ result = joint_graph(*operands, *grad_outs)
263
+ grad_inputs = result[: -len(grad_outputs)]
264
+ return grad_inputs
265
+
266
+ return (
267
+ None,
268
+ None,
269
+ None,
270
+ *ctx.hop(
271
+ FunctionWithNoFreeVars(bwd_fn), *operands, *grad_outputs, **kwargs
272
+ ),
273
+ )
274
+
275
+
276
+ class FunctionWithNoFreeVars:
277
+ def __init__(self, fn):
278
+ self.fn = fn
279
+
280
+ def __call__(self, *args, **kwargs):
281
+ return self.fn(*args, **kwargs)
.venv/lib/python3.10/site-packages/torch/_higher_order_ops/cond.py ADDED
@@ -0,0 +1,757 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-decorators
2
+ # mypy: allow-untyped-defs
3
+ import contextlib
4
+ import functools
5
+ import logging
6
+ import warnings
7
+ from collections.abc import Callable
8
+ from typing import Any, Optional, Union
9
+
10
+ import torch
11
+ import torch.utils._pytree as pytree
12
+ from torch._C import DispatchKey
13
+ from torch._C._functorch import (
14
+ _add_batch_dim,
15
+ get_unwrapped,
16
+ is_batchedtensor,
17
+ maybe_get_bdim,
18
+ )
19
+ from torch._functorch.utils import exposed_in
20
+ from torch._higher_order_ops.utils import (
21
+ _maybe_run_with_interpreter,
22
+ check_input_alias_and_mutation_return_outputs,
23
+ create_bw_fn,
24
+ fill_none_with_masks,
25
+ filter_with_masks,
26
+ materialize_as_graph,
27
+ reenter_make_fx,
28
+ save_values_for_backward,
29
+ saved_values,
30
+ unique_graph_id,
31
+ validate_subgraph_args_types,
32
+ )
33
+ from torch._ops import HigherOrderOperator
34
+ from torch._subclasses.fake_tensor import FakeTensor, FakeTensorMode
35
+ from torch.fx.experimental.proxy_tensor import ProxyTorchDispatchMode, track_tensor_tree
36
+ from torch.utils._python_dispatch import _get_current_dispatch_mode
37
+
38
+
39
+ log = logging.getLogger(__name__)
40
+
41
+ """
42
+ We're going to define a `cond_op` operation.
43
+ In order to do this, we need implementations for each of the dispatch keys.
44
+ """
45
+
46
+
47
+ class CondOp(HigherOrderOperator):
48
+ def __init__(self):
49
+ super().__init__("cond")
50
+
51
+ def __call__(self, pred, true_fn, false_fn, operands):
52
+ validate_subgraph_args_types(operands)
53
+ # pyrefly: ignore [missing-attribute]
54
+ return super().__call__(pred, true_fn, false_fn, operands)
55
+
56
+ # pyrefly: ignore [bad-override]
57
+ def gen_schema(self, pred, true_fn, false_fn, operands):
58
+ from torch._higher_order_ops.schema import HopSchemaGenerator
59
+ from torch._higher_order_ops.utils import materialize_as_graph
60
+
61
+ then_gm: torch.fx.GraphModule = materialize_as_graph(true_fn, operands)
62
+ else_gm: torch.fx.GraphModule = materialize_as_graph(false_fn, operands)
63
+ (
64
+ _,
65
+ _,
66
+ _,
67
+ then_mutated_inputs,
68
+ then_outputs,
69
+ ) = check_input_alias_and_mutation_return_outputs(then_gm)
70
+ (
71
+ _,
72
+ _,
73
+ _,
74
+ else_mutated_inputs,
75
+ else_outputs,
76
+ ) = check_input_alias_and_mutation_return_outputs(else_gm)
77
+ mutated_inputs = set(then_mutated_inputs) | set(else_mutated_inputs)
78
+
79
+ schema_gen = HopSchemaGenerator(self)
80
+ schema_gen.add_arg("pred", pred)
81
+ schema_gen.add_arg("true_fn", then_gm)
82
+ schema_gen.add_arg("false_fn", else_gm)
83
+ for idx, arg in enumerate(operands):
84
+ schema_gen.add_arg(f"operand{idx}", arg, is_mutated=idx in mutated_inputs)
85
+
86
+ for out in then_outputs:
87
+ schema_gen.add_output(out)
88
+ schema_gen.add_schema_tree_spec(pred, true_fn, false_fn, operands)
89
+ return schema_gen.gen_schema()
90
+
91
+
92
+ cond_op = CondOp()
93
+
94
+
95
+ @exposed_in("torch")
96
+ def cond(
97
+ pred: Union[bool, int, float, torch.Tensor],
98
+ true_fn: Callable,
99
+ false_fn: Callable,
100
+ operands: Union[tuple, list] = (),
101
+ ) -> Any:
102
+ r"""
103
+ Conditionally applies `true_fn` or `false_fn`.
104
+
105
+ .. warning::
106
+
107
+ `torch.cond` is a prototype feature in PyTorch. It has limited support for input and output types.
108
+ Please look forward to a more stable implementation in a future version of PyTorch.
109
+ Read more about feature classification at: https://pytorch.org/blog/pytorch-feature-classification-changes/#prototype
110
+
111
+ `cond` is structured control flow operator. That is, it is like a Python if-statement,
112
+ but has restrictions on `true_fn`, `false_fn`, and `operands` that enable it to be
113
+ capturable using torch.compile and torch.export.
114
+
115
+ Assuming the constraints on `cond`'s arguments are met, `cond` is equivalent to the following::
116
+
117
+ def cond(pred, true_branch, false_branch, operands):
118
+ if pred:
119
+ return true_branch(*operands)
120
+ else:
121
+ return false_branch(*operands)
122
+
123
+ Args:
124
+ pred (Union[bool, torch.Tensor]): A boolean expression or a tensor with one element,
125
+ indicating which branch function to apply.
126
+
127
+ true_fn (Callable): A callable function (a -> b) that is within the
128
+ scope that is being traced.
129
+
130
+ false_fn (Callable): A callable function (a -> b) that is within the
131
+ scope that is being traced. The true branch and false branch must
132
+ have consistent input and outputs, meaning the inputs have to be
133
+ the same, and the outputs have to be the same type and shape. Int
134
+ output is also allowed. We'll make the output dynamic by turning it
135
+ into a symint.
136
+
137
+ operands (Tuple of possibly nested dict/list/tuple of torch.Tensor): A tuple of inputs to the
138
+ true/false functions. It can be empty if true_fn/false_fn doesn't require input. Defaults to ().
139
+
140
+ Example::
141
+
142
+ def true_fn(x: torch.Tensor):
143
+ return x.cos()
144
+
145
+
146
+ def false_fn(x: torch.Tensor):
147
+ return x.sin()
148
+
149
+
150
+ return cond(x.shape[0] > 4, true_fn, false_fn, (x,))
151
+
152
+ Restrictions:
153
+ - The conditional statement (aka `pred`) must meet one of the following constraints:
154
+
155
+ - It's a `torch.Tensor` with only one element, and torch.bool dtype
156
+
157
+ - It's a boolean expression, e.g. `x.shape[0] > 10` or `x.dim() > 1 and x.shape[1] > 10`
158
+
159
+ - The branch function (aka `true_fn`/`false_fn`) must meet all of the following constraints:
160
+
161
+ - The function signature must match with operands.
162
+
163
+ - The function must return a tensor with the same metadata, e.g. shape,
164
+ dtype, etc.
165
+
166
+ - The function cannot have in-place mutations on inputs or global variables.
167
+ (Note: in-place tensor operations such as `add_` for intermediate results
168
+ are allowed in a branch)
169
+
170
+ """
171
+ if torch.compiler.is_dynamo_compiling():
172
+ return cond_op(pred, true_fn, false_fn, operands)
173
+
174
+ if isinstance(pred, (bool, int, float)):
175
+ # This is the non-strict export case. Strict export and torch.compile are
176
+ # handled above in dynamo.
177
+ if torch.compiler.is_compiling():
178
+ warnings.warn(
179
+ "Pred is a Python constant. When used with torch.cond, it specializes on one of the branches."
180
+ " If you want torch.cond to preserve two branches, please make the predicate a boolean tensor or a SymBool.",
181
+ UserWarning,
182
+ stacklevel=2,
183
+ )
184
+ # This is the eager case. We can just run the true or false branch.
185
+ if pred:
186
+ return true_fn(*operands)
187
+ else:
188
+ return false_fn(*operands)
189
+
190
+ def _validate_input(pred, true_fn, false_fn, operands):
191
+ if not isinstance(pred, (bool, torch.Tensor, torch.SymBool)):
192
+ raise RuntimeError(f"Expected pred to be bool or tensor, but got {pred}.")
193
+
194
+ if isinstance(pred, torch.Tensor) and pred.numel() != 1:
195
+ raise RuntimeError(
196
+ f"Expected pred to be bool or single-element tensor, but got {pred}."
197
+ )
198
+
199
+ if not callable(true_fn) or not callable(false_fn):
200
+ raise RuntimeError("Expect both branches to be callable.")
201
+
202
+ if not isinstance(operands, (tuple, list)) or pytree.tree_any(
203
+ lambda t: not isinstance(t, torch.Tensor), operands
204
+ ):
205
+ raise RuntimeError(
206
+ "Expect operands to be a tuple of possibly nested dict/list/tuple that only "
207
+ f"consists of tensor leaves, but got {operands}."
208
+ )
209
+
210
+ _validate_input(pred, true_fn, false_fn, operands)
211
+
212
+ if not torch._dynamo.is_dynamo_supported():
213
+ raise RuntimeError("torch.cond requires dynamo support.")
214
+
215
+ # Dynamo is expecting a callable with "__code__" attribute.
216
+ # We cannot directly pass cond_op to it. So we wrap it in a dummy function.
217
+ def _cond_op_wrapper(*args, **kwargs):
218
+ return cond_op(*args, **kwargs)
219
+
220
+ from torch._higher_order_ops.utils import setup_compilation_env
221
+
222
+ with setup_compilation_env() as backend:
223
+ return torch.compile(_cond_op_wrapper, backend=backend, fullgraph=True)(
224
+ pred, true_fn, false_fn, operands
225
+ )
226
+
227
+
228
+ def trace_cond(proxy_mode, func_overload, pred, true_fn, false_fn, operands):
229
+ if not isinstance(operands, (list, tuple)):
230
+ raise AssertionError(
231
+ f"Cond operands must be a list or tuple of tensors and SymInts {operands}"
232
+ )
233
+
234
+ true_graph = reenter_make_fx(true_fn)(*operands)
235
+ false_graph = reenter_make_fx(false_fn)(*operands)
236
+
237
+ true_outs = []
238
+ false_outs = []
239
+ for node in true_graph.graph.nodes:
240
+ if node.op == "output":
241
+ true_outs.extend(node.args)
242
+
243
+ for node in false_graph.graph.nodes:
244
+ if node.op == "output":
245
+ false_outs.extend(node.args)
246
+
247
+ flat_true_outs = pytree.arg_tree_leaves(*true_outs)
248
+ flat_false_outs = pytree.arg_tree_leaves(*false_outs)
249
+ if len(flat_true_outs) != len(flat_false_outs):
250
+ raise torch._dynamo.exc.CondOpArgsMismatchError(
251
+ f"Expected to return same number of outputs but got:"
252
+ f"\n true branch returns {len(flat_true_outs)} item(s)"
253
+ f"\n false branch returns {len(flat_false_outs)} item(s)"
254
+ )
255
+
256
+ i, true_name = unique_graph_id(proxy_mode, prefix="true_graph")
257
+
258
+ false_name = f"false_graph_{i}"
259
+ if hasattr(proxy_mode.tracer.root, false_name):
260
+ raise AssertionError(
261
+ f"proxy_mode.tracer.root already has attribute {false_name}"
262
+ )
263
+
264
+ proxy_mode.tracer.root.register_module(true_name, true_graph)
265
+ proxy_mode.tracer.root.register_module(false_name, false_graph)
266
+
267
+ args = (pred, true_graph, false_graph, operands)
268
+
269
+ proxy_args = pytree.tree_map(proxy_mode.tracer.unwrap_proxy, args)
270
+
271
+ out_proxy = proxy_mode.tracer.create_proxy(
272
+ "call_function", func_overload, proxy_args, {}
273
+ )
274
+
275
+ out = func_overload(pred, true_graph, false_graph, operands)
276
+
277
+ return track_tensor_tree(out, out_proxy, constant=None, tracer=proxy_mode.tracer)
278
+
279
+
280
+ @cond_op.py_impl(DispatchKey.CompositeExplicitAutograd)
281
+ def cond_op_dense(pred, true_fn, false_fn, operands):
282
+ if not all(isinstance(o, (torch.Tensor, int)) for o in operands):
283
+ raise AssertionError(
284
+ f"Dense implementation operands must be a list of tensors and ints {operands}"
285
+ )
286
+ mode = _get_current_dispatch_mode()
287
+ if mode is not None:
288
+ raise AssertionError("Mode should never be enabled for CPU/CUDA key")
289
+ if pred:
290
+ return true_fn(*operands)
291
+ else:
292
+ return false_fn(*operands)
293
+
294
+
295
+ class CondAutogradOp(torch.autograd.Function):
296
+ @staticmethod
297
+ # pyrefly: ignore [bad-override]
298
+ def forward(
299
+ ctx,
300
+ pred,
301
+ true_fn,
302
+ false_fn,
303
+ *operands,
304
+ ):
305
+ ctx._pred = pred
306
+ ctx._true_bw_fn = create_bw_fn(
307
+ true_fn,
308
+ operands,
309
+ )
310
+ ctx._false_bw_fn = create_bw_fn(
311
+ false_fn,
312
+ operands,
313
+ )
314
+ # We snapshot the dispatch keys in forward for materializing the
315
+ # the bw_graph in backward.
316
+ ctx._fw_include_key_set = torch._C._dispatch_tls_local_include_set()
317
+ ctx._fw_exclude_key_set = torch._C._dispatch_tls_local_exclude_set()
318
+ save_values_for_backward(ctx, operands)
319
+
320
+ with torch._C._AutoDispatchBelowAutograd():
321
+ return cond_op(pred, true_fn, false_fn, operands)
322
+
323
+ @staticmethod
324
+ def backward(ctx, *flat_grads):
325
+ operands = saved_values(ctx)
326
+ args = operands + flat_grads
327
+ # TODO: we need to materialize the bw graphs because dynamo is unable to
328
+ # trace through the joint function when torch.compile torch.autograd.grad.
329
+
330
+ grads_tensor_masks = []
331
+
332
+ def create_fn_remove_none(fn):
333
+ @functools.wraps(fn)
334
+ def wrapped(*args):
335
+ nonlocal grads_tensor_masks
336
+
337
+ true_outputs = fn(*args)
338
+ grads_tensor_masks = [
339
+ bool(isinstance(out, torch.Tensor)) for out in true_outputs
340
+ ]
341
+ return filter_with_masks(true_outputs, grads_tensor_masks)
342
+
343
+ return wrapped
344
+
345
+ true_bw_gm = materialize_as_graph(
346
+ create_fn_remove_none(ctx._true_bw_fn),
347
+ args,
348
+ ctx._fw_include_key_set,
349
+ ctx._fw_exclude_key_set,
350
+ force_enable_grad=True,
351
+ )
352
+ false_bw_gm = materialize_as_graph(
353
+ create_fn_remove_none(ctx._false_bw_fn),
354
+ args,
355
+ ctx._fw_include_key_set,
356
+ ctx._fw_exclude_key_set,
357
+ force_enable_grad=True,
358
+ )
359
+ grads = cond_op(
360
+ ctx._pred,
361
+ true_bw_gm,
362
+ false_bw_gm,
363
+ args,
364
+ )
365
+ return None, None, None, *fill_none_with_masks(grads, grads_tensor_masks)
366
+
367
+
368
+ # Note:
369
+ # As long as one of the tensors in pred or operands requires grad,
370
+ # all the output would require grad with backward fn set to be the CondAutogradOp.
371
+ # This is consistent with autograd.Function's semantic.
372
+ @cond_op.py_autograd_impl
373
+ def cond_autograd(pred, true_fn, false_fn, operands):
374
+ return CondAutogradOp.apply(
375
+ pred,
376
+ true_fn,
377
+ false_fn,
378
+ *operands,
379
+ )
380
+
381
+
382
+ @cond_op.py_impl(ProxyTorchDispatchMode)
383
+ def inner(mode, pred, true_fn, false_fn, operands):
384
+ return trace_cond(mode, cond_op, pred, true_fn, false_fn, operands)
385
+
386
+
387
+ @cond_op.py_impl(FakeTensorMode)
388
+ def cond_fake_tensor_mode(mode, pred, true_fn, false_fn, operands):
389
+ # Ignore here, because if you've gotten here but you're not manually
390
+ # tracing the inner graphs, that means that you intend to reuse the graph
391
+ # directly. Which means the old unbacked symbol bindings are appropriate.
392
+ # This strategy will not work if unbacked symbols can escape.
393
+ ignore_fresh_unbacked = contextlib.nullcontext()
394
+ if mode.shape_env:
395
+ ignore_fresh_unbacked = mode.shape_env.ignore_fresh_unbacked_symbols()
396
+
397
+ with mode, ignore_fresh_unbacked:
398
+ flat_true_outs, true_out_spec = pytree.tree_flatten(true_fn(*operands))
399
+ flat_false_outs, false_out_spec = pytree.tree_flatten(false_fn(*operands))
400
+ if true_out_spec != false_out_spec:
401
+ raise RuntimeError(
402
+ "Unmatched output spec from torch.cond branches: "
403
+ f"true branch tree_spec {true_out_spec} vs false branch tree_spec {false_out_spec}."
404
+ )
405
+
406
+ merged_outs = []
407
+ for true_out, false_out in zip(flat_true_outs, flat_false_outs):
408
+ merged_outs.append(_merge_output(true_out, false_out, mode))
409
+ return pytree.tree_unflatten(merged_outs, true_out_spec)
410
+
411
+
412
+ def check_tensor_meta_match(
413
+ t1: torch.Tensor, t2: torch.Tensor, attr_names: tuple[str, ...], msg_prefix: str
414
+ ) -> None:
415
+ def _get_attr_maybe_call(t: torch.Tensor, attr_name: str) -> Any:
416
+ attr = getattr(t, attr_name)
417
+ if callable(attr):
418
+ return attr()
419
+ return attr
420
+
421
+ for attr_name in attr_names:
422
+ lattr = _get_attr_maybe_call(t1, attr_name)
423
+ rattr = _get_attr_maybe_call(t2, attr_name)
424
+ torch._check(
425
+ lattr == rattr,
426
+ lambda: f"{msg_prefix} expected same {attr_name} but got {lattr} and {rattr}.",
427
+ )
428
+
429
+
430
+ def _merge_output(
431
+ a: Optional[Union[torch.Tensor, int]],
432
+ b: Optional[Union[torch.Tensor, int]],
433
+ mode: FakeTensorMode,
434
+ ):
435
+ from torch.fx.experimental.symbolic_shapes import (
436
+ has_free_unbacked_symbols,
437
+ SymIntEqByExpr,
438
+ )
439
+
440
+ if a is None or b is None:
441
+ if not (a is None and b is None):
442
+ raise AssertionError(f"expected both a and b to be None, got a={a}, b={b}")
443
+ return None
444
+
445
+ def min_max(s0, s1):
446
+ def _bound(s0, lower_bound: bool):
447
+ if isinstance(s0, int):
448
+ return s0
449
+ r = mode.shape_env.var_to_range.get( # type: ignore[union-attr]
450
+ s0.node.expr,
451
+ torch.utils._sympy.value_ranges.ValueRanges.unknown(),
452
+ )
453
+ return r.lower if lower_bound else r.upper
454
+
455
+ return min(_bound(s0, True), _bound(s1, True)), max(
456
+ _bound(s0, False), _bound(s1, False)
457
+ )
458
+
459
+ if type(a) is int and type(b) is int:
460
+ if a == b:
461
+ return a
462
+ if mode.shape_env is None:
463
+ raise AssertionError("mode.shape_env is None")
464
+ merged_out = mode.shape_env.create_unbacked_symint()
465
+ mode.shape_env.constrain_symbol_range(merged_out.node.expr, *min_max(a, b))
466
+ return merged_out
467
+
468
+ if not (type(a) is FakeTensor and type(b) is FakeTensor):
469
+ raise AssertionError(
470
+ f"expected both a and b to be FakeTensor, got a={type(a)}, b={type(b)}"
471
+ )
472
+
473
+ # Note: we don't check size, stride because
474
+ # they'll be merged with unbacked symints if they differ.
475
+ _meta_to_check = {
476
+ "dtype",
477
+ "device",
478
+ "layout",
479
+ "dim",
480
+ "is_quantized",
481
+ "is_conj",
482
+ "is_sparse",
483
+ "storage_offset",
484
+ }
485
+ check_tensor_meta_match(
486
+ a,
487
+ b,
488
+ tuple(_meta_to_check),
489
+ msg_prefix="When merging two branches' output in torch.cond, ",
490
+ )
491
+ # NYI
492
+ if a.is_quantized or b.is_quantized:
493
+ raise AssertionError("quantized tensors not yet implemented")
494
+ if a.is_sparse or b.is_sparse:
495
+ raise AssertionError("sparse tensors not yet implemented")
496
+ if a.is_conj() or b.is_conj():
497
+ raise AssertionError("conjugate tensors not yet implemented")
498
+
499
+ """
500
+ Step 1: create unbacked symints for sizes that are different
501
+ along the same axis. For example:
502
+ a.size is [s0, 4, s0, 5, 4, 5]
503
+ b.size is [s1, 4, s2, 8, 4, 7]
504
+ merged_size will be [u0, 4, u1, u2, 4, u3], where
505
+ u0 has range [min(s0, s1), max(s0, s1)]
506
+ u1 has range [min(s0, s2), max(s0, s2)]
507
+ u2 has range [5, 8]
508
+ u3 has range [5, 7]
509
+ """
510
+ merged_size: list[Union[int, torch.SymInt]] = []
511
+
512
+ def _has_unbacked_symbols(s: Union[int, torch.SymInt]) -> bool:
513
+ if isinstance(s, int):
514
+ return False
515
+ else:
516
+ return has_free_unbacked_symbols(s.node.expr)
517
+
518
+ for s0, s1 in zip(a.size(), b.size()):
519
+ # If there are unbacked symbols leaked out of true_branch or false_branch
520
+ # we need to merge them with a new unbacked symbol and track in parent graph.
521
+ if (
522
+ not _has_unbacked_symbols(s0)
523
+ and not _has_unbacked_symbols(s1)
524
+ and SymIntEqByExpr(s0) == SymIntEqByExpr(s1)
525
+ ):
526
+ merged_size.append(s0)
527
+ else:
528
+ if mode.shape_env is None:
529
+ raise AssertionError("mode.shape_env is None")
530
+ new_size = mode.shape_env.create_unbacked_symint()
531
+ mode.shape_env.constrain_symbol_range(new_size.node.expr, *min_max(s0, s1))
532
+ merged_size.append(new_size)
533
+
534
+ """
535
+ This follows the logic in symbolic_shapes._compute_symbolic_stride
536
+ Step 2: Since tensor stride is an accumulative multiplication of the sizes, which is a permutated
537
+ (due to view ops) non-descending sequence.
538
+
539
+ Case 1: No size is 1. In this case, strides have unique values.
540
+ For example, suppose we have a tensor with:
541
+ size [3, 4, 3, 5, 4, 5],
542
+ stride (1200, 300, 1, 12, 3, 60),
543
+ merged_size [u0, u1, u2, u3, u4, u5].
544
+
545
+ We visit the strides in ascending order: 1, 3, 12, 60, 300, 1200. In each step, we check whether
546
+ the current stride is bounded or not and bound next stride by setting.
547
+ stride_expr[next_stride] = current_stride_expr * current_size_expr
548
+ 1st round:
549
+ current_stride is 1, current_size is 3, so next_stride is 1 * 3 = 3,
550
+ current_stride_expr is set to 1, current_size_expr is u2, so stride_expr[3] is therefore 1 * u2 = u2
551
+ 2nd round:
552
+ current_stride is 3, current_size is 4, so next_stride is 3 * 4 = 12,
553
+ current_stride_expr is stride_expr[3] i.e. u2, current_size_expr is u4, so stride_expr[12] = u2 * u4
554
+ ...
555
+
556
+ Case 2: At least one dimension has size 1, which can produce duplicates in strides.
557
+ In this case, theoretically, we cannot uniquely determine the expr of strides because
558
+ the accessing stride_expr with same key in different order causes the final stride expression
559
+ to be different.
560
+
561
+ Suppose we have:
562
+ size: (3, 1)
563
+ stride: (1, 1)
564
+ merged_size: (u0, u1)
565
+
566
+ The stride expr could either be (u1, 1) or (1, u0) depending on whether we start with u1 or u0.
567
+ For this reason, we try to break tie by sorting via descending index so we always get (u1, 1).
568
+
569
+ Note that backend might optimize the strides anyway so this is usually not a problem as long
570
+ as two branches matches. See relevant discussions in https://github.com/pytorch/pytorch/issues/142024.
571
+
572
+ Case 3: Dim has 0 stride. 0 stride doesn't participate in the accumulative multiplication of
573
+ sizes. So they're always treated as constant even if their corresponding size is turned into unbacked symint.
574
+
575
+ Suppose we have:
576
+ size: (3, 3)
577
+ stride: (0, 1)
578
+ merged_size: (u0, u1)
579
+
580
+ The merged stride would be (0, 1)
581
+ """
582
+
583
+ def _bound_stride(
584
+ a_ex_size: torch.Size,
585
+ b_ex_size: torch.Size,
586
+ a_ex_stride: tuple[int, ...],
587
+ b_ex_stride: tuple[int, ...],
588
+ merged_size: list[Union[int, torch.SymInt]],
589
+ ) -> list[Union[int, torch.SymInt]]:
590
+ from torch._inductor.ir import get_stride_order
591
+
592
+ a_sorted_stride_idx = get_stride_order(a_ex_stride, mode.shape_env)
593
+ b_sorted_stride_idx = get_stride_order(b_ex_stride, mode.shape_env)
594
+
595
+ a_stride_li: list[Optional[tuple[Union[int, torch.SymInt], int]]] = [
596
+ None
597
+ ] * len(a_ex_stride)
598
+ b_stride_li: list[Optional[tuple[Union[int, torch.SymInt], int]]] = [
599
+ None
600
+ ] * len(b_ex_stride)
601
+ for i, idx in enumerate(a_sorted_stride_idx):
602
+ a_stride_li[idx] = (a_ex_stride[i], -i)
603
+ for i, idx in enumerate(b_sorted_stride_idx):
604
+ b_stride_li[idx] = (b_ex_stride[i], -i)
605
+
606
+ for a_pair, b_pair in zip(a_stride_li, b_stride_li):
607
+ if a_pair is None or b_pair is None:
608
+ raise AssertionError(
609
+ f"expected a_pair and b_pair to be non-None, got a_pair={a_pair}, b_pair={b_pair}"
610
+ )
611
+ _, a_idx = a_pair
612
+ _, b_idx = b_pair
613
+
614
+ if a_idx != b_idx:
615
+ raise RuntimeError(
616
+ f"The sorted order of strides of the two branches' output doesn't match."
617
+ f"this indicates the contiguousness of the two branches are different. "
618
+ f"True branch has stride {a_ex_stride} but false branch has stride {b_ex_stride}."
619
+ f"Consider using contiguous() to make the two branches have the same contiguousness."
620
+ )
621
+
622
+ def _maybe_expr(s: Union[int, torch.SymInt]):
623
+ if isinstance(s, int):
624
+ return s
625
+ return s.node.expr
626
+
627
+ a_stride_expr: dict[Any, Union[int, torch.SymInt]] = {}
628
+ b_stride_expr: dict[Any, Union[int, torch.SymInt]] = {}
629
+ merged_strides: list[Union[int, torch.SymInt]] = [None] * len(a_ex_stride) # type: ignore[list-item]
630
+ for a_pair, b_pair in zip(a_stride_li, b_stride_li):
631
+ if a_pair is None or b_pair is None:
632
+ raise AssertionError(
633
+ f"expected a_pair and b_pair to be non-None, got a_pair={a_pair}, b_pair={b_pair}"
634
+ )
635
+ a_val, neg_i = a_pair
636
+ b_val, _ = b_pair
637
+
638
+ i = -neg_i
639
+ if a_val == 0:
640
+ if b_val != 0:
641
+ raise AssertionError(
642
+ f"expected b_val == 0 when a_val == 0, got a_val={a_val}, b_val={b_val}"
643
+ )
644
+ merged_strides[i] = 0
645
+ continue
646
+
647
+ if _maybe_expr(a_val) in a_stride_expr:
648
+ a_expr = a_stride_expr[_maybe_expr(a_val)]
649
+ if b_stride_expr[_maybe_expr(b_val)] != a_expr:
650
+ raise AssertionError(
651
+ f"a_stride_expr:{a_stride_expr}, b_stride_expr:{b_stride_expr}"
652
+ )
653
+ merged_strides[i] = a_expr
654
+ else:
655
+ if a_val == 1:
656
+ if b_val != 1:
657
+ raise AssertionError(
658
+ f"expected b_val == 1 when a_val == 1, got b_val={b_val}"
659
+ )
660
+ a_stride_expr[_maybe_expr(a_val)] = 1
661
+ b_stride_expr[_maybe_expr(b_val)] = 1
662
+ merged_strides[i] = 1
663
+ else:
664
+ # If we cannot find the expr of a_val in a_stride_expr, it means
665
+ # the strides is not a simple accumulative multiplication of sizes.
666
+ # In this case, we cannot determine the expr of strides from the new
667
+ # shapes so we error out and hint users to call contiguous().
668
+ raise RuntimeError(
669
+ f"It seems one of cond's output stride is not a simple accumulative multiplication of sizes. "
670
+ f"This could be because cond returns a slice of a tensor, which is not dense in memory. "
671
+ f"True branch has size {a_ex_size}, stride {a_ex_stride} and false branch has size {b_ex_size} "
672
+ f"stride {b_ex_stride}. Hint: can call t.contiguous(). "
673
+ )
674
+ nxt_merged_stride_expr = merged_strides[i] * merged_size[i]
675
+ a_stride_expr[_maybe_expr(a_val * a_ex_size[i])] = nxt_merged_stride_expr
676
+ b_stride_expr[_maybe_expr(b_val * b_ex_size[i])] = nxt_merged_stride_expr
677
+ return merged_strides
678
+
679
+ merged_stride: list[Union[int, torch.SymInt]] = _bound_stride(
680
+ a.size(), b.size(), a.stride(), b.stride(), merged_size
681
+ )
682
+
683
+ with mode:
684
+ return torch.empty_strided(
685
+ merged_size, merged_stride, dtype=a.dtype, device=a.device
686
+ )
687
+
688
+
689
+ @cond_op.py_functionalize_impl
690
+ def cond_func(ctx, pred, true_fn, false_fn, inputs):
691
+ from torch._higher_order_ops.utils import _check_alias_and_mutation
692
+
693
+ unwrapped_inputs = ctx.unwrap_tensors(inputs)
694
+ unwrapped_pred = ctx.unwrap_tensors(pred)
695
+ with ctx.redispatch_to_next():
696
+ functional_true = ctx.functionalize(_maybe_run_with_interpreter(true_fn))
697
+ functional_false = ctx.functionalize(_maybe_run_with_interpreter(false_fn))
698
+ pre_dispatch = hasattr(ctx, "mode") and ctx.mode.pre_dispatch
699
+ for branch, branch_name in [(true_fn, "cond_true"), (false_fn, "cond_false")]:
700
+ _check_alias_and_mutation(
701
+ branch, unwrapped_inputs, branch_name, pre_dispatch
702
+ )
703
+
704
+ cond_return = cond_op(
705
+ unwrapped_pred, functional_true, functional_false, unwrapped_inputs
706
+ )
707
+ return ctx.wrap_tensors(cond_return)
708
+
709
+
710
+ @cond_op.py_impl(torch._C._functorch.TransformType.Vmap)
711
+ def cond_batch_rule(interpreter, pred, true_fn, false_fn, inputs):
712
+ if not isinstance(inputs, (list, tuple)):
713
+ raise AssertionError(
714
+ f"Cond inputs must be a list or tuple of tensors, got {type(inputs)}"
715
+ )
716
+ if not all(isinstance(i, torch.Tensor) for i in inputs):
717
+ raise AssertionError(
718
+ f"Cond inputs must be a list of tensors, got {[type(i) for i in inputs]}"
719
+ )
720
+
721
+ pred_is_batched = isinstance(pred, torch.Tensor) and is_batchedtensor(pred)
722
+ pred_ = get_unwrapped(pred) if pred_is_batched else pred
723
+
724
+ # unbatched tensors are not vmapped
725
+ tensors, in_dims = zip(
726
+ *[
727
+ (get_unwrapped(t), maybe_get_bdim(t)) if is_batchedtensor(t) else (t, None)
728
+ for t in inputs
729
+ ]
730
+ )
731
+
732
+ if pred_is_batched:
733
+ # prepend "pred" and vmap everything
734
+ tensors = (pred_,) + tensors
735
+ in_dims = (0,) + in_dims
736
+
737
+ def fn(p, *args):
738
+ t = true_fn(*args)
739
+ f = false_fn(*args)
740
+ return torch.where(p, t[0], f[0])
741
+
742
+ with interpreter.lower():
743
+ result = torch.vmap(fn, in_dims=in_dims)(*tensors)
744
+
745
+ else:
746
+ # predicate is known at this stage and it is a boolean expression or a
747
+ # tensor with one element.
748
+ true_fn = torch.vmap(true_fn, in_dims=in_dims)
749
+ false_fn = torch.vmap(false_fn, in_dims=in_dims)
750
+
751
+ with interpreter.lower():
752
+ result = cond_op(pred, true_fn, false_fn, tensors)
753
+
754
+ if not isinstance(result, tuple):
755
+ result = (result,)
756
+ lvl = interpreter.level()
757
+ return tuple(_add_batch_dim(r, 0, lvl) for r in result)
.venv/lib/python3.10/site-packages/torch/_higher_order_ops/effects.py ADDED
@@ -0,0 +1,340 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from typing import Any, Optional, Union
3
+
4
+ import torch
5
+ import torch.utils._pytree as pytree
6
+ from torch._C import DispatchKey
7
+ from torch._higher_order_ops.invoke_leaf_function import invoke_leaf_function
8
+ from torch._higher_order_ops.print import print as hop_print
9
+ from torch._higher_order_ops.schema import HopSchema
10
+ from torch._higher_order_ops.torchbind import call_torchbind
11
+ from torch._library.custom_ops import CustomOpDef
12
+ from torch._library.effects import EffectType
13
+ from torch._library.utils import RegistrationHandle
14
+ from torch._ops import HigherOrderOperator
15
+ from torch._subclasses.fake_tensor import FakeTensorMode
16
+ from torch.fx.experimental.proxy_tensor import (
17
+ disable_proxy_modes_tracing,
18
+ ProxyTorchDispatchMode,
19
+ track_tensor_tree,
20
+ )
21
+
22
+
23
+ _op_identifier = Union[
24
+ str,
25
+ "torch._ops.OpOverload",
26
+ "torch._library.custom_ops.CustomOpDef",
27
+ "torch._ops.HigherOrderOperator",
28
+ ]
29
+ OpType = Union["torch._ops.HigherOrderOperator", "torch._ops.OpOverload"]
30
+
31
+ _EffectType = EffectType
32
+
33
+
34
+ def _get_op_qualname(op: _op_identifier) -> str:
35
+ """Convert an op identifier to a qualified string key."""
36
+ if isinstance(op, torch._ops.OpOverload):
37
+ return op._name
38
+ elif isinstance(op, torch._ops.HigherOrderOperator):
39
+ return f"{op.namespace}::{op.name()}"
40
+ elif isinstance(op, CustomOpDef):
41
+ return op._qualname
42
+ elif isinstance(op, str):
43
+ return op
44
+
45
+ raise ValueError(f"Invalid operator input {op}")
46
+
47
+
48
+ def _register_effectful_op(
49
+ op: _op_identifier, effect: Optional[EffectType]
50
+ ) -> RegistrationHandle:
51
+ qualname = _get_op_qualname(op)
52
+ entry = torch._library.simple_registry.singleton.find(qualname)
53
+ handle = entry.effect.register(effect)
54
+ return handle
55
+
56
+
57
+ def _get_effect(op: _op_identifier) -> Optional[_EffectType]:
58
+ qualname = _get_op_qualname(op)
59
+ entry = torch._library.simple_registry.singleton.find(qualname)
60
+ return entry.effect.effect
61
+
62
+
63
+ _register_effectful_op("aten::_print", _EffectType.ORDERED)
64
+ _register_effectful_op("profiler::_record_function_exit._RecordFunction", None)
65
+ _register_effectful_op(call_torchbind, _EffectType.ORDERED)
66
+ _register_effectful_op(hop_print, _EffectType.ORDERED)
67
+ _register_effectful_op(invoke_leaf_function, _EffectType.ORDERED)
68
+
69
+
70
+ class WithEffects(HigherOrderOperator):
71
+ """
72
+ with_effects(token, op, args, kwargs) -> (new_token, op_results)
73
+
74
+ This HOP helps ensure ordering between side effectful ops like prints or ops
75
+ using torchbind objects. This is needed to ensure a traced graph from
76
+ AOTAutograd is functional so that future optimization passes do not reorder
77
+ these operators. This is done through threading "effect tokens" through the
78
+ graph to enforce data dependence between side effectful ops.
79
+
80
+ The tokens are basically dummy values (torch.tensor([])). We create a token
81
+ per "effect type", which are enumerated in the _EffectType enum.
82
+ """
83
+
84
+ def __init__(self) -> None:
85
+ super().__init__("with_effects")
86
+
87
+ def __call__(
88
+ self,
89
+ token,
90
+ op: OpType,
91
+ *args: tuple[Any, ...],
92
+ **kwargs: dict[str, Any],
93
+ ) -> tuple[Any, ...]:
94
+ if not isinstance(op, (torch._ops.HigherOrderOperator, torch._ops.OpOverload)):
95
+ raise AssertionError(
96
+ f"op must be HigherOrderOperator or OpOverload, got {type(op)}"
97
+ )
98
+ if has_aliasing(op):
99
+ raise AssertionError("Ops with aliasing is not supported")
100
+ if not isinstance(kwargs, dict):
101
+ raise AssertionError(f"kwargs must be a dict, got {type(kwargs)}")
102
+ # pyrefly: ignore [missing-attribute]
103
+ return super().__call__(token, op, *args, **kwargs)
104
+
105
+
106
+ with_effects = WithEffects()
107
+
108
+
109
+ def has_aliasing(op: OpType):
110
+ # NOT FOR PUBLIC USE
111
+ if isinstance(op, torch._ops.HigherOrderOperator):
112
+ return False
113
+
114
+ for arg in op._schema.arguments:
115
+ if arg.alias_info is not None:
116
+ return True
117
+ for arg in op._schema.returns:
118
+ if arg.alias_info is not None:
119
+ return True
120
+ return False
121
+
122
+
123
+ def has_effects(op) -> bool:
124
+ return (
125
+ isinstance(op, (torch._ops.HigherOrderOperator, torch._ops.OpOverload))
126
+ and not has_aliasing(op)
127
+ and _get_effect(op) is not None
128
+ )
129
+
130
+
131
+ def new_token_tensor() -> torch.Tensor:
132
+ return torch.tensor([])
133
+
134
+
135
+ @with_effects.py_impl(DispatchKey.CompositeExplicitAutograd)
136
+ def with_effects_dense(
137
+ token: torch.Tensor,
138
+ op: torch._ops.OpOverload,
139
+ *args: tuple[Any, ...],
140
+ **kwargs: dict[str, Any],
141
+ ) -> tuple[torch.Tensor, ...]:
142
+ out = op(*args, **kwargs)
143
+ new_token = new_token_tensor()
144
+ # [NOTE: with_effects return type]
145
+ # Note that we should only do *out for tuple type, but not list type.
146
+ # This is to match the schema of the op.
147
+ # For tuple output, the length of schema output is the same as the length of out.
148
+ # For list output, the length of schema output is 1 (e.g. Tensor[]) regardless of the
149
+ # length of the list.
150
+ if isinstance(out, tuple):
151
+ return (new_token, *out)
152
+ return (new_token, out)
153
+
154
+
155
+ @with_effects.py_impl(FakeTensorMode)
156
+ def with_effects_fake(
157
+ mode,
158
+ token: torch.Tensor,
159
+ op: torch._ops.OpOverload,
160
+ *args: tuple[Any, ...],
161
+ **kwargs: dict[str, Any],
162
+ ) -> tuple[torch.Tensor, ...]:
163
+ with mode:
164
+ result = with_effects_dense(token, op, *args, **kwargs)
165
+ return result
166
+
167
+
168
+ @with_effects.py_impl(ProxyTorchDispatchMode)
169
+ def with_effects_proxy(
170
+ mode,
171
+ token: torch.Tensor,
172
+ op: torch._ops.OpOverload,
173
+ *args: tuple[Any, ...],
174
+ **kwargs: dict[str, Any],
175
+ ) -> tuple[torch.Tensor, ...]:
176
+ with disable_proxy_modes_tracing():
177
+ out = with_effects(token, op, *args, **kwargs)
178
+
179
+ proxy_token = mode.tracer.unwrap_proxy(token)
180
+ proxy_args = pytree.tree_map(mode.tracer.unwrap_proxy, args)
181
+ proxy_kwargs = pytree.tree_map(mode.tracer.unwrap_proxy, kwargs)
182
+
183
+ from torch.fx.node import has_side_effect
184
+
185
+ # To avoid the being DCEed by graph.eliminate_dead_code if they.
186
+ # don't have output or their outputs are not used.
187
+ has_side_effect(op)
188
+
189
+ out_proxy = mode.tracer.create_proxy(
190
+ "call_function",
191
+ with_effects,
192
+ (proxy_token, op, *proxy_args),
193
+ proxy_kwargs,
194
+ )
195
+ result = track_tensor_tree(out, out_proxy, constant=None, tracer=mode.tracer)
196
+ return result
197
+
198
+
199
+ with_effects.fallthrough(DispatchKey.AutogradCPU)
200
+ with_effects.fallthrough(DispatchKey.AutogradCUDA)
201
+
202
+
203
+ @with_effects.py_functionalize_impl
204
+ def with_effects_functional(
205
+ ctx,
206
+ token: torch.Tensor,
207
+ op: torch._ops.OpOverload,
208
+ *args: tuple[Any, ...],
209
+ **kwargs: dict[str, Any],
210
+ ) -> tuple[torch.Tensor, ...]:
211
+ # with_effects is already functional, so just re-emit it.
212
+ unwrapped_token, unwrapped_args, unwrapped_kwargs = ctx.unwrap_tensors(
213
+ [token, args, kwargs]
214
+ )
215
+ with ctx.redispatch_to_next():
216
+ result = with_effects(unwrapped_token, op, *unwrapped_args, **unwrapped_kwargs)
217
+ return ctx.wrap_tensors(result)
218
+
219
+
220
+ _EFFECTFUL_HOPS_WITH_SCHEMA = {hop_print, invoke_leaf_function}
221
+
222
+
223
+ def _get_schema(op, args, kwargs: Optional[dict] = None) -> torch.FunctionSchema:
224
+ if isinstance(op, torch._ops.OpOverload):
225
+ return op._schema
226
+ elif op == call_torchbind:
227
+ return getattr(args[0], args[1]).schema
228
+ elif op in _EFFECTFUL_HOPS_WITH_SCHEMA:
229
+ extra_kwargs = kwargs or {}
230
+ return op.gen_schema(*args, **extra_kwargs)
231
+ else:
232
+ raise RuntimeError(f"Unable to get schema for op {op}")
233
+
234
+
235
+ def handle_effects(
236
+ allow_token_discovery: bool,
237
+ tokens: dict[_EffectType, torch.Tensor],
238
+ op: OpType,
239
+ args: tuple[Any, ...],
240
+ kwargs: dict[str, Any],
241
+ ) -> Any:
242
+ """
243
+ Args:
244
+ allow_token_discovery: Whether or not we are discovering tokens. If this
245
+ is true, we will create a token for every side effect type seen that
246
+ does not have a token assigned yet. If this is false, the tokens
247
+ should've all been created ahead of time, so we will error if there is
248
+ no token mapping to every effect type.
249
+
250
+ tokens: Map of effect type to tokens. This is to chain operators of the
251
+ same effects together so that they do not get reordered in later
252
+ optimization passes.
253
+ """
254
+
255
+ # Get a token. We can't do `tokens.get(op, torch.tensor([]))` because
256
+ # this will create an empty tensor during proxy mode tracing if the token
257
+ # doesn't exist. But the tokens should always exist during proxy mode tracing.
258
+ key = _get_effect(op)
259
+ if key is None:
260
+ raise AssertionError(f"effect key must not be None for op {op}")
261
+ if key not in tokens:
262
+ if not allow_token_discovery:
263
+ raise AssertionError(
264
+ f"Could not find a token for effect {key} which came from the function {op}"
265
+ )
266
+ proxy_tensor_mode = torch._C._get_dispatch_mode(
267
+ torch._C._TorchDispatchModeKey.PROXY
268
+ )
269
+ if proxy_tensor_mode is not None:
270
+ # If we discovered a new token during tracing, we are in backward.
271
+ # Then we patch the graph, adding additional tangents_token as input to the joint graph.
272
+ tracer = proxy_tensor_mode.tracer
273
+
274
+ from torch.fx.experimental.proxy_tensor import (
275
+ disable_proxy_modes_tracing,
276
+ track_tensor_tree,
277
+ )
278
+
279
+ with disable_proxy_modes_tracing():
280
+ token_tensor = new_token_tensor()
281
+
282
+ token_proxy = proxy_tensor_mode.tracer.create_proxy(
283
+ "placeholder", "tangents_token", (), {}, name="tangents_token"
284
+ )
285
+ track_tensor_tree(token_tensor, token_proxy, constant=None, tracer=tracer)
286
+
287
+ tokens[key] = token_tensor
288
+ else:
289
+ tokens[key] = new_token_tensor()
290
+
291
+ token = tokens[key]
292
+
293
+ from torch._subclasses.functional_tensor import PythonFunctionalizeAPI
294
+
295
+ ctx = PythonFunctionalizeAPI()
296
+
297
+ unwrapped_token = ctx.unwrap_tensors([token])[0]
298
+ unwrapped_args = ctx.unwrap_tensors(args)
299
+ unwrapped_kwargs = ctx.unwrap_tensors(kwargs) # type: ignore[arg-type]
300
+ with ctx.redispatch_to_next():
301
+ (new_token, *unwrapped_outs) = with_effects(
302
+ unwrapped_token, op, *unwrapped_args, **unwrapped_kwargs
303
+ )
304
+
305
+ schema = _get_schema(op, unwrapped_args, unwrapped_kwargs)
306
+
307
+ if isinstance(schema, HopSchema):
308
+ if len(schema.returns) == 0:
309
+ unwrapped_outs = ()
310
+ else:
311
+ if len(unwrapped_outs) != len(schema.returns):
312
+ raise AssertionError(
313
+ f"expected {len(schema.returns)} outputs but got {len(unwrapped_outs)}"
314
+ )
315
+ unwrapped_outs = tuple(unwrapped_outs)
316
+ elif len(schema.returns) == 0:
317
+ if unwrapped_outs[0] is not None:
318
+ raise AssertionError(f"expected no outputs but got {unwrapped_outs[0]}")
319
+ unwrapped_outs = None # type: ignore[assignment]
320
+ elif len(schema.returns) == 1:
321
+ if len(unwrapped_outs) != 1:
322
+ raise AssertionError(f"expected 1 output but got {len(unwrapped_outs)}")
323
+ unwrapped_outs = unwrapped_outs[0]
324
+ else:
325
+ if len(unwrapped_outs) != len(schema.returns):
326
+ raise AssertionError(
327
+ f"expected {len(schema.returns)} outputs but got {len(unwrapped_outs)}"
328
+ )
329
+
330
+ # Add the newly created token into the tokens map for a following call to
331
+ # use this token.
332
+ wrapped_token = ctx.wrap_tensors(new_token)
333
+ if not isinstance(wrapped_token, torch.Tensor):
334
+ raise AssertionError(
335
+ f"expected wrapped_token to be torch.Tensor, got {type(wrapped_token)}"
336
+ )
337
+ tokens[key] = wrapped_token
338
+
339
+ # pyrefly: ignore [bad-argument-type]
340
+ return ctx.wrap_tensors(unwrapped_outs)
.venv/lib/python3.10/site-packages/torch/_higher_order_ops/executorch_call_delegate.py ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+
3
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
4
+ # All rights reserved.
5
+ #
6
+ # This source code is licensed under the BSD-style license found in the
7
+ # LICENSE file in the root directory of this source tree.
8
+
9
+ # pyre-strict
10
+
11
+ from __future__ import annotations
12
+
13
+ from typing import Any, cast
14
+
15
+ import torch
16
+ import torch.utils._pytree as pytree
17
+ from torch._ops import HigherOrderOperator
18
+ from torch._subclasses.fake_tensor import FakeTensorMode
19
+ from torch.fx.experimental.proxy_tensor import (
20
+ disable_proxy_modes_tracing,
21
+ get_proxy_slot,
22
+ ProxyTorchDispatchMode,
23
+ track_tensor_tree,
24
+ )
25
+ from torch.utils._pytree import tree_flatten
26
+
27
+
28
+ class ExecutorchCallDelegate(HigherOrderOperator):
29
+ def __init__(self):
30
+ super().__init__("executorch_call_delegate")
31
+
32
+ def __call__(self, lowered_module, *args):
33
+ # pyrefly: ignore [missing-attribute]
34
+ return super().__call__(lowered_module, *args)
35
+
36
+
37
+ executorch_call_delegate = ExecutorchCallDelegate()
38
+ executorch_call_delegate.fallthrough(torch._C.DispatchKey.PythonDispatcher)
39
+ executorch_call_delegate.fallthrough(torch._C.DispatchKey.PythonTLSSnapshot)
40
+ executorch_call_delegate.fallthrough(torch._C.DispatchKey.ADInplaceOrView)
41
+ executorch_call_delegate.fallthrough(torch._C.DispatchKey.AutocastCPU)
42
+
43
+ LOWERED_BACKEND_MODULE_TYPE = "LoweredBackendModule"
44
+
45
+
46
+ # pyre-ignore
47
+ def trace_call_delegate(proxy_mode, func_overload, lowered_module, *args):
48
+ # pyre-ignore
49
+ def _unwrap_proxy(e):
50
+ if not isinstance(e, (torch.Tensor, torch.SymInt, torch.SymFloat)):
51
+ return e
52
+ return get_proxy_slot(
53
+ cast(torch.Tensor, e),
54
+ proxy_mode.tracer,
55
+ e,
56
+ lambda e: e.proxy, # type: ignore[attr-defined]
57
+ )
58
+
59
+ if not is_lowered_module(lowered_module):
60
+ raise ValueError(
61
+ "executorch_call_delegate()'s first argument must be a LoweredBackendModule"
62
+ )
63
+
64
+ with disable_proxy_modes_tracing():
65
+ out = call_delegate_cpu(lowered_module, *args)
66
+
67
+ get_lowered_module_name(proxy_mode.tracer.root, lowered_module)
68
+
69
+ node_args = (lowered_module, *args)
70
+ proxy_args = pytree.tree_map(_unwrap_proxy, node_args)
71
+ out_proxy = proxy_mode.tracer.create_proxy(
72
+ "call_function", func_overload, proxy_args, {}, name="executorch_call_delegate"
73
+ )
74
+ return track_tensor_tree(out, out_proxy, constant=None, tracer=proxy_mode.tracer)
75
+
76
+
77
+ @executorch_call_delegate.py_impl(torch._C.DispatchKey.CompositeExplicitAutograd)
78
+ # pyre-ignore
79
+ def call_delegate_cpu(lowered_module, *args):
80
+ # FX creates this immutable_dict/list concept. Get rid of this.
81
+ map_types: dict[type, type] = {
82
+ torch.fx.immutable_collections.immutable_dict: dict,
83
+ torch.fx.immutable_collections.immutable_list: list,
84
+ }
85
+ new_args = pytree.tree_map_only(
86
+ tuple(map_types.keys()),
87
+ lambda a: map_types[type(a)](a),
88
+ args,
89
+ lambda a: isinstance(a, tuple(map_types.keys())),
90
+ )
91
+ return lowered_module.original_module.module()(*new_args)
92
+
93
+
94
+ @executorch_call_delegate.py_autograd_impl
95
+ # pyre-ignore
96
+ def call_delegate_autograd(lowered_module, *args):
97
+ # TODO: support autograd
98
+ flat_operands, _ = tree_flatten([lowered_module, *args])
99
+ requires_grad = any(
100
+ f.requires_grad for f in flat_operands if isinstance(f, torch.Tensor)
101
+ )
102
+
103
+ with torch._C._ExcludeDispatchKeyGuard(
104
+ torch._C.DispatchKeySet(torch._C.DispatchKey.AutogradCPU)
105
+ ):
106
+ res = executorch_call_delegate(lowered_module, *args)
107
+
108
+ if requires_grad:
109
+ # Create aliases of the output that has requires_grad=True. We need
110
+ # at least one of the inputs to err_fn to require grad so that the
111
+ # output will have a grad_fn.
112
+
113
+ # pyre-ignore
114
+ def fake_requires_grad(var):
115
+ if var is not None:
116
+ var = var.detach()
117
+ if torch.is_floating_point(var) or torch.is_complex(var):
118
+ var.requires_grad = True
119
+ return var
120
+
121
+ return pytree.tree_map_only(torch.Tensor, fake_requires_grad, res)
122
+
123
+ return res
124
+
125
+
126
+ @executorch_call_delegate.py_impl(ProxyTorchDispatchMode)
127
+ # pyre-ignore
128
+ def call_delegate_proxy_torch_dispatch_mode(mode, lowered_module, *args):
129
+ res = trace_call_delegate(mode, executorch_call_delegate, lowered_module, *args)
130
+ return res
131
+
132
+
133
+ @executorch_call_delegate.py_impl(FakeTensorMode)
134
+ # pyre-ignore
135
+ def call_delegate_fake_tensor_mode(mode, lowered_module, *args):
136
+ with mode:
137
+ return call_delegate_cpu(lowered_module, *args)
138
+
139
+
140
+ @executorch_call_delegate.py_functionalize_impl
141
+ # pyre-ignore
142
+ def call_delegate_functionalize(ctx, lowered_module, *args):
143
+ unwrapped_args = tuple(ctx.unwrap_tensors(arg) for arg in args)
144
+ with ctx.redispatch_to_next():
145
+ res = executorch_call_delegate(lowered_module, *unwrapped_args)
146
+ return ctx.wrap_tensors(res)
147
+
148
+
149
+ # pyre-ignore: Missing parameter annotation [2]: Parameter `obj` must have a type other than `Any`.Pyre
150
+ def is_lowered_module(obj: Any) -> bool:
151
+ """
152
+ This function is added to avoid using isinstance(obj,
153
+ LoweredBackendModule) as it will import LoweredBackendModule, which may
154
+ cause a circular import.
155
+ """
156
+ return type(obj).__name__ == LOWERED_BACKEND_MODULE_TYPE
157
+
158
+
159
+ def get_lowered_module_name(
160
+ root: torch.nn.Module,
161
+ # pyre-ignore: Undefined or invalid type [11]: Annotation `LoweredBackendModule` is not defined as a type.
162
+ lowered_module: LOWERED_BACKEND_MODULE_TYPE, # type: ignore[valid-type]
163
+ ) -> str:
164
+ """
165
+ Adds the given lowered_module into the given root module and returns the
166
+ name of the module added.
167
+ """
168
+ # Find a qualifying name for the lowered submodule
169
+ qualname = None
170
+ i = 0
171
+ while True:
172
+ qualname = f"lowered_module_{i}"
173
+ if not hasattr(root, qualname):
174
+ break
175
+ i += 1
176
+ if qualname is None:
177
+ raise AssertionError(
178
+ "qualname must not be None after finding unused module slot"
179
+ )
180
+
181
+ root.add_module(qualname, lowered_module)
182
+ return qualname
.venv/lib/python3.10/site-packages/torch/_higher_order_ops/flat_apply.py ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import typing
2
+ from collections.abc import Callable, Sequence
3
+ from dataclasses import dataclass
4
+ from typing import Generic, overload, TypeAlias, TypeVar
5
+ from typing_extensions import ParamSpec, TypeIs, TypeVarTuple, Unpack
6
+
7
+ import torch
8
+ import torch.fx.node
9
+ import torch.utils._pytree as pytree
10
+ from torch._library.fake_class_registry import FakeScriptObject
11
+ from torch._library.opaque_object import is_opaque_type
12
+ from torch._ops import HigherOrderOperator
13
+
14
+
15
+ _R = TypeVar("_R")
16
+ _P = ParamSpec("_P")
17
+ _Ts = TypeVarTuple("_Ts")
18
+
19
+
20
+ def is_graphable(val: object) -> TypeIs[torch.fx.node.BaseArgumentTypes]:
21
+ """Definition: a graphable type is a type that is an acceptable input/output type to a FX node."""
22
+ return isinstance(
23
+ val, (*torch.fx.node.base_types, FakeScriptObject)
24
+ ) or is_opaque_type(type(val))
25
+
26
+
27
+ def is_graphable_type(typ: type[object]) -> bool:
28
+ """Return whether the given type is graphable."""
29
+ return (
30
+ issubclass(typ, torch.fx.node.base_types)
31
+ or is_opaque_type(typ)
32
+ or issubclass(typ, FakeScriptObject)
33
+ )
34
+
35
+
36
+ def to_graphable(stuff: pytree.PyTree) -> tuple[list[object], pytree.TreeSpec]:
37
+ """Flattens stuff into a flat list of graphable types."""
38
+ # We can consider preserving things like List[int] to improve
39
+ # perf and readability (right now that is all flattened out)
40
+ flat_args, spec = pytree.tree_flatten(stuff)
41
+ for arg in flat_args:
42
+ if not is_graphable(arg):
43
+ raise RuntimeError(
44
+ f"Expected all pytree.tree_leaves of (args, kwargs) to be graphable types, but found "
45
+ f"non-fx-graphable type {type(arg)}. If this type is meant to be constant, mark it as "
46
+ f"via pytree.register_constant; otherwise, register it as a pytree."
47
+ )
48
+ return flat_args, spec
49
+
50
+
51
+ def from_graphable(
52
+ flat_args: tuple[Unpack[_Ts]], spec: pytree.TreeSpec
53
+ ) -> pytree.PyTree:
54
+ """The inverse of to_graphable."""
55
+ stuff = pytree.tree_unflatten(flat_args, spec)
56
+ return stuff
57
+
58
+
59
+ def func_to_graphable(
60
+ func: Callable[..., object],
61
+ ) -> tuple[list[object], pytree.TreeSpec]:
62
+ """
63
+ Pack and flatten a function type into graphable types.
64
+ This is useful for legalizing the function argument of `flat_apply`.
65
+ """
66
+ return pytree.tree_flatten(_ConstantFunction(func))
67
+
68
+
69
+ @dataclass(frozen=True, slots=True)
70
+ class _ConstantFunction(Generic[_P, _R]):
71
+ func: Callable[_P, _R]
72
+
73
+ def __call__(self, *args: _P.args, **kwargs: _P.kwargs) -> _R:
74
+ return self.func(*args, **kwargs)
75
+
76
+
77
+ pytree.register_constant(_ConstantFunction)
78
+
79
+
80
+ _OpTypes = (
81
+ torch._ops.OpOverload | torch._ops.OpOverloadPacket | torch._ops.HigherOrderOperator
82
+ )
83
+ _op_types = typing.get_args(_OpTypes)
84
+
85
+
86
+ _Base: TypeAlias = torch.fx.node.BaseArgumentTypes
87
+ # pyrefly bug: pyrefly is complaining: Expected a type form, got instance of `Literal['_FXOutput']
88
+ # pyrefly: ignore[not-a-type]
89
+ _FXOutput = _Base | Sequence["_FXOutput"]
90
+
91
+
92
+ class FlatApply(HigherOrderOperator):
93
+ def __init__(self) -> None:
94
+ super().__init__("flat_apply")
95
+
96
+ def __call__(
97
+ self,
98
+ func: _OpTypes | pytree.TreeSpec,
99
+ in_spec: pytree.TreeSpec,
100
+ *flat_args: Unpack[_Ts],
101
+ # If True then the output is checked to be valid. If False then it is up
102
+ # to the caller to ensure the output is appropriate.
103
+ checked_output: bool = True,
104
+ **_unused: object,
105
+ ) -> object:
106
+ """
107
+ Functions that take in non-graphable types cannot directly be put into FX graph.
108
+
109
+ Given func(*args, **kwargs), if all of the non-graphable types are pytrees,
110
+ then we're able to store a call to flat_apply(func, in_spec, *flat_args) in the FX graph.
111
+
112
+ The semantics of flat_apply(func, in_spec, *flat_args) are roughly equivalent to:
113
+
114
+ >>> def flat_apply_impl(func, in_spec, *flat_args):
115
+ >>> args, kwargs = pytree.tree_unflatten(flat_args, in_spec)
116
+ >>> output = func(*args, **kwargs)
117
+ >>> return output
118
+
119
+ flat_apply supports the following two cases:
120
+ - an input type is a container type (e.g. of tensors) registered as a pytree.
121
+ We'll tree_flatten the input type and store the spec.
122
+ - an input type is a constant type (i.e. torch.compile will specialize on it)
123
+ registered with pytree.register_constant. The constant type goes directly
124
+ into the spec.
125
+ """
126
+ if not (isinstance(func, _op_types) or pytree._is_constant_holder(func)):
127
+ raise AssertionError(
128
+ f"func must be an op type or constant holder, got {type(func)}"
129
+ )
130
+ if len(_unused) != 0:
131
+ raise AssertionError(f"unexpected keyword arguments: {_unused}")
132
+ # pyrefly: ignore[bad-argument-type] # pyrefly bug?
133
+ return impl(func, in_spec, flat_args, checked_output)
134
+
135
+
136
+ @overload
137
+ def is_valid_output(x: tuple[object, ...]) -> TypeIs[tuple[_FXOutput, ...]]: ...
138
+
139
+
140
+ @overload
141
+ def is_valid_output(x: Sequence[object]) -> TypeIs[Sequence[_FXOutput]]: ...
142
+
143
+
144
+ def is_valid_output(x: object) -> bool:
145
+ if isinstance(x, (tuple, list)):
146
+ return all(map(is_valid_output, x))
147
+ return is_graphable(x)
148
+
149
+
150
+ def impl(
151
+ func: _OpTypes | pytree.TreeSpec,
152
+ in_spec: pytree.TreeSpec,
153
+ flat_args: tuple[Unpack[_Ts]],
154
+ checked_output: bool,
155
+ ) -> _FXOutput:
156
+ if isinstance(func, pytree.TreeSpec):
157
+ # assume _ConstantFunction
158
+ func = pytree._retrieve_constant(func)
159
+ if not isinstance(func, _ConstantFunction):
160
+ raise AssertionError(
161
+ f"expected retrieved constant to be _ConstantFunction, got {type(func)}"
162
+ )
163
+
164
+ # pyrefly: ignore[bad-argument-type] # pyrefly bug?
165
+ args, kwargs = from_graphable(flat_args, in_spec)
166
+ out = func(*args, **kwargs)
167
+
168
+ if checked_output:
169
+ # For "normal" usage all outputs must either be graphable or
170
+ # lists/tuples of graphables.
171
+ if not is_valid_output(out):
172
+ raise AssertionError(
173
+ f"output must be graphable or nested list/tuple of graphables, got {type(out)}"
174
+ )
175
+ return out
176
+
177
+
178
+ flat_apply = FlatApply()
.venv/lib/python3.10/site-packages/torch/_higher_order_ops/flex_attention.py ADDED
@@ -0,0 +1,1461 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from collections.abc import Callable, Sequence
3
+ from typing import Any, Optional, Union
4
+
5
+ import torch
6
+ import torch.utils._pytree as pytree
7
+ from torch import Tensor
8
+ from torch._C import DispatchKey
9
+ from torch._higher_order_ops.utils import (
10
+ _has_potential_branch_input_mutation,
11
+ _maybe_reenter_make_fx,
12
+ autograd_not_implemented,
13
+ has_user_subclass,
14
+ redirect_to_mode,
15
+ reenter_make_fx,
16
+ register_fake,
17
+ save_values_for_backward,
18
+ saved_values,
19
+ UnsupportedAliasMutationException,
20
+ validate_subgraph_args_types,
21
+ )
22
+ from torch._ops import HigherOrderOperator
23
+ from torch._subclasses import FakeTensor
24
+ from torch.amp.autocast_mode import _cast as _autocast_cast
25
+ from torch.fx.experimental.proxy_tensor import (
26
+ make_fx,
27
+ ProxyTorchDispatchMode,
28
+ track_tensor_tree,
29
+ )
30
+ from torch.fx.graph_module import GraphModule
31
+ from torch.utils.checkpoint import _CachedTorchDispatchMode, _CachingTorchDispatchMode
32
+
33
+
34
+ # Duplicate of _inductor/kernel/flex_attention.py to avoid circular import
35
+ def _construct_strides(
36
+ sizes: Sequence[int],
37
+ fill_order: Sequence[int],
38
+ ) -> Sequence[int]:
39
+ """From a list of sizes and a fill order, construct the strides of the permuted tensor."""
40
+ # Initialize strides
41
+ if len(sizes) != len(fill_order):
42
+ raise AssertionError(
43
+ f"Length of sizes must match the length of the fill order, got {len(sizes)} vs {len(fill_order)}"
44
+ )
45
+ strides = [0] * len(sizes)
46
+
47
+ # Start with stride 1 for the innermost dimension
48
+ current_stride = 1
49
+
50
+ # Iterate through the fill order populating strides
51
+ for dim in fill_order:
52
+ strides[dim] = current_stride
53
+ current_stride *= sizes[dim]
54
+
55
+ return strides
56
+
57
+
58
+ def _permute_strides(out: torch.Tensor, query_strides: tuple[int, ...]) -> torch.Tensor:
59
+ """
60
+ Create a new tensor with the same data and shape as the input,
61
+ but with strides permuted based on the input tensor's stride order.
62
+
63
+ Args:
64
+ out (torch.Tensor): The output tensor of attention.
65
+ query_strides (List[int]): The stride order of the input query tensor
66
+
67
+ Returns:
68
+ torch.Tensor: A new tensor with same shape and data as the input,
69
+ but with strides permuted based on the query tensor's stride order.
70
+ """
71
+ from torch._inductor.ir import get_fill_order
72
+
73
+ fill_order = get_fill_order(query_strides)
74
+ if out.storage_offset() != 0:
75
+ raise AssertionError(
76
+ f"Only support storage_offset == 0, got {out.storage_offset()}"
77
+ )
78
+ out_strides = _construct_strides(out.shape, fill_order)
79
+
80
+ # Attention kernels require stride[-1]=1 for efficient memory access.
81
+ # Ensure this by moving last dim to front of fill_order if needed.
82
+ if out_strides[-1] != 1:
83
+ last_dim = len(out.shape) - 1
84
+ fill_order = list(fill_order)
85
+ fill_order.remove(last_dim)
86
+ fill_order = [last_dim] + fill_order
87
+ out_strides = _construct_strides(out.shape, fill_order)
88
+
89
+ new_out = out.new_empty(out.shape).as_strided(out.shape, out_strides)
90
+ new_out.copy_(out)
91
+ return new_out
92
+
93
+
94
+ class FlexAttentionHOP(HigherOrderOperator):
95
+ def __init__(self) -> None:
96
+ super().__init__("flex_attention", cacheable=True)
97
+
98
+ def __call__(
99
+ self,
100
+ query: torch.Tensor,
101
+ key: torch.Tensor,
102
+ value: torch.Tensor,
103
+ score_mod: Callable,
104
+ block_mask: tuple,
105
+ scale: float,
106
+ kernel_options: dict[str, Any],
107
+ score_mod_other_buffers: tuple = (),
108
+ mask_mod_other_buffers: tuple = (),
109
+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
110
+ validate_subgraph_args_types(score_mod_other_buffers + mask_mod_other_buffers)
111
+ # pyrefly: ignore [missing-attribute]
112
+ return super().__call__(
113
+ query,
114
+ key,
115
+ value,
116
+ score_mod,
117
+ block_mask,
118
+ scale,
119
+ kernel_options,
120
+ score_mod_other_buffers,
121
+ mask_mod_other_buffers,
122
+ )
123
+
124
+
125
+ flex_attention = FlexAttentionHOP()
126
+
127
+
128
+ class FlexAttentionBackwardHOP(HigherOrderOperator):
129
+ def __init__(self) -> None:
130
+ super().__init__("flex_attention_backward", cacheable=True)
131
+
132
+ def __call__(
133
+ self,
134
+ query: torch.Tensor,
135
+ key: torch.Tensor,
136
+ value: torch.Tensor,
137
+ out: torch.Tensor,
138
+ logsumexp: torch.Tensor,
139
+ grad_out: torch.Tensor | None,
140
+ grad_logsumexp: torch.Tensor | None,
141
+ fw_graph: Union[Callable, GraphModule],
142
+ joint_graph: GraphModule,
143
+ block_mask: tuple,
144
+ scale: float,
145
+ kernel_options: dict[str, Any],
146
+ score_mod_other_buffers: tuple = (),
147
+ mask_mod_other_buffers: tuple = (),
148
+ ) -> tuple[
149
+ torch.Tensor, torch.Tensor, torch.Tensor, tuple[Optional[torch.Tensor], ...]
150
+ ]:
151
+ validate_subgraph_args_types(score_mod_other_buffers + mask_mod_other_buffers)
152
+
153
+ # pyrefly: ignore [missing-attribute]
154
+ return super().__call__(
155
+ query,
156
+ key,
157
+ value,
158
+ out,
159
+ logsumexp,
160
+ grad_out,
161
+ grad_logsumexp,
162
+ fw_graph,
163
+ joint_graph,
164
+ block_mask,
165
+ scale,
166
+ kernel_options,
167
+ score_mod_other_buffers,
168
+ mask_mod_other_buffers,
169
+ )
170
+
171
+
172
+ flex_attention_backward = FlexAttentionBackwardHOP()
173
+
174
+
175
+ def _math_attention_inner(
176
+ query: torch.Tensor,
177
+ key: torch.Tensor,
178
+ value: torch.Tensor,
179
+ score_mod: Callable,
180
+ block_mask: tuple,
181
+ scale: float,
182
+ kernel_options: dict[str, Any],
183
+ score_mod_other_buffers: tuple = (),
184
+ mask_mod_other_buffers: tuple = (),
185
+ ) -> tuple[torch.Tensor, torch.Tensor]:
186
+ from torch._dynamo._trace_wrapped_higher_order_op import TransformGetItemToIndex
187
+
188
+ working_precision = torch.float64 if query.dtype == torch.float64 else torch.float32
189
+
190
+ scores = query.to(working_precision) @ key.to(working_precision).transpose(-2, -1)
191
+
192
+ b = torch.arange(0, scores.size(0), device=scores.device)
193
+ h = torch.arange(0, scores.size(1), device=scores.device)
194
+ m = torch.arange(0, scores.size(2), device=scores.device)
195
+ n = torch.arange(0, scores.size(3), device=scores.device)
196
+
197
+ captured_buffers_in_dim = (None,) * len(score_mod_other_buffers)
198
+ from torch.nn.attention.flex_attention import _vmap_for_bhqkv
199
+
200
+ # first input is score
201
+ score_mod = _vmap_for_bhqkv(score_mod, prefix=(0,), suffix=captured_buffers_in_dim)
202
+
203
+ mask_mod = block_mask[-1]
204
+ mask_mod_in_dim_buffers = (None,) * len(mask_mod_other_buffers)
205
+ mask_mod = _vmap_for_bhqkv(mask_mod, prefix=(), suffix=mask_mod_in_dim_buffers)
206
+
207
+ with TransformGetItemToIndex():
208
+ scores = (scores * scale).to(working_precision)
209
+ post_mod_scores = torch.where(
210
+ mask_mod(b, h, m, n, *mask_mod_other_buffers),
211
+ score_mod(scores, b, h, m, n, *score_mod_other_buffers),
212
+ torch.tensor(-float("inf"), dtype=working_precision, device=scores.device),
213
+ )
214
+
215
+ return scores, post_mod_scores
216
+
217
+
218
+ def math_attention(
219
+ query: torch.Tensor,
220
+ key: torch.Tensor,
221
+ value: torch.Tensor,
222
+ score_mod: Callable,
223
+ block_mask: tuple,
224
+ scale: float,
225
+ kernel_options: dict[str, Any],
226
+ score_mod_other_buffers: tuple = (),
227
+ mask_mod_other_buffers: tuple = (),
228
+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
229
+ """Eager implementation
230
+
231
+ This implementation uses vmap to vectorize the score_mod function over the batch, head, m, and n dimensions.
232
+ We then apply the vectorized score_mod function to the scores matrix. Each wrap of vmap applies one of the
233
+ batch, head, m, or n dimensions. We need to apply vmap 4 times to vectorized over all 4 dimensions.
234
+
235
+ Args:
236
+ query: The query tensor
237
+ key: The key tensor
238
+ value: The value tensor
239
+ score_mod: The score_mod function
240
+ other_buffers: Other buffers that are passed to the score_mod function
241
+
242
+ Notes:
243
+ Query and Keys are dtype cast up to float64 (if query.dtype is float64) and float32 otherwise.
244
+ Scores and Values are dtype cast to input query.dtype at the end.
245
+ """
246
+ # broadcast query & key along head dim for GQA
247
+ G = query.size(1) // key.size(1)
248
+ value = torch.repeat_interleave(value, G, dim=1)
249
+ key = torch.repeat_interleave(key, G, dim=1)
250
+
251
+ Bq, Bkv = query.size(0), key.size(0)
252
+ if not ((Bq == Bkv) or (Bq > 1 and Bkv == 1)):
253
+ raise RuntimeError(f"Bq and Bkv must broadcast. Got Bq={Bq} and Bkv={Bkv}")
254
+
255
+ key = key.expand((Bq, *key.size()[1:]))
256
+ value = value.expand((Bq, *value.size()[1:]))
257
+
258
+ _, post_mod_scores = _math_attention_inner(
259
+ query,
260
+ key,
261
+ value,
262
+ score_mod,
263
+ block_mask,
264
+ scale,
265
+ kernel_options,
266
+ score_mod_other_buffers,
267
+ mask_mod_other_buffers,
268
+ )
269
+
270
+ # Set fully masked rows' sumexp to 0.0
271
+ logsumexp = post_mod_scores.logsumexp(dim=-1)
272
+ masked_rows = torch.all(post_mod_scores == -float("inf"), dim=-1)
273
+ logsumexp = torch.where(masked_rows, -float("inf"), logsumexp)
274
+
275
+ # working precision will be used so no need to cast to fp32
276
+ max_scores = torch.max(post_mod_scores, dim=-1)[0]
277
+
278
+ post_mod_scores = torch._safe_softmax(post_mod_scores, dim=-1)
279
+
280
+ # NB: kernel computes in ln2 space, we always convert back at the top level op, so
281
+ # for math impl we divide by log(2) because we will multiply by log(2)
282
+
283
+ return (
284
+ post_mod_scores.to(query.dtype) @ value.to(query.dtype),
285
+ logsumexp / math.log(2),
286
+ max_scores / math.log(2),
287
+ )
288
+
289
+
290
+ def _flex_attention_autocast_impl(
291
+ query: torch.Tensor,
292
+ key: torch.Tensor,
293
+ value: torch.Tensor,
294
+ score_mod: Callable,
295
+ block_mask: tuple,
296
+ scale: float,
297
+ kernel_options: dict[str, Any],
298
+ score_mod_other_buffers: tuple,
299
+ mask_mod_other_buffers: tuple,
300
+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
301
+ """
302
+ Forward-only autocast shim: cast Q/K/V to the active autocast dtype, then
303
+ redispatch with Autocast keys excluded so we hit the normal implementation.
304
+ """
305
+ device_type = query.device.type
306
+ autocast_dtype = torch.get_autocast_dtype(device_type)
307
+
308
+ query = _autocast_cast(query, device_type, autocast_dtype)
309
+ key = _autocast_cast(key, device_type, autocast_dtype)
310
+ value = _autocast_cast(value, device_type, autocast_dtype)
311
+
312
+ autocast_keyset = torch._C.DispatchKeySet(
313
+ DispatchKey.AutocastCPU
314
+ ) | torch._C.DispatchKeySet(DispatchKey.AutocastCUDA)
315
+ with torch._C._ExcludeDispatchKeyGuard(autocast_keyset):
316
+ return flex_attention(
317
+ query,
318
+ key,
319
+ value,
320
+ score_mod,
321
+ block_mask,
322
+ scale,
323
+ kernel_options,
324
+ score_mod_other_buffers,
325
+ mask_mod_other_buffers,
326
+ )
327
+
328
+
329
+ @flex_attention.py_impl(DispatchKey.AutocastCUDA)
330
+ def flex_attention_autocast_cuda(
331
+ query: torch.Tensor,
332
+ key: torch.Tensor,
333
+ value: torch.Tensor,
334
+ score_mod: Callable,
335
+ block_mask: tuple,
336
+ scale: float,
337
+ kernel_options: dict[str, Any],
338
+ score_mod_other_buffers: tuple = (),
339
+ mask_mod_other_buffers: tuple = (),
340
+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
341
+ return _flex_attention_autocast_impl(
342
+ query,
343
+ key,
344
+ value,
345
+ score_mod,
346
+ block_mask,
347
+ scale,
348
+ kernel_options,
349
+ score_mod_other_buffers,
350
+ mask_mod_other_buffers,
351
+ )
352
+
353
+
354
+ @flex_attention.py_impl(DispatchKey.AutocastCPU)
355
+ def flex_attention_autocast_cpu(
356
+ query: torch.Tensor,
357
+ key: torch.Tensor,
358
+ value: torch.Tensor,
359
+ score_mod: Callable,
360
+ block_mask: tuple,
361
+ scale: float,
362
+ kernel_options: dict[str, Any],
363
+ score_mod_other_buffers: tuple = (),
364
+ mask_mod_other_buffers: tuple = (),
365
+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
366
+ return _flex_attention_autocast_impl(
367
+ query,
368
+ key,
369
+ value,
370
+ score_mod,
371
+ block_mask,
372
+ scale,
373
+ kernel_options,
374
+ score_mod_other_buffers,
375
+ mask_mod_other_buffers,
376
+ )
377
+
378
+
379
+ @flex_attention.py_impl(DispatchKey.CompositeExplicitAutograd)
380
+ def sdpa_dense(
381
+ query: torch.Tensor,
382
+ key: torch.Tensor,
383
+ value: torch.Tensor,
384
+ score_mod: Callable,
385
+ block_mask: tuple,
386
+ scale: float,
387
+ kernel_options: dict[str, Any],
388
+ score_mod_other_buffers: tuple = (),
389
+ mask_mod_other_buffers: tuple = (),
390
+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
391
+ out, lse, max_scores = math_attention(
392
+ query,
393
+ key,
394
+ value,
395
+ score_mod,
396
+ block_mask,
397
+ scale,
398
+ kernel_options,
399
+ score_mod_other_buffers,
400
+ mask_mod_other_buffers,
401
+ )
402
+ out = _permute_strides(out, query.stride())
403
+ return out, lse, max_scores
404
+
405
+
406
+ def trace_flex_attention(
407
+ proxy_mode: ProxyTorchDispatchMode,
408
+ query: torch.Tensor,
409
+ key: torch.Tensor,
410
+ value: torch.Tensor,
411
+ score_mod: Callable,
412
+ block_mask: tuple,
413
+ scale: float,
414
+ kernel_options: dict[str, Any],
415
+ score_mod_other_buffers: tuple = (),
416
+ mask_mod_other_buffers: tuple = (),
417
+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
418
+ """Traces the flex_attention operator with the given score_mod function and other_buffers.
419
+
420
+ Trace SDPA will call make_fx with "fake" example vals and then trace the score_mod function
421
+ This will produce a GraphModule that will be stored on the root tracer as "sdpa_score". We
422
+ access this graph module in inductor to inline the score_mod function to the triton template.
423
+ """
424
+ from torch._dynamo._trace_wrapped_higher_order_op import TransformGetItemToIndex
425
+
426
+ example_out = flex_attention(
427
+ query,
428
+ key,
429
+ value,
430
+ score_mod,
431
+ block_mask,
432
+ scale,
433
+ kernel_options,
434
+ score_mod_other_buffers,
435
+ mask_mod_other_buffers,
436
+ )
437
+ example_vals = [query.new_zeros((), requires_grad=query.requires_grad)] + [
438
+ query.new_zeros((), dtype=torch.int) for _ in range(4)
439
+ ]
440
+ mask_example_vals = [query.new_zeros((), dtype=torch.int) for _ in range(4)]
441
+ mask_mod = block_mask[-1]
442
+ with TransformGetItemToIndex():
443
+ score_graph = reenter_make_fx(score_mod)(
444
+ *example_vals, *score_mod_other_buffers
445
+ )
446
+ mask_graph = reenter_make_fx(mask_mod)(
447
+ *mask_example_vals, *mask_mod_other_buffers
448
+ )
449
+ if not isinstance(proxy_mode.tracer, torch.fx.Tracer):
450
+ raise AssertionError(
451
+ f"expected proxy_mode.tracer to be torch.fx.Tracer, got {type(proxy_mode.tracer)}"
452
+ )
453
+ block_mask = block_mask[:-1] + (mask_graph,)
454
+ qualname = proxy_mode.tracer.get_fresh_qualname("sdpa_score")
455
+ proxy_mode.tracer.root.register_module(qualname, score_graph)
456
+ mask_qualname = proxy_mode.tracer.get_fresh_qualname("sdpa_mask")
457
+ proxy_mode.tracer.root.register_module(mask_qualname, mask_graph)
458
+ node_args = (
459
+ query,
460
+ key,
461
+ value,
462
+ score_graph,
463
+ block_mask,
464
+ scale,
465
+ kernel_options,
466
+ score_mod_other_buffers,
467
+ mask_mod_other_buffers,
468
+ )
469
+ # pyrefly: ignore [missing-attribute]
470
+ proxy_args = pytree.tree_map(proxy_mode.tracer.unwrap_proxy, node_args)
471
+ with torch.fx.experimental.proxy_tensor.set_original_aten_op(flex_attention):
472
+ out_proxy = proxy_mode.tracer.create_proxy(
473
+ "call_function", flex_attention, proxy_args, {}
474
+ )
475
+ return track_tensor_tree(
476
+ example_out,
477
+ out_proxy,
478
+ constant=None,
479
+ tracer=proxy_mode.tracer,
480
+ )
481
+
482
+
483
+ @flex_attention.py_impl(ProxyTorchDispatchMode)
484
+ def flex_attention_proxy_torch_dispatch_mode(
485
+ mode: ProxyTorchDispatchMode,
486
+ query: torch.Tensor,
487
+ key: torch.Tensor,
488
+ value: torch.Tensor,
489
+ score_mod: Callable,
490
+ block_mask: tuple,
491
+ scale: float,
492
+ kernel_options: dict[str, Any],
493
+ score_mod_other_buffers: tuple = (),
494
+ mask_mod_other_buffers: tuple = (),
495
+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
496
+ if mode is None:
497
+ raise AssertionError("Mode should always be enabled for python fallback key")
498
+ return trace_flex_attention(
499
+ mode,
500
+ query,
501
+ key,
502
+ value,
503
+ score_mod,
504
+ block_mask,
505
+ scale,
506
+ kernel_options,
507
+ score_mod_other_buffers,
508
+ mask_mod_other_buffers,
509
+ )
510
+
511
+
512
+ @flex_attention.py_functionalize_impl
513
+ def flex_attention_functionalize(
514
+ ctx: torch._subclasses.functional_tensor.BaseFunctionalizeAPI,
515
+ query: torch.Tensor,
516
+ key: torch.Tensor,
517
+ value: torch.Tensor,
518
+ score_mod: Callable,
519
+ block_mask: tuple,
520
+ scale: float,
521
+ kernel_options: dict[str, Any],
522
+ score_mod_other_buffers: tuple = (),
523
+ mask_mod_other_buffers: tuple = (),
524
+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
525
+ """Defines the functionalization rules for the flex_attention operator.
526
+
527
+ Write now we are unwrapping each tensor and then redispatching to the next, however we want to
528
+ guard against any mutations in the score_mod function, to the other_buffers since those
529
+ are free variables.
530
+ """
531
+ from torch._dynamo._trace_wrapped_higher_order_op import TransformGetItemToIndex
532
+
533
+ query_unwrapped = ctx.unwrap_tensors(query)
534
+ key_unwrapped = ctx.unwrap_tensors(key)
535
+ value_unwrapped = ctx.unwrap_tensors(value)
536
+ block_mask_unwrapped = ctx.unwrap_tensors(block_mask)
537
+ score_mod_other_buffers_unwrapped = ctx.unwrap_tensors(score_mod_other_buffers)
538
+ mask_mod_other_buffers_unwrapped = ctx.unwrap_tensors(mask_mod_other_buffers)
539
+
540
+ # Appease the mypy overlords
541
+ if not isinstance(query_unwrapped, torch.Tensor):
542
+ raise AssertionError(
543
+ f"expected query_unwrapped to be torch.Tensor, got {type(query_unwrapped)}"
544
+ )
545
+ if not isinstance(key_unwrapped, torch.Tensor):
546
+ raise AssertionError(
547
+ f"expected key_unwrapped to be torch.Tensor, got {type(key_unwrapped)}"
548
+ )
549
+ if not isinstance(value_unwrapped, torch.Tensor):
550
+ raise AssertionError(
551
+ f"expected value_unwrapped to be torch.Tensor, got {type(value_unwrapped)}"
552
+ )
553
+ if not isinstance(block_mask_unwrapped, tuple):
554
+ raise AssertionError(
555
+ f"expected block_mask_unwrapped to be tuple, got {type(block_mask_unwrapped)}"
556
+ )
557
+ if not isinstance(score_mod_other_buffers_unwrapped, tuple):
558
+ raise AssertionError(
559
+ f"expected score_mod_other_buffers_unwrapped to be tuple, got {type(score_mod_other_buffers_unwrapped)}"
560
+ )
561
+ if not isinstance(mask_mod_other_buffers_unwrapped, tuple):
562
+ raise AssertionError(
563
+ f"expected mask_mod_other_buffers_unwrapped to be tuple, got {type(mask_mod_other_buffers_unwrapped)}"
564
+ )
565
+
566
+ example_vals = (
567
+ [query_unwrapped.new_zeros(())]
568
+ + [query_unwrapped.new_zeros((), dtype=torch.int) for _ in range(4)]
569
+ + list(score_mod_other_buffers_unwrapped)
570
+ )
571
+ with ctx.redispatch_to_next():
572
+ functional_score_mod = ctx.functionalize(score_mod)
573
+ pre_dispatch = hasattr(ctx, "mode") and ctx.mode.pre_dispatch
574
+ with TransformGetItemToIndex():
575
+ # TODO: So far only the input mutations are checked
576
+ # In the other HOPs, also aliases are checked which is
577
+ # omitted here
578
+ mutates = _has_potential_branch_input_mutation(
579
+ score_mod, example_vals, pre_dispatch
580
+ )
581
+ # The only care about mutations of existing buffers since we can't replay these.
582
+ # However, we can just error if anything is detected
583
+ if mutates:
584
+ raise UnsupportedAliasMutationException("Mutations detected in score_mod")
585
+
586
+ out = flex_attention(
587
+ query_unwrapped,
588
+ key_unwrapped,
589
+ value_unwrapped,
590
+ functional_score_mod,
591
+ block_mask_unwrapped,
592
+ scale,
593
+ kernel_options,
594
+ score_mod_other_buffers_unwrapped,
595
+ mask_mod_other_buffers_unwrapped,
596
+ )
597
+ return ctx.wrap_tensors(out) # type: ignore[return-value, arg-type]
598
+
599
+
600
+ @register_fake(flex_attention)
601
+ def flex_attention_fake_impl(
602
+ query: torch.Tensor,
603
+ key: torch.Tensor,
604
+ value: torch.Tensor,
605
+ score_mod: Callable,
606
+ block_mask: tuple,
607
+ scale: float,
608
+ kernel_options: dict[str, Any],
609
+ score_mod_other_buffers: tuple = (),
610
+ mask_mod_other_buffers: tuple = (),
611
+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
612
+ if has_user_subclass(
613
+ (
614
+ query,
615
+ key,
616
+ value,
617
+ score_mod,
618
+ block_mask,
619
+ scale,
620
+ kernel_options,
621
+ score_mod_other_buffers,
622
+ mask_mod_other_buffers,
623
+ ),
624
+ allowed_subclasses=(FakeTensor,),
625
+ ):
626
+ return NotImplemented
627
+
628
+ v_head_dim = value.size(-1)
629
+ batch_size, num_heads, seq_len_q, _q_head_dim = query.shape
630
+ logsumexp = query.new_empty(batch_size, num_heads, seq_len_q, dtype=torch.float32)
631
+ max_scores = query.new_empty(batch_size, num_heads, seq_len_q, dtype=torch.float32)
632
+ out_shape = (batch_size, num_heads, seq_len_q, v_head_dim)
633
+ out = query.new_empty(out_shape)
634
+ out = _permute_strides(out, query.stride())
635
+ return out, logsumexp, max_scores
636
+
637
+
638
+ # Registers dispatches for SAC
639
+ redirect_to_mode(flex_attention, _CachingTorchDispatchMode)
640
+ redirect_to_mode(flex_attention, _CachedTorchDispatchMode)
641
+
642
+
643
+ # ---------------------------- Autograd Implementation ----------------------------
644
+ def create_fw_bw_graph(
645
+ score_mod: Callable,
646
+ index_values: tuple[Tensor, Tensor, Tensor, Tensor, Tensor],
647
+ other_buffers: tuple[Tensor, ...],
648
+ ) -> tuple[Callable, Callable]:
649
+ # See Note:[HOP create fw_bw graph]
650
+
651
+ # All of these imports need to be here in order to avoid circular dependencies
652
+ from torch._dispatch.python import suspend_functionalization
653
+ from torch._functorch.aot_autograd import AOTConfig, create_joint
654
+ from torch._subclasses.fake_tensor import FakeTensor, FakeTensorMode
655
+ from torch._subclasses.functional_tensor import disable_functional_mode
656
+ from torch.fx.experimental.proxy_tensor import disable_proxy_modes_tracing
657
+
658
+ dummy_aot_config = AOTConfig(
659
+ fw_compiler=None, # type: ignore[arg-type]
660
+ bw_compiler=None, # type: ignore[arg-type]
661
+ partition_fn=None, # type: ignore[arg-type]
662
+ decompositions={},
663
+ num_params_buffers=0,
664
+ aot_id=0,
665
+ keep_inference_input_mutations=False,
666
+ )
667
+
668
+ with suspend_functionalization(), disable_functional_mode():
669
+ with disable_proxy_modes_tracing():
670
+
671
+ def _from_fun(
672
+ t: Union[Tensor, torch.SymInt, int],
673
+ ) -> Union[Tensor, torch.SymInt, int]:
674
+ if isinstance(t, torch.Tensor):
675
+ return torch.empty_strided(
676
+ t.size(),
677
+ t.stride(),
678
+ device=t.device,
679
+ dtype=t.dtype,
680
+ requires_grad=t.requires_grad,
681
+ )
682
+ return t
683
+
684
+ # If someone runs this hop under the default compiler backend ("eager")
685
+ # Then this path will be run with the actual user inputs. We convert them
686
+ # to fake tensors in order to not perform any actual compute.
687
+ from torch._guards import detect_fake_mode
688
+
689
+ fake_mode = detect_fake_mode(index_values)
690
+ if fake_mode is None:
691
+ fake_mode = FakeTensorMode(allow_non_fake_inputs=True)
692
+
693
+ with fake_mode:
694
+ unwrapped_score_mod_indexes = pytree.tree_map(_from_fun, index_values)
695
+ unwrapped_other_buffers = pytree.tree_map(_from_fun, other_buffers)
696
+
697
+ if not all(
698
+ isinstance(t, (FakeTensor, int, torch.SymInt))
699
+ for t in unwrapped_score_mod_indexes + unwrapped_other_buffers
700
+ ):
701
+ raise AssertionError(
702
+ f"all unwrapped values must be FakeTensor, int, or SymInt, got "
703
+ f"{[type(t) for t in unwrapped_score_mod_indexes + unwrapped_other_buffers]}"
704
+ )
705
+
706
+ example_flat_out = pytree.tree_map(
707
+ _from_fun,
708
+ score_mod(*unwrapped_score_mod_indexes, *unwrapped_other_buffers),
709
+ )
710
+ if not isinstance(example_flat_out, torch.Tensor):
711
+ raise RuntimeError(
712
+ "Expected output of score_mod to be a tensor."
713
+ f"Got type {type(example_flat_out)}."
714
+ )
715
+ example_grad = _from_fun(example_flat_out)
716
+
717
+ def joint_f(
718
+ score: Tensor,
719
+ b: Tensor,
720
+ h: Tensor,
721
+ m: Tensor,
722
+ n: Tensor,
723
+ example_grad: Tensor,
724
+ *other_buffers: tuple[Tensor, ...],
725
+ ) -> tuple[Tensor, ...]:
726
+ def fw_with_masks(
727
+ *args: tuple[Tensor, ...],
728
+ ) -> tuple[tuple[Tensor], tuple[bool]]:
729
+ fw_out = score_mod(*args)
730
+ out_requires_grad = fw_out.requires_grad
731
+ return ((fw_out,), (out_requires_grad,))
732
+
733
+ joint = create_joint(fw_with_masks, aot_config=dummy_aot_config)
734
+ args = [score, b, h, m, n] + list(other_buffers)
735
+ optional_grad = [example_grad] if example_grad.requires_grad else []
736
+ _, grads = joint(args, optional_grad)
737
+
738
+ return grads
739
+
740
+ joint_graph = make_fx(joint_f)(
741
+ *unwrapped_score_mod_indexes, example_grad, *unwrapped_other_buffers
742
+ )
743
+ # pyrefly: ignore [bad-return]
744
+ return score_mod, joint_graph
745
+
746
+
747
+ class FlexAttentionAutogradOp(torch.autograd.Function):
748
+ @staticmethod
749
+ # pyrefly: ignore [bad-override]
750
+ def forward(
751
+ ctx: Any,
752
+ query: Tensor,
753
+ key: Tensor,
754
+ value: Tensor,
755
+ fw_graph: Callable,
756
+ joint_graph: Callable,
757
+ block_mask: tuple[Any, ...],
758
+ scale: float,
759
+ kernel_options: dict[str, Any],
760
+ mask_mod_other_buffers: tuple[Any, ...],
761
+ *score_mod_other_buffers: tuple[Any, ...],
762
+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
763
+ ctx.set_materialize_grads(False)
764
+ any_buffer_requires_grad = any(
765
+ buffer.requires_grad
766
+ for buffer in mask_mod_other_buffers
767
+ if isinstance(buffer, torch.Tensor)
768
+ )
769
+ if any_buffer_requires_grad:
770
+ raise AssertionError(
771
+ "Captured buffers from mask mod that require grad are not supported."
772
+ )
773
+ ctx._fw_graph = fw_graph
774
+ ctx._joint_graph = joint_graph
775
+ ctx._mask_graph = block_mask[-1]
776
+ ctx.scale = scale
777
+ ctx.kernel_options = kernel_options
778
+ ctx._score_mod_other_buffers_len = len(score_mod_other_buffers)
779
+ with torch._C._AutoDispatchBelowAutograd():
780
+ out, logsumexp, max_scores = flex_attention(
781
+ query,
782
+ key,
783
+ value,
784
+ fw_graph,
785
+ block_mask,
786
+ scale,
787
+ kernel_options,
788
+ score_mod_other_buffers,
789
+ mask_mod_other_buffers,
790
+ )
791
+ # no grads for you sir
792
+ ctx.mark_non_differentiable(max_scores)
793
+ save_values_for_backward(
794
+ ctx,
795
+ (
796
+ query,
797
+ key,
798
+ value,
799
+ out,
800
+ logsumexp,
801
+ max_scores,
802
+ *block_mask[:-1],
803
+ *score_mod_other_buffers,
804
+ *mask_mod_other_buffers,
805
+ ),
806
+ )
807
+ return out, logsumexp, max_scores
808
+
809
+ @staticmethod
810
+ def backward( # type: ignore[override]
811
+ ctx: Any,
812
+ grad_out: Tensor,
813
+ grad_logsumexp: Tensor,
814
+ grad_max_scores: Tensor,
815
+ ) -> tuple[Optional[Tensor], ...]:
816
+ fw_args = saved_values(ctx)
817
+ (
818
+ query,
819
+ key,
820
+ value,
821
+ out,
822
+ logsumexp,
823
+ max_scores,
824
+ query_lengths,
825
+ kv_lengths,
826
+ kv_num_blocks,
827
+ kv_indices,
828
+ full_kv_num_blocks,
829
+ full_kv_indices,
830
+ q_num_blocks,
831
+ q_indices,
832
+ full_q_num_blocks,
833
+ full_q_indices,
834
+ Q_BLOCK_SIZE,
835
+ KV_BLOCK_SIZE,
836
+ *other_buffers,
837
+ ) = fw_args
838
+ fw_graph = ctx._fw_graph
839
+ joint_graph = ctx._joint_graph
840
+ mask_graph = ctx._mask_graph
841
+ scale = ctx.scale
842
+ kernel_options = ctx.kernel_options
843
+ score_mod_other_buffers = tuple(
844
+ other_buffers[: ctx._score_mod_other_buffers_len]
845
+ )
846
+ mask_mod_other_buffers = tuple(
847
+ other_buffers[ctx._score_mod_other_buffers_len :]
848
+ )
849
+ # We have asserted that mask_mod_other_buffers do not require grad,
850
+ # but score_mod_other_buffers can require grad.
851
+ none_grads = [None] * 6
852
+ (
853
+ grad_query,
854
+ grad_key,
855
+ grad_value,
856
+ grad_score_mod_captured,
857
+ ) = flex_attention_backward(
858
+ query,
859
+ key,
860
+ value,
861
+ out,
862
+ logsumexp,
863
+ grad_out,
864
+ grad_logsumexp,
865
+ fw_graph,
866
+ joint_graph,
867
+ (
868
+ query_lengths,
869
+ kv_lengths,
870
+ kv_num_blocks,
871
+ kv_indices,
872
+ full_kv_num_blocks,
873
+ full_kv_indices,
874
+ q_num_blocks,
875
+ q_indices,
876
+ full_q_num_blocks,
877
+ full_q_indices,
878
+ Q_BLOCK_SIZE,
879
+ KV_BLOCK_SIZE,
880
+ mask_graph,
881
+ ),
882
+ scale,
883
+ kernel_options,
884
+ score_mod_other_buffers,
885
+ mask_mod_other_buffers,
886
+ )
887
+ return grad_query, grad_key, grad_value, *none_grads, *grad_score_mod_captured
888
+
889
+
890
+ # TODO: Rework DispatchKey.Autograd to py_autograd_impl
891
+ @flex_attention.py_impl(DispatchKey.Autograd)
892
+ def flex_attention_autograd(
893
+ query: torch.Tensor,
894
+ key: torch.Tensor,
895
+ value: torch.Tensor,
896
+ score_mod: Callable,
897
+ block_mask: tuple,
898
+ scale: float,
899
+ kernel_options: dict[str, Any],
900
+ score_mod_other_buffers: tuple[Tensor, ...] = (),
901
+ mask_mod_other_buffers: tuple[Tensor, ...] = (),
902
+ ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
903
+ from torch._dynamo._trace_wrapped_higher_order_op import TransformGetItemToIndex
904
+
905
+ with TransformGetItemToIndex():
906
+ input_requires_grad = any(
907
+ isinstance(t, torch.Tensor) and t.requires_grad
908
+ for t in (query, key, value, *score_mod_other_buffers)
909
+ )
910
+ if torch.is_grad_enabled() and input_requires_grad:
911
+ if block_mask[7] is None:
912
+ raise RuntimeError(
913
+ "BlockMask q_indices is None. Backward pass requires q_indices to be computed. "
914
+ "Please create the BlockMask with compute_q_blocks=True"
915
+ )
916
+ example_vals = (
917
+ query.new_zeros((), requires_grad=input_requires_grad),
918
+ query.new_zeros((), dtype=torch.int),
919
+ query.new_zeros((), dtype=torch.int),
920
+ query.new_zeros((), dtype=torch.int),
921
+ query.new_zeros((), dtype=torch.int),
922
+ )
923
+ fw_graph, bw_graph = create_fw_bw_graph(
924
+ score_mod, example_vals, score_mod_other_buffers
925
+ )
926
+ else:
927
+ fw_graph, bw_graph = score_mod, None
928
+ out, logsumexp, max_scores = FlexAttentionAutogradOp.apply(
929
+ query,
930
+ key,
931
+ value,
932
+ fw_graph,
933
+ bw_graph,
934
+ block_mask,
935
+ scale,
936
+ kernel_options,
937
+ mask_mod_other_buffers,
938
+ *score_mod_other_buffers,
939
+ )
940
+ return out, logsumexp, max_scores
941
+
942
+
943
+ # ---------------------------- Backward HOP Implementation ----------------------------
944
+
945
+
946
+ @flex_attention_backward.py_impl(DispatchKey.CompositeExplicitAutograd)
947
+ def sdpa_dense_backward(
948
+ query: torch.Tensor,
949
+ key: torch.Tensor,
950
+ value: torch.Tensor,
951
+ out: torch.Tensor,
952
+ logsumexp: torch.Tensor,
953
+ grad_out: torch.Tensor | None,
954
+ grad_logsumexp: torch.Tensor | None,
955
+ fw_graph: Callable, # GraphModule type hint?
956
+ joint_graph: Callable,
957
+ block_mask: tuple,
958
+ scale: float,
959
+ kernel_options: dict[str, Any],
960
+ score_mod_other_buffers: tuple,
961
+ mask_mod_other_buffers: tuple,
962
+ ) -> tuple[
963
+ torch.Tensor, torch.Tensor, torch.Tensor, tuple[Optional[torch.Tensor], ...]
964
+ ]:
965
+ if query.dtype != key.dtype or query.dtype != value.dtype:
966
+ raise ValueError(
967
+ f"Backward pass with mixed query, key, and value dtype is not supported, "
968
+ f"got query.dtype={query.dtype}, key.dtype={key.dtype}, "
969
+ f"and value.dtype={value.dtype}"
970
+ )
971
+ from torch._dynamo._trace_wrapped_higher_order_op import TransformGetItemToIndex
972
+
973
+ Bq, Hq, seq_len_q, qk_head_dim = query.shape
974
+ Bkv, Hkv, seq_len_kv, v_head_dim = value.shape
975
+
976
+ # Get outputs before calling repeat interleave and permute to input stride orders
977
+ actual_grad_query = query.new_empty((Bq, Hq, seq_len_q, qk_head_dim))
978
+ actual_grad_query = _permute_strides(actual_grad_query, query.stride())
979
+
980
+ actual_grad_key = key.new_empty((Bq, Hkv, seq_len_kv, qk_head_dim))
981
+ actual_grad_key = _permute_strides(actual_grad_key, key.stride())
982
+
983
+ actual_grad_value = value.new_empty((Bq, Hkv, seq_len_kv, v_head_dim))
984
+ actual_grad_value = _permute_strides(actual_grad_value, value.stride())
985
+
986
+ def _maybe_new_buffer(
987
+ buffer: Union[torch.Tensor, torch.SymInt, int],
988
+ ) -> Optional[Union[torch.Tensor, torch.SymInt, int]]:
989
+ if isinstance(buffer, torch.Tensor):
990
+ return (
991
+ torch.empty_like(buffer, memory_format=torch.contiguous_format)
992
+ if buffer.requires_grad
993
+ else None
994
+ )
995
+ return buffer
996
+
997
+ actual_grad_score_mod_captured = [
998
+ _maybe_new_buffer(buffer) for buffer in score_mod_other_buffers
999
+ ]
1000
+
1001
+ Bq, Bkv = query.size(0), key.size(0)
1002
+ if not ((Bq == Bkv) or (Bq > 1 and Bkv == 1)):
1003
+ raise RuntimeError(f"Bq and Bkv must broadcast. Got Bq={Bq} and Bkv={Bkv}")
1004
+
1005
+ key = key.expand((Bq, *key.size()[1:]))
1006
+ value = value.expand((Bq, *value.size()[1:]))
1007
+
1008
+ G = query.size(1) // key.size(1)
1009
+ key = torch.repeat_interleave(key, G, dim=1)
1010
+ value = torch.repeat_interleave(value, G, dim=1)
1011
+
1012
+ if grad_out is None:
1013
+ grad_out = torch.zeros_like(out)
1014
+ if grad_logsumexp is None:
1015
+ grad_logsumexp = torch.zeros_like(logsumexp)
1016
+
1017
+ # We're undoing the log -> log2 change of base in the forwards
1018
+ logsumexp = logsumexp * math.log(2)
1019
+ # The backwards formula for the log -> log2 change of base in the forwards
1020
+ grad_logsumexp = grad_logsumexp / math.log(2)
1021
+ scores, post_mod_scores = _math_attention_inner(
1022
+ query,
1023
+ key,
1024
+ value,
1025
+ fw_graph,
1026
+ block_mask,
1027
+ scale,
1028
+ kernel_options,
1029
+ score_mod_other_buffers,
1030
+ mask_mod_other_buffers,
1031
+ )
1032
+ masked_out_rows = logsumexp == -float("inf")
1033
+ softmax_scores = torch.exp(post_mod_scores - logsumexp.unsqueeze(-1))
1034
+ softmax_scores = torch.where(masked_out_rows.unsqueeze(-1), 0, softmax_scores)
1035
+
1036
+ grad_value = softmax_scores.to(query.dtype).transpose(-2, -1) @ grad_out
1037
+
1038
+ grad_softmax_scores = grad_out.to(dtype=softmax_scores.dtype) @ value.to(
1039
+ dtype=softmax_scores.dtype
1040
+ ).transpose(-2, -1)
1041
+
1042
+ sum_scores = torch.sum(
1043
+ out.to(dtype=softmax_scores.dtype) * grad_out.to(dtype=softmax_scores.dtype),
1044
+ -1,
1045
+ keepdim=True,
1046
+ )
1047
+ grad_score_mod = softmax_scores * (
1048
+ grad_softmax_scores - sum_scores + grad_logsumexp.unsqueeze(-1)
1049
+ )
1050
+
1051
+ b = torch.arange(0, scores.size(0), device=scores.device)
1052
+ h = torch.arange(0, scores.size(1), device=scores.device)
1053
+ m = torch.arange(0, scores.size(2), device=scores.device)
1054
+ n = torch.arange(0, scores.size(3), device=scores.device)
1055
+
1056
+ mask_graph = block_mask[-1]
1057
+ # Gradient of the inline score_mod function, with respect to the scores
1058
+ captured_buffers_in_dim = (None,) * len(score_mod_other_buffers)
1059
+ out_dims = [0, None, None, None, None] + [None] * len(score_mod_other_buffers)
1060
+ from torch.nn.attention.flex_attention import _vmap_for_bhqkv
1061
+
1062
+ # inputs are [score, b, h, q_idx, kv_idx, gradOut, ...]
1063
+ # score and gradOut are "fully" batched
1064
+ joint_score_mod = _vmap_for_bhqkv(
1065
+ joint_graph,
1066
+ prefix=(0,),
1067
+ suffix=(0,) + captured_buffers_in_dim,
1068
+ out_dims=out_dims,
1069
+ )
1070
+ with TransformGetItemToIndex():
1071
+ grad_scores, _, _, _, _, *grad_score_mod_captured = joint_score_mod(
1072
+ scores, b, h, m, n, grad_score_mod, *score_mod_other_buffers
1073
+ )
1074
+ grad_scores = grad_scores * scale
1075
+ grad_scores = grad_scores.to(query.dtype)
1076
+
1077
+ mask_mod = _vmap_for_bhqkv(
1078
+ mask_graph, prefix=(), suffix=(None,) * len(mask_mod_other_buffers)
1079
+ )
1080
+ with TransformGetItemToIndex():
1081
+ mask_scores = mask_mod(b, h, m, n, *mask_mod_other_buffers)
1082
+ grad_scores = torch.where(
1083
+ mask_scores, grad_scores, torch.tensor(0, dtype=query.dtype)
1084
+ )
1085
+
1086
+ grad_query = grad_scores @ key
1087
+ grad_key = grad_scores.transpose(-2, -1) @ query
1088
+
1089
+ # Reduce DK, DV along broadcasted heads.
1090
+ grad_key = grad_key.view(
1091
+ grad_key.size(0), -1, G, grad_key.size(-2), grad_key.size(-1)
1092
+ )
1093
+ grad_value = grad_value.view(
1094
+ grad_value.size(0), -1, G, grad_value.size(-2), grad_value.size(-1)
1095
+ )
1096
+
1097
+ grad_key = torch.sum(grad_key, 2, keepdim=False)
1098
+ grad_value = torch.sum(grad_value, 2, keepdim=False)
1099
+
1100
+ # Fill to correctly strided outputs
1101
+ actual_grad_query.copy_(grad_query)
1102
+ actual_grad_key.copy_(grad_key)
1103
+ actual_grad_value.copy_(grad_value)
1104
+
1105
+ if Bq != Bkv:
1106
+ if not (Bq > 1 and Bkv == 1):
1107
+ raise AssertionError(
1108
+ f"Bq and Bkv must broadcast. Got Bq={Bq} and Bkv={Bkv}"
1109
+ )
1110
+
1111
+ actual_grad_key = torch.sum(actual_grad_key, 0, keepdim=True)
1112
+ actual_grad_value = torch.sum(actual_grad_value, 0, keepdim=True)
1113
+
1114
+ score_mod_other_buffer_grads = [
1115
+ actual_grad.copy_(grad) if isinstance(actual_grad, torch.Tensor) else None
1116
+ for actual_grad, grad in zip(
1117
+ actual_grad_score_mod_captured, grad_score_mod_captured
1118
+ )
1119
+ ]
1120
+
1121
+ return (
1122
+ actual_grad_query,
1123
+ actual_grad_key,
1124
+ actual_grad_value,
1125
+ tuple(score_mod_other_buffer_grads),
1126
+ )
1127
+
1128
+
1129
+ def trace_flex_attention_backward(
1130
+ proxy_mode: ProxyTorchDispatchMode,
1131
+ query: torch.Tensor,
1132
+ key: torch.Tensor,
1133
+ value: torch.Tensor,
1134
+ out: torch.Tensor,
1135
+ logsumexp: torch.Tensor,
1136
+ grad_out: torch.Tensor,
1137
+ grad_logsumexp: torch.Tensor,
1138
+ fw_graph: Union[Callable, GraphModule],
1139
+ joint_graph: GraphModule,
1140
+ block_mask: tuple,
1141
+ scale: float,
1142
+ kernel_options: dict[str, Any],
1143
+ score_mod_other_buffers: tuple = (),
1144
+ mask_mod_other_buffers: tuple = (),
1145
+ ) -> tuple[
1146
+ torch.Tensor, torch.Tensor, torch.Tensor, tuple[Optional[torch.Tensor], ...]
1147
+ ]:
1148
+ """We already have the forward graph and joint graph from the forward pass, so we create a proxy attach both graphs"""
1149
+ from torch._dynamo._trace_wrapped_higher_order_op import TransformGetItemToIndex
1150
+
1151
+ example_out = flex_attention_backward(
1152
+ query,
1153
+ key,
1154
+ value,
1155
+ out,
1156
+ logsumexp,
1157
+ grad_out,
1158
+ grad_logsumexp,
1159
+ fw_graph,
1160
+ joint_graph,
1161
+ block_mask,
1162
+ scale,
1163
+ kernel_options,
1164
+ score_mod_other_buffers,
1165
+ mask_mod_other_buffers,
1166
+ )
1167
+
1168
+ requires_grad = any(pytree.tree_map(lambda x: x.requires_grad, (query, key)))
1169
+ fw_example_vals = [query.new_zeros((), requires_grad=requires_grad)] + [
1170
+ query.new_zeros((), dtype=torch.int) for _ in range(4)
1171
+ ]
1172
+ bw_example_vals = fw_example_vals + [query.new_zeros(())]
1173
+ mask_example_vals = [query.new_zeros((), dtype=torch.int) for _ in range(4)]
1174
+ mask_graph = block_mask[-1]
1175
+ with TransformGetItemToIndex():
1176
+ # There's no active make_fx during the compiled autograd graph's initial capture
1177
+ fw_graph = _maybe_reenter_make_fx(fw_graph)(
1178
+ *fw_example_vals, *score_mod_other_buffers
1179
+ )
1180
+ joint_graph = _maybe_reenter_make_fx(joint_graph)(
1181
+ *bw_example_vals, *score_mod_other_buffers
1182
+ )
1183
+ mask_graph = _maybe_reenter_make_fx(mask_graph)(
1184
+ *mask_example_vals, *mask_mod_other_buffers
1185
+ )
1186
+ if not isinstance(proxy_mode.tracer, torch.fx.Tracer):
1187
+ raise AssertionError(
1188
+ f"expected proxy_mode.tracer to be torch.fx.Tracer, got {type(proxy_mode.tracer)}"
1189
+ )
1190
+ block_mask = block_mask[:-1] + (mask_graph,)
1191
+
1192
+ qualname = proxy_mode.tracer.get_fresh_qualname("fw_graph")
1193
+ proxy_mode.tracer.root.register_module(qualname, fw_graph) # type: ignore[arg-type]
1194
+ qualname = proxy_mode.tracer.get_fresh_qualname("joint_graph")
1195
+ proxy_mode.tracer.root.register_module(qualname, joint_graph)
1196
+ qualname = proxy_mode.tracer.get_fresh_qualname("mask_graph")
1197
+ proxy_mode.tracer.root.register_module(qualname, mask_graph)
1198
+
1199
+ node_args = (
1200
+ query,
1201
+ key,
1202
+ value,
1203
+ out,
1204
+ logsumexp,
1205
+ grad_out,
1206
+ grad_logsumexp,
1207
+ fw_graph,
1208
+ joint_graph,
1209
+ block_mask,
1210
+ scale,
1211
+ kernel_options,
1212
+ score_mod_other_buffers,
1213
+ mask_mod_other_buffers,
1214
+ )
1215
+ # pyrefly: ignore [missing-attribute]
1216
+ proxy_args = pytree.tree_map(proxy_mode.tracer.unwrap_proxy, node_args)
1217
+ out_proxy = proxy_mode.tracer.create_proxy(
1218
+ "call_function",
1219
+ flex_attention_backward,
1220
+ proxy_args,
1221
+ {},
1222
+ name="flex_attention_backward",
1223
+ )
1224
+ return track_tensor_tree(
1225
+ example_out,
1226
+ out_proxy,
1227
+ constant=None,
1228
+ tracer=proxy_mode.tracer,
1229
+ )
1230
+
1231
+
1232
+ @flex_attention_backward.py_impl(ProxyTorchDispatchMode)
1233
+ def flex_attention_backward_proxy_torch_dispatch_mode(
1234
+ mode: ProxyTorchDispatchMode,
1235
+ query: torch.Tensor,
1236
+ key: torch.Tensor,
1237
+ value: torch.Tensor,
1238
+ out: torch.Tensor,
1239
+ logsumexp: torch.Tensor,
1240
+ grad_out: torch.Tensor,
1241
+ grad_logsumexp: torch.Tensor,
1242
+ fw_graph: Union[Callable, GraphModule],
1243
+ joint_graph: GraphModule,
1244
+ block_mask: tuple,
1245
+ scale: float,
1246
+ kernel_options: dict[str, Any],
1247
+ score_mod_other_buffers: tuple = (),
1248
+ mask_mod_other_buffers: tuple = (),
1249
+ ) -> tuple[
1250
+ torch.Tensor, torch.Tensor, torch.Tensor, tuple[Optional[torch.Tensor], ...]
1251
+ ]:
1252
+ if mode is None:
1253
+ raise AssertionError("Mode should always be enabled for python fallback key")
1254
+ with torch.fx.experimental.proxy_tensor.set_original_aten_op(
1255
+ flex_attention_backward
1256
+ ):
1257
+ return trace_flex_attention_backward(
1258
+ mode,
1259
+ query,
1260
+ key,
1261
+ value,
1262
+ out,
1263
+ logsumexp,
1264
+ grad_out,
1265
+ grad_logsumexp,
1266
+ fw_graph,
1267
+ joint_graph,
1268
+ block_mask,
1269
+ scale,
1270
+ kernel_options,
1271
+ score_mod_other_buffers,
1272
+ mask_mod_other_buffers,
1273
+ )
1274
+
1275
+
1276
+ @flex_attention_backward.py_functionalize_impl
1277
+ def flex_attention_backward_functionalize(
1278
+ ctx: torch._subclasses.functional_tensor.BaseFunctionalizeAPI,
1279
+ query: torch.Tensor,
1280
+ key: torch.Tensor,
1281
+ value: torch.Tensor,
1282
+ out: torch.Tensor,
1283
+ logsumexp: torch.Tensor,
1284
+ grad_out: torch.Tensor,
1285
+ grad_logsumexp: torch.Tensor,
1286
+ fw_graph: Union[Callable, GraphModule],
1287
+ joint_graph: GraphModule,
1288
+ block_mask: tuple,
1289
+ scale: float,
1290
+ kernel_options: dict[str, Any],
1291
+ score_mod_other_buffers: tuple = (),
1292
+ mask_mod_other_buffers: tuple = (),
1293
+ ) -> tuple[
1294
+ torch.Tensor, torch.Tensor, torch.Tensor, tuple[Optional[torch.Tensor], ...]
1295
+ ]:
1296
+ """Defines the functionalization rules for the flex_attention operator.
1297
+
1298
+ Write now we are unwrapping each tensor and then redispatching to the next,
1299
+ since we know that the forward score mod function is assured to be free of mutations
1300
+ to the other_buffers, we skip that mutate check and go straight to redispatching.
1301
+ """
1302
+
1303
+ query_unwrapped = ctx.unwrap_tensors(query)
1304
+ key_unwrapped = ctx.unwrap_tensors(key)
1305
+ value_unwrapped = ctx.unwrap_tensors(value)
1306
+ out_unwrapped = ctx.unwrap_tensors(out)
1307
+ logsumexp_unwrapped = ctx.unwrap_tensors(logsumexp)
1308
+ grad_out_unwrapped = ctx.unwrap_tensors(grad_out)
1309
+ grad_logsumexp_unwrapped = ctx.unwrap_tensors(grad_logsumexp)
1310
+ block_mask_unwrapped = ctx.unwrap_tensors(block_mask)
1311
+ score_mod_other_buffers_unwrapped = ctx.unwrap_tensors(score_mod_other_buffers)
1312
+ mask_mod_other_buffers_unwrapped = ctx.unwrap_tensors(mask_mod_other_buffers)
1313
+
1314
+ # Appease the mypy overlords
1315
+ if not isinstance(query_unwrapped, torch.Tensor):
1316
+ raise AssertionError(
1317
+ f"expected query_unwrapped to be torch.Tensor, got {type(query_unwrapped)}"
1318
+ )
1319
+ if not isinstance(key_unwrapped, torch.Tensor):
1320
+ raise AssertionError(
1321
+ f"expected key_unwrapped to be torch.Tensor, got {type(key_unwrapped)}"
1322
+ )
1323
+ if not isinstance(value_unwrapped, torch.Tensor):
1324
+ raise AssertionError(
1325
+ f"expected value_unwrapped to be torch.Tensor, got {type(value_unwrapped)}"
1326
+ )
1327
+ if not isinstance(out_unwrapped, torch.Tensor):
1328
+ raise AssertionError(
1329
+ f"expected out_unwrapped to be torch.Tensor, got {type(out_unwrapped)}"
1330
+ )
1331
+ if not isinstance(logsumexp_unwrapped, torch.Tensor):
1332
+ raise AssertionError(
1333
+ f"expected logsumexp_unwrapped to be torch.Tensor, got {type(logsumexp_unwrapped)}"
1334
+ )
1335
+ if grad_out_unwrapped is not None and not isinstance(
1336
+ grad_out_unwrapped, torch.Tensor
1337
+ ):
1338
+ raise AssertionError(
1339
+ f"expected grad_out_unwrapped to be torch.Tensor or None, got {type(grad_out_unwrapped)}"
1340
+ )
1341
+ if grad_logsumexp_unwrapped is not None and not isinstance(
1342
+ grad_logsumexp_unwrapped, torch.Tensor
1343
+ ):
1344
+ raise AssertionError(
1345
+ f"expected grad_logsumexp_unwrapped to be torch.Tensor or None, got {type(grad_logsumexp_unwrapped)}"
1346
+ )
1347
+ if not isinstance(block_mask_unwrapped, tuple):
1348
+ raise AssertionError(
1349
+ f"expected block_mask_unwrapped to be tuple, got {type(block_mask_unwrapped)}"
1350
+ )
1351
+ if not isinstance(score_mod_other_buffers_unwrapped, tuple):
1352
+ raise AssertionError(
1353
+ f"expected score_mod_other_buffers_unwrapped to be tuple, got {type(score_mod_other_buffers_unwrapped)}"
1354
+ )
1355
+ if not isinstance(mask_mod_other_buffers_unwrapped, tuple):
1356
+ raise AssertionError(
1357
+ f"expected mask_mod_other_buffers_unwrapped to be tuple, got {type(mask_mod_other_buffers_unwrapped)}"
1358
+ )
1359
+
1360
+ with ctx.redispatch_to_next():
1361
+ # pyrefly: ignore [bad-argument-type]
1362
+ functional_fw_graph = ctx.functionalize(fw_graph)
1363
+ # pyrefly: ignore [bad-argument-type]
1364
+ functional_joint_graph = ctx.functionalize(joint_graph)
1365
+
1366
+ (
1367
+ grad_query,
1368
+ grad_key,
1369
+ grad_value,
1370
+ grad_score_mod_captured,
1371
+ ) = flex_attention_backward(
1372
+ query_unwrapped,
1373
+ key_unwrapped,
1374
+ value_unwrapped,
1375
+ out_unwrapped,
1376
+ logsumexp_unwrapped,
1377
+ grad_out_unwrapped,
1378
+ grad_logsumexp_unwrapped,
1379
+ functional_fw_graph, # type: ignore[arg-type]
1380
+ functional_joint_graph, # type: ignore[arg-type]
1381
+ block_mask_unwrapped,
1382
+ scale,
1383
+ kernel_options,
1384
+ score_mod_other_buffers_unwrapped,
1385
+ mask_mod_other_buffers_unwrapped,
1386
+ )
1387
+
1388
+ return ctx.wrap_tensors((grad_query, grad_key, grad_value, grad_score_mod_captured)) # type: ignore[return-value,arg-type]
1389
+
1390
+
1391
+ @register_fake(flex_attention_backward)
1392
+ def flex_attention_backward_fake_tensor_mode(
1393
+ query: torch.Tensor,
1394
+ key: torch.Tensor,
1395
+ value: torch.Tensor,
1396
+ out: torch.Tensor,
1397
+ logsumexp: torch.Tensor,
1398
+ grad_out: torch.Tensor,
1399
+ grad_logsumexp: torch.Tensor,
1400
+ fw_graph: Union[Callable, GraphModule],
1401
+ joint_graph: GraphModule,
1402
+ block_mask: tuple,
1403
+ scale: float,
1404
+ kernel_options: dict[str, Any],
1405
+ score_mod_other_buffers: tuple = (),
1406
+ mask_mod_other_buffers: tuple = (),
1407
+ ) -> tuple[
1408
+ torch.Tensor, torch.Tensor, torch.Tensor, tuple[Optional[torch.Tensor], ...]
1409
+ ]:
1410
+ if has_user_subclass(
1411
+ (
1412
+ query,
1413
+ key,
1414
+ value,
1415
+ out,
1416
+ logsumexp,
1417
+ grad_out,
1418
+ grad_logsumexp,
1419
+ block_mask,
1420
+ scale,
1421
+ kernel_options,
1422
+ score_mod_other_buffers,
1423
+ mask_mod_other_buffers,
1424
+ ),
1425
+ allowed_subclasses=(FakeTensor,),
1426
+ ):
1427
+ return NotImplemented
1428
+ Bq, _, _, qk_head_dim = query.shape
1429
+ Bkv, Hkv, seq_len_kv, v_head_dim = value.shape
1430
+
1431
+ grad_query = query.new_empty(query.shape)
1432
+ grad_query = _permute_strides(grad_query, query.stride())
1433
+ # zeros_and_scatter creates a contiguous zeros tensor -> contiguous_format
1434
+ grad_score_mod_captured = tuple(
1435
+ (
1436
+ torch.empty_like(buffer, memory_format=torch.contiguous_format)
1437
+ if isinstance(buffer, torch.Tensor)
1438
+ else None
1439
+ )
1440
+ for buffer in score_mod_other_buffers
1441
+ )
1442
+
1443
+ broadcasted_grad_key = key.new_empty((Bq, Hkv, seq_len_kv, qk_head_dim))
1444
+ broadcasted_grad_key = _permute_strides(broadcasted_grad_key, key.stride())
1445
+
1446
+ broadcasted_grad_value = value.new_empty((Bq, Hkv, seq_len_kv, v_head_dim))
1447
+ broadcasted_grad_value = _permute_strides(broadcasted_grad_value, value.stride())
1448
+
1449
+ if Bq > 1 and Bkv == 1:
1450
+ grad_key = torch.sum(broadcasted_grad_key, dim=0, keepdim=True)
1451
+ grad_value = torch.sum(broadcasted_grad_value, dim=0, keepdim=True)
1452
+ else:
1453
+ grad_key = broadcasted_grad_key
1454
+ grad_value = broadcasted_grad_value
1455
+
1456
+ return grad_query, grad_key, grad_value, grad_score_mod_captured
1457
+
1458
+
1459
+ flex_attention_backward.py_autograd_impl(
1460
+ autograd_not_implemented(flex_attention_backward, deferred_error=True)
1461
+ )
.venv/lib/python3.10/site-packages/torch/_higher_order_ops/foreach_map.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-decorators
2
+ # mypy: allow-untyped-defs
3
+ from collections.abc import Callable
4
+ from typing import Any
5
+
6
+ from torch._higher_order_ops.base_hop import BaseHOP, FunctionWithNoFreeVars
7
+
8
+
9
+ class ForeachMap(BaseHOP):
10
+ def __init__(self):
11
+ super().__init__("foreach_map")
12
+
13
+ def __call__(self, fn, *operands, **kwargs): # type: ignore[override]
14
+ fn = FunctionWithNoFreeVars(fn)
15
+ return super().__call__(fn, *operands, **kwargs)
16
+
17
+
18
+ _foreach_map = ForeachMap()
19
+
20
+
21
+ def foreach_map(op: Callable, *operands: Any, **kwargs: dict[str, Any]):
22
+ from torch._dynamo.polyfills import foreach_map_fn
23
+
24
+ return _foreach_map(foreach_map_fn, op, *operands, **kwargs)
.venv/lib/python3.10/site-packages/torch/_higher_order_ops/hints_wrap.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import torch
3
+ import torch.utils._pytree as pytree
4
+ from torch._C import DispatchKey
5
+ from torch._higher_order_ops.utils import (
6
+ autograd_not_implemented,
7
+ reenter_make_fx,
8
+ unique_graph_id,
9
+ )
10
+ from torch._ops import HigherOrderOperator
11
+ from torch._subclasses.fake_tensor import FakeTensorMode
12
+ from torch.fx.experimental.proxy_tensor import ProxyTorchDispatchMode, track_tensor_tree
13
+
14
+
15
+ # used for wrapping a function/op with context hints
16
+ class HintsWrapper(HigherOrderOperator):
17
+ def __init__(self):
18
+ super().__init__("hints_wrapper")
19
+
20
+ def __call__(self, body_fn, args, kwargs, hints):
21
+ r"""
22
+ Call implementation of hints_wrapper
23
+
24
+ Args:
25
+ body_fn (Callable): A callable function that is within the scope
26
+ that is being traced.
27
+
28
+ args (Tuple of torch.Tensor/int/float/bool): A tuple of inputs to
29
+ body_fn.
30
+
31
+ kwargs (dict): Keyword argument to the body_fn.
32
+
33
+ hints (dict): A dict of context hints which could be passed to
34
+ backend compiler.
35
+ """
36
+ if not isinstance(args, tuple):
37
+ args = tuple(args)
38
+
39
+ if not all(isinstance(t, (torch.Tensor, int, float, bool)) for t in args):
40
+ raise RuntimeError(
41
+ f"args must be a tuple of tensors, ints, floats, or bools, got {args}"
42
+ )
43
+
44
+ if not isinstance(kwargs, dict):
45
+ raise RuntimeError(f"kwargs must be a dict, got {type(kwargs)}")
46
+
47
+ if len(kwargs) > 0:
48
+ raise RuntimeError(
49
+ f"kwargs except for hints are not supported, got {kwargs}"
50
+ )
51
+
52
+ if not isinstance(hints, dict):
53
+ raise RuntimeError(f"hints must be a dict, got {type(hints)}")
54
+
55
+ for k, v in hints.items():
56
+ if not isinstance(k, str):
57
+ raise RuntimeError(f"hints key must be a str, got {k}.")
58
+
59
+ if not isinstance(v, (int, float, bool, str)):
60
+ raise RuntimeError(
61
+ "hints must be a dict containing int, float, bool or str "
62
+ f"value, got value {v} for key {k}."
63
+ )
64
+
65
+ # pyrefly: ignore [missing-attribute]
66
+ return super().__call__(body_fn, args, kwargs, hints)
67
+
68
+
69
+ hints_wrapper = HintsWrapper()
70
+
71
+
72
+ @hints_wrapper.py_impl(DispatchKey.CompositeExplicitAutograd)
73
+ def hints_wrapper_dense(body_fn, args, kwargs, hints):
74
+ return body_fn(*args, **kwargs)
75
+
76
+
77
+ hints_wrapper.py_autograd_impl(
78
+ autograd_not_implemented(hints_wrapper, deferred_error=True)
79
+ )
80
+
81
+
82
+ @hints_wrapper.py_impl(FakeTensorMode)
83
+ def hints_wrapper_fake_tensor_mode(mode, body_func, args, kwargs, hints):
84
+ flat_args = pytree.tree_leaves(args)
85
+ with mode:
86
+ return body_func(*flat_args, **kwargs)
87
+
88
+
89
+ @hints_wrapper.py_functionalize_impl
90
+ def hints_wrapper_functionalize(ctx, body_fn, args, kwargs, hints):
91
+ from torch._higher_order_ops.utils import _check_alias_and_mutation
92
+
93
+ unwrapped_args = ctx.unwrap_tensors(args)
94
+ unwrapped_kwargs = ctx.unwrap_tensors(kwargs)
95
+ unwrapped_hints = ctx.unwrap_tensors(hints)
96
+ with ctx.redispatch_to_next():
97
+ functional_body_fn = ctx.functionalize(body_fn)
98
+ pre_dispatch = hasattr(ctx, "mode") and ctx.mode.pre_dispatch
99
+ _check_alias_and_mutation(
100
+ body_fn, unwrapped_args, "hints_wrapper", pre_dispatch
101
+ )
102
+
103
+ outputs = hints_wrapper(
104
+ functional_body_fn,
105
+ unwrapped_args,
106
+ unwrapped_kwargs,
107
+ unwrapped_hints,
108
+ )
109
+ return ctx.wrap_tensors(outputs)
110
+
111
+
112
+ def trace_hints_wrapper(proxy_mode, hints_wrapper, body_fn, args, kwargs, hints):
113
+ flat_args = tuple(pytree.tree_leaves(args))
114
+ body_graph = reenter_make_fx(body_fn)(*flat_args, **kwargs)
115
+
116
+ _, body_graph_name = unique_graph_id(proxy_mode, prefix="hints_wrapper_body_graph")
117
+ proxy_mode.tracer.root.register_module(body_graph_name, body_graph)
118
+
119
+ new_args: tuple = (body_graph, flat_args, {})
120
+ # merge hints into kwargs
121
+ new_kwargs = {}
122
+ new_kwargs["hints"] = hints
123
+
124
+ proxy_args = pytree.tree_map(proxy_mode.tracer.unwrap_proxy, new_args)
125
+ proxy_kwargs = pytree.tree_map(proxy_mode.tracer.unwrap_proxy, new_kwargs)
126
+
127
+ out_proxy = proxy_mode.tracer.create_proxy(
128
+ "call_function", hints_wrapper, proxy_args, proxy_kwargs, name="hints_wrapper"
129
+ )
130
+
131
+ out = body_fn(*flat_args, **kwargs)
132
+ return track_tensor_tree(out, out_proxy, constant=None, tracer=proxy_mode.tracer)
133
+
134
+
135
+ @hints_wrapper.py_impl(ProxyTorchDispatchMode)
136
+ def inner(proxy_mode, body_fn, args, kwargs, hints):
137
+ if proxy_mode.enable_tracing:
138
+ return trace_hints_wrapper(
139
+ proxy_mode, hints_wrapper, body_fn, args, kwargs, hints
140
+ )
141
+ else:
142
+ return hints_wrapper(body_fn, args, kwargs, hints)
.venv/lib/python3.10/site-packages/torch/_higher_order_ops/invoke_leaf_function.py ADDED
@@ -0,0 +1,608 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import contextlib
2
+ import functools
3
+ from collections.abc import Callable, Generator, Sequence
4
+ from dataclasses import dataclass
5
+ from typing import Any, NamedTuple
6
+
7
+ import torch
8
+ import torch.utils._pytree as pytree
9
+ from torch._C import DispatchKey, DispatchKeySet
10
+ from torch._higher_order_ops.utils import register_fake
11
+ from torch._ops import HigherOrderOperator
12
+ from torch.autograd.graph import get_gradient_edge
13
+ from torch.fx.experimental.proxy_tensor import ProxyTorchDispatchMode, track_tensor_tree
14
+ from torch.nn.utils.stateless import _reparametrize_module
15
+
16
+ from .flat_apply import func_to_graphable
17
+
18
+
19
+ _leaf_function_module_retriever: Callable[[int], Any] | None = None
20
+
21
+
22
+ def set_leaf_function_module_retriever(retriever: Callable[[int], Any]) -> None:
23
+ global _leaf_function_module_retriever
24
+ _leaf_function_module_retriever = retriever
25
+
26
+
27
+ class LeafModuleState(NamedTuple):
28
+ """
29
+ In dynamo, nn.Module arguments to leaf functions are converted to this
30
+ pytree format (index, parameters, buffers). This structure is then
31
+ flattened to produce the actual inputs to invoke_leaf_function.
32
+
33
+ At runtime, the original module is reconstructed from it.
34
+ """
35
+
36
+ nn_module_index: int
37
+ named_parameters: dict[str, torch.nn.Parameter]
38
+ named_buffers: dict[str, torch.Tensor]
39
+
40
+
41
+ @dataclass
42
+ class GradientInfo:
43
+ """
44
+ We need the gradient edge to trigger the autograd engine backward.
45
+
46
+ We need the tensor metadata (size, stride, dtype, device) to create zeros when
47
+ gradient is None at runtime but required by the backward graph (because the graph
48
+ is traced with fake implementation).
49
+ """
50
+
51
+ edge: torch.autograd.graph.GradientEdge
52
+ size: torch.Size
53
+ stride: tuple[int, ...]
54
+ dtype: torch.dtype
55
+ device: torch.device
56
+
57
+
58
+ def unwrap_fn_spec(fn_spec: pytree.TreeSpec) -> Callable:
59
+ return pytree.tree_unflatten((), fn_spec)
60
+
61
+
62
+ def _retrieve_module_by_index(nn_module_index: int) -> torch.nn.Module:
63
+ if _leaf_function_module_retriever is None:
64
+ raise RuntimeError("Leaf function module retriever not set.")
65
+
66
+ mod = _leaf_function_module_retriever(nn_module_index)
67
+ if not isinstance(mod, torch.nn.Module):
68
+ raise TypeError(
69
+ f"Expected nn.Module at index {nn_module_index} for leaf function invocation, "
70
+ f"but got {type(mod).__name__}."
71
+ )
72
+ return mod
73
+
74
+
75
+ def check_escaped_gradients(
76
+ outputs: Any,
77
+ inputs: Sequence[Any],
78
+ requires_grad_indices: set[int],
79
+ ) -> None:
80
+ """
81
+ Check if autograd graph depends on tensors that not passed as explicit inputs.
82
+
83
+ Controlled by torch._dynamo.config.leaf_function_check_escaped_gradients.
84
+ """
85
+ if not requires_grad_indices:
86
+ return
87
+
88
+ import torch._dynamo.config as config
89
+
90
+ if not config.leaf_function_check_escaped_gradients:
91
+ return
92
+
93
+ input_nodes: set[torch.autograd.graph.Node] = set()
94
+ for i, inp in enumerate(inputs):
95
+ if (
96
+ isinstance(inp, torch.Tensor)
97
+ and i in requires_grad_indices
98
+ and inp.requires_grad
99
+ ):
100
+ edge = get_gradient_edge(inp)
101
+ if edge.node is not None:
102
+ input_nodes.add(edge.node)
103
+
104
+ flat_outputs = outputs if isinstance(outputs, tuple) else (outputs,)
105
+ start_nodes: set[torch.autograd.graph.Node] = {
106
+ out.grad_fn
107
+ for out in flat_outputs
108
+ if isinstance(out, torch.Tensor)
109
+ and out.requires_grad
110
+ and out.grad_fn is not None
111
+ }
112
+ if not start_nodes:
113
+ return
114
+
115
+ escaped: set[torch.autograd.graph.Node] = set()
116
+ visited: set[torch.autograd.graph.Node] = set()
117
+ stack = list(start_nodes)
118
+
119
+ while stack:
120
+ node = stack.pop()
121
+ if node in visited or node in input_nodes:
122
+ continue
123
+ visited.add(node)
124
+
125
+ for next_node, _ in node.next_functions:
126
+ if next_node is None or next_node in input_nodes:
127
+ continue
128
+ if not next_node.next_functions:
129
+ escaped.add(next_node)
130
+ else:
131
+ stack.append(next_node)
132
+
133
+ if escaped:
134
+ tensor_info = []
135
+ for node in escaped:
136
+ if hasattr(node, "variable"):
137
+ t = node.variable
138
+ tensor_info.append(
139
+ f" - Tensor(shape={list(t.shape)}, dtype={t.dtype})"
140
+ )
141
+ tensor_details = (
142
+ "\n".join(tensor_info) if tensor_info else " (tensor details unavailable)"
143
+ )
144
+
145
+ raise RuntimeError(
146
+ f"@leaf_function detected {len(escaped)} tensor(s) with requires_grad=True "
147
+ f"that are not passed as explicit inputs:\n{tensor_details}\n"
148
+ f"Gradients will not flow back to closure-captured or global tensors. "
149
+ f"Pass them as explicit arguments to the leaf function."
150
+ )
151
+
152
+
153
+ @contextlib.contextmanager
154
+ def reconstruct_original_args(
155
+ input_spec: pytree.TreeSpec | None, flat_args: tuple[Any, ...]
156
+ ) -> Generator[tuple[list[Any] | tuple[Any, ...], dict[str, Any]], None, None]:
157
+ if input_spec is None:
158
+ yield flat_args, {}
159
+ return
160
+
161
+ args, kwargs = pytree.tree_unflatten(flat_args, input_spec)
162
+
163
+ with contextlib.ExitStack() as stack:
164
+
165
+ def process_module_state(state: LeafModuleState) -> torch.nn.Module:
166
+ orig_module = _retrieve_module_by_index(state.nn_module_index)
167
+ stack.enter_context(
168
+ _reparametrize_module(
169
+ orig_module,
170
+ {**state.named_parameters, **state.named_buffers},
171
+ )
172
+ )
173
+ return orig_module
174
+
175
+ new_args, new_kwargs = pytree.tree_map_only(
176
+ LeafModuleState,
177
+ process_module_state,
178
+ (args, kwargs),
179
+ is_leaf=lambda x: isinstance(x, LeafModuleState),
180
+ )
181
+ yield new_args, new_kwargs
182
+
183
+
184
+ def autograd_grad_with_gradient_info(
185
+ output_infos: Sequence[GradientInfo | None],
186
+ input_infos: Sequence[GradientInfo | None],
187
+ grad_outputs: Sequence[Any] | None = None,
188
+ retain_graph: bool | None = None,
189
+ create_graph: bool = False,
190
+ allow_unused: bool = False,
191
+ ) -> tuple[torch.Tensor | None, ...]:
192
+ """
193
+ Compute gradients using GradientInfo, it additionally handles the case
194
+ where input and output infos are None.
195
+
196
+ Args:
197
+ output_infos: GradientInfo for each output (None if no grad_fn),
198
+ input_infos: GradientInfo for each input (None if not requires_grad)
199
+ grad_outputs: Gradients w.r.t. outputs
200
+
201
+ Returns a tuple of gradients with None for inputs that don't require grad.
202
+ """
203
+ filtered_output_edges = []
204
+ filtered_grad_outputs = []
205
+ for i, info in enumerate(output_infos):
206
+ if info is not None and info.edge.node is not None:
207
+ filtered_output_edges.append(info.edge)
208
+ if grad_outputs is not None:
209
+ filtered_grad_outputs.append(grad_outputs[i])
210
+
211
+ filtered_input_edges = []
212
+ filtered_input_infos = []
213
+ input_indices = []
214
+ for i, info in enumerate(input_infos):
215
+ if info is not None:
216
+ filtered_input_edges.append(info.edge)
217
+ filtered_input_infos.append(info)
218
+ input_indices.append(i)
219
+
220
+ if not filtered_output_edges or not filtered_input_edges:
221
+ return tuple(None for _ in input_infos)
222
+
223
+ grads = torch.autograd.grad(
224
+ outputs=filtered_output_edges,
225
+ inputs=filtered_input_edges,
226
+ grad_outputs=filtered_grad_outputs if grad_outputs is not None else None,
227
+ retain_graph=retain_graph,
228
+ create_graph=create_graph,
229
+ allow_unused=allow_unused,
230
+ )
231
+
232
+ # Reconstruct full gradient tuple with Nones at proper positions.
233
+ #
234
+ # NB: For unused inputs that require grad, we return zeros instead of None.
235
+ # This is necessary because during AOT tracing, we use fake_impl to determine
236
+ # the backward graph structure. fake_impl may not accurately reflect which
237
+ # inputs are truly used for gradients in real_impl. For example, users often
238
+ # write fake_impl by returning torch.empty_like(input) to get the right shape
239
+ # without actually using the input in a differentiable computation. So we must
240
+ # be permissive and assume all inputs with requires_grad=True could need
241
+ # gradients. When multiple invoke_leaf_function calls share an input (e.g.,
242
+ # a module's forward + hook both receiving the same tensor), the traced
243
+ # backward graph generates explicit add operations to accumulate their
244
+ # gradients. At runtime, if one leaf function doesn't actually use the input,
245
+ # autograd.grad returns None for it, and the traced add(grad1, grad2) fails
246
+ # because one operand is None. Returning zeros ensures the add always works.
247
+ result: list[torch.Tensor | None] = [None] * len(input_infos)
248
+ for filtered_idx, original_idx in enumerate(input_indices):
249
+ grad = grads[filtered_idx]
250
+ if grad is None:
251
+ info = filtered_input_infos[filtered_idx]
252
+ grad = torch.empty_strided(
253
+ info.size, info.stride, dtype=info.dtype, device=info.device
254
+ ).zero_()
255
+ result[original_idx] = grad
256
+
257
+ return tuple(result)
258
+
259
+
260
+ def _make_forward(
261
+ fn: Callable,
262
+ requires_grad_indices: set[int],
263
+ include_keys: DispatchKeySet,
264
+ exclude_keys: DispatchKeySet,
265
+ ) -> tuple[Callable, dict[str, Any]]:
266
+ state: dict[str, Any] = {"inputs": None, "outputs": None}
267
+
268
+ @functools.wraps(fn)
269
+ def forward(*flat_args):
270
+ # Detach all tensor inputs to isolate from external autograd context
271
+ flat_args = [
272
+ arg.detach() if isinstance(arg, torch.Tensor) else arg for arg in flat_args
273
+ ]
274
+
275
+ # Restore requires_grad state that was captured at tracing time.
276
+ # We need this because at runtime with aot_eager, the forward graph
277
+ # runs inside autograd.Function.forward(), which is a no-grad context.
278
+ # This means intermediate tensors can lose their requires_grad status
279
+ # by the time they reach invoke_leaf_function, even though they had it
280
+ # during tracing.
281
+ inputs = [
282
+ arg.requires_grad_(True)
283
+ if isinstance(arg, torch.Tensor) and idx in requires_grad_indices
284
+ else arg
285
+ for idx, arg in enumerate(flat_args)
286
+ ]
287
+
288
+ # NB: we capture dispatch keys at creation time (during tracing), where PythonDispatcher
289
+ # is active, but at runtime it's not so we remove it from the effective keys.
290
+ effective_keys = include_keys
291
+ if include_keys.has(DispatchKey.PythonDispatcher):
292
+ effective_keys = include_keys.remove(DispatchKey.PythonDispatcher)
293
+ with torch._C._ForceDispatchKeyGuard(effective_keys, exclude_keys):
294
+ with torch.enable_grad():
295
+ outputs = fn(*inputs)
296
+
297
+ check_escaped_gradients(outputs, inputs, requires_grad_indices)
298
+
299
+ state["inputs"] = tuple(
300
+ GradientInfo(
301
+ edge=get_gradient_edge(inp),
302
+ size=inp.size(),
303
+ stride=inp.stride(),
304
+ dtype=inp.dtype,
305
+ device=inp.device,
306
+ )
307
+ if isinstance(inp, torch.Tensor) and inp.requires_grad
308
+ else None
309
+ for inp in inputs
310
+ )
311
+
312
+ if outputs is None:
313
+ state["outputs"] = ()
314
+ else:
315
+ state["outputs"] = tuple(
316
+ GradientInfo(
317
+ edge=get_gradient_edge(out),
318
+ size=out.size(),
319
+ stride=out.stride(),
320
+ dtype=out.dtype,
321
+ device=out.device,
322
+ )
323
+ if isinstance(out, torch.Tensor)
324
+ and out.requires_grad
325
+ and out.grad_fn is not None
326
+ else None
327
+ for out in outputs
328
+ )
329
+
330
+ return pytree.tree_map_only(
331
+ torch.Tensor,
332
+ lambda t: t.detach().requires_grad_(t.requires_grad),
333
+ outputs,
334
+ )
335
+
336
+ return forward, state
337
+
338
+
339
+ class InvokeLeafFunction(HigherOrderOperator):
340
+ def __init__(self):
341
+ super().__init__("invoke_leaf_function")
342
+
343
+ def __call__(self, real_fn_spec, fake_fn_spec, *flat_args):
344
+ """
345
+ real_fn_spec: pytree.TreeSpec for the real function that's wrapped in dynamo
346
+ fake_fn_spec: pytree.TreeSpec for the fake function that's wrapped in dynamo
347
+ """
348
+ return super().__call__(real_fn_spec, fake_fn_spec, *flat_args) # type: ignore[attr-defined]
349
+
350
+ # pyrefly: ignore [bad-override]
351
+ def gen_schema(self, real_fn_spec, fake_fn_spec, *flat_args):
352
+ from torch._higher_order_ops.schema import HopSchemaGenerator
353
+ from torch._higher_order_ops.utils import _maybe_fake_prop_ignore_unbacked
354
+
355
+ fake_fn = unwrap_fn_spec(fake_fn_spec)
356
+ fake_outputs = _maybe_fake_prop_ignore_unbacked(fake_fn, flat_args)
357
+
358
+ gen = HopSchemaGenerator(self)
359
+ gen.add_arg("real_fn_spec", real_fn_spec)
360
+ gen.add_arg("fake_fn_spec", fake_fn_spec)
361
+ for i, arg in enumerate(flat_args):
362
+ gen.add_arg(f"arg{i}", arg)
363
+
364
+ if isinstance(fake_outputs, tuple):
365
+ for out in fake_outputs:
366
+ gen.add_output(out)
367
+ else:
368
+ if fake_outputs is not None:
369
+ raise AssertionError(
370
+ f"Expected fake_outputs to be a tuple or None, got {type(fake_outputs)}"
371
+ )
372
+ gen.add_output(fake_outputs)
373
+
374
+ return gen.gen_schema()
375
+
376
+
377
+ invoke_leaf_function = InvokeLeafFunction()
378
+
379
+
380
+ # NOTE: [Autograd support for invoke_leaf_function]
381
+ #
382
+ # The oveerall idea is that when the real forward executes, we are going to build an autograd graph
383
+ # and save it. When the real backward executes, we are going to invoke the autograd graph.
384
+ # We need to build these "real_forward" and "real_backward" functions from the "real_fn".
385
+ #
386
+ # Inputs:
387
+ # real_fn_spec/fake_fn_spec are pytree.TreeSpecs that contain real_fn and fake_fn.
388
+ # These functions were created in dynamo by wrapping the user's original leaf function and fake function:
389
+ # - They accept *flat_args (flattened LeafModuleState objects + other args)
390
+ # - They unflatten flat_args and convert LeafModuleState back to nn.Modules
391
+ # - They call the user's original leaf function with the reconstructed args
392
+ # - They return the user function's outputs
393
+ #
394
+ # We wrap real_fn (via _make_forward) to handle autograd properly:
395
+ # 1. Detach inputs and outputs to isolate the leaf function's autograd graph from the
396
+ # outer graph (gradients flow through our backward, not internal ops)
397
+ # 2. Real function is invoked at backend dispatch keys (i.e. CompositeExplicitAutograd)
398
+ # where autograd is disabled. We re-enable grad and restore dispatch keys for the autograd engine to work.
399
+ # 3. Store GradientInfo (gradient edges + tensor metadata) instead of full tensors for backward,
400
+ # which is sufficient for autograd.grad and avoids keeping tensors alive.
401
+ #
402
+ # We automatically generate backward functions:
403
+ # - real_backward uses the stored input/output GradientInfo and invokes the autograd engine
404
+ # - fake_backward creates empty gradients for inputs that requires grad
405
+
406
+
407
+ class InvokeLeafFunctionAutogradOp(torch.autograd.Function):
408
+ @staticmethod
409
+ # pyrefly: ignore [bad-override]
410
+ def forward(ctx, real_fn_spec, fake_fn_spec, *flat_args):
411
+ real_fn = unwrap_fn_spec(real_fn_spec)
412
+
413
+ include_keys = torch._C._dispatch_tls_local_include_set()
414
+ exclude_keys = torch._C._dispatch_tls_local_exclude_set()
415
+
416
+ requires_grad_indices = {
417
+ i
418
+ for i, arg in enumerate(flat_args)
419
+ if isinstance(arg, torch.Tensor) and arg.requires_grad
420
+ }
421
+
422
+ real_forward, real_state = _make_forward(
423
+ real_fn, requires_grad_indices, include_keys, exclude_keys
424
+ )
425
+
426
+ def real_backward(*grads):
427
+ if real_state["inputs"] is None or real_state["outputs"] is None:
428
+ raise RuntimeError(
429
+ "invoke_leaf_function backward expects inputs/outputs to be set in forward."
430
+ )
431
+ return autograd_grad_with_gradient_info(
432
+ output_infos=real_state["outputs"],
433
+ input_infos=real_state["inputs"],
434
+ grad_outputs=grads,
435
+ allow_unused=True,
436
+ )
437
+
438
+ input_infos_for_fake = tuple(
439
+ GradientInfo(
440
+ edge=None, # type: ignore[arg-type]
441
+ size=arg.size(),
442
+ stride=arg.stride(),
443
+ dtype=arg.dtype,
444
+ device=arg.device,
445
+ )
446
+ if isinstance(arg, torch.Tensor) and arg.requires_grad
447
+ else None
448
+ for arg in flat_args
449
+ )
450
+
451
+ def fake_backward(*grads):
452
+ return tuple(
453
+ torch.empty_strided(
454
+ info.size, info.stride, dtype=info.dtype, device=info.device
455
+ )
456
+ if info is not None
457
+ else None
458
+ for info in input_infos_for_fake
459
+ )
460
+
461
+ _, new_real_fn_spec = func_to_graphable(real_forward)
462
+
463
+ with torch._C._AutoDispatchBelowAutograd():
464
+ fw_outputs = invoke_leaf_function(
465
+ new_real_fn_spec, fake_fn_spec, *flat_args
466
+ )
467
+
468
+ ctx.real_backward = real_backward
469
+ ctx.fake_backward = fake_backward
470
+
471
+ return fw_outputs
472
+
473
+ @staticmethod
474
+ # pyrefly: ignore [bad-override]
475
+ def backward(ctx, *grads):
476
+ _, real_bw_spec = func_to_graphable(ctx.real_backward)
477
+ _, fake_bw_spec = func_to_graphable(ctx.fake_backward)
478
+ fw_grads = invoke_leaf_function(real_bw_spec, fake_bw_spec, *grads)
479
+ return None, None, *fw_grads
480
+
481
+
482
+ @invoke_leaf_function.py_autograd_impl
483
+ def invoke_leaf_function_autograd(real_fn_spec, fake_fn_spec, *flat_args):
484
+ return InvokeLeafFunctionAutogradOp.apply(real_fn_spec, fake_fn_spec, *flat_args)
485
+
486
+
487
+ # TODO: allow user annotated mutation and aliasing info
488
+ @invoke_leaf_function.py_functionalize_impl
489
+ def invoke_leaf_function_functionalization(ctx, *all_args):
490
+ from torch._higher_order_ops.effects import handle_effects
491
+
492
+ return handle_effects(
493
+ ctx.mode._allow_token_discovery,
494
+ ctx.mode._tokens,
495
+ invoke_leaf_function,
496
+ all_args,
497
+ {},
498
+ )
499
+
500
+
501
+ @invoke_leaf_function.py_impl(ProxyTorchDispatchMode)
502
+ def invoke_leaf_function_proxy_mode(proxy_mode, *all_args):
503
+ out = invoke_leaf_function(*all_args)
504
+ proxies = pytree.tree_map(proxy_mode.tracer.unwrap_proxy, all_args)
505
+ proxy = proxy_mode.tracer.create_proxy(
506
+ "call_function", invoke_leaf_function, proxies, {}
507
+ )
508
+ return track_tensor_tree(out, proxy, constant=None, tracer=proxy_mode.tracer)
509
+
510
+
511
+ def _validate_outputs_match(
512
+ fake_output: Any,
513
+ real_output: Any,
514
+ ) -> None:
515
+ """
516
+ Validate that fake_fn and real_fn outputs have matching pytree structure,
517
+ shapes, and dtypes.
518
+
519
+ Raises:
520
+ RuntimeError: If outputs don't match with detailed error message.
521
+ """
522
+ fake_flat, fake_spec = pytree.tree_flatten(fake_output)
523
+ real_flat, real_spec = pytree.tree_flatten(real_output)
524
+
525
+ if fake_spec != real_spec:
526
+ raise RuntimeError(
527
+ f"Output structure mismatch in @leaf_function decorator.\n"
528
+ f"fake_impl returned structure: {fake_spec}\n"
529
+ f"real_impl returned structure: {real_spec}\n"
530
+ f"The fake_impl must return outputs with the same pytree structure as real_impl."
531
+ )
532
+
533
+ if len(fake_flat) != len(real_flat):
534
+ raise RuntimeError(
535
+ f"Output count mismatch in @leaf_function decorator.\n"
536
+ f"fake_impl returned {len(fake_flat)} values\n"
537
+ f"real_impl returned {len(real_flat)} values"
538
+ )
539
+
540
+ for i, (fake_val, real_val) in enumerate(zip(fake_flat, real_flat)):
541
+ fake_is_tensor = isinstance(fake_val, torch.Tensor)
542
+ real_is_tensor = isinstance(real_val, torch.Tensor)
543
+
544
+ if fake_is_tensor != real_is_tensor:
545
+ raise RuntimeError(
546
+ f"Output type mismatch at position {i} in @leaf_function decorator.\n"
547
+ f"fake_impl returned: {type(fake_val).__name__}\n"
548
+ f"real_impl returned: {type(real_val).__name__}"
549
+ )
550
+
551
+ if fake_is_tensor:
552
+ if fake_val.shape != real_val.shape:
553
+ raise RuntimeError(
554
+ f"Shape mismatch at output position {i} in @leaf_function decorator.\n"
555
+ f"fake_impl output shape: {list(fake_val.shape)}\n"
556
+ f"real_impl output shape: {list(real_val.shape)}\n"
557
+ f"The fake_impl must produce tensors with the same shapes as real_impl."
558
+ )
559
+
560
+ if fake_val.dtype != real_val.dtype:
561
+ raise RuntimeError(
562
+ f"Dtype mismatch at output position {i} in @leaf_function decorator.\n"
563
+ f"fake_impl output dtype: {fake_val.dtype}\n"
564
+ f"real_impl output dtype: {real_val.dtype}\n"
565
+ f"The fake_impl must produce tensors with the same dtypes as real_impl."
566
+ )
567
+
568
+
569
+ def _check_no_input_mutation(
570
+ flat_args: tuple[Any, ...],
571
+ version_before: list[int],
572
+ ) -> None:
573
+ for i, arg in enumerate(flat_args):
574
+ if isinstance(arg, torch.Tensor):
575
+ if arg._version != version_before[i]:
576
+ raise RuntimeError(
577
+ f"In-place mutation detected on input tensor at position {i} "
578
+ f"(in the pytree-flattened inputs with nn.Module states expanded) in "
579
+ f"@leaf_function. In-place mutations on inputs are not supported yet."
580
+ f"Consider cloning the input before mutating it."
581
+ )
582
+
583
+
584
+ @register_fake(invoke_leaf_function)
585
+ def invoke_leaf_function_fake(real_fn_spec, fake_fn_spec, *flat_args):
586
+ fake_fn = unwrap_fn_spec(fake_fn_spec)
587
+ return fake_fn(*flat_args)
588
+
589
+
590
+ @invoke_leaf_function.py_impl(DispatchKey.CompositeExplicitAutograd)
591
+ def invoke_leaf_function_dense(real_fn_spec, fake_fn_spec, *flat_args):
592
+ from torch._dynamo import config as dynamo_config
593
+
594
+ version_before = [
595
+ arg._version if isinstance(arg, torch.Tensor) else 0 for arg in flat_args
596
+ ]
597
+
598
+ real_fn = unwrap_fn_spec(real_fn_spec)
599
+ real_output = real_fn(*flat_args)
600
+
601
+ _check_no_input_mutation(flat_args, version_before)
602
+
603
+ if dynamo_config.leaf_function_validate_outputs:
604
+ fake_fn = unwrap_fn_spec(fake_fn_spec)
605
+ fake_output = fake_fn(*flat_args)
606
+ _validate_outputs_match(fake_output, real_output)
607
+
608
+ return real_output
.venv/lib/python3.10/site-packages/torch/_higher_order_ops/invoke_subgraph.py ADDED
@@ -0,0 +1,1063 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+
3
+ import contextlib
4
+ import copy
5
+ import functools
6
+ from collections import defaultdict
7
+ from collections.abc import Callable
8
+ from contextlib import nullcontext
9
+ from dataclasses import dataclass, field
10
+ from typing import Any, Optional, Union
11
+
12
+ import torch
13
+ import torch.utils._pytree as pytree
14
+ from torch._C import DispatchKey
15
+ from torch._dispatch.python import suspend_functionalization
16
+ from torch._higher_order_ops.utils import (
17
+ _from_fun,
18
+ _maybe_reenter_make_fx,
19
+ clone_outputs_aliasing_inputs,
20
+ FunctionalizeCtxWrapper,
21
+ get_dummy_aot_autograd_config,
22
+ HopInstance,
23
+ prepare_fw_with_masks,
24
+ redirect_to_mode,
25
+ reenter_make_fx,
26
+ register_fake,
27
+ save_values_for_backward,
28
+ saved_values,
29
+ )
30
+ from torch._library.fake_class_registry import FakeScriptObject
31
+ from torch._library.opaque_object import is_opaque_type
32
+ from torch._ops import HigherOrderOperator
33
+ from torch._subclasses.functional_tensor import disable_functional_mode
34
+ from torch.fx.experimental.proxy_tensor import (
35
+ disable_proxy_modes_tracing,
36
+ ProxyTorchDispatchMode,
37
+ track_tensor_tree,
38
+ )
39
+ from torch.fx.graph_module import GraphModule
40
+ from torch.fx.passes.runtime_assert import insert_deferred_runtime_asserts
41
+ from torch.utils._debug_mode import DebugMode
42
+ from torch.utils.checkpoint import _CachedTorchDispatchMode, _CachingTorchDispatchMode
43
+
44
+
45
+ invoke_subgraph_counter = 0
46
+
47
+
48
+ # During the tracing of the joint graph, we construct this information. This is
49
+ # used to filter out grad_outs/tangents in the `backward` method of
50
+ # InvokeSubgraphAutogradOp.
51
+ @dataclass
52
+ class OutputMetadata:
53
+ num_fw_outs: Optional[int] = None
54
+ indexes_with_symint: set[int] = field(default_factory=set)
55
+ indexes_with_no_grad: set[int] = field(default_factory=set)
56
+
57
+
58
+ # This config will be stored in invoke_subgraph HOP node.meta["custom"]["nested_region_config"]
59
+ # as well as the subgraph's gm.meta["nested_region_config"].
60
+ @dataclass
61
+ class NestedCompileRegionOptions:
62
+ # A Callable that takes (gm, example_inputs, decompositions=None, **kwargs) as inputs.
63
+ # Returns AOTCompiledArtifact
64
+ fw_compiler: Optional[Callable] = None
65
+ bw_compiler: Optional[Callable] = None
66
+
67
+ # Note: [InvokeSubgraphHOP Partitioner]
68
+ # If not None, add "partitioner" to HOP node meta.
69
+ # If Callable, directly assign the callable, but the callable cannot be pickled
70
+ # If str, the options are "default_partition" and "min_cut_rematerialization_partition".
71
+ # The HOP joint graph will be partitioned using the corresponding functions in
72
+ # torch/_functorch/partitioners.py
73
+ partitioner: Optional[Callable | str] = None
74
+
75
+ # If it's None, we'll inherit the parent call's decompositions.
76
+ # Otherwise, the nested region will use this decompositions.
77
+ decompositions: Optional[dict[str, Any]] = None
78
+
79
+
80
+ def _extract_nested_region_config(fn):
81
+ """
82
+ Extract the NestedCompileRegionOptions from the HOP subgraph gm.meta["nested_region_config"]
83
+ """
84
+ gm_to_compile = None
85
+ if isinstance(fn, torch.fx.GraphModule):
86
+ gm_to_compile = fn
87
+ elif isinstance(fn, FunctionalizeCtxWrapper):
88
+ gm_to_compile = fn.subgraph
89
+
90
+ if (
91
+ isinstance(gm_to_compile, torch.fx.GraphModule)
92
+ and hasattr(gm_to_compile, "meta")
93
+ and "nested_region_config" in gm_to_compile.meta
94
+ ):
95
+ if isinstance(
96
+ gm_to_compile.meta["nested_region_config"], NestedCompileRegionOptions
97
+ ):
98
+ return gm_to_compile.meta["nested_region_config"].decompositions
99
+ return None
100
+
101
+
102
+ class InvokeSubgraphHOP(HigherOrderOperator):
103
+ def __init__(self) -> None:
104
+ # Invoke subgraph does not have any state, it is just a wrapper over a
105
+ # subgraph, so we can safely cache the HOP.
106
+ super().__init__("invoke_subgraph", cacheable=True)
107
+ # This is used by the fake tensor cache key validator to extract the
108
+ # subgraph and iterate over the nodes to find if all nodes are fake
109
+ # tensor cacheable.
110
+ self.subgraph_indexes = [
111
+ 0,
112
+ ]
113
+
114
+ # identifier is setup by upper part of the stack. This helps us in
115
+ # identifying two invoke_subgraph calls have same subgraph.
116
+ def __call__(
117
+ self,
118
+ subgraph: Union[GraphModule, FunctionalizeCtxWrapper],
119
+ identifier: Optional[str],
120
+ *operands,
121
+ ):
122
+ if identifier is not None and not isinstance(identifier, str):
123
+ raise AssertionError(
124
+ f"identifier must be None or a string, got {type(identifier)}"
125
+ )
126
+
127
+ if not all(
128
+ isinstance(
129
+ o, (torch.Tensor, int, torch.SymInt, torch.Generator, FakeScriptObject)
130
+ )
131
+ or is_opaque_type(type(o))
132
+ for o in operands
133
+ if o is not None
134
+ ):
135
+ raise AssertionError(
136
+ f"invoke_subgraph operands must be a list of tensors/ints/SymInts/Generator, got {operands}"
137
+ )
138
+
139
+ # pyrefly: ignore [missing-attribute]
140
+ return super().__call__(subgraph, identifier, *operands)
141
+
142
+ # pyrefly: ignore [bad-override]
143
+ def gen_schema(self, subgraph, identifier, *operands):
144
+ from torch._higher_order_ops.schema import HopSchemaGenerator
145
+ from torch._higher_order_ops.utils import (
146
+ check_input_alias_and_mutation_return_outputs,
147
+ materialize_as_graph,
148
+ )
149
+
150
+ subgraph_decomp_table = _extract_nested_region_config(subgraph)
151
+ gm: torch.fx.GraphModule = materialize_as_graph(
152
+ subgraph, operands, subgraph_decomp_table=subgraph_decomp_table
153
+ )
154
+
155
+ schema_gen = HopSchemaGenerator(self)
156
+ schema_gen.add_arg("subgraph", gm)
157
+ schema_gen.add_arg("identifier", identifier)
158
+ (
159
+ _,
160
+ _,
161
+ _,
162
+ mutated_inputs,
163
+ outputs,
164
+ ) = check_input_alias_and_mutation_return_outputs(gm)
165
+ for idx, arg in enumerate(operands):
166
+ schema_gen.add_arg(f"arg{idx}", arg, is_mutated=idx in mutated_inputs)
167
+ for out in outputs:
168
+ schema_gen.add_output(out)
169
+
170
+ return schema_gen.gen_schema()
171
+
172
+
173
+ invoke_subgraph = InvokeSubgraphHOP()
174
+
175
+
176
+ def invoke_subgraph_infer(
177
+ subgraph: Union[GraphModule, FunctionalizeCtxWrapper],
178
+ *operands,
179
+ ):
180
+ """Inference-only entrypoint for invoke_subgraph that auto-generates identifier.
181
+
182
+ This is intended for use cases where we are building an inference graph and
183
+ don't need the forward/backward caching that requires a stable identifier.
184
+ The identifier is automatically computed based on the current proxy mode's
185
+ tracer state.
186
+
187
+ If no proxy mode is active, the subgraph is called directly.
188
+ """
189
+ from torch.fx.experimental.proxy_tensor import get_proxy_mode
190
+
191
+ proxy_mode = get_proxy_mode()
192
+ if proxy_mode is None:
193
+ # No tracing active, just call the subgraph directly
194
+ if getattr(subgraph, "_boxed_call", False):
195
+ return subgraph(list(operands))
196
+ else:
197
+ return subgraph(*operands)
198
+
199
+ from torch._dynamo.utils import get_unique_name_wrt
200
+
201
+ # How exactly should we allocate names for the HOP invoke_subgraph we
202
+ # are going to put into the graph? This is a bit tricky. In the
203
+ # original design of invoke_subgraph, this HOP never shows up in the
204
+ # wild: it is only generated Dynamo, so Dynamo can take sure of
205
+ # ensuring it picks unique names in the context of the particular
206
+ # Dynamo compilation. However, these invoke_subgraph are different:
207
+ # they live as Dynamo compiled code that can potentially get traced
208
+ # multiple times! If they get retraced several times in the same
209
+ # trace, deduplication occurs; but if I make_fx a function f once,
210
+ # and then do a separate new trace, there's no relationship between
211
+ # these. Additionally, we also want the name we put in the graph to
212
+ # be deterministic, and for it to be indifferent to how many
213
+ # unrelated invoke_subgraphs/make_fxs we've done, prior to THIS
214
+ # particular make_fx.
215
+ #
216
+ # To satisfy all of these constraints, it's impossible to preallocate
217
+ # a name before tracing actually goes through us (since those names
218
+ # would have to all be unique even if a subgraph never gets used.)
219
+ # So we allocate the subgraph a fresh name PER proxy mode, and then
220
+ # consistently reuse it if it hits again.
221
+ #
222
+ # Note we do NOT do equality comparison subgraph, since it has
223
+ # reference equality semantics.
224
+
225
+ if subgraph in proxy_mode._invoke_subgraph_cache:
226
+ name = proxy_mode._invoke_subgraph_cache[subgraph]
227
+ else:
228
+ name = get_unique_name_wrt(
229
+ "invoke_subgraph",
230
+ proxy_mode._invoke_subgraph_names,
231
+ requires_suffix=True,
232
+ )
233
+ proxy_mode._invoke_subgraph_names.add(name)
234
+ proxy_mode._invoke_subgraph_cache[subgraph] = name
235
+
236
+ return invoke_subgraph(subgraph, name, *operands)
237
+
238
+
239
+ # Registers dispatches for SAC
240
+ redirect_to_mode(invoke_subgraph, _CachingTorchDispatchMode)
241
+ redirect_to_mode(invoke_subgraph, _CachedTorchDispatchMode)
242
+
243
+
244
+ def invoke_subgraph_placeholder(func, *args, **kwargs):
245
+ if torch.compiler.is_dynamo_compiling():
246
+ # This is just a placeholder for Dynamo to replace with invoke_subgraph
247
+ raise RuntimeError("invoke_subgraph should not be called directly in Dynamo")
248
+
249
+ if torch.compiler.is_compiling():
250
+ # For non-strict export tracing, we still want to go through Dynamo
251
+
252
+ def _invoke_subgraph_placeholder_wrapper(func, args):
253
+ return invoke_subgraph_placeholder(func, *args)
254
+
255
+ from torch._higher_order_ops.utils import setup_compilation_env
256
+
257
+ with setup_compilation_env() as backend:
258
+ return torch.compile(
259
+ _invoke_subgraph_placeholder_wrapper,
260
+ backend=backend,
261
+ fullgraph=True,
262
+ )(func, args)
263
+
264
+ return func(*args, **kwargs)
265
+
266
+
267
+ def mark_compile_region(fn=None, options: Optional[NestedCompileRegionOptions] = None):
268
+ """
269
+ This wrapper instructs torch.compile to compile the wrapped region once and
270
+ reuse the compiled artifact, instead of the usual way of aggressively
271
+ inlining the function.
272
+
273
+ Under the hood, it tells TorchDynamo to use InvokeSubgraph HOP for the
274
+ region. For PyTorch eager, this is a no-op.
275
+
276
+ Args:
277
+ fn: The function to wrap
278
+ options: Optional config to use for compiling the subgraph.
279
+ Warning: this is an experimental feature under development and
280
+ not ready for use yet.
281
+ """
282
+
283
+ def wrap(func):
284
+ def inner(*args, **kwargs):
285
+ # Get the innermost function to avoid nested compile regions
286
+ inner_func = func
287
+ while hasattr(inner_func, "__marked_compile_region_fn__"):
288
+ inner_func = inner_func.__marked_compile_region_fn__
289
+ return invoke_subgraph_placeholder(inner_func, *args, **kwargs)
290
+
291
+ inner.__marked_compile_region_fn__ = func # type: ignore[attr-defined]
292
+ func.__marked_compile_region_config__ = options # type: ignore[attr-defined]
293
+
294
+ return inner
295
+
296
+ if fn:
297
+ return wrap(fn)
298
+ else:
299
+ return wrap
300
+
301
+
302
+ def get_invoke_subgraph_cache():
303
+ cache = None
304
+ if tracing_ctx := torch._guards.TracingContext.try_get():
305
+ cache = tracing_ctx.hop_dispatch_set_cache.get_cache(invoke_subgraph)
306
+ return cache
307
+
308
+
309
+ # TODO (@anijain2305) - Delete this function when base_hop uses invoke_subgraph infra
310
+ def trace_joint_graph(fn, fw_inputs, fw_outputs):
311
+ """
312
+ Naively trace out a joint graph. This simplifies the reconstruction of joint
313
+ graph in the min-cut partitioner later on.
314
+ """
315
+ from torch._functorch.aot_autograd import create_joint
316
+
317
+ dummy_aot_config = get_dummy_aot_autograd_config()
318
+
319
+ # This joint_fn is inserted as the backward graph as is. This simplifies the
320
+ # min-cut partitioner work later on.
321
+ # Input signature - (*primals, *tangents)
322
+ # Output signature - (*grads, *fw_outs)
323
+ # The output signature is deliberately kept grads first and fw_outs second.
324
+ # Having grads first makes the min-cut partitioner HOP graph stitching
325
+ # easier.
326
+ def joint_fn(*primals_and_tangents):
327
+ primals = primals_and_tangents[: len(fw_inputs)]
328
+ tangents = primals_and_tangents[len(fw_inputs) :]
329
+
330
+ fw_outs, grads = create_joint(
331
+ prepare_fw_with_masks(fn), aot_config=dummy_aot_config
332
+ )(primals, tangents)
333
+
334
+ maybe_clone = clone_outputs_aliasing_inputs(primals_and_tangents)
335
+
336
+ # return signature is deliberately kept (*grads, *fw_outs). This
337
+ # simplifies partitioning work later on.
338
+ return pytree.tree_map(maybe_clone, tuple(grads + list(fw_outs)))
339
+
340
+ primals = list(fw_inputs)
341
+ # This assumes that the tangent strides match fw_outputs strides. Check the
342
+ # InvokeSubgraphAutogradOp backward op for the contiguous call.
343
+ tangents = [_from_fun(out) for out in fw_outputs]
344
+
345
+ joint_operands = primals + tangents
346
+
347
+ return _maybe_reenter_make_fx(joint_fn)(*joint_operands)
348
+
349
+
350
+ # TODO (@anijain2305) - Delete this function when base_hop uses invoke_subgraph infra
351
+ def create_fw_bw_graph(subgraph, operands, grad_outputs=None):
352
+ with suspend_functionalization(), disable_functional_mode():
353
+ with disable_proxy_modes_tracing():
354
+ # args are functional tensors, generate some example tensors
355
+ fw_inputs = pytree.tree_map(_from_fun, operands)
356
+
357
+ from torch._guards import detect_fake_mode
358
+
359
+ fake_mode = detect_fake_mode(fw_inputs)
360
+ context = (
361
+ nullcontext()
362
+ if fake_mode is None or fake_mode.shape_env is None
363
+ else fake_mode.shape_env.ignore_fresh_unbacked_symbols()
364
+ )
365
+
366
+ with context:
367
+ fw_outs = pytree.tree_map(_from_fun, subgraph(*fw_inputs))
368
+
369
+ num_fw_outs = len(fw_outs)
370
+
371
+ # Collect the indexes of none in the output to check that the grad
372
+ # is None at the corresponding index in the backward. This check is
373
+ # performed in the autograd.Function - InvokeSubgraphAutogradOp.
374
+ # Also collect the indexes of no_grad in the output to filter out
375
+ # the grad_outs in the `backward` method.
376
+ output_metadata = OutputMetadata()
377
+
378
+ output_metadata.num_fw_outs = num_fw_outs
379
+ for idx, fw_out in enumerate(fw_outs):
380
+ if isinstance(fw_out, torch.SymInt):
381
+ output_metadata.indexes_with_symint.add(idx)
382
+ elif not fw_out.requires_grad:
383
+ output_metadata.indexes_with_no_grad.add(idx)
384
+
385
+ if grad_outputs is None:
386
+ # Infer grad_outputs to be the same properties as the fw_outputs
387
+ # if they're not passed in
388
+ # Although fw_outs are equivalent to grad_outputs for tracing
389
+ # purposes, we have to carefully handle the None and fw_out that do
390
+ # not have require_grad. At those indexes, we will have None in the
391
+ # backward graph.
392
+ grad_outputs = fw_outs
393
+ grad_outputs = [grad for grad in grad_outputs if grad is not None]
394
+ grad_outputs = [grad for grad in grad_outputs if grad.requires_grad]
395
+
396
+ # Force grad_out to be contiguous. This is because at runtime,
397
+ # grad_out could have different strides than fw_outs. So, we
398
+ # force the grad_outs to be contiguous for both tracing and
399
+ # runtime.
400
+ grad_outputs = [grad.contiguous() for grad in grad_outputs]
401
+
402
+ if any(
403
+ not isinstance(out, torch.Tensor)
404
+ for out in grad_outputs
405
+ if out is not None
406
+ ):
407
+ raise RuntimeError(
408
+ "Expect outputs of invoke_subgraph to only contains tensors or None. "
409
+ f"Got types {[type(out) for out in grad_outputs]}."
410
+ )
411
+
412
+ # Trace the forward subgraph
413
+ fw_graph = _maybe_reenter_make_fx(subgraph)(*fw_inputs)
414
+
415
+ # Trace the joint graph and assign it to the bwd graph
416
+ bw_graph = trace_joint_graph(
417
+ subgraph,
418
+ fw_inputs,
419
+ grad_outputs,
420
+ )
421
+ return fw_graph, bw_graph, output_metadata
422
+
423
+
424
+ def get_output_metadata(subgraph, *operands):
425
+ """
426
+ Extract metadata about the subgraph outputs WITHOUT executing the subgraph.
427
+ This avoids running side-effectful operations twice (once here, once in forward).
428
+ We analyze the graph structure statically to extract metadata.
429
+ """
430
+ # Unwrap FunctionalizeCtxWrapper if present
431
+ if isinstance(subgraph, FunctionalizeCtxWrapper):
432
+ subgraph = subgraph.subgraph
433
+
434
+ # If not a GraphModule, fall back to execution-based metadata extraction
435
+ if not isinstance(subgraph, torch.fx.GraphModule):
436
+ return _get_output_metadata_by_execution(subgraph, *operands)
437
+
438
+ output_metadata = OutputMetadata()
439
+
440
+ # Extract output arguments from the output node
441
+ # The output node has args=(output_values,) where output_values is a tuple/list
442
+ output_node = next(reversed(subgraph.graph.find_nodes(op="output")))
443
+ output_metadata.num_fw_outs = len(output_node.args[0])
444
+
445
+ for idx, output_arg in enumerate(output_node.args[0]):
446
+ if not isinstance(output_arg, torch.fx.Node):
447
+ if isinstance(output_arg, int):
448
+ output_metadata.indexes_with_symint.add(idx)
449
+ output_metadata.indexes_with_no_grad.add(idx)
450
+ continue
451
+
452
+ # Check node metadata for type information
453
+ if output_arg.meta.get("val") is None:
454
+ # If we don't have complete metadata for all outputs, fall back to execution
455
+ # This is important for correctness (e.g., detecting SymInts) even though it
456
+ # runs side-effectful operations
457
+ return _get_output_metadata_by_execution(subgraph, *operands)
458
+
459
+ val = output_arg.meta["val"]
460
+ if isinstance(val, torch.SymInt):
461
+ output_metadata.indexes_with_symint.add(idx)
462
+ output_metadata.indexes_with_no_grad.add(idx)
463
+ elif isinstance(val, torch.Tensor):
464
+ # Check if tensor requires grad from metadata
465
+ if hasattr(val, "requires_grad") and not val.requires_grad:
466
+ output_metadata.indexes_with_no_grad.add(idx)
467
+ else:
468
+ # Non-tensor, non-symint (shouldn't happen but be safe)
469
+ output_metadata.indexes_with_no_grad.add(idx)
470
+
471
+ return output_metadata
472
+
473
+
474
+ def _get_output_metadata_by_execution(subgraph, *operands):
475
+ """
476
+ Fallback: Extract metadata by executing the subgraph.
477
+ This should only be used when static analysis fails.
478
+ WARNING: This will run side-effectful operations!
479
+ """
480
+
481
+ with suspend_functionalization(), disable_functional_mode():
482
+ with disable_proxy_modes_tracing():
483
+ # args are functional tensors, generate some example tensors
484
+ fw_inputs = pytree.tree_map(_from_fun, operands)
485
+
486
+ from torch._guards import detect_fake_mode
487
+
488
+ fake_mode = detect_fake_mode(fw_inputs)
489
+ context = (
490
+ nullcontext()
491
+ if fake_mode is None or fake_mode.shape_env is None
492
+ else fake_mode.shape_env.ignore_fresh_unbacked_symbols()
493
+ )
494
+
495
+ with context:
496
+ fw_outs = pytree.tree_map(_from_fun, subgraph(*fw_inputs))
497
+
498
+ num_fw_outs = len(fw_outs)
499
+
500
+ output_metadata = OutputMetadata()
501
+ output_metadata.num_fw_outs = num_fw_outs
502
+
503
+ for idx, fw_out in enumerate(fw_outs):
504
+ if isinstance(fw_out, torch.SymInt):
505
+ output_metadata.indexes_with_symint.add(idx)
506
+ elif not fw_out.requires_grad:
507
+ output_metadata.indexes_with_no_grad.add(idx)
508
+
509
+ return output_metadata
510
+
511
+
512
+ def trace_joint_graph_as_bwd(
513
+ subgraph, num_primals, joint_operands, include_key_set, exclude_key_set
514
+ ):
515
+ """
516
+ Naively trace out a joint graph. This simplifies the reconstruction of joint
517
+ graph in the min-cut partitioner later on.
518
+ """
519
+ from torch._functorch.aot_autograd import create_joint
520
+
521
+ dummy_aot_config = get_dummy_aot_autograd_config()
522
+
523
+ if isinstance(subgraph, torch.fx.GraphModule):
524
+
525
+ def graph_with_interpreter(*args):
526
+ # Running graph with interpreter is needed for propagating the stack_trace
527
+ with torch.fx.traceback.preserve_node_meta():
528
+ return torch.fx.Interpreter(subgraph).run(*args)
529
+
530
+ fn = graph_with_interpreter
531
+ else:
532
+ fn = subgraph
533
+
534
+ # This joint_fn is inserted as the backward graph as is. This simplifies the
535
+ # min-cut partitioner work later on.
536
+ # Input signature - (*primals, *tangents)
537
+ # Output signature - (*grads, *fw_outs)
538
+ # The output signature is deliberately kept grads first and fw_outs second.
539
+ # Having grads first makes the min-cut partitioner HOP graph stitching
540
+ # easier.
541
+ def joint_fn(*primals_and_tangents):
542
+ primals = primals_and_tangents[:num_primals]
543
+ tangents = primals_and_tangents[num_primals:]
544
+
545
+ fw_outs, grads = create_joint(
546
+ prepare_fw_with_masks(fn), aot_config=dummy_aot_config
547
+ )(primals, tangents)
548
+
549
+ maybe_clone = clone_outputs_aliasing_inputs(primals_and_tangents)
550
+
551
+ # return signature is deliberately kept (*grads, *fw_outs). This
552
+ # simplifies partitioning work later on.
553
+ return pytree.tree_map(maybe_clone, tuple(grads + list(fw_outs)))
554
+
555
+ with suspend_functionalization(), disable_functional_mode():
556
+ with disable_proxy_modes_tracing():
557
+ joint_operands = [_from_fun(arg) for arg in joint_operands]
558
+ with contextlib.ExitStack() as stack:
559
+ stack.enter_context(
560
+ torch._C._ForceDispatchKeyGuard(include_key_set, exclude_key_set),
561
+ )
562
+ subgraph_decomp_table = _extract_nested_region_config(subgraph)
563
+ with torch.enable_grad():
564
+ return _maybe_reenter_make_fx(
565
+ joint_fn, subgraph_decomp_table=subgraph_decomp_table
566
+ )(*joint_operands)
567
+
568
+
569
+ class InvokeSubgraphAutogradOp(torch.autograd.Function):
570
+ """
571
+ Saves the subgraph, i.e. original callable, in the forward method. And then
572
+ traces out a joint graph in the backward. This delaying of tracing in
573
+ backward, also called as lazy backward, ensures that the assumptions about
574
+ the grad_out strides and tensor-subclass-ness are already accounted for.
575
+ """
576
+
577
+ @staticmethod
578
+ # pyrefly: ignore [bad-override]
579
+ def forward(
580
+ ctx,
581
+ subgraph,
582
+ identifier,
583
+ output_metadata,
584
+ *operands,
585
+ ):
586
+ # We want to delay the backward graph construction until the backward.
587
+ # So in forward, we just run the fw callable as is. And save all the
588
+ # information necessary to construct the backward graph in the ctx.
589
+ ctx._subgraph = subgraph
590
+ ctx._identifier = identifier
591
+ ctx._output_metadata = output_metadata
592
+ # We snapshot the dispatch keys in forward for materializing the
593
+ # the bw_graph in backward.
594
+ ctx._fw_include_key_set = torch._C._dispatch_tls_local_include_set()
595
+ ctx._fw_exclude_key_set = torch._C._dispatch_tls_local_exclude_set()
596
+
597
+ save_values_for_backward(ctx, operands)
598
+
599
+ with torch._C._AutoDispatchBelowAutograd():
600
+ out = invoke_subgraph(
601
+ subgraph,
602
+ f"fw_{identifier}",
603
+ *operands,
604
+ )
605
+
606
+ # Check that int (coming from symint) is at expected indexes.
607
+ for idx, o in enumerate(out):
608
+ if isinstance(o, int):
609
+ if idx not in output_metadata.indexes_with_symint:
610
+ raise AssertionError(
611
+ f"unexpected int output at index {idx}, not in indexes_with_symint"
612
+ )
613
+
614
+ return out
615
+
616
+ @staticmethod
617
+ def backward(
618
+ ctx,
619
+ *grad_outs,
620
+ ):
621
+ from torch._dynamo.utils import dynamo_timed
622
+
623
+ subgraph = ctx._subgraph
624
+ identifier = ctx._identifier
625
+ output_metadata = ctx._output_metadata
626
+ primals = saved_values(ctx)
627
+
628
+ # Filter out grads that are None or do not require_grad. This was
629
+ # the assumption we made during the tracing of joint_graph.
630
+ filtered_grad_outs = []
631
+ for idx, o in enumerate(grad_outs):
632
+ if o is None:
633
+ if idx not in output_metadata.indexes_with_symint:
634
+ raise AssertionError(
635
+ f"unexpected None grad_out at index {idx}, not in indexes_with_symint"
636
+ )
637
+ elif idx in output_metadata.indexes_with_no_grad:
638
+ # Deliberately skip over the grad_outs which we know should be
639
+ # None because the corresponding fwd_out does not require_grad.
640
+ pass
641
+ else:
642
+ filtered_grad_outs.append(o)
643
+ filtered_grad_outs = tuple(filtered_grad_outs)
644
+
645
+ # Important note - Even though the forward graph can be same for
646
+ # different invoke_subgraphs, the backward graph can be different
647
+ # because the tangent strides can be different. So, here we cache on
648
+ # tangent_metadata in addition to identifier
649
+ from torch._guards import detect_fake_mode
650
+ from torch._subclasses._fake_tensor_utils import _CacheKeyState
651
+ from torch._subclasses.fake_tensor import extract_tensor_metadata
652
+
653
+ fake_mode = detect_fake_mode(primals + filtered_grad_outs)
654
+ if fake_mode is None:
655
+ raise AssertionError("fake_mode should be enabled for HOPs")
656
+ state = _CacheKeyState(fake_mode.shape_env)
657
+
658
+ tangent_metadata: list[object] = []
659
+ for tangent in filtered_grad_outs:
660
+ metadata = extract_tensor_metadata(tangent)
661
+ metadata._flatten_into(tangent_metadata, fake_mode, state)
662
+
663
+ # Add aliasing information to tangent_metadata
664
+ # Two tangents are aliased if they are the same tensor object (using id())
665
+ # We create a tuple of tuples where each inner tuple contains indices of aliased tensors
666
+ # e.g. ((0, 1),) would mean there is one aliasing group, and the first and second tangents are aliased
667
+ # e.g. () would mean there is no aliasing between tangents
668
+ tensor_to_indices: dict[int, list[int]] = defaultdict(list)
669
+ for i, tangent in enumerate(filtered_grad_outs):
670
+ if isinstance(tangent, torch.Tensor):
671
+ tensor_to_indices[id(tangent)].append(i)
672
+
673
+ aliasing_groups = tuple(
674
+ sorted(
675
+ tuple(indices)
676
+ for indices in tensor_to_indices.values()
677
+ if len(indices) > 1
678
+ )
679
+ )
680
+ tangent_metadata.append(aliasing_groups)
681
+
682
+ # pyrefly: ignore [bad-assignment]
683
+ tangent_metadata = tuple(tangent_metadata)
684
+
685
+ # bw_graph is a joint graph with signature (*primals_and_tangents) and
686
+ # returns (*grads_and_fw_outs). To get the grads, we use the num_fw_outs
687
+ # to extract the grads.
688
+ primals_and_tangents = primals + filtered_grad_outs
689
+
690
+ # Check if we have already traced the bwd subgraph.
691
+ bw_graph = None
692
+ suffix = None
693
+ invoke_subgraph_cache = get_invoke_subgraph_cache()
694
+ cache_hit = False
695
+ if invoke_subgraph_cache:
696
+ bw_graph, suffix = invoke_subgraph_cache.get_lazy_bwd_entry(
697
+ identifier, tangent_metadata
698
+ )
699
+ cache_hit = bw_graph is not None
700
+
701
+ if bw_graph is None:
702
+ if suffix is not None:
703
+ raise AssertionError(
704
+ f"suffix should be None when bw_graph is None, got {suffix}"
705
+ )
706
+ with dynamo_timed(
707
+ "invoke_subgraph_trace_joint_graph", log_pt2_compile_event=True
708
+ ):
709
+ bw_graph = trace_joint_graph_as_bwd(
710
+ subgraph,
711
+ len(primals),
712
+ primals_and_tangents,
713
+ ctx._fw_include_key_set,
714
+ ctx._fw_exclude_key_set,
715
+ )
716
+ if (
717
+ hasattr(subgraph, "meta")
718
+ and "nested_region_config" in subgraph.meta
719
+ ):
720
+ bw_graph.meta["nested_region_config"] = subgraph.meta[
721
+ "nested_region_config"
722
+ ]
723
+
724
+ if invoke_subgraph_cache and not cache_hit:
725
+ suffix = invoke_subgraph_cache.add_lazy_bwd_entry(
726
+ identifier, tangent_metadata, bw_graph
727
+ )
728
+
729
+ grads = invoke_subgraph(
730
+ bw_graph, f"bw_{identifier}_{suffix}", *primals_and_tangents
731
+ )[: -output_metadata.num_fw_outs]
732
+ return None, None, None, *grads
733
+
734
+
735
+ @invoke_subgraph.py_autograd_impl
736
+ def _(subgraph, identifier, *operands):
737
+ # Check if we have already traced the subgraph.
738
+ invoke_subgraph_cache = get_invoke_subgraph_cache()
739
+ if invoke_subgraph_cache:
740
+ if saved_autograd_fn := invoke_subgraph_cache.get_autograd_key_entry(
741
+ identifier
742
+ ):
743
+ return saved_autograd_fn(*operands)
744
+
745
+ output_metadata = get_output_metadata(subgraph, *operands)
746
+
747
+ def autograd_fn_callable(*args):
748
+ return InvokeSubgraphAutogradOp.apply(
749
+ subgraph, identifier, output_metadata, *args
750
+ )
751
+
752
+ # Save the autograd_fn_callable in the dispatch set cache.
753
+ if invoke_subgraph_cache:
754
+ invoke_subgraph_cache.add_autograd_key_entry(identifier, autograd_fn_callable)
755
+
756
+ return autograd_fn_callable(*operands)
757
+
758
+
759
+ @invoke_subgraph.py_impl(DebugMode)
760
+ def _(debug_mode, subgraph, identifier, *operands):
761
+ # record HOP call
762
+ call = torch.utils._debug_mode._OpCall(
763
+ invoke_subgraph,
764
+ (identifier, *operands),
765
+ kwargs={},
766
+ call_depth=debug_mode.call_depth + 1,
767
+ stack=debug_mode.record_stack_trace,
768
+ )
769
+ debug_mode._record_call(call)
770
+
771
+ debug_mode.call_depth += 1
772
+ debug_mode._handle_annotate(f"[enter InvokeSubgraph HOP] {identifier}")
773
+
774
+ # If the HOP is dispatched from DebugMode, we should enable debug_mode
775
+ # for the subgraph call.
776
+ with debug_mode:
777
+ if getattr(subgraph, "_boxed_call", False):
778
+ result = subgraph(list(operands))
779
+ else:
780
+ result = subgraph(*operands)
781
+ debug_mode._handle_annotate(f"[exit InvokeSubgraph HOP] {identifier}")
782
+ debug_mode.call_depth -= 1
783
+ # record output of HOP
784
+ debug_mode._record_call_output(call, result)
785
+ return result
786
+
787
+
788
+ @invoke_subgraph.py_impl(DispatchKey.CompositeExplicitAutograd)
789
+ def _(subgraph, identifier, *operands):
790
+ from torch.utils._python_dispatch import _get_current_dispatch_mode
791
+
792
+ mode = _get_current_dispatch_mode()
793
+
794
+ if mode is not None:
795
+ raise AssertionError("Mode should never be enabled for CPU/CUDA key")
796
+
797
+ if getattr(subgraph, "_boxed_call", False):
798
+ return subgraph(list(operands))
799
+ else:
800
+ return subgraph(*operands)
801
+
802
+
803
+ @invoke_subgraph.py_functionalize_impl
804
+ def _(ctx, subgraph, identifier, *operands):
805
+ from torch._higher_order_ops.auto_functionalize import (
806
+ can_auto_functionalize,
807
+ do_auto_functionalize_v2,
808
+ )
809
+
810
+ # (in the functionalization metadata phase) Capture tokens before
811
+ tokens_before = dict(ctx.mode._tokens)
812
+
813
+ # Check if this subgraph has effects stored in the cache
814
+ invoke_subgraph_cache = get_invoke_subgraph_cache()
815
+ effects = None
816
+ if invoke_subgraph_cache:
817
+ effects = invoke_subgraph_cache.get_effects(identifier)
818
+
819
+ if effects:
820
+ if len(effects) != 1:
821
+ raise AssertionError(
822
+ f"Multiple effects within a subgraph NYI, got {len(effects)} effects"
823
+ )
824
+ tokens = ctx.mode._tokens
825
+ effects = next(iter(effects))
826
+ token_input = tokens[effects]
827
+
828
+ operands = (token_input, *operands)
829
+
830
+ def wrap_subgraph(subgraph):
831
+ def wrapped_subgraph(token, *args):
832
+ res = subgraph(*args)
833
+ return ctx.unwrap_tensors(ctx.mode._tokens[effects]), *res
834
+
835
+ return wrapped_subgraph
836
+
837
+ subgraph = wrap_subgraph(subgraph)
838
+
839
+ unwrapped_operands = ctx.unwrap_tensors(operands)
840
+
841
+ hop_instance = HopInstance.create(invoke_subgraph, subgraph, identifier, *operands)
842
+ if can_auto_functionalize(hop_instance):
843
+ # NOTE: [auto_functionalize x invoke_subgraph caching]
844
+ # We call auto_functionalized_v2 to support input mutation of invoke_subgraph.
845
+ # See NOTE [Support input mutation of hops] for the overall design.
846
+ #
847
+ # invoke_subgraph is special because of its identifier based caching mechanism.
848
+ # In invoke_subgraph's functionalization key implementation, we create a new
849
+ # identifier because the subgraph is replaced by FunctionWithNoFreeVars in a
850
+ # functional + epilogue form.
851
+ if not isinstance(identifier, str):
852
+ raise AssertionError(
853
+ f"identifier must be a string for auto_functionalize, got {type(identifier)}"
854
+ )
855
+ return do_auto_functionalize_v2(
856
+ ctx.mode,
857
+ hop_instance,
858
+ (subgraph, "auto_functionalized_" + identifier, *operands),
859
+ {},
860
+ )
861
+
862
+ with ctx.redispatch_to_next():
863
+ # NB: There is an assumption that subgraph does not mutate inputs and
864
+ # there is no aliasing. It's Dynamo's responsibility to prevent formation
865
+ # of invoke_subgraph ops if input aliasing/mutation is detected.
866
+ functionalized_subgraph = FunctionalizeCtxWrapper(ctx, subgraph)
867
+ out = invoke_subgraph(functionalized_subgraph, identifier, *unwrapped_operands)
868
+
869
+ if effects:
870
+ (new_token, *out) = out
871
+ ctx.mode._tokens[effects] = new_token
872
+
873
+ # (in the functionalization metadata phase) Capture tokens after and see if
874
+ # there are any differences (there are new effects or the token value for an
875
+ # effect type has changed)
876
+ tokens_after = dict(ctx.mode._tokens)
877
+ discovered_effects = set()
878
+ for effect_type, token in tokens_after.items():
879
+ if effect_type not in tokens_before or tokens_before[effect_type] is not token:
880
+ discovered_effects.add(effect_type)
881
+
882
+ if discovered_effects:
883
+ if not ctx.mode._allow_token_discovery:
884
+ raise AssertionError(
885
+ f"Number of tokens changed by {len(discovered_effects)} when tracing subgraph {subgraph}."
886
+ )
887
+ # Store discovered effects in the cache by identifier
888
+ if invoke_subgraph_cache:
889
+ invoke_subgraph_cache.add_effects(identifier, discovered_effects)
890
+
891
+ return ctx.wrap_tensors(out)
892
+
893
+
894
+ # Register the hop fake fn. This will be called in the fake_tensor _dispatch_impl.
895
+ @register_fake(invoke_subgraph)
896
+ def _(subgraph, identifier, *operands):
897
+ from torch._dynamo.utils import dynamo_timed
898
+
899
+ with dynamo_timed("invoke_subgraph_fake_tensor", log_pt2_compile_event=True):
900
+ return subgraph(*operands)
901
+
902
+
903
+ @invoke_subgraph.py_impl(ProxyTorchDispatchMode)
904
+ def _(proxy_mode: ProxyTorchDispatchMode, subgraph, identifier, *operands):
905
+ # Check if we have already traced the subgraph.
906
+ graph = None
907
+ invoke_subgraph_cache = get_invoke_subgraph_cache()
908
+ if invoke_subgraph_cache:
909
+ graph = invoke_subgraph_cache.get_proxy_dispatch_entry(identifier)
910
+
911
+ if graph is None:
912
+ from torch._dynamo.utils import dynamo_timed
913
+
914
+ with dynamo_timed("invoke_subgraph_proxy_tensor", log_pt2_compile_event=True):
915
+ subgraph_decomp_table = _extract_nested_region_config(subgraph)
916
+
917
+ # NB: invoke_subgraph subgraph re-trace seq_nr
918
+ # The joint graph seq_nr will get wrong in the subsequent re-trace (all nodes will have the same seq_nr),
919
+ # so we preserve the original graph's seq_nr here.
920
+ with torch.fx.traceback._preserve_node_seq_nr():
921
+ graph = reenter_make_fx(
922
+ subgraph, subgraph_decomp_table=subgraph_decomp_table
923
+ )(*operands)
924
+
925
+ from torch._guards import detect_fake_mode
926
+
927
+ fake_mode = detect_fake_mode(operands)
928
+ # Only insert deferred runtime asserts when we have dynamic shapes.
929
+ # When shape_env is None (static shapes), there are no deferred asserts to insert.
930
+ if fake_mode is not None and fake_mode.shape_env is not None:
931
+ insert_deferred_runtime_asserts(
932
+ graph,
933
+ fake_mode.shape_env,
934
+ "invoke_subgraph_proxy_torch_dispatch_mode",
935
+ export=True,
936
+ )
937
+ graph.recompile()
938
+
939
+ if not isinstance(proxy_mode.tracer, torch.fx.Tracer):
940
+ raise AssertionError(
941
+ f"expected proxy_mode.tracer to be torch.fx.Tracer, got {type(proxy_mode.tracer)}"
942
+ )
943
+ if invoke_subgraph_cache:
944
+ invoke_subgraph_cache.add_proxy_dispatch_entry(identifier, graph)
945
+
946
+ node_args = (graph, identifier, *operands)
947
+
948
+ def _unwrap_proxy(arg):
949
+ if isinstance(arg, torch.fx.GraphModule):
950
+ # NOTE: [invoke_subgraph proxy_mode x auto_functionalize]
951
+ # Previously, we assumed that `invoke_subgraph` would always be traced with the same tracer.
952
+ # This allowed us to cache modules by their identifiers, assuming they were already registered.
953
+ #
954
+ # However, this assumption no longer holds when we auto-functionalize `invoke_subgraph`.
955
+ # auto_functionalize functionalizes the subgraph and wrap it with `FunctionWithNoFreeVars`.
956
+ # In the proxy mode implementation of `auto_functionalized_v2`, we need to materialize `FunctionWithNoFreeVars`
957
+ # input as a graph module. To do this, we re-trace the `invoke_subgraph` hop, which starts a new sub-tracer
958
+ # (see NOTE [materialize callable inputs as graph]). # When the new sub-tracer traces the `invoke_subgraph`
959
+ # with a previously cached identifier, the corresponding graph module might not
960
+ # exist as a submodule in the new tracer's root. Therefore, we register it as a submodule below.
961
+ #
962
+ # The alternative is to give a new identifier when we re-trace the invoke_subgraph but this will increase
963
+ # the compilation time, which defeats the purpose of caching.
964
+ registered_before = False
965
+ for (
966
+ _,
967
+ submod,
968
+ ) in proxy_mode.tracer.root.named_modules(): # type: ignore[union-attr]
969
+ if arg is submod:
970
+ registered_before = True
971
+
972
+ if not registered_before:
973
+ qualname = proxy_mode.tracer.get_fresh_qualname("repeated_subgraph") # type: ignore[union-attr]
974
+ proxy_mode.tracer.root.register_module(qualname, arg) # type: ignore[union-attr]
975
+ return proxy_mode.tracer.unwrap_proxy(arg) # type: ignore[union-attr]
976
+
977
+ proxy_args = pytree.tree_map(_unwrap_proxy, node_args) # type: ignore[union-attr]
978
+ out_proxy = proxy_mode.tracer.create_proxy(
979
+ "call_function", invoke_subgraph, proxy_args, {}
980
+ )
981
+
982
+ example_out = invoke_subgraph(graph, identifier, *operands)
983
+ return track_tensor_tree(
984
+ example_out, out_proxy, constant=None, tracer=proxy_mode.tracer
985
+ )
986
+
987
+
988
+ def invoke_subgraph_inductor_compile(
989
+ gm, example_inputs, inductor_config_patches=None, **kwargs
990
+ ):
991
+ from torch._functorch._aot_autograd.runtime_wrappers import (
992
+ SerializableCompiledFunction,
993
+ )
994
+ from torch._functorch._aot_autograd.utils import simple_wraps
995
+ from torch._inductor import config
996
+ from torch._inductor.compile_fx import compile_fx_inner
997
+ from torch._inductor.standalone_compile import AOTCompiledArtifact
998
+
999
+ # Used for testing only, should only be changed via _testing_capture_invoke_subgraph_inductor_compile_gms()
1000
+ if (
1001
+ torch._dynamo.testing._testing_invoke_subgraph_inductor_compile_captured_gms
1002
+ is not None
1003
+ ):
1004
+ torch._dynamo.testing._testing_invoke_subgraph_inductor_compile_captured_gms.append(
1005
+ copy.deepcopy(gm)
1006
+ )
1007
+
1008
+ if inductor_config_patches is None:
1009
+ inductor_config_patches = {}
1010
+ compile_fn = config.patch(inductor_config_patches)(compile_fx_inner)
1011
+ compiled_fn_inner = compile_fn(gm, example_inputs)
1012
+ if not compiled_fn_inner._boxed_call:
1013
+ raise AssertionError(
1014
+ "compiled_fn_inner must have _boxed_call attribute set to True"
1015
+ )
1016
+
1017
+ # Follow boxed calling convention
1018
+ @simple_wraps(compiled_fn_inner)
1019
+ def forward(*runtime_args: tuple[Any]):
1020
+ full_args = []
1021
+ full_args.extend(runtime_args)
1022
+ return compiled_fn_inner(full_args)
1023
+
1024
+ # Just for convenience
1025
+ forward.zero_grad = gm.zero_grad # type: ignore[attr-defined]
1026
+ forward.named_parameters = gm.named_parameters # type: ignore[attr-defined]
1027
+ forward.named_buffers = gm.named_buffers # type: ignore[attr-defined]
1028
+
1029
+ # TODO: Do we need the post compile passes in _aot_stage2b_compile_forward_or_inference?
1030
+ # TODO: add a real serialize function for SerializableCompiledFunction like _cache_inference_info
1031
+ forward.serialize = SerializableCompiledFunction(forward, lambda: None) # type: ignore[attr-defined]
1032
+ return AOTCompiledArtifact(forward)
1033
+
1034
+
1035
+ def get_invoke_subgraph_compile_options(
1036
+ inductor_config_patches=None,
1037
+ decompositions=None,
1038
+ partitioner="min_cut_rematerialization_partition",
1039
+ ):
1040
+ if inductor_config_patches is None:
1041
+ inductor_config_patches = {"triton.autotune_at_compile_time": True}
1042
+ inductor_compile = functools.partial(
1043
+ invoke_subgraph_inductor_compile,
1044
+ inductor_config_patches=inductor_config_patches,
1045
+ )
1046
+
1047
+ if inductor_config_patches:
1048
+ from torch._inductor import config as inductor_config
1049
+
1050
+ # Validate that all config keys exist
1051
+ for key in inductor_config_patches:
1052
+ if not hasattr(inductor_config, key):
1053
+ raise ValueError(
1054
+ f"Invalid inductor config key '{key}' in get_invoke_subgraph_compile_options. "
1055
+ f"Available config keys can be found in torch._inductor.config"
1056
+ )
1057
+
1058
+ return NestedCompileRegionOptions(
1059
+ fw_compiler=inductor_compile,
1060
+ bw_compiler=inductor_compile,
1061
+ partitioner=partitioner,
1062
+ decompositions=decompositions,
1063
+ )
.venv/lib/python3.10/site-packages/torch/_higher_order_ops/local_map.py ADDED
@@ -0,0 +1,641 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
2
+ #
3
+ # This source code is licensed under the BSD license found in the
4
+ # LICENSE file in the root directory of this source tree.
5
+
6
+ # NOTE: this file may be removed once we move to a dynamo frontend
7
+
8
+ import contextlib
9
+ import functools
10
+ from collections.abc import Callable, Generator, Sequence
11
+ from contextlib import contextmanager
12
+ from typing import Any, Optional, TypeAlias
13
+
14
+ import torch
15
+ import torch.utils._pytree as pytree
16
+ from torch._C import DispatchKey
17
+ from torch._higher_order_ops.utils import (
18
+ clone_outputs_aliasing_inputs,
19
+ redirect_to_mode,
20
+ save_values_for_backward,
21
+ saved_values,
22
+ )
23
+ from torch._ops import HigherOrderOperator
24
+ from torch._subclasses.fake_tensor import FakeTensor, FakeTensorMode
25
+ from torch._subclasses.functional_tensor import FunctionalTensor
26
+ from torch.fx import GraphModule
27
+ from torch.fx.experimental.proxy_tensor import ProxyTorchDispatchMode, track_tensor_tree
28
+ from torch.utils.checkpoint import _CachedTorchDispatchMode, _CachingTorchDispatchMode
29
+
30
+
31
+ # Proxy the HOP instead of inlining into it
32
+ # And trace it with local shapes for AP
33
+ _DEFER_INLINING = False
34
+
35
+ GraphArg: TypeAlias = tuple[torch.Tensor, int, torch.SymInt, None]
36
+
37
+
38
+ @contextmanager
39
+ def defer_inlining() -> Generator[None, None, None]:
40
+ global _DEFER_INLINING
41
+ prior = _DEFER_INLINING
42
+ try:
43
+ _DEFER_INLINING = True
44
+ yield
45
+ finally:
46
+ _DEFER_INLINING = prior
47
+
48
+
49
+ # Used to unwrap tensors classes like FunctionalTensor and Parameter
50
+ def _new_tensor(
51
+ t: Any,
52
+ new_shape: Optional[Sequence[int]] = None,
53
+ new_stride: Optional[Sequence[int]] = None,
54
+ ) -> Any:
55
+ if isinstance(t, torch.Tensor):
56
+ if type(t) not in (FunctionalTensor, FakeTensor, torch.Tensor):
57
+ raise AssertionError(f"No subclasses support for now, found {type(t)}")
58
+ return torch.empty_strided(
59
+ t.size() if new_shape is None else new_shape,
60
+ t.stride() if new_stride is None else new_stride,
61
+ device=t.device,
62
+ dtype=t.dtype,
63
+ requires_grad=t.requires_grad,
64
+ )
65
+ return t
66
+
67
+
68
+ # Autoparallel specific, we want to treat plain tensors as DTensors
69
+ def _redistribute(
70
+ args: Any,
71
+ all_placements: tuple[Any],
72
+ mesh: Any,
73
+ shape_stride_fn: Callable[[torch.Tensor, Any, Any], tuple[list[int], list[int]]],
74
+ ) -> GraphArg:
75
+ from torch._dispatch.python import suspend_functionalization
76
+ from torch._guards import detect_fake_mode
77
+ from torch._subclasses.functional_tensor import disable_functional_mode
78
+ from torch.fx.experimental.proxy_tensor import disable_proxy_modes_tracing
79
+
80
+ with (
81
+ suspend_functionalization(),
82
+ disable_functional_mode(),
83
+ disable_proxy_modes_tracing(),
84
+ ):
85
+ fake_mode = detect_fake_mode(args)
86
+ if fake_mode is None:
87
+ raise AssertionError("defer_inlining() is only supported for FakeTensors")
88
+
89
+ with fake_mode:
90
+ new_args = list(pytree.tree_map(_new_tensor, args))
91
+ for i, (tensor, placements) in enumerate(zip(new_args, all_placements)):
92
+ if tensor is None:
93
+ # Sometimes gradients can be None
94
+ continue
95
+
96
+ new_shape, new_stride = shape_stride_fn(
97
+ tensor,
98
+ mesh,
99
+ placements,
100
+ )
101
+ new_args[i] = _new_tensor(
102
+ tensor, new_shape=new_shape, new_stride=new_stride
103
+ )
104
+
105
+ new_args = tuple(new_args)
106
+ if not all(
107
+ isinstance(t, (FakeTensor, int, torch.SymInt, type(None)))
108
+ for t in new_args
109
+ ):
110
+ raise AssertionError(f"Unexpected element in {args=}")
111
+
112
+ return new_args
113
+
114
+
115
+ def redistribute_fw_inputs(
116
+ global_args: Any, all_placements: Any, mesh: Any, _: Optional[int] = None
117
+ ) -> GraphArg:
118
+ if len(global_args) != len(all_placements):
119
+ raise AssertionError(
120
+ f"global_args length ({len(global_args)}) != all_placements length ({len(all_placements)})"
121
+ )
122
+ return _redistribute(
123
+ global_args,
124
+ all_placements,
125
+ mesh,
126
+ torch.distributed.tensor._utils.compute_local_tensor_info,
127
+ )
128
+
129
+
130
+ def redistribute_fw_outputs(
131
+ local_outs: Any, all_placements: Any, mesh: Any, num_activations: int
132
+ ) -> GraphArg:
133
+ if len(local_outs) != len(all_placements) + num_activations:
134
+ raise AssertionError(
135
+ f"local_outs length ({len(local_outs)}) != "
136
+ f"all_placements length ({len(all_placements)}) + num_activations ({num_activations})"
137
+ )
138
+ num_fw_outs = len(local_outs) - num_activations
139
+ if num_fw_outs <= 0:
140
+ raise AssertionError(f"num_fw_outs must be > 0, got {num_fw_outs}")
141
+ outs, activations = local_outs[:num_fw_outs], local_outs[num_fw_outs:]
142
+ return (
143
+ *_redistribute(
144
+ outs,
145
+ all_placements,
146
+ mesh,
147
+ torch.distributed.tensor._utils.compute_global_tensor_info,
148
+ ),
149
+ *activations,
150
+ )
151
+
152
+
153
+ def redistribute_bw_inputs(
154
+ global_args: Any, all_placements: Any, mesh: Any, num_activations: int
155
+ ) -> GraphArg:
156
+ if len(global_args) != len(all_placements) + num_activations:
157
+ raise AssertionError(
158
+ f"global_args length ({len(global_args)}) != "
159
+ f"all_placements length ({len(all_placements)}) + num_activations ({num_activations})"
160
+ )
161
+ activations, inputs = global_args[:num_activations], global_args[num_activations:]
162
+ if len(inputs) <= 0:
163
+ raise AssertionError("inputs must not be empty")
164
+ local_inputs = _redistribute(
165
+ inputs,
166
+ all_placements,
167
+ mesh,
168
+ torch.distributed.tensor._utils.compute_local_tensor_info,
169
+ )
170
+ return (
171
+ *activations,
172
+ *local_inputs,
173
+ )
174
+
175
+
176
+ def redistribute_bw_outputs(
177
+ local_outs: Any, all_placements: Any, mesh: Any, _: Optional[int] = None
178
+ ) -> GraphArg:
179
+ if len(local_outs) != len(all_placements):
180
+ raise AssertionError(
181
+ f"local_outs length ({len(local_outs)}) != all_placements length ({len(all_placements)})"
182
+ )
183
+ return _redistribute(
184
+ local_outs,
185
+ all_placements,
186
+ mesh,
187
+ torch.distributed.tensor._utils.compute_global_tensor_info,
188
+ )
189
+
190
+
191
+ class LocalMapHOP(HigherOrderOperator):
192
+ def __init__(self) -> None:
193
+ super().__init__("local_map_hop")
194
+
195
+ def __call__(self, gm: GraphModule, *args: Any, **kwargs: Any) -> Any:
196
+ # pyrefly: ignore [missing-attribute]
197
+ return super().__call__(gm, *args, **kwargs)
198
+
199
+
200
+ local_map_hop = LocalMapHOP()
201
+
202
+ # Registers dispatches for SAC
203
+ redirect_to_mode(local_map_hop, _CachingTorchDispatchMode)
204
+ redirect_to_mode(local_map_hop, _CachedTorchDispatchMode)
205
+
206
+
207
+ def create_hop_fw_bw(
208
+ fw_gm: GraphModule,
209
+ *_args: Any,
210
+ ) -> tuple[GraphModule, GraphModule, int, int, set[int]]:
211
+ """
212
+ Traces a joint, applies passes and partitions it
213
+ """
214
+ # Keeping these imports here
215
+ # Avoid circular dependencies once we upstream with dynamo frontend
216
+ from torch._dispatch.python import suspend_functionalization
217
+ from torch._functorch.aot_autograd import AOTConfig, create_joint
218
+ from torch._guards import detect_fake_mode
219
+ from torch._subclasses.fake_tensor import FakeTensor, FakeTensorMode
220
+ from torch._subclasses.functional_tensor import disable_functional_mode
221
+ from torch.fx.experimental.proxy_tensor import disable_proxy_modes_tracing, make_fx
222
+
223
+ local_map_kwargs = fw_gm.meta["local_map_kwargs"] # type: ignore[attr-defined]
224
+ if "in_placements" not in local_map_kwargs:
225
+ raise AssertionError("'in_placements' not found in local_map_kwargs")
226
+ if "out_placements" not in local_map_kwargs:
227
+ raise AssertionError("'out_placements' not found in local_map_kwargs")
228
+ if "device_mesh" not in local_map_kwargs:
229
+ raise AssertionError("'device_mesh' not found in local_map_kwargs")
230
+ if len(local_map_kwargs["in_placements"]) != len(_args):
231
+ raise AssertionError(
232
+ f"in_placements length ({len(local_map_kwargs['in_placements'])}) != _args length ({len(_args)})"
233
+ )
234
+
235
+ dummy_aot_config = AOTConfig(
236
+ fw_compiler=None, # type: ignore[arg-type]
237
+ bw_compiler=None, # type: ignore[arg-type]
238
+ partition_fn=None, # type: ignore[arg-type]
239
+ decompositions={},
240
+ num_params_buffers=0,
241
+ aot_id=0,
242
+ keep_inference_input_mutations=False,
243
+ )
244
+
245
+ with suspend_functionalization(), disable_functional_mode():
246
+ with disable_proxy_modes_tracing():
247
+ # If someone runs this hop under the default compiler backend ("eager")
248
+ # Then this path will be run with the actual user inputs. We convert them
249
+ # to fake tensors in order to not perform any actual compute.
250
+
251
+ fake_mode = detect_fake_mode(_args)
252
+ if fake_mode is None:
253
+ fake_mode = FakeTensorMode(allow_non_fake_inputs=True)
254
+
255
+ with fake_mode:
256
+ fw_inputs = redistribute_fw_inputs(
257
+ _args,
258
+ local_map_kwargs["in_placements"],
259
+ local_map_kwargs["device_mesh"],
260
+ )
261
+ if len(fw_inputs) != len(local_map_kwargs["in_placements"]):
262
+ raise AssertionError(
263
+ f"fw_inputs length ({len(fw_inputs)}) != "
264
+ f"in_placements length ({len(local_map_kwargs['in_placements'])})"
265
+ )
266
+
267
+ if not all(
268
+ isinstance(t, (FakeTensor, int, torch.SymInt)) for t in fw_inputs
269
+ ):
270
+ raise AssertionError(f"Unexpected element in {fw_inputs=}")
271
+
272
+ ctx = (
273
+ fake_mode.shape_env.ignore_fresh_unbacked_symbols
274
+ if fake_mode.shape_env is not None
275
+ else contextlib.nullcontext
276
+ )
277
+ with ctx():
278
+ fw_outs = fw_gm(*fw_inputs)
279
+
280
+ example_grads = pytree.tree_map(
281
+ _new_tensor,
282
+ fw_outs,
283
+ )
284
+ if not isinstance(example_grads, (list, tuple)):
285
+ example_grads = [example_grads]
286
+
287
+ num_fw_inputs = len(fw_inputs)
288
+ num_fw_outputs = len(example_grads)
289
+
290
+ def joint_f(
291
+ *primals_and_tangents: list[torch.Tensor],
292
+ ) -> Any:
293
+ primals = primals_and_tangents[:num_fw_inputs]
294
+ tangents = primals_and_tangents[num_fw_inputs:]
295
+
296
+ def prepare_fw_with_masks(
297
+ fw_gm: torch.fx.GraphModule,
298
+ ) -> Callable[..., Any]:
299
+ def fw_with_masks(*args: Any) -> tuple[tuple[Any], list[bool]]:
300
+ # The Interpreter here is required to propagate metadata
301
+ # from the dynamo graph body to the local_map graph body.
302
+ # This is required for fx_traceback.annotate for work.
303
+ fw_out = torch.fx.Interpreter(fw_gm).run(*args)
304
+ if not isinstance(fw_out, tuple):
305
+ raise AssertionError(
306
+ "Dynamo traced submodule should return tuple"
307
+ )
308
+ return fw_out, [
309
+ bool(isinstance(ret, torch.Tensor) and ret.requires_grad)
310
+ for ret in fw_out
311
+ ]
312
+
313
+ return fw_with_masks
314
+
315
+ fw_outs, grads = create_joint(
316
+ prepare_fw_with_masks(fw_gm), aot_config=dummy_aot_config
317
+ )(primals, tangents)
318
+ from torch.fx.experimental.symbolic_shapes import has_free_unbacked_symbols
319
+
320
+ if has_free_unbacked_symbols((*fw_outs, *grads)):
321
+ raise AssertionError(
322
+ "Unbacked symints leaking outside of the joint graph is not yet supported."
323
+ )
324
+
325
+ maybe_clone = clone_outputs_aliasing_inputs(primals_and_tangents)
326
+ # put grads first to work with existing hop utils
327
+ return pytree.tree_map(maybe_clone, (*grads, *fw_outs))
328
+
329
+ filtered_grads_idx = set()
330
+ for i, example_grad in enumerate(example_grads):
331
+ # Filter out grads that are None or do not require_grad.
332
+ # The AOTAutograd utils we rely on force this assumption.
333
+ # We must also filter the runtime tangents too.
334
+ if example_grad is not None and (
335
+ isinstance(example_grad, torch.Tensor) and example_grad.requires_grad
336
+ ):
337
+ filtered_grads_idx.add(i)
338
+
339
+ primals_and_tangents = [
340
+ *fw_inputs,
341
+ *[example_grads[i] for i in filtered_grads_idx],
342
+ ]
343
+ joint_hop_gm = make_fx(joint_f)(*primals_and_tangents)
344
+ from torch._functorch._aot_autograd.graph_capture import (
345
+ copy_fwd_metadata_to_bw_nodes,
346
+ )
347
+
348
+ copy_fwd_metadata_to_bw_nodes(joint_hop_gm)
349
+
350
+ from torch._functorch._aot_autograd.graph_compile import prepare_for_partitioner
351
+ from torch._inductor.compile_fx import partition_fn
352
+
353
+ # Match partitioner convention
354
+ prepped_joint_hop_gm = prepare_for_partitioner(
355
+ joint_hop_gm, num_fw_inputs, num_fw_outputs
356
+ )
357
+ with disable_proxy_modes_tracing():
358
+ # Also runs joint passes
359
+ new_fw_gm, new_bw_gm = partition_fn(
360
+ prepped_joint_hop_gm,
361
+ [],
362
+ num_fwd_outputs=num_fw_outputs,
363
+ static_lifetime_input_indices=[],
364
+ )
365
+
366
+ # Fix tags because min-cut does not respect fw/bw boundary, breaking
367
+ # default partitioner's assumptions.
368
+ for node in new_fw_gm.graph.nodes:
369
+ node.meta["partitioner_tag"] = "is_forward"
370
+ for node in new_bw_gm.graph.nodes:
371
+ node.meta["partitioner_tag"] = "is_backward"
372
+
373
+ # Propagate meta onto fw/bw graphs, later will be set on proxied nodes
374
+ new_fw_gm.meta["local_map_kwargs"] = local_map_kwargs
375
+ new_bw_gm.meta["local_map_kwargs"] = {**local_map_kwargs}
376
+ # Okay because Autoparallel assumes same sharding between param and grads
377
+ new_bw_gm.meta["local_map_kwargs"]["in_placements"] = tuple(
378
+ [local_map_kwargs["out_placements"][i] for i in filtered_grads_idx]
379
+ )
380
+ new_bw_gm.meta["local_map_kwargs"]["out_placements"] = local_map_kwargs[
381
+ "in_placements"
382
+ ]
383
+
384
+ # Validate Forward
385
+ fw_kwargs = new_fw_gm.meta["local_map_kwargs"]
386
+ expected_fw_inputs = len(fw_kwargs["in_placements"])
387
+ expected_fw_outputs = len(fw_kwargs["out_placements"])
388
+ actual_fw_inputs = len(new_fw_gm.graph.find_nodes(op="placeholder"))
389
+ actual_fw_outputs = num_fw_outputs
390
+ if expected_fw_inputs != actual_fw_inputs:
391
+ raise AssertionError(
392
+ f"expected_fw_inputs ({expected_fw_inputs}) != actual_fw_inputs ({actual_fw_inputs})"
393
+ )
394
+ if expected_fw_outputs != actual_fw_outputs:
395
+ raise AssertionError(
396
+ f"expected_fw_outputs ({expected_fw_outputs}) != actual_fw_outputs ({actual_fw_outputs})"
397
+ )
398
+
399
+ # Validate Activations
400
+ if len(new_fw_gm.graph.find_nodes(op="output")) != 1:
401
+ raise AssertionError(
402
+ f"Expected exactly 1 output node, got {len(new_fw_gm.graph.find_nodes(op='output'))}"
403
+ )
404
+ num_activations = (
405
+ len(new_fw_gm.graph.find_nodes(op="output")[0].args[0]) - num_fw_outputs
406
+ )
407
+ # tensors first, then symints
408
+ if num_activations < 0:
409
+ raise AssertionError(f"num_activations must be >= 0, got {num_activations}")
410
+
411
+ # Validate Backward
412
+ bw_kwargs = new_bw_gm.meta["local_map_kwargs"]
413
+ expected_bw_inputs = len(bw_kwargs["in_placements"])
414
+ expected_bw_outputs = len(bw_kwargs["out_placements"])
415
+ actual_bw_inputs = (
416
+ len(new_bw_gm.graph.find_nodes(op="placeholder")) - num_activations
417
+ )
418
+ if actual_bw_inputs <= 0:
419
+ raise AssertionError(
420
+ f"actual_bw_inputs must be > 0, got {actual_bw_inputs}"
421
+ )
422
+ if expected_fw_inputs + expected_bw_inputs != len(primals_and_tangents):
423
+ raise AssertionError(
424
+ f"expected_fw_inputs ({expected_fw_inputs}) + expected_bw_inputs ({expected_bw_inputs}) "
425
+ f"!= primals_and_tangents length ({len(primals_and_tangents)})"
426
+ )
427
+ if actual_fw_inputs + actual_bw_inputs != len(primals_and_tangents):
428
+ raise AssertionError(
429
+ f"actual_fw_inputs ({actual_fw_inputs}) + actual_bw_inputs ({actual_bw_inputs}) "
430
+ f"!= primals_and_tangents length ({len(primals_and_tangents)})"
431
+ )
432
+ if len(new_bw_gm.graph.find_nodes(op="output")) != 1:
433
+ raise AssertionError(
434
+ f"Expected exactly 1 bw output node, got {len(new_bw_gm.graph.find_nodes(op='output'))}"
435
+ )
436
+ actual_bw_outputs = len(new_bw_gm.graph.find_nodes(op="output")[0].args[0])
437
+ if expected_bw_inputs != actual_bw_inputs:
438
+ raise AssertionError(
439
+ f"expected_bw_inputs ({expected_bw_inputs}) != actual_bw_inputs ({actual_bw_inputs})"
440
+ )
441
+ if expected_bw_outputs != actual_bw_outputs:
442
+ raise AssertionError(
443
+ f"expected_bw_outputs ({expected_bw_outputs}) != actual_bw_outputs ({actual_bw_outputs})"
444
+ )
445
+
446
+ new_fw_gm.meta["num_activations"] = num_activations
447
+ new_fw_gm.meta["is_backward"] = False
448
+ new_bw_gm.meta["num_activations"] = num_activations
449
+ new_bw_gm.meta["is_backward"] = True
450
+
451
+ return new_fw_gm, new_bw_gm, num_fw_inputs, num_fw_outputs, filtered_grads_idx
452
+
453
+
454
+ class LocalMapAutogradOp(torch.autograd.Function):
455
+ @staticmethod
456
+ # pyrefly: ignore [bad-override]
457
+ def forward(
458
+ ctx: Any,
459
+ fw_gm: GraphModule,
460
+ bw_gm: GraphModule,
461
+ num_fw_ins: int,
462
+ num_fw_outs: int,
463
+ filtered_grads_idx: set[int],
464
+ *args: Any,
465
+ **kwargs: Any,
466
+ ) -> tuple[Optional[torch.Tensor], ...]:
467
+ from torch._functorch._aot_autograd.schemas import MemoryFormatMeta
468
+
469
+ ctx.bw_gm = bw_gm
470
+ ctx.num_fw_ins = num_fw_ins
471
+ ctx.filtered_grads_idx = filtered_grads_idx
472
+
473
+ with torch._C._AutoDispatchBelowAutograd():
474
+ fw_outs_with_saved_activations = local_map_hop(fw_gm, *args, **kwargs)
475
+
476
+ fw_outs = fw_outs_with_saved_activations[:num_fw_outs]
477
+ saved_activations = fw_outs_with_saved_activations[num_fw_outs:]
478
+ save_values_for_backward(ctx, saved_activations)
479
+
480
+ ctx.expected_tangent_metadata = {
481
+ i: MemoryFormatMeta.from_tensor(fw_outs[i]) for i in filtered_grads_idx
482
+ }
483
+ return fw_outs
484
+
485
+ @staticmethod
486
+ def backward(
487
+ ctx: Any, *_grads: tuple[torch.Tensor]
488
+ ) -> tuple[Optional[torch.Tensor], ...]:
489
+ from torch._functorch._aot_autograd.runtime_wrappers import (
490
+ coerce_to_expected_memory_format,
491
+ )
492
+
493
+ if ctx.pos != sorted(ctx.pos):
494
+ raise AssertionError(
495
+ "Interleaving saved tensor activations and symints is not expected from min-cut partitioner."
496
+ )
497
+ ctx.pos = list(reversed(ctx.pos)) # make saved_values return symints first
498
+ saved_activations = saved_values(ctx)
499
+ with torch._C._AutoDispatchBelowAutograd():
500
+ # Filter out grads that are None or do not require_grad.
501
+ # The AOTAutograd utils we rely on force this assumption.
502
+ grads = [_grads[i] for i in ctx.filtered_grads_idx]
503
+ if len(grads) != len(ctx.expected_tangent_metadata):
504
+ raise AssertionError(
505
+ f"{len(grads)=} vs {len(ctx.expected_tangent_metadata)}"
506
+ )
507
+
508
+ for i, meta in ctx.expected_tangent_metadata.items():
509
+ grads[i] = coerce_to_expected_memory_format(grads[i], meta)
510
+
511
+ grad_ins = local_map_hop(ctx.bw_gm, *saved_activations, *grads)
512
+ if len(grad_ins) != ctx.num_fw_ins:
513
+ raise RuntimeError(
514
+ f"Expected {ctx.num_fw_ins} grad_ins, got {len(grad_ins)}"
515
+ )
516
+ return None, None, None, None, None, *grad_ins
517
+
518
+
519
+ @local_map_hop.py_impl(torch._C.DispatchKey.Autograd)
520
+ def autograd_key(
521
+ fw_gm: GraphModule,
522
+ *args: Any,
523
+ **kwargs: Any,
524
+ ) -> Any:
525
+ local_map_kwargs = fw_gm.meta["local_map_kwargs"] # type: ignore[attr-defined]
526
+ if local_map_kwargs.get("in_grad_placements", None) is not None:
527
+ raise AssertionError("local_map in_grad_placements are not yet supported.")
528
+ if _DEFER_INLINING:
529
+ fw_gm, bw_gm, num_fw_ins, num_fw_outs, filtered_grads_idx = create_hop_fw_bw(
530
+ fw_gm, *args
531
+ )
532
+ return LocalMapAutogradOp.apply(
533
+ fw_gm, bw_gm, num_fw_ins, num_fw_outs, filtered_grads_idx, *args, **kwargs
534
+ )
535
+
536
+ # TODO: get rid of this when we can install as a subgraph
537
+ return torch.fx.Interpreter(fw_gm).run(*args, **kwargs)
538
+
539
+
540
+ @local_map_hop.py_functionalize_impl
541
+ def functional_mode_key(
542
+ ctx: Any, gm: GraphModule, *args: Any, **kwargs: Any
543
+ ) -> tuple[torch.Tensor]:
544
+ if kwargs:
545
+ raise AssertionError(f"kwargs must be empty, got {kwargs}")
546
+
547
+ unwrapped_inputs = ctx.unwrap_tensors(args)
548
+ with ctx.redispatch_to_next():
549
+ out = local_map_hop(gm, *unwrapped_inputs)
550
+ return ctx.wrap_tensors(out)
551
+
552
+
553
+ @local_map_hop.py_impl(FakeTensorMode)
554
+ def fake_mode_key(
555
+ mode: FakeTensorMode,
556
+ gm: GraphModule,
557
+ *args: Any,
558
+ **kwargs: Any,
559
+ ) -> GraphArg:
560
+ with mode:
561
+ if not _DEFER_INLINING:
562
+ return gm(*args, **kwargs)
563
+
564
+ # otherwise, we need to convert to local shapes for AP
565
+ is_backward = gm.meta["is_backward"]
566
+ redistribute_inputs = (
567
+ redistribute_bw_inputs if is_backward else redistribute_fw_inputs
568
+ )
569
+ local_args = redistribute_inputs(
570
+ args,
571
+ gm.meta["local_map_kwargs"]["in_placements"],
572
+ gm.meta["local_map_kwargs"]["device_mesh"],
573
+ gm.meta["num_activations"],
574
+ )
575
+ local_outs = gm(*local_args)
576
+ redistribute_outputs = (
577
+ redistribute_bw_outputs if is_backward else redistribute_fw_outputs
578
+ )
579
+ global_outs = redistribute_outputs(
580
+ local_outs,
581
+ gm.meta["local_map_kwargs"]["out_placements"],
582
+ gm.meta["local_map_kwargs"]["device_mesh"],
583
+ gm.meta["num_activations"],
584
+ )
585
+ return global_outs
586
+
587
+
588
+ def proxy_mode_key_common(
589
+ call_hop: Callable[..., Any],
590
+ proxy_mode: ProxyTorchDispatchMode,
591
+ gm: GraphModule,
592
+ *args: Any,
593
+ **kwargs: Any,
594
+ ) -> tuple[torch.Tensor]:
595
+ if proxy_mode is None:
596
+ raise AssertionError("Mode should always be enabled for python fallback key")
597
+ if len(kwargs) != 0:
598
+ raise AssertionError(f"kwargs must be empty, got {kwargs}")
599
+
600
+ example_out = call_hop(*args, **kwargs)
601
+ proxy_args = pytree.tree_map(proxy_mode.tracer.unwrap_proxy, args) # type: ignore[union-attr]
602
+
603
+ out_proxy = proxy_mode.tracer.create_proxy(
604
+ "call_function", call_hop, proxy_args, {}
605
+ )
606
+
607
+ # extract local_map args, post-dispatch operates on GraphModules
608
+ if not gm.meta["local_map_kwargs"]:
609
+ raise AssertionError("gm.meta['local_map_kwargs'] must be set")
610
+ local_map_kwargs = gm.meta["local_map_kwargs"]
611
+
612
+ # propagate local_map args to the call_function node
613
+ out_proxy.node.meta["local_map_kwargs"] = local_map_kwargs
614
+
615
+ return track_tensor_tree(
616
+ example_out, out_proxy, constant=None, tracer=proxy_mode.tracer
617
+ )
618
+
619
+
620
+ @local_map_hop.py_impl(ProxyTorchDispatchMode)
621
+ def proxy_mode_key(
622
+ proxy_mode: ProxyTorchDispatchMode,
623
+ gm: GraphModule,
624
+ *args: Any,
625
+ **kwargs: Any,
626
+ ) -> tuple[torch.Tensor]:
627
+ # TODO: get rid of this when we can install as a subgraph
628
+ def call_local_map(*_args: Any, **_kwargs: Any) -> Any:
629
+ return functools.partial(local_map_hop, gm)(*_args, **_kwargs)
630
+
631
+ return proxy_mode_key_common(call_local_map, proxy_mode, gm, *args, **kwargs)
632
+
633
+
634
+ # Running HOP in eager with real tensors
635
+ @local_map_hop.py_impl(DispatchKey.CompositeExplicitAutograd)
636
+ def real_impl(
637
+ gm: GraphModule,
638
+ *args: Any,
639
+ **kwargs: Any,
640
+ ) -> tuple[torch.Tensor]:
641
+ return gm(*args, **kwargs)
.venv/lib/python3.10/site-packages/torch/_higher_order_ops/map.py ADDED
@@ -0,0 +1,338 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import functools
3
+ from collections.abc import Callable
4
+ from typing import Union
5
+ from typing_extensions import TypeVarTuple
6
+
7
+ import torch
8
+ import torch.utils._pytree as pytree
9
+ from torch._C import DispatchKey
10
+ from torch._dispatch.python import suspend_functionalization
11
+ from torch._higher_order_ops.utils import _maybe_run_with_interpreter, reenter_make_fx
12
+ from torch._ops import HigherOrderOperator
13
+ from torch._subclasses.fake_tensor import FakeTensorMode
14
+ from torch._subclasses.functional_tensor import disable_functional_mode
15
+ from torch.fx.experimental.proxy_tensor import (
16
+ disable_proxy_modes_tracing,
17
+ ProxyTorchDispatchMode,
18
+ track_tensor_tree,
19
+ )
20
+
21
+ from .utils import (
22
+ _from_fun,
23
+ _stack_pytree,
24
+ _unstack_pytree,
25
+ create_bw_fn,
26
+ fill_none_with_masks,
27
+ filter_with_masks,
28
+ first_slice_copy,
29
+ materialize_as_graph,
30
+ save_values_for_backward,
31
+ saved_values,
32
+ split_into_chunks,
33
+ )
34
+
35
+
36
+ class MapImpl(HigherOrderOperator):
37
+ def __init__(self):
38
+ super().__init__("map_impl")
39
+
40
+ def __call__(self, *args, **kwargs):
41
+ # pyrefly: ignore [missing-attribute]
42
+ return super().__call__(*args, **kwargs)
43
+
44
+
45
+ map_impl = MapImpl()
46
+
47
+
48
+ def map(
49
+ f: Callable[[pytree.PyTree, tuple[pytree.PyTree, ...]], pytree.PyTree],
50
+ xs: Union[pytree.PyTree, torch.Tensor],
51
+ *args: TypeVarTuple,
52
+ ):
53
+ r"""
54
+ Performs a map of f with xs. Intuitively, you can think of the semantic being::
55
+
56
+ out = []
57
+ for idx in len(xs.size(0)):
58
+ xs_sliced = xs.select(0, idx)
59
+ out.append(f(xs_sliced, *args))
60
+ torch.stack(out)
61
+
62
+ .. warning::
63
+
64
+ ``torch._higher_order_ops.map`` is a prototype feature in PyTorch. It currently
65
+ does not support autograd and you may run into miscompiles.
66
+ Read more about feature classification at:
67
+ https://pytorch.org/blog/pytorch-feature-classification-changes/#prototype
68
+
69
+
70
+ Args:
71
+ f (Callable): a callable that takes an input x, that could either be a single Tensor
72
+ or a nested dict, list of tensors and some additional inputs
73
+ xs: the inputs that're to be mapped over. We'll iterate over the first dim of each x
74
+ and perform f on each slice.
75
+
76
+ *args: additional arguments provided to each step of f. They could also be omitted and
77
+ map is able to automatically figure out the read dependency.
78
+
79
+ Return:
80
+ the stacked output for each step of f
81
+
82
+ Example::
83
+
84
+ def f(xs):
85
+ return xs[0] + xs[1] + const1 + const2
86
+
87
+
88
+ xs = [torch.randn(2, 3), torch.randn(2, 3)]
89
+ const1 = torch.randn(2, 3)
90
+ const2 = torch.randn(2, 3)
91
+ # returns a tensor of shape [2, 2, 3]
92
+ torch._higher_order_ops.map(f, xs)
93
+
94
+ """
95
+ flat_xs, xs_spec = pytree.tree_flatten(xs)
96
+ flat_args, args_spec = pytree.tree_flatten(args)
97
+ if not all(isinstance(t, torch.Tensor) for t in flat_xs):
98
+ raise RuntimeError(f"Mapped xs can only consist of tensors. Got xs {flat_xs}.")
99
+
100
+ shapes = [xs.shape for xs in flat_xs]
101
+ leading_dim_size = shapes[0][0]
102
+ if leading_dim_size == 0:
103
+ raise RuntimeError("Leading dimensions of mapped xs cannot be 0.")
104
+
105
+ if any(cur_shape[0] != leading_dim_size for cur_shape in shapes):
106
+ raise RuntimeError(
107
+ f"Leading dimensions of mapped xs must be consistent. Got shapes {shapes}."
108
+ )
109
+
110
+ def run_flattened_map(f, flat_xs, flat_args):
111
+ def wrapped_fn(*flat_args, f, xs_tree_spec, args_tree_spec, num_xs):
112
+ xs = pytree.tree_unflatten(flat_args[:num_xs], xs_tree_spec)
113
+ args = pytree.tree_unflatten(flat_args[num_xs:], args_tree_spec)
114
+ return f(xs, *args)
115
+
116
+ inner_f = functools.partial(
117
+ wrapped_fn,
118
+ f=f,
119
+ xs_tree_spec=xs_spec,
120
+ args_tree_spec=args_spec,
121
+ num_xs=len(flat_xs),
122
+ )
123
+ return map_impl(inner_f, flat_xs, flat_args)
124
+
125
+ from torch._higher_order_ops.utils import _maybe_compile_and_run_fn
126
+
127
+ return _maybe_compile_and_run_fn(run_flattened_map, f, flat_xs, flat_args)
128
+
129
+
130
+ class MapAutogradOp(torch.autograd.Function):
131
+ @staticmethod
132
+ # pyrefly: ignore [bad-override]
133
+ def forward(ctx, f, num_mapped_args, *flat_args):
134
+ ctx._f = f
135
+ ctx._num_mapped_args = num_mapped_args
136
+ ctx._num_pos_args = len(flat_args) - num_mapped_args
137
+
138
+ # We snapshot the dispatch keys in forward for materializing the
139
+ # the bw_graph in backward.
140
+ ctx._fw_include_key_set = torch._C._dispatch_tls_local_include_set()
141
+ ctx._fw_exclude_key_set = torch._C._dispatch_tls_local_exclude_set()
142
+ save_values_for_backward(ctx, flat_args)
143
+ with torch._C._AutoDispatchBelowAutograd():
144
+ return (
145
+ *map_impl(f, flat_args[:num_mapped_args], flat_args[num_mapped_args:]),
146
+ )
147
+
148
+ @staticmethod
149
+ def backward(ctx, *flat_grads):
150
+ fw_args = saved_values(ctx)
151
+ num_mapped_args = ctx._num_mapped_args
152
+ num_pos_args = ctx._num_pos_args
153
+ num_grads = len(flat_grads)
154
+
155
+ fw_mapped_args, pos_args = split_into_chunks(
156
+ fw_args,
157
+ [
158
+ num_mapped_args,
159
+ num_pos_args,
160
+ ],
161
+ )
162
+
163
+ bw_f = create_bw_fn(ctx._f, fw_args)
164
+
165
+ grads_tensor_masks = []
166
+
167
+ # Create a wrapper around thefor the bw_f
168
+ def bw_f_wrapper(*args):
169
+ nonlocal grads_tensor_masks
170
+
171
+ # Dissect args and re-order them for the ``ctx._bw_f``
172
+ # args provided to the wrapper are composed of [*fw_mapped_args, *flat_grads, *pos_args]
173
+ # The content of ``bw_f_tangents`` are the upstream gradients, i.e. flat_grads
174
+ # The content of ``bw_f_primals`` are the fw_args, i.e., [*fw_mapped_args, *pos_args]
175
+ # The bw_f requires *bw_f_primals, *bw_f_tangents
176
+ fw_m_args, bw_f_tangents, pos_args = split_into_chunks(
177
+ args, [num_mapped_args, num_grads, num_pos_args]
178
+ )
179
+ bw_f_primals = *fw_m_args, *pos_args
180
+ gradients = bw_f(*bw_f_primals, *bw_f_tangents)
181
+ grads_tensor_masks = [
182
+ True if isinstance(out, torch.Tensor) else out for out in gradients
183
+ ]
184
+ return filter_with_masks(gradients, grads_tensor_masks)
185
+
186
+ def construct_args_single_step_bw():
187
+ unwrapped_mapped_xs = pytree.tree_map(_from_fun, fw_mapped_args)
188
+ # Use first_slice_copy instead of _unstack_pytree to avoid
189
+ # iterating over batch dim, which would guard on symbolic sizes.
190
+ example_xs = [
191
+ first_slice_copy(x).requires_grad_(x.requires_grad)
192
+ for x in unwrapped_mapped_xs
193
+ ]
194
+ unwrapped_grads = pytree.tree_map(_from_fun, flat_grads)
195
+ example_grads = [
196
+ first_slice_copy(x).requires_grad_(x.requires_grad)
197
+ for x in unwrapped_grads
198
+ ]
199
+ example_pos_args = [
200
+ _from_fun(arg) if isinstance(arg, torch.Tensor) else arg
201
+ for arg in pos_args
202
+ ]
203
+ return *example_xs, *example_grads, *example_pos_args
204
+
205
+ with suspend_functionalization(), disable_functional_mode():
206
+ with disable_proxy_modes_tracing():
207
+ args_single_step_bw = construct_args_single_step_bw()
208
+
209
+ # TODO: we need to materialize the bw graphs because dynamo is unable to
210
+ # trace through the joint function when torch.compile torch.autograd.grad.
211
+ fn_bw_gm = materialize_as_graph(
212
+ bw_f_wrapper,
213
+ args_single_step_bw,
214
+ ctx._fw_include_key_set,
215
+ ctx._fw_exclude_key_set,
216
+ force_enable_grad=True,
217
+ )
218
+
219
+ grads = map_impl(fn_bw_gm, fw_mapped_args + flat_grads, pos_args)
220
+
221
+ return None, None, *fill_none_with_masks(grads, grads_tensor_masks)
222
+
223
+
224
+ def _broadcast_to_batch(output, batch_size):
225
+ """Expand each tensor in output pytree to include batch dimension.
226
+
227
+ Note: Although outputs are flattened in the compiled path (via torch.compile),
228
+ users may call map_impl directly with pytree outputs, so we support pytrees
229
+ for backward compatibility.
230
+ """
231
+
232
+ def expand_with_batch(t):
233
+ if isinstance(t, torch.Tensor):
234
+ # Use contiguous_format to match torch.stack behavior
235
+ return (
236
+ t.unsqueeze(0)
237
+ .expand(batch_size, *t.shape)
238
+ .clone(memory_format=torch.contiguous_format)
239
+ )
240
+ return t
241
+
242
+ return pytree.tree_map(expand_with_batch, output)
243
+
244
+
245
+ def trace_map(proxy_mode, func_overload, f, xs, pos_args):
246
+ from torch._higher_order_ops.utils import first_slice_copy
247
+
248
+ with disable_proxy_modes_tracing():
249
+ # Use first_slice_copy instead of _unstack_pytree to avoid
250
+ # iterating over batch dim, which would guard on symbolic sizes.
251
+ example_input = pytree.tree_map(first_slice_copy, xs)
252
+
253
+ body_graph = f
254
+
255
+ body_graph = reenter_make_fx(body_graph)(*example_input, *pos_args)
256
+
257
+ next_name = proxy_mode.tracer.get_fresh_qualname("body_graph_")
258
+
259
+ proxy_mode.tracer.root.register_module(next_name, body_graph)
260
+
261
+ fake_outs = map_impl(body_graph, xs, pos_args)
262
+
263
+ node_args = (body_graph, list(xs), list(pos_args))
264
+ proxy_args = pytree.tree_map(proxy_mode.tracer.unwrap_proxy, node_args)
265
+ out_proxy = proxy_mode.tracer.create_proxy(
266
+ "call_function", func_overload, proxy_args, {}, name="map_impl"
267
+ )
268
+ return track_tensor_tree(
269
+ fake_outs, out_proxy, constant=None, tracer=proxy_mode.tracer
270
+ )
271
+
272
+
273
+ @map_impl.py_impl(DispatchKey.CompositeExplicitAutograd)
274
+ def map_dense(f, xs, pos_args):
275
+ pytrees = [f(*inp, *pos_args) for inp in _unstack_pytree(xs)]
276
+ return _stack_pytree(pytrees)
277
+
278
+
279
+ @map_impl.py_autograd_impl
280
+ def map_autograd(f, xs, pos_args):
281
+ num_mapped_args = len(xs)
282
+ flat_out = MapAutogradOp.apply(f, num_mapped_args, *xs, *pos_args)
283
+ return flat_out
284
+
285
+
286
+ @map_impl.py_impl(ProxyTorchDispatchMode)
287
+ def map_proxy_torch_dispatch_mode(mode, f, xs, args):
288
+ return trace_map(mode, map_impl, f, xs, args)
289
+
290
+
291
+ @map_impl.py_impl(FakeTensorMode)
292
+ def map_fake_tensor_mode(mode, f, xs, args):
293
+ from torch._higher_order_ops.utils import first_slice_copy
294
+
295
+ with mode:
296
+ # Use first_slice_copy instead of _unstack_pytree to avoid
297
+ # iterating over batch dim, which would guard on symbolic sizes.
298
+ first_row = pytree.tree_map(first_slice_copy, xs)
299
+ example_output = f(*first_row, *args)
300
+
301
+ flat_xs, _ = pytree.tree_flatten(xs)
302
+ batch_size = flat_xs[0].shape[0]
303
+
304
+ return _broadcast_to_batch(example_output, batch_size)
305
+
306
+
307
+ @map_impl.py_functionalize_impl
308
+ def map_functionalize(ctx, f, xs, pos_args):
309
+ from torch._higher_order_ops.utils import (
310
+ _check_alias_and_mutation,
311
+ first_slice_copy,
312
+ )
313
+
314
+ unwrapped_xs = ctx.unwrap_tensors(xs)
315
+ unwrapped_args = ctx.unwrap_tensors(pos_args)
316
+ wrapped_fn = ctx.functionalize(_maybe_run_with_interpreter(f))
317
+
318
+ with ctx.redispatch_to_next():
319
+ # Use first_slice_copy instead of _unstack_pytree to avoid
320
+ # iterating over batch dim, which would guard on symbolic sizes.
321
+ example_inputs = (
322
+ *pytree.tree_map(first_slice_copy, unwrapped_xs),
323
+ *unwrapped_args,
324
+ )
325
+ pre_dispatch = hasattr(ctx, "mode") and ctx.mode.pre_dispatch
326
+ _check_alias_and_mutation(f, example_inputs, "map", pre_dispatch)
327
+ map_return = map_impl(wrapped_fn, unwrapped_xs, unwrapped_args)
328
+ return ctx.wrap_tensors(map_return)
329
+
330
+
331
+ def _fake_map(f, x, *args):
332
+ from functorch.experimental.control_flow import _stack_pytree, _unstack_pytree
333
+
334
+ x_pytrees = _unstack_pytree(x)
335
+ zs = []
336
+ for xp in x_pytrees:
337
+ zs.append(f(xp, *args))
338
+ return _stack_pytree(zs)
.venv/lib/python3.10/site-packages/torch/_higher_order_ops/out_dtype.py ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+
3
+ import torch
4
+ import torch.utils._pytree as pytree
5
+ from torch._C import DispatchKey
6
+ from torch._higher_order_ops.utils import autograd_not_implemented
7
+ from torch._ops import HigherOrderOperator
8
+ from torch._prims_common import elementwise_dtypes, ELEMENTWISE_TYPE_PROMOTION_KIND
9
+ from torch._subclasses.fake_tensor import FakeTensorMode
10
+ from torch.fx.experimental.proxy_tensor import (
11
+ disable_proxy_modes_tracing,
12
+ maybe_handle_decomp,
13
+ ProxyTorchDispatchMode,
14
+ track_tensor_tree,
15
+ )
16
+
17
+
18
+ # TODO to figure out a more generic approach
19
+ ALLOWABLE_OPS = [
20
+ torch.ops.aten.linear.default,
21
+ torch.ops.aten.mm.default,
22
+ torch.ops.aten.conv2d.default,
23
+ torch.ops.aten.convolution.default,
24
+ torch.ops.aten.mul.Tensor,
25
+ torch.ops.aten.mul.Scalar,
26
+ torch.ops.aten.div.Tensor,
27
+ torch.ops.aten.div.Scalar,
28
+ ]
29
+
30
+
31
+ class OutDtypeOperator(HigherOrderOperator):
32
+ """
33
+ The out_dtype operator takes an existing ATen functional operator, an
34
+ `out_dtype` argument, and arguments to the original operator, and executes
35
+ the original operator and returns a Tensor with the `out_dtype` precision.
36
+ This operator does not mandate a compute precision so it allows the
37
+ representation to not be opinionated about the exact implementation.
38
+
39
+ The general implementation for all operators will be the following:
40
+ 1. Promote inputs dtypes based on default PyTorch dtype promotion rules,
41
+ using the dtypes of all input Tensors/Scalars and the `out_dtype`
42
+ arugument.
43
+ 2. Execute the operator
44
+ 3. Cast the output to `out_dtype`
45
+ """
46
+
47
+ def __init__(self) -> None:
48
+ super().__init__("out_dtype")
49
+
50
+ def __call__(self, op, output_dtype, *args):
51
+ if not isinstance(op, torch._ops.OpOverload):
52
+ raise ValueError("out_dtype's first argument must be an OpOverload")
53
+ if op._schema.is_mutable:
54
+ raise ValueError(
55
+ "out_dtype's first argument needs to be a functional operator"
56
+ )
57
+ if not (
58
+ len(op._schema.returns) == 1
59
+ and isinstance(op._schema.returns[0].type, torch.TensorType)
60
+ ):
61
+ raise ValueError(
62
+ "out_dtype's can only apply to ops that return a single tensor"
63
+ f"Instead got {[r.type for r in op._schema.returns]}"
64
+ )
65
+
66
+ if op not in ALLOWABLE_OPS:
67
+ raise ValueError(
68
+ f"out_dtype only allows the following operators: {ALLOWABLE_OPS}."
69
+ )
70
+
71
+ # pyrefly: ignore [missing-attribute]
72
+ res = super().__call__(op, output_dtype, *args)
73
+
74
+ return res
75
+
76
+
77
+ out_dtype = OutDtypeOperator()
78
+
79
+
80
+ def trace_out_dtype(proxy_mode, func_overload, op, output_dtype, *args):
81
+ # NB: Long-term we should put the decomposition logic into
82
+ # ProxyTorchDispatchMode so that people do not need to call maybe_handle_decomp
83
+ # in all HigherOrderOp proxy implementations.
84
+ r = maybe_handle_decomp(proxy_mode, func_overload, (op, output_dtype, *args), {})
85
+ if r is not NotImplemented:
86
+ return r
87
+
88
+ with disable_proxy_modes_tracing():
89
+ # This is a simplified implementation of this operator just for tracing.
90
+ # Actual implementation may also first promote the arguments
91
+ out = op(*args).to(dtype=output_dtype)
92
+
93
+ node_args = (op, output_dtype, *args)
94
+ proxy_args = pytree.tree_map(proxy_mode.tracer.unwrap_proxy, node_args)
95
+ out_proxy = proxy_mode.tracer.create_proxy(
96
+ "call_function", func_overload, proxy_args, {}, name="out_dtype"
97
+ )
98
+ return track_tensor_tree(out, out_proxy, constant=None, tracer=proxy_mode.tracer)
99
+
100
+
101
+ @out_dtype.py_impl(DispatchKey.CompositeExplicitAutograd)
102
+ def out_dtype_dense(op: torch._ops.OpOverload, output_dtype: torch.dtype, *args):
103
+ if is_int_mm(op, output_dtype, args):
104
+ return torch._int_mm(*args)
105
+ return out_dtype_fallback(op, output_dtype, *args)
106
+
107
+
108
+ def is_int_mm(op, output_dtype, args):
109
+ return (
110
+ op is torch.ops.aten.mm.default
111
+ and output_dtype == torch.int32
112
+ and len(args) == 2
113
+ and args[0].dtype == torch.int8
114
+ and args[1].dtype == torch.int8
115
+ and (args[0].is_cuda or args[0].is_xpu)
116
+ and (args[1].is_cuda or args[1].is_xpu)
117
+ )
118
+
119
+
120
+ def out_dtype_fallback(op, output_dtype, *args):
121
+ flat_inputs = pytree.arg_tree_leaves(*args) + [torch.ones(1, dtype=output_dtype)]
122
+ promote_dtype: torch.dtype = elementwise_dtypes(
123
+ *flat_inputs,
124
+ type_promotion_kind=ELEMENTWISE_TYPE_PROMOTION_KIND.DEFAULT,
125
+ )[0]
126
+
127
+ casted_args = pytree.tree_map_only(
128
+ torch.Tensor, lambda arg: arg.to(dtype=promote_dtype), args
129
+ )
130
+ res = op(*casted_args).to(dtype=output_dtype)
131
+ return res
132
+
133
+
134
+ out_dtype.py_autograd_impl(autograd_not_implemented(out_dtype, deferred_error=True))
135
+
136
+
137
+ @out_dtype.py_impl(ProxyTorchDispatchMode)
138
+ def out_dtype_proxy(
139
+ mode: ProxyTorchDispatchMode,
140
+ op: torch._ops.OpOverload,
141
+ output_dtype: torch.dtype,
142
+ *args,
143
+ ):
144
+ return trace_out_dtype(mode, out_dtype, op, output_dtype, *args)
145
+
146
+
147
+ @out_dtype.py_impl(FakeTensorMode)
148
+ def out_dtype_fake_tensor_mode(
149
+ mode: FakeTensorMode,
150
+ op: torch._ops.OpOverload,
151
+ output_dtype: torch.dtype,
152
+ *args,
153
+ ):
154
+ with mode:
155
+ return out_dtype_dense(op, output_dtype, *args)
156
+
157
+
158
+ @out_dtype.py_functionalize_impl
159
+ def out_dtype_func(ctx, op, output_dtype, *args):
160
+ unwrapped_args = tuple(ctx.unwrap_tensors(arg) for arg in args)
161
+
162
+ with ctx.redispatch_to_next():
163
+ res = out_dtype(op, output_dtype, *unwrapped_args)
164
+ return ctx.wrap_tensors(res)
.venv/lib/python3.10/site-packages/torch/_higher_order_ops/partitioner.py ADDED
@@ -0,0 +1,381 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ from collections.abc import Callable
3
+ from typing import Any, Union
4
+
5
+ import torch
6
+ from torch._higher_order_ops.utils import create_bw_fn, materialize_as_graph
7
+
8
+
9
+ logger: logging.Logger = logging.getLogger(__name__)
10
+
11
+ logger.setLevel(logging.DEBUG)
12
+
13
+
14
+ def _find_hop_subgraph_outputs(gm: torch.fx.GraphModule) -> tuple[torch.fx.Node]:
15
+ output_node_args = gm.graph.find_nodes(op="output")[0].args
16
+ if not isinstance(output_node_args, tuple):
17
+ raise AssertionError(
18
+ f"expected output_node_args to be tuple, got {type(output_node_args)}"
19
+ )
20
+ return output_node_args[0]
21
+
22
+
23
+ def is_complex_expr(expr: Any) -> bool:
24
+ return not expr.is_symbol and not expr.is_constant()
25
+
26
+
27
+ class HopPartitionedGraph:
28
+ def __init__(
29
+ self,
30
+ fw_gm: torch.fx.GraphModule,
31
+ bw_gm: torch.fx.GraphModule,
32
+ n_fw_outputs: int,
33
+ n_intermediates: int,
34
+ no_complex_exprs_at_boundary: bool,
35
+ ):
36
+ self.fw_gm = fw_gm
37
+ self.bw_gm = bw_gm
38
+ self.n_fw_outputs = n_fw_outputs
39
+ self.n_intermediates = n_intermediates
40
+ self.no_complex_exprs_at_boundary = no_complex_exprs_at_boundary
41
+ self._reorder_fw_output()
42
+ self._check_partition_boundary()
43
+
44
+ def _check_partition_boundary(self) -> None:
45
+ """check partitioned graph is in valid state."""
46
+ invalid_reasons = []
47
+ fw_outputs = _find_hop_subgraph_outputs(self.fw_gm)
48
+ for i, out in enumerate(fw_outputs):
49
+ if "val" not in out.meta:
50
+ invalid_reasons.append(f"fw_gm output[{i}] doesn't have a 'val' meta.")
51
+ elif not isinstance(out.meta["val"], (torch.SymInt, torch.Tensor)):
52
+ invalid_reasons.append(
53
+ f"fw_gm output[{i}] is of type {type(out.meta['val'])} but only SymInt or Tensor are allowed."
54
+ )
55
+
56
+ elif (
57
+ isinstance(out.meta["val"], torch.SymInt)
58
+ and is_complex_expr(out.meta["val"].node.expr)
59
+ and self.no_complex_exprs_at_boundary
60
+ ):
61
+ invalid_reasons.append(
62
+ f"fw_gm output[{i}] must be of type SymInt with basic symbols or "
63
+ f"Tensor but got {type(out.meta['val'])} {out.meta['val']}"
64
+ )
65
+
66
+ if len(fw_outputs) != self.n_fw_outputs + self.n_intermediates:
67
+ invalid_reasons.append(
68
+ f"len(fw_outputs) ({len(fw_outputs)}) != n_fw_outputs ({self.n_fw_outputs}) + n_intermediates ({self.n_intermediates})" # noqa: B950
69
+ )
70
+
71
+ bw_phs = list(self.bw_gm.graph.find_nodes(op="placeholder"))
72
+
73
+ if len(fw_outputs) != len(bw_phs):
74
+ invalid_reasons.append(
75
+ f"Expect number of fw_gm's output to be the same as bw_gm's input but "
76
+ f"fw_gm has {len(fw_outputs)} outputs, bw_gm takes {len(bw_phs)} inputs."
77
+ )
78
+
79
+ original_forward_outputs = fw_outputs[: self.n_fw_outputs]
80
+ fw_intermediates = fw_outputs[self.n_fw_outputs :]
81
+
82
+ bw_intermediates = bw_phs[: -self.n_fw_outputs]
83
+ bw_grads = bw_phs[-self.n_fw_outputs :]
84
+
85
+ def _match_size_or_expr(
86
+ val1: Union[torch.SymInt, torch.Tensor],
87
+ val2: Union[torch.SymInt, torch.Tensor],
88
+ ) -> bool:
89
+ if type(val1) is not type(val2):
90
+ return False
91
+
92
+ if isinstance(val1, torch.SymInt) and isinstance(val2, torch.SymInt):
93
+ return val1.node.expr == val2.node.expr
94
+ elif isinstance(val1, torch.Tensor) and isinstance(val2, torch.Tensor):
95
+ return val1.size() == val2.size()
96
+
97
+ return False
98
+
99
+ for fw, bw in zip(fw_intermediates, bw_intermediates):
100
+ if fw.name != bw.name or not _match_size_or_expr(
101
+ fw.meta["val"], bw.meta["val"]
102
+ ):
103
+ invalid_reasons.append("fw intermediates don't match bw intermediates")
104
+
105
+ for fw_out, bw_grad in zip(original_forward_outputs, bw_grads):
106
+ if not _match_size_or_expr(fw_out.meta["val"], bw_grad.meta["val"]):
107
+ invalid_reasons.append("fw outputs don't match bw gradients")
108
+
109
+ if len(invalid_reasons) > 0:
110
+ newline = "\n"
111
+ raise RuntimeError(
112
+ "Invalid HopPartitionedGraph. Reasons:\n",
113
+ f"{newline.join(invalid_reasons)}",
114
+ )
115
+
116
+ def _reorder_fw_output(self) -> None:
117
+ """
118
+ Before the pass, fw_gm returns (*fw_outputs, *intermediates1)
119
+ and bw_gm takes (*intermediates2, *grad_fw_outputs) as input.
120
+ intermediates1 and intermediates2 share the same node names but
121
+ they might be in different order. E.g. this could happen if there
122
+ are inputs that contain symints.
123
+
124
+ To simplify downstream processing, this graph pass normalizes the output of fw_gm
125
+ to be consistent with the bacwkard inputs:
126
+
127
+ fw_gm:
128
+ - input: fw_args
129
+ - output: (*fw_outputs, *intermediates)
130
+
131
+ bw_gm:
132
+ - input: (*intermediates, *grad_fw_outputs)
133
+ - output: grad_fw_args
134
+
135
+ Example:
136
+
137
+ def fw_gm(x, y, z):
138
+ a, b, c = f(x), g(y), k(z)
139
+ return a, b, c, f_tmp, g_tmp, k_tmp
140
+
141
+ , where a, b, c are fw_outputs, f_tmp, g_tmp, k_tmp are intermediates
142
+
143
+ The corresponding bw_gm has the following signature:
144
+
145
+ def bw_gm(f_tmp, g_tmp, k_tmp, grad_a, grad_b, grac):
146
+ return grad_x, grad_y, grad_z
147
+ """
148
+ fw_gm_output_nodes = _find_hop_subgraph_outputs(self.fw_gm)
149
+ fw_outputs_nodes = fw_gm_output_nodes[: self.n_fw_outputs]
150
+ fw_intermediates_nodes = fw_gm_output_nodes[self.n_fw_outputs :]
151
+ if len(fw_intermediates_nodes) > 0:
152
+ fw_intermediates_name_to_node = {n.name: n for n in fw_intermediates_nodes}
153
+
154
+ # First n_intermediates placeholders
155
+ bw_names: list[str] = [
156
+ ph.name
157
+ for ph in list(self.bw_gm.graph.find_nodes(op="placeholder"))[
158
+ : self.n_intermediates
159
+ ]
160
+ ]
161
+ new_fw_outputs = list(fw_outputs_nodes) + [
162
+ fw_intermediates_name_to_node[name] for name in bw_names
163
+ ]
164
+
165
+ output_node = self.fw_gm.graph.find_nodes(op="output")[0]
166
+ output_node.args = (tuple(new_fw_outputs),)
167
+
168
+ self.fw_gm.graph.lint()
169
+ self.fw_gm.recompile()
170
+
171
+
172
+ class HopJointGraph:
173
+ def __init__(
174
+ self,
175
+ joint_gm: torch.fx.GraphModule,
176
+ n_primals: int,
177
+ n_fw_outputs: int,
178
+ *,
179
+ functionalized: bool,
180
+ ):
181
+ self.joint_gm = joint_gm
182
+ self.n_primals = n_primals
183
+ self.n_fw_outputs = n_fw_outputs
184
+ self.functionalized = functionalized
185
+
186
+ self._rename_phs()
187
+ self._remove_redundant_sym_size_ops()
188
+
189
+ def _rename_phs(self) -> None:
190
+ """
191
+ Rename the placeholders for joint_gm so that the partitioner
192
+ could recognize which inputs are primals and which are tangents.
193
+ """
194
+ self.n_tangents = 0
195
+ for i, ph in enumerate(self.joint_gm.graph.find_nodes(op="placeholder")):
196
+ if i < self.n_primals:
197
+ ph.target = f"primals_{i}"
198
+ ph.name = f"primals_{i}"
199
+ else:
200
+ self.n_tangents += 1
201
+ ph.target = f"tangents_{i - self.n_primals}"
202
+ ph.name = f"tangents_{i - self.n_primals}"
203
+
204
+ self.joint_gm.graph.lint()
205
+ self.joint_gm.compile()
206
+
207
+ def _remove_redundant_sym_size_ops(self) -> None:
208
+ """
209
+ Deletes torch.ops.sym_size.int operators whose output is a
210
+ corresponding placeholder that holds the same symbol, and replace all usage
211
+ of the sym_size node to be directly using the placeholders.
212
+
213
+ This is to make sure all basic symbols come from inputs.
214
+ """
215
+ placeholder_exprs = {}
216
+ for node in self.joint_gm.graph.nodes:
217
+ if (
218
+ isinstance(node, torch.fx.Node)
219
+ and node.op == "placeholder"
220
+ and hasattr(node, "meta")
221
+ and "val" in node.meta
222
+ ):
223
+ val = node.meta["val"]
224
+ if isinstance(val, torch.SymInt):
225
+ placeholder_exprs[val.node.expr] = node
226
+
227
+ nodes_to_remove = []
228
+ for node in self.joint_gm.graph.find_nodes(
229
+ op="call_function", target=torch.ops.aten.sym_size.int
230
+ ):
231
+ if not (hasattr(node, "meta") and "val" in node.meta):
232
+ raise AssertionError(
233
+ f"node {node} must have 'meta' attribute with 'val' key"
234
+ )
235
+ val = node.meta["val"]
236
+ expr = val.node.expr
237
+ if expr in placeholder_exprs:
238
+ placeholder_node = placeholder_exprs[expr]
239
+ node.replace_all_uses_with(placeholder_node)
240
+ nodes_to_remove.append(node)
241
+
242
+ for node in nodes_to_remove:
243
+ self.joint_gm.graph.erase_node(node)
244
+
245
+ self.joint_gm.graph.lint()
246
+ self.joint_gm.recompile()
247
+
248
+ def _mark_complex_exprs_as_must_recompute(self) -> None:
249
+ """
250
+ For control flow operators such as scan, we don't want to
251
+ have symint in the partitioning boundaries because otherwise we would need to support stacking
252
+ the symints up, which causes more entropy in the stack.
253
+
254
+ By marking the recompute polify for complex nodes as MUST_RECOMPUTE, the partitioning boundary
255
+ no longer contains complex expressions.
256
+
257
+ Note that this pass doesn't exclude basic symbols from partitioning boundary
258
+ and it's up to the downstream to decide whether to return the basic symbol
259
+ or have a separate graph pass to remove them.
260
+ """
261
+
262
+ from torch._functorch.partitioners import CheckpointPolicy
263
+
264
+ for n in (
265
+ node for node in self.joint_gm.graph.nodes if node.op == "call_function"
266
+ ):
267
+ if "val" not in n.meta:
268
+ continue
269
+ val = n.meta["val"]
270
+ if isinstance(val, torch.SymInt) and is_complex_expr(val.node.expr):
271
+ if n.meta.get("recompute", None) is not None:
272
+ raise AssertionError(
273
+ f"node {n} with complex SymInt expression should not have recompute policy set"
274
+ )
275
+
276
+ n.meta["recompute"] = CheckpointPolicy.MUST_RECOMPUTE
277
+
278
+ self.joint_gm.graph.lint()
279
+ self.joint_gm.recompile()
280
+
281
+ def partition(
282
+ self, partition_fn: Callable, always_recompute_complex_exprs: bool
283
+ ) -> HopPartitionedGraph:
284
+ if logger.isEnabledFor(logging.DEBUG):
285
+ logger.debug(
286
+ "before min_cut_partition:\n%s",
287
+ self.joint_gm.print_readable(print_output=False),
288
+ )
289
+
290
+ if always_recompute_complex_exprs:
291
+ self._mark_complex_exprs_as_must_recompute()
292
+
293
+ fw_gm, bw_gm = partition_fn(
294
+ self.joint_gm, None, num_fwd_outputs=self.n_fw_outputs
295
+ )
296
+
297
+ if logger.isEnabledFor(logging.DEBUG):
298
+ logger.debug("after partition_fn:")
299
+ logger.debug("fw_gm:\n%s", fw_gm.print_readable(print_output=False))
300
+ logger.debug("bw_gm:\n%s", bw_gm.print_readable(print_output=False))
301
+
302
+ n_intermediates = len(_find_hop_subgraph_outputs(fw_gm)) - self.n_fw_outputs
303
+
304
+ return HopPartitionedGraph(
305
+ fw_gm,
306
+ bw_gm,
307
+ self.n_fw_outputs,
308
+ n_intermediates,
309
+ always_recompute_complex_exprs,
310
+ )
311
+
312
+
313
+ def create_hop_joint_graph(
314
+ fw_fn: Callable,
315
+ fw_args: tuple[Union[torch.Tensor, torch.SymInt], ...],
316
+ functionalize: bool,
317
+ ) -> HopJointGraph:
318
+ fw_gm = materialize_as_graph(fw_fn, fw_args, force_enable_grad=True)
319
+ fw_gm_output_nodes = _find_hop_subgraph_outputs(fw_gm)
320
+
321
+ if not all(
322
+ isinstance(n, torch.fx.Node) and "val" in n.meta for n in fw_gm_output_nodes
323
+ ):
324
+ raise AssertionError(
325
+ "all fw_gm output nodes must be torch.fx.Node with 'val' in meta"
326
+ )
327
+ fw_gm_output_vals = tuple(n.meta["val"] for n in fw_gm_output_nodes) # type: ignore[arg-type]
328
+
329
+ if not all(isinstance(val, torch.Tensor) for val in fw_gm_output_vals):
330
+ raise AssertionError(
331
+ f"all fw_gm output values must be torch.Tensor, got {[type(v) for v in fw_gm_output_vals]}"
332
+ )
333
+ example_grads = tuple(torch.zeros_like(val) for val in fw_gm_output_vals)
334
+
335
+ joint_fn = create_bw_fn(fw_fn, fw_args, return_fw_outputs=True)
336
+ joint_gm = materialize_as_graph(
337
+ joint_fn, fw_args + example_grads, force_enable_grad=True
338
+ )
339
+ if functionalize:
340
+ # Need to first trace out the joint_fn with autograd info on
341
+ # then functionalize the graph otherwise the grad information is lost
342
+ joint_gm = materialize_as_graph(
343
+ # pyrefly: ignore [bad-argument-type]
344
+ torch.func.functionalize(joint_gm, remove="mutations_and_views"),
345
+ fw_args + example_grads,
346
+ )
347
+
348
+ return HopJointGraph(
349
+ joint_gm,
350
+ len(fw_args),
351
+ len(fw_gm_output_nodes),
352
+ functionalized=functionalize,
353
+ )
354
+
355
+
356
+ class HopGraphMinCutPartitioner:
357
+ @staticmethod
358
+ def create_partitioned_graph(
359
+ fw_fn: Callable,
360
+ fw_args: tuple[Union[torch.Tensor, torch.SymInt], ...],
361
+ *,
362
+ always_recompute_complex_exprs: bool = False,
363
+ ) -> HopPartitionedGraph:
364
+ """
365
+ Inputs:
366
+ - fw_fn: the forward function that we'll use to create a joint graph and partition
367
+ - fw_args: the flat_args to fw_fn
368
+ - always_recompute_complex_exprs: when set to True, the bw_gm will do a re-compute
369
+ for inputs that are complex expressions such that the partitioning boundary
370
+ only consists of basic symbols and tensors.
371
+
372
+ Returns a HopPartitionedGraph
373
+ """
374
+ from torch._functorch.partitioners import min_cut_rematerialization_partition
375
+
376
+ joint_graph: HopJointGraph = create_hop_joint_graph(
377
+ fw_fn, fw_args, functionalize=True
378
+ )
379
+ return joint_graph.partition(
380
+ min_cut_rematerialization_partition, always_recompute_complex_exprs
381
+ )
.venv/lib/python3.10/site-packages/torch/_higher_order_ops/print.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import builtins
2
+
3
+ import torch
4
+ import torch.utils._pytree as pytree
5
+ from torch._ops import HigherOrderOperator
6
+ from torch._subclasses.fake_tensor import FakeTensorMode
7
+ from torch.fx.experimental.proxy_tensor import ProxyTorchDispatchMode
8
+
9
+
10
+ class Print(HigherOrderOperator):
11
+ """
12
+ print(format_str, *args, **kwargs) -> None
13
+
14
+ This Higher Order Operator (HOP) provides a functional version of print for use in PyTorch graphs.
15
+ It supports the calling conventions of print(format_str.format(*args, **kwargs)):
16
+
17
+ 1. Format string with keyword arguments (named placeholders):
18
+ torch._higher_order_ops.print("moo {x} {y}", x=1, y=2)
19
+ Output: "moo 1 2"
20
+
21
+ 2. Format string with positional arguments (positional placeholders):
22
+ torch._higher_order_ops.print("moo {} {}", 1, 2)
23
+ Output: "moo 1 2"
24
+
25
+ 3. Mixed positional and keyword arguments:
26
+ torch._higher_order_ops.print("moo {} {y}", 1, y=2)
27
+ Output: "moo 1 2"
28
+
29
+ This HOP enables printing without causing graph break.
30
+ """
31
+
32
+ def __init__(self) -> None:
33
+ super().__init__("print")
34
+
35
+ def __call__(self, format_str: str, *args: object, **kwargs: object) -> None:
36
+ if not isinstance(format_str, str):
37
+ raise AssertionError(f"format_str must be a string, got {type(format_str)}")
38
+ # pyrefly: ignore [missing-attribute]
39
+ return super().__call__(format_str, *args, **kwargs)
40
+
41
+ # pyrefly: ignore [bad-override]
42
+ def gen_schema(
43
+ self, format_str: str, *args: object, **kwargs: object
44
+ ) -> torch.FunctionSchema:
45
+ from torch._higher_order_ops.schema import HopSchemaGenerator
46
+
47
+ schema_gen = HopSchemaGenerator(self)
48
+ schema_gen.add_arg("format_str", format_str[0])
49
+
50
+ # Add each positional arg
51
+ for i, value in enumerate(args):
52
+ schema_gen.add_arg(f"arg{i}", value)
53
+
54
+ # Add each kwarg as a keyword-only argument
55
+ for key, value in kwargs.items():
56
+ schema_gen.add_arg(key, value, kw_only=True)
57
+
58
+ schema_gen.add_schema_tree_spec(format_str, *args, **kwargs)
59
+
60
+ return schema_gen.gen_schema()
61
+
62
+
63
+ print = Print()
64
+
65
+
66
+ @print.py_impl(ProxyTorchDispatchMode)
67
+ # pyre-ignore
68
+ def print_proxy_torch_dispatch_mode(
69
+ mode: ProxyTorchDispatchMode, format_str: str, *args: object, **kwargs: object
70
+ ) -> None:
71
+ proxy_args = pytree.tree_map(mode.tracer.unwrap_proxy, args) # type: ignore[union-attr]
72
+ proxy_kwargs = pytree.tree_map(mode.tracer.unwrap_proxy, kwargs) # type: ignore[union-attr]
73
+ mode.tracer.create_proxy(
74
+ "call_function", print, (format_str, *proxy_args), proxy_kwargs
75
+ )
76
+
77
+
78
+ @print.py_impl(FakeTensorMode)
79
+ # pyre-ignore
80
+ def print_fake_tensor_mode(mode, format_str: str, *args: object, **kwargs: object):
81
+ return None
82
+
83
+
84
+ @print.py_impl(torch._C.DispatchKey.CompositeExplicitAutograd)
85
+ # pyre-ignore
86
+ def print_impl(format_str: str, *args: object, **kwargs: object) -> None:
87
+ # Ensure all immutable_dict/list in args and kwargs are converted to regular dict/list
88
+ map_types: dict[type, type] = {
89
+ torch.fx.immutable_collections.immutable_dict: dict,
90
+ torch.fx.immutable_collections.immutable_list: list,
91
+ }
92
+ new_args, new_kwargs = pytree.tree_map_only(
93
+ tuple(map_types.keys()),
94
+ lambda a: map_types[type(a)](a),
95
+ (args, kwargs),
96
+ lambda a: isinstance(a, tuple(map_types.keys())),
97
+ )
98
+ # Use built-in print to avoid recursion with the HOP print
99
+ builtins.print(format_str.format(*new_args, **new_kwargs))
100
+
101
+
102
+ print.fallthrough(torch._C.DispatchKey.AutogradCPU)
103
+ print.fallthrough(torch._C.DispatchKey.AutogradCUDA)
104
+
105
+
106
+ @print.py_functionalize_impl
107
+ def print_func(ctx, format_str: str, *args: object, **kwargs: object):
108
+ from torch._higher_order_ops.effects import handle_effects
109
+
110
+ return handle_effects(
111
+ ctx.mode._allow_token_discovery,
112
+ ctx.mode._tokens,
113
+ print, # type: ignore[arg-type]
114
+ (format_str, *args),
115
+ kwargs, # type: ignore[arg-type]
116
+ )
.venv/lib/python3.10/site-packages/torch/_higher_order_ops/run_const_graph.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, TYPE_CHECKING
2
+
3
+ import torch
4
+ from torch._C import DispatchKey
5
+ from torch._higher_order_ops.utils import autograd_not_implemented
6
+ from torch._ops import HigherOrderOperator
7
+ from torch._subclasses.fake_tensor import FakeTensorMode
8
+
9
+
10
+ if TYPE_CHECKING:
11
+ from torch._subclasses.functional_tensor import BaseFunctionalizeAPI
12
+
13
+ from torch.fx.experimental.proxy_tensor import ProxyTorchDispatchMode, track_tensor_tree
14
+ from torch.utils import _pytree as pytree
15
+
16
+
17
+ class RunConstGraph(HigherOrderOperator):
18
+ def __init__(self) -> None:
19
+ super().__init__("run_const_graph")
20
+
21
+ def __call__(self, graph: torch.fx.GraphModule, args: tuple[object, ...]) -> object:
22
+ # pyrefly: ignore [missing-attribute]
23
+ return super().__call__(graph, args)
24
+
25
+
26
+ run_const_graph = RunConstGraph()
27
+
28
+
29
+ @run_const_graph.py_impl(ProxyTorchDispatchMode)
30
+ def run_const_graph_dispatch_mode(
31
+ mode: ProxyTorchDispatchMode, graph: torch.fx.GraphModule, args: tuple[object, ...]
32
+ ) -> object:
33
+ const_gm, weights = graph, args
34
+ p_args = pytree.tree_map(mode.tracer.unwrap_proxy, (graph, args)) # type: ignore[union-attr]
35
+ if not isinstance(const_gm, torch.fx.GraphModule):
36
+ raise AssertionError(
37
+ f"expected const_gm to be torch.fx.GraphModule, got {type(const_gm)}"
38
+ )
39
+ if hasattr(mode.tracer.root, "_const_graph"): # type: ignore[union-attr]
40
+ raise AssertionError("mode.tracer.root already has _const_graph attribute")
41
+ mode.tracer.root.register_module("_const_graph", const_gm) # type: ignore[union-attr]
42
+
43
+ proxy = mode.tracer.create_proxy("call_function", run_const_graph, p_args, {})
44
+
45
+ out = const_gm(*weights)
46
+ return track_tensor_tree(out, proxy, constant=None, tracer=mode.tracer)
47
+
48
+
49
+ @run_const_graph.py_functionalize_impl
50
+ def run_const_graph_functional(
51
+ ctx: "BaseFunctionalizeAPI", graph: torch.fx.GraphModule, args: tuple[Any, ...]
52
+ ) -> Any:
53
+ unwrapped_args = ctx.unwrap_tensors(args)
54
+
55
+ with ctx.redispatch_to_next():
56
+ out = run_const_graph(graph, unwrapped_args)
57
+ return ctx.wrap_tensors(out) # type: ignore[arg-type]
58
+
59
+
60
+ run_const_graph.py_autograd_impl(
61
+ autograd_not_implemented(run_const_graph, deferred_error=True)
62
+ )
63
+
64
+
65
+ @run_const_graph.py_impl(FakeTensorMode)
66
+ def run_const_graph_fake_tensor_mode(
67
+ mode: FakeTensorMode, graph: torch.fx.GraphModule, args: tuple[object, ...]
68
+ ) -> object:
69
+ if not isinstance(graph, torch.fx.GraphModule):
70
+ raise AssertionError(
71
+ f"expected graph to be torch.fx.GraphModule, got {type(graph)}"
72
+ )
73
+ with mode:
74
+ return graph(*args)
75
+
76
+
77
+ @run_const_graph.py_impl(DispatchKey.CPU)
78
+ def run_const_graph_cpu(
79
+ graph: torch.fx.GraphModule, args: tuple[object, ...]
80
+ ) -> object:
81
+ if not isinstance(graph, torch.fx.GraphModule):
82
+ raise AssertionError(
83
+ f"expected graph to be torch.fx.GraphModule, got {type(graph)}"
84
+ )
85
+ return graph(*args)
.venv/lib/python3.10/site-packages/torch/_higher_order_ops/scan.py ADDED
@@ -0,0 +1,990 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import enum
3
+ import functools
4
+ import itertools
5
+ import logging
6
+ from collections.abc import Callable
7
+ from typing import Any
8
+
9
+ import torch
10
+ import torch._prims_common as utils
11
+ import torch.utils._pytree as pytree
12
+ from torch._C import DispatchKey
13
+ from torch._higher_order_ops.partitioner import (
14
+ _find_hop_subgraph_outputs,
15
+ HopGraphMinCutPartitioner,
16
+ HopPartitionedGraph,
17
+ )
18
+ from torch._higher_order_ops.utils import (
19
+ _maybe_compile_and_run_fn,
20
+ check_input_alias_and_mutation_return_outputs,
21
+ check_meta_consistency,
22
+ fill_none_with_masks,
23
+ filter_with_masks,
24
+ first_slice_copy,
25
+ get_tensor_mask,
26
+ mask_list,
27
+ materialize_as_graph,
28
+ reenter_make_fx,
29
+ split_into_chunks,
30
+ unique_graph_id,
31
+ validate_subgraph_args_types,
32
+ )
33
+ from torch._ops import HigherOrderOperator
34
+ from torch._subclasses.fake_tensor import FakeTensorMode
35
+ from torch.fx.experimental.proxy_tensor import (
36
+ disable_proxy_modes_tracing,
37
+ ProxyTorchDispatchMode,
38
+ track_tensor_tree,
39
+ )
40
+ from torch.utils._python_dispatch import _get_current_dispatch_mode
41
+
42
+
43
+ logger: logging.Logger = logging.getLogger(__name__)
44
+ aten = torch._ops.ops.aten
45
+
46
+
47
+ def wrap_combine_fn_flat(
48
+ *args, combine_fn, spec_init, spec_xs, num_init_leaves, num_inp_leaves
49
+ ):
50
+ if len(args) != (num_init_leaves + num_inp_leaves):
51
+ raise AssertionError(
52
+ f"combine_fn received wrong number of arguments, expected {num_init_leaves + num_inp_leaves}, but got {len(args)}"
53
+ )
54
+ carry = pytree.tree_unflatten(args[:num_init_leaves], spec_init)
55
+ xs = pytree.tree_unflatten(args[num_init_leaves:], spec_xs)
56
+ return combine_fn(carry, xs)
57
+
58
+
59
+ def _extract_carry_and_out(flat_out: list[Any], num_carry: int):
60
+ return split_into_chunks(flat_out, [num_carry, len(flat_out) - num_carry])
61
+
62
+
63
+ # We also do a clone with contiguous_format. This is to be consistent with
64
+ # eager semantic of scan, which stacks the outputs. The result is contiguous
65
+ # as a result of the stack operation.
66
+ def stack_y(y: torch.Tensor, scan_length: int) -> torch.Tensor:
67
+ return (
68
+ y.unsqueeze(0)
69
+ .repeat(*([scan_length] + [1] * y.ndim))
70
+ .clone(memory_format=torch.contiguous_format)
71
+ )
72
+
73
+
74
+ def call_operator(operator, *args):
75
+ return pytree.tree_leaves(operator(*args))
76
+
77
+
78
+ def scan(
79
+ combine_fn: Callable[
80
+ [pytree.PyTree, pytree.PyTree], tuple[pytree.PyTree, pytree.PyTree]
81
+ ],
82
+ init: pytree.PyTree,
83
+ xs: pytree.PyTree,
84
+ *,
85
+ dim: int = 0,
86
+ reverse: bool = False,
87
+ ) -> tuple[pytree.PyTree, pytree.PyTree]:
88
+ r"""
89
+ Performs an inclusive scan with a combine function.
90
+
91
+ .. warning::
92
+
93
+ ``torch.scan`` is a prototype feature in PyTorch. You may run into miscompiles.
94
+ Read more about feature classification at:
95
+ https://pytorch.org/blog/pytorch-feature-classification-changes/#prototype
96
+
97
+ Args:
98
+ combine_fn (Callable): A binary callable with type ``(Tensor, Tensor) -> (Tensor, Tensor)``,
99
+ or if xs is a pytree ``(pytree, pytree) -> (pytree, pytree)``.
100
+ The first input to ``combine_fn`` is the previous or initial scan carry
101
+ and the second input element to ``combine_fn`` is a slice of the input along dim.
102
+ The first output element of ``combine_fn`` is the next scan carry
103
+ and the second output of ``combine_fn`` represents a slice of the output.
104
+ This function must be pure, i.e., no lifted arguments are supported at the moment
105
+ and may not have any side effects.
106
+ init (torch.Tensor or pytree with tensor leaves): The initial scan carry, a tensor, or nested pytree of tensors.
107
+ The ``init`` is expected to have the same pytree structure as the first output element (i.e. carry)
108
+ of ``combine_fn``.
109
+ xs (torch.Tensor or pytree with tensor leaves): The input tensor, or nested pytree of tensors.
110
+
111
+ Kwargs:
112
+ dim (int): the dimension to scan over, default 0.
113
+ reverse (bool): A boolean stating if the scan should be reversed with respect to ``dim``, default ``False``.
114
+
115
+ Returns:
116
+ final_carry (torch.Tensor or pytree with tensor leaves),
117
+ the final carry of the scan operation with same pytree structure as init.
118
+ out (torch.Tensor or pytree with tensor leaves),
119
+ each tensor leaf is a stacked output along first dim, where each slice is the output of a scan iteration.
120
+
121
+ Restrictions:
122
+ - The combine_fn shouldn't have any aliasing between input-input, input-output, and output-output. E.g. return a view
123
+ or the same tensor as input is not supported. As a workaround, can clone the output to avoid aliasing.
124
+
125
+ - The combine_fn shouldn't mutate any inputs. We'll remove the mutation restriction for inference soon. Please file an issue
126
+ if you input mutation support for training is needed.
127
+
128
+ - The combine_fn's init carry should match the next_carry in pytree structure and in tensor metadata.
129
+
130
+ Example::
131
+
132
+ def add(x: torch.Tensor, y: torch.Tensor):
133
+ next_carry = y = x + y
134
+ # clone the output to avoid output-output aliasing
135
+ return next_carry, y.clone()
136
+
137
+
138
+ i0 = torch.zeros(1)
139
+ xs = torch.arange(5)
140
+ # returns torch.tensor([10.]), torch.tensor([[0], [1.], [3.], [6.], [10.]])
141
+ last_carry, cumsum = scan(add, init=i0, xs=xs)
142
+
143
+
144
+ """
145
+ # The reason we flatten init and xs before calling into dynamo is that
146
+ # we want to create a consistent input ordering for combine_fn
147
+ # and we also want to the input ordering matches the output ordering.
148
+ leaves_init, spec_init = pytree.tree_flatten(init)
149
+ leaves_xs_orig, spec_xs = pytree.tree_flatten(xs)
150
+
151
+ # Shortcut if no xs is provided
152
+ if len(leaves_xs_orig) == 0:
153
+ return init, []
154
+
155
+ def _validate_input(cfn, lxs, linit, d, r):
156
+ # Basic arguments check
157
+ if not callable(cfn):
158
+ raise RuntimeError(f"Combine_fn must be a callable, but got {cfn}")
159
+ if not isinstance(d, int):
160
+ raise RuntimeError("Dim must be an int, but got " + str(type(d)))
161
+ if not isinstance(r, bool):
162
+ raise RuntimeError("Reverse must be a bool, but got " + str(type(r)))
163
+
164
+ # Checks for init
165
+ if len(linit) == 0:
166
+ raise RuntimeError("scan() operator requires init leaves.")
167
+ for x in linit:
168
+ if not isinstance(x, torch.Tensor):
169
+ raise RuntimeError(f"All init leaves must be a Tensor but got {x}")
170
+
171
+ # Checks for xs
172
+ for x in lxs:
173
+ if not isinstance(x, torch.Tensor):
174
+ raise RuntimeError(f"All xs leaves must be a Tensor but got {x}")
175
+ if any(x.ndim <= d for x in lxs):
176
+ raise RuntimeError(
177
+ "All xs leaves must at least have 'dim' number of dimensions and scan dimension > 0"
178
+ )
179
+ if any(x.shape[d] == 0 for x in lxs):
180
+ raise RuntimeError(
181
+ "All xs leaves must at least have 'dim' number of dimensions and scan dimension > 0"
182
+ )
183
+
184
+ ndim = leaves_xs_orig[0].ndim
185
+ dim = utils.canonicalize_dim(ndim, dim)
186
+
187
+ _validate_input(combine_fn, leaves_xs_orig, leaves_init, dim, reverse)
188
+
189
+ # Move scan dim to 0 and always perform scan on dim 0
190
+ leaves_xs = []
191
+ for elem in leaves_xs_orig:
192
+ leaves_xs.append(torch.movedim(elem, dim, 0) if dim != 0 else elem)
193
+
194
+ if reverse:
195
+ leaves_xs = [torch.flip(elem, [0]) for elem in leaves_xs]
196
+
197
+ # TODO: Support _inductor lowering
198
+ # TODO: Unify handling of pytrees for control flow ops, such as cond, while_loop, etc.
199
+
200
+ combine_fn = functools.partial(
201
+ wrap_combine_fn_flat,
202
+ combine_fn=combine_fn,
203
+ spec_init=spec_init,
204
+ spec_xs=spec_xs,
205
+ num_init_leaves=len(leaves_init),
206
+ num_inp_leaves=len(leaves_xs),
207
+ )
208
+
209
+ def run_flattened_scan(combine_fn, leaves_init, leaves_xs):
210
+ return scan_op(combine_fn, leaves_init, leaves_xs, additional_inputs=())
211
+
212
+ carry, out = _maybe_compile_and_run_fn(
213
+ run_flattened_scan,
214
+ combine_fn,
215
+ leaves_init,
216
+ leaves_xs,
217
+ )
218
+
219
+ if reverse:
220
+ out = pytree.tree_map(lambda elem: elem.flip([0]), out)
221
+
222
+ return carry, out
223
+
224
+
225
+ class ScanOp(HigherOrderOperator):
226
+ def __init__(self):
227
+ super().__init__("scan")
228
+
229
+ def __call__(self, combine_fn, init, xs, additional_inputs):
230
+ # There is currently an issue that the ScanOp is sometimes called with
231
+ # the additional_inputs being a list. See https://github.com/pytorch/pytorch/issues/145785
232
+ # Once this issue is resolved, the assertion should only allow tuples
233
+ # and the tuple cast should be removed
234
+ if not isinstance(additional_inputs, (tuple, list)):
235
+ raise AssertionError(
236
+ f"additional_inputs must be a tuple or list, got {type(additional_inputs)}"
237
+ )
238
+ additional_inputs = (
239
+ tuple(additional_inputs)
240
+ if isinstance(additional_inputs, list)
241
+ else additional_inputs
242
+ )
243
+ validate_subgraph_args_types(additional_inputs)
244
+ # pyrefly: ignore [missing-attribute]
245
+ return super().__call__(combine_fn, init, xs, additional_inputs)
246
+
247
+ # pyrefly: ignore [bad-override]
248
+ def gen_schema(self, combine_fn, init, xs, additional_inputs):
249
+ from torch._higher_order_ops.schema import HopSchemaGenerator
250
+ from torch._higher_order_ops.utils import materialize_as_graph
251
+
252
+ all_inputs = tuple(
253
+ list(init) + [first_slice_copy(x) for x in xs] + list(additional_inputs)
254
+ )
255
+
256
+ combine_gm: torch.fx.GraphModule = materialize_as_graph(combine_fn, all_inputs)
257
+
258
+ (
259
+ _,
260
+ _,
261
+ _,
262
+ mutated_inputs,
263
+ outputs,
264
+ ) = check_input_alias_and_mutation_return_outputs(combine_gm)
265
+ if len(mutated_inputs) > 0:
266
+ raise RuntimeError(
267
+ "For scan, combine_fn cannot have in-place mutations but found "
268
+ f"{mutated_inputs}-th inputs are mutated."
269
+ )
270
+
271
+ schema_gen = HopSchemaGenerator(self)
272
+ schema_gen.add_arg("combine_fn", combine_gm)
273
+
274
+ for idx, arg in enumerate(init):
275
+ schema_gen.add_arg(f"init{idx}", arg)
276
+
277
+ for idx, arg in enumerate(xs):
278
+ schema_gen.add_arg(f"xs{idx}", arg)
279
+
280
+ for idx, arg in enumerate(additional_inputs):
281
+ schema_gen.add_arg(f"additional_input{idx}", arg)
282
+
283
+ for out in outputs:
284
+ schema_gen.add_output(out)
285
+
286
+ schema_gen.add_schema_tree_spec(combine_fn, init, xs, additional_inputs)
287
+ return schema_gen.gen_schema()
288
+
289
+
290
+ scan_op = ScanOp()
291
+
292
+
293
+ def generic_scan(operator, init, xs, dim=0, additional_inputs=()):
294
+ def _scan(init, xs):
295
+ """Perform scan on `elems` using `elems_init."""
296
+ carry = init
297
+ if len(xs) == 0:
298
+ return carry, []
299
+
300
+ num_elems = xs[0].shape[dim]
301
+ ind = 0
302
+
303
+ # Compute dummy shapes for the pre-allocation
304
+ num_init_leaves = len(init)
305
+ dummy_carry, dummy_out = _extract_carry_and_out(
306
+ call_operator(
307
+ operator,
308
+ *carry,
309
+ *[first_slice_copy(elem, dim) for elem in xs],
310
+ *additional_inputs,
311
+ ),
312
+ num_init_leaves,
313
+ )
314
+
315
+ out_tensor_mask = get_tensor_mask(dummy_out)
316
+ dummy_out_masked = mask_list(out_tensor_mask, dummy_out)
317
+
318
+ # Pre-allocate
319
+ # outs -> Output matrix
320
+ # idxs -> Index matrix for scatter_
321
+ # out: (num_elems, M, N, ...)
322
+ # idx: (1, M, N)
323
+ outs = [
324
+ torch.zeros(
325
+ [num_elems] + list(e.size()),
326
+ dtype=e.dtype,
327
+ device=e.device,
328
+ )
329
+ for i, e in enumerate(dummy_out_masked)
330
+ ]
331
+ idxs = [
332
+ torch.ones_like(e, dtype=torch.int64).unsqueeze(0)
333
+ for i, e in enumerate(dummy_out_masked)
334
+ ]
335
+
336
+ def store_out_in_outs(out, ind):
337
+ # Store the intermediate out in the outs matrix
338
+ for o, x, idx in zip(outs, out, idxs):
339
+ # o: (num_elems, M, N ...)
340
+ # x: (M, N, ...) -> (1, M, N)
341
+ # ind * idx: (1, M, N,) with values to be ind
342
+ # essentially: o[ind][n][k] = x[0][n][k]
343
+ o.scatter_(0, ind * idx, x.unsqueeze(0))
344
+
345
+ for i in range(num_elems):
346
+ ind = i
347
+ carry, out = _extract_carry_and_out(
348
+ call_operator(
349
+ operator,
350
+ *carry,
351
+ *[elem.select(dim, ind) for elem in xs],
352
+ *additional_inputs,
353
+ ),
354
+ num_init_leaves,
355
+ )
356
+
357
+ # Store the inits in the outs matrix.
358
+ store_out_in_outs(mask_list(out_tensor_mask, out), ind)
359
+
360
+ # Expand outs with None depending on the tensor mask of the output
361
+ outs_expanded = [outs.pop(0) if out_m else None for out_m in out_tensor_mask]
362
+
363
+ return (*carry, *outs_expanded)
364
+
365
+ scans = _scan(init, xs)
366
+ return scans
367
+
368
+
369
+ def trace_scan(
370
+ proxy_mode,
371
+ func_overload,
372
+ combine_fn: Callable,
373
+ init: list[torch.Tensor],
374
+ xs: list[torch.Tensor],
375
+ additional_inputs: tuple[torch.Tensor],
376
+ ):
377
+ from torch._dynamo.utils import clone_input
378
+
379
+ with disable_proxy_modes_tracing():
380
+ sample_inits = [clone_input(x_init) for x_init in init]
381
+ sample_inputs = [first_slice_copy(x) for x in xs]
382
+ sample_additional_inputs = [
383
+ clone_input(x) if isinstance(x, torch.Tensor) else x
384
+ for x in additional_inputs
385
+ ]
386
+ combine_graph = reenter_make_fx(combine_fn)(
387
+ *sample_inits, *sample_inputs, *sample_additional_inputs
388
+ )
389
+
390
+ outputs = None
391
+ for node in combine_graph.graph.nodes:
392
+ if node.op == "output":
393
+ if outputs is not None:
394
+ raise AssertionError("found multiple output nodes in combine_graph")
395
+ if len(node.args) != 1:
396
+ raise AssertionError(
397
+ f"expected output node to have 1 arg, got {len(node.args)}"
398
+ )
399
+ outputs = node.args[0]
400
+
401
+ if outputs is None:
402
+ raise AssertionError("no output node found in combine_graph")
403
+
404
+ carry, output = _extract_carry_and_out(outputs, len(init))
405
+ init_fake_tensors: list[torch.Tensor | torch.SymInt | int] = [
406
+ i.clone() for i in init
407
+ ]
408
+ carry_fake_tensors: list[torch.Tensor | torch.SymInt | int] = [
409
+ c.meta["val"] for c in carry
410
+ ]
411
+ check_meta_consistency(
412
+ init_fake_tensors, carry_fake_tensors, "init", "carry", include_contiguity=False
413
+ )
414
+
415
+ _, combine_graph_name = unique_graph_id(proxy_mode, prefix="scan_combine_graph")
416
+
417
+ proxy_mode.tracer.root.register_module(combine_graph_name, combine_graph)
418
+
419
+ args = (combine_graph, init, xs, additional_inputs)
420
+ proxy_args = pytree.tree_map(proxy_mode.tracer.unwrap_proxy, args)
421
+ out_proxy = proxy_mode.tracer.create_proxy(
422
+ "call_function", func_overload, proxy_args, {}, name="scan"
423
+ )
424
+
425
+ with disable_proxy_modes_tracing():
426
+ scan_length = xs[0].shape[0]
427
+ fake_carry, fake_outputs = _extract_carry_and_out(
428
+ [o.meta["val"] for o in outputs], len(init)
429
+ )
430
+ out = (
431
+ *fake_carry,
432
+ *(stack_y(t, scan_length) for t in fake_outputs),
433
+ )
434
+
435
+ return track_tensor_tree(out, out_proxy, constant=None, tracer=proxy_mode.tracer)
436
+
437
+
438
+ @scan_op.py_impl(DispatchKey.CompositeExplicitAutograd)
439
+ def scan_op_dense(combine_fn, init, xs, additional_inputs):
440
+ mode = _get_current_dispatch_mode()
441
+ if mode is not None:
442
+ raise AssertionError("Mode should never be enabled for CPU/CUDA key")
443
+ return generic_scan(combine_fn, init, xs, additional_inputs=additional_inputs)
444
+
445
+
446
+ class ScanAutogradOp(torch.autograd.Function):
447
+ """
448
+ NOTE: [scan partial grad handling]
449
+ If any element of init, of xs, of the outputs or of the additional_inputs does not require gradients,
450
+ i.e., requires_grad=False, there will be still gradients returned for those elements,
451
+ but those gradients will be a tensor filled with zeros of the same shape as the element itself.
452
+
453
+ A special case are additional_inputs that are not tensors. Such inputs can occur for example with symbolic tracing,
454
+ where the shape symbol (SymInt) becomes an additional_input.
455
+ For such cases, we compute a ``additional_inputs_tensor_mask``, which is True for elements of additional_inputs
456
+ that are tensors and False otherwise. Gradients of additional_inputs are only accumulated if this mask is True,
457
+ otherwise, the value of initial_g_additional_inputs is passed, which is None for non-Tensor values.
458
+ """
459
+
460
+ @staticmethod
461
+ # pyrefly: ignore [bad-override]
462
+ def forward(
463
+ ctx,
464
+ hop_partitioned_graph,
465
+ n_init,
466
+ n_xs,
467
+ n_additional_inputs,
468
+ *operands,
469
+ ):
470
+ init, xs, additional_inputs = split_into_chunks(
471
+ operands, [n_init, n_xs, n_additional_inputs]
472
+ )
473
+ ctx._scan_impl = ScanAutogradImpl(
474
+ hop_partitioned_graph, init, xs, additional_inputs
475
+ )
476
+ with torch._C._AutoDispatchBelowAutograd():
477
+ return ctx._scan_impl.call_forward()
478
+
479
+ @staticmethod
480
+ def backward(ctx, *grad_fw_outputs):
481
+ return (
482
+ None,
483
+ None,
484
+ None,
485
+ None,
486
+ *ctx._scan_impl.call_backward(*grad_fw_outputs),
487
+ )
488
+
489
+
490
+ class ScanForwardIntermediatesHandlingPolicy(enum.Enum):
491
+ """
492
+ Partitioner can add interemdiates to the output of original graph.
493
+ These intermediates fall into 4 categories and we want to have different policies for handling them by
494
+ modifying the graph:
495
+
496
+ CLONE: we clone the intermediate when it is a carried input (i.e. init). In this case, this carry will be
497
+ replaced with new values at each forward step so we need to clone the carry as part of return (i.e. ys)
498
+ so as to remove the aliasing and that each step's intermediate will be stacked together and saved in bacwkard.
499
+
500
+ REMOVE_XS: we remove the intermediate from output when it is part of xs. Since xs is read-only, in this case,
501
+ we can directly save them for backward to use.
502
+
503
+ REMOVE_ADDITIONAL_INPUTS: we remove the intermediate from output when it is part of additinonal_inputs. additional_inputs
504
+ are also read-only in each step, we can directly save them for bacwkard to use. We differentiate XS and ADDITIONAL_INPUTS
505
+ so that we could have different treatment for them in backward. In backward, we need to put xs intermediates in carry but
506
+ put additional_inputs as backward scan's additional_inputs.
507
+
508
+ KEEP: this corresponds to a real intermediate tensor operations' output. It varies at each forward step, we could just keep
509
+ it as part of ys.
510
+
511
+ """
512
+
513
+ KEEP = 0
514
+ CLONE = 1
515
+ REMOVE_XS = 2
516
+ REMOVE_ADDITIONAL_INPUTS = 3
517
+
518
+
519
+ class ScanAutogradImpl:
520
+ """
521
+ Wraps over partitioned graph and encapsulates scan-specific implementation details
522
+ """
523
+
524
+ def __init__(
525
+ self, hop_partitioned_graph: HopPartitionedGraph, init, xs, additional_inputs
526
+ ):
527
+ self.hop_partitioned_graph = hop_partitioned_graph
528
+ self.init = init
529
+ self.xs = xs
530
+ self.additional_inputs = additional_inputs
531
+ self.forward_intermediates_handling_policies: list[
532
+ ScanForwardIntermediatesHandlingPolicy
533
+ ] = []
534
+ self.saved_fw_xs: list[Any] = []
535
+ self.saved_fw_additional_inputs: list[Any] = []
536
+ self.saved_intermediates: list[Any] = []
537
+ self.fw_spec = pytree.tree_flatten((init, xs, additional_inputs))[1]
538
+ self._optimize_forward_intermediates()
539
+
540
+ def _insert_clone(
541
+ self, need_copy_node: torch.fx.Node, output_node: torch.fx.Node
542
+ ) -> torch.fx.Node:
543
+ graph: torch.fx.Graph = output_node.graph
544
+ with graph.inserting_before(output_node):
545
+ clone_node = graph.call_function(
546
+ torch.ops.aten.clone.default,
547
+ args=(need_copy_node,),
548
+ )
549
+ clone_node.meta = (
550
+ need_copy_node.meta.copy() if hasattr(need_copy_node, "meta") else {}
551
+ )
552
+ return clone_node
553
+
554
+ def _optimize_forward_intermediates(self):
555
+ """
556
+ We optimize the forward intermediates by categorize forward intermediates into categories
557
+ and construct a ScanForwardIntermediatesHandlingPolicy for them
558
+
559
+ """
560
+ if logger.isEnabledFor(logging.DEBUG):
561
+ logger.debug(
562
+ "Need remove aliasing in fw_gm:\n%s",
563
+ self.hop_partitioned_graph.fw_gm.print_readable(print_output=False),
564
+ )
565
+
566
+ fw_gm = self.hop_partitioned_graph.fw_gm
567
+ fw_all_outputs = _find_hop_subgraph_outputs(fw_gm)
568
+ phs = list(fw_gm.graph.find_nodes(op="placeholder"))
569
+ fw_outputs = fw_all_outputs[: self.hop_partitioned_graph.n_fw_outputs]
570
+ fw_intermediates = fw_all_outputs[self.hop_partitioned_graph.n_fw_outputs :]
571
+
572
+ init_phs, xs_phs, additional_inputs_phs = pytree.tree_unflatten(
573
+ phs, self.fw_spec
574
+ )
575
+ init_node_set, xs_node_set, addi_node_set = (
576
+ set(init_phs),
577
+ set(xs_phs),
578
+ set(additional_inputs_phs),
579
+ )
580
+
581
+ if len(self.forward_intermediates_handling_policies) != 0:
582
+ raise AssertionError(
583
+ "forward_intermediates_handling_policies should be empty"
584
+ )
585
+ if len(self.saved_fw_xs) != 0:
586
+ raise AssertionError("saved_fw_xs should be empty")
587
+ if len(self.saved_fw_additional_inputs) != 0:
588
+ raise AssertionError("saved_fw_additional_inputs should be empty")
589
+ intermediate_idx_to_ph_idx = {}
590
+ ph_idx = {ph: i for i, ph in enumerate(phs)}
591
+ for i, out in enumerate(fw_intermediates):
592
+ if out in init_node_set:
593
+ self.forward_intermediates_handling_policies.append(
594
+ ScanForwardIntermediatesHandlingPolicy.CLONE
595
+ )
596
+ intermediate_idx_to_ph_idx[i] = ph_idx[out]
597
+ elif out in xs_node_set:
598
+ self.forward_intermediates_handling_policies.append(
599
+ ScanForwardIntermediatesHandlingPolicy.REMOVE_XS
600
+ )
601
+ intermediate_idx_to_ph_idx[i] = ph_idx[out]
602
+ elif out in addi_node_set:
603
+ self.forward_intermediates_handling_policies.append(
604
+ ScanForwardIntermediatesHandlingPolicy.REMOVE_ADDITIONAL_INPUTS
605
+ )
606
+ intermediate_idx_to_ph_idx[i] = ph_idx[out]
607
+ else:
608
+ self.forward_intermediates_handling_policies.append(
609
+ ScanForwardIntermediatesHandlingPolicy.KEEP
610
+ )
611
+
612
+ new_output_node = []
613
+ real_graph_inputs = (
614
+ list(self.init) + list(self.xs) + list(self.additional_inputs)
615
+ )
616
+ fw_output_node = next(iter(fw_gm.graph.find_nodes(op="output")))
617
+ for intermediate_idx, (node, policy) in enumerate(
618
+ zip(fw_intermediates, self.forward_intermediates_handling_policies)
619
+ ):
620
+ if policy == ScanForwardIntermediatesHandlingPolicy.CLONE:
621
+ new_output_node.append(self._insert_clone(node, fw_output_node))
622
+ elif policy == ScanForwardIntermediatesHandlingPolicy.REMOVE_XS:
623
+ if intermediate_idx not in intermediate_idx_to_ph_idx:
624
+ raise AssertionError(
625
+ f"intermediate_idx {intermediate_idx} not in intermediate_idx_to_ph_idx"
626
+ )
627
+ inp_idx = intermediate_idx_to_ph_idx[intermediate_idx]
628
+ self.saved_fw_xs.append(real_graph_inputs[inp_idx])
629
+ elif (
630
+ policy
631
+ == ScanForwardIntermediatesHandlingPolicy.REMOVE_ADDITIONAL_INPUTS
632
+ ):
633
+ if intermediate_idx not in intermediate_idx_to_ph_idx:
634
+ raise AssertionError(
635
+ f"intermediate_idx {intermediate_idx} not in intermediate_idx_to_ph_idx for REMOVE_ADDITIONAL_INPUTS"
636
+ )
637
+ inp_idx = intermediate_idx_to_ph_idx[intermediate_idx]
638
+ self.saved_fw_additional_inputs.append(real_graph_inputs[inp_idx])
639
+ else:
640
+ new_output_node.append(node)
641
+
642
+ fw_output_node.args = (tuple(fw_outputs) + tuple(new_output_node),)
643
+ fw_gm.graph.lint()
644
+ fw_gm.recompile()
645
+
646
+ if logger.isEnabledFor(logging.DEBUG):
647
+ logger.debug(
648
+ "after removing aliasing:\n%s", fw_gm.print_readable(print_output=False)
649
+ )
650
+
651
+ def call_forward(self):
652
+ fw_outputs_and_intermediates: tuple[Any] = scan_op(
653
+ self.hop_partitioned_graph.fw_gm, self.init, self.xs, self.additional_inputs
654
+ ) # type: ignore[return-type]
655
+ fw_outs = fw_outputs_and_intermediates[
656
+ : self.hop_partitioned_graph.n_fw_outputs
657
+ ]
658
+ saved_intermediates = fw_outputs_and_intermediates[
659
+ self.hop_partitioned_graph.n_fw_outputs :
660
+ ]
661
+ if len(self.saved_intermediates) != 0:
662
+ raise AssertionError(
663
+ "saved_intermediates should be empty before call_forward"
664
+ )
665
+ self.saved_intermediates.extend(saved_intermediates)
666
+ return tuple(fw_outs)
667
+
668
+ def call_backward(self, *grad_fw_outputs):
669
+ """
670
+ Recall that fw_outputs = (*carry, *ys), bw_gm takes in (*fw_intermediates, *grad_carry, *grad_ys)
671
+ and returns (*grad_init, *grad_xs, *grad_additional_inputs)
672
+ The bacwkard is a reversed scan that can be constructed as follows:
673
+
674
+ grad_additonal_inputs = torch.zeros_like(additional_inputs)
675
+ bw_init = (grad_carry, grad_additional_inputs)
676
+ bw_xs = (fw_intermediates, grad_ys)
677
+ grad_init, grad_additional_inputs, grad_xs = scan(
678
+ combine_fn,
679
+ bw_init,
680
+ bw_xs,
681
+ reverse = True
682
+ )
683
+ , where combine_fn is defined as follows:
684
+
685
+ def combine_fn(bw_init, bw_xs):
686
+ grad_carry, grad_additional_inputs = bw_init
687
+ fw_intermediates, grad_y = bw_xs
688
+ nxt_grad_carry, grad_x, nxt_grad_additional_inputs = bw_gm(*fw_intermediates, *grad_carry, *grad_y)
689
+ return (nxt_grad_carry, grad_additional_inputs + nxt_grad_additional_inputs), grad_x
690
+
691
+ Note that grad_additional_inputs is accumulated with add, grad_carry is carried over to next iteration and
692
+ grad_x is the ys output, which will be stacked together after the loop and will have the same shape as xs.
693
+ """
694
+ fw_policy = self.forward_intermediates_handling_policies
695
+ saved_intermediates = self.saved_intermediates
696
+ saved_fw_xs = self.saved_fw_xs
697
+ saved_fw_additional_inputs = self.saved_fw_additional_inputs
698
+
699
+ n_carry = len(self.init)
700
+
701
+ grad_carry, grad_ys = grad_fw_outputs[:n_carry], grad_fw_outputs[n_carry:]
702
+ additional_inputs_tensor_masks = [
703
+ bool(isinstance(t, torch.Tensor)) for t in self.additional_inputs
704
+ ]
705
+ grad_additional_inputs = [
706
+ torch.zeros_like(t)
707
+ for t in filter_with_masks(
708
+ self.additional_inputs, additional_inputs_tensor_masks
709
+ )
710
+ ]
711
+
712
+ bw_init = [grad_carry, grad_additional_inputs]
713
+ bw_xs = [
714
+ grad_ys,
715
+ saved_fw_xs,
716
+ saved_intermediates,
717
+ ]
718
+ bw_additional_inputs = saved_fw_additional_inputs
719
+
720
+ _, flat_spec = pytree.tree_flatten((bw_init, bw_xs, bw_additional_inputs))
721
+
722
+ grad_spec = None
723
+
724
+ def bw_single_step_wrapper(*args):
725
+ bw_init, bw_xs, bw_additional_inputs = pytree.tree_unflatten(
726
+ args, flat_spec
727
+ )
728
+ grad_carry, grad_additional_inputs = bw_init
729
+ grad_y, saved_fw_xs, saved_intermediates = bw_xs
730
+ saved_fw_additional_inputs = bw_additional_inputs
731
+
732
+ fw_intermediates = []
733
+ xs_it = iter(saved_fw_xs)
734
+ carry_it = iter(saved_intermediates)
735
+ addi_it = iter(saved_fw_additional_inputs)
736
+ for policy in fw_policy:
737
+ if policy in (
738
+ ScanForwardIntermediatesHandlingPolicy.CLONE,
739
+ ScanForwardIntermediatesHandlingPolicy.KEEP,
740
+ ):
741
+ fw_intermediates.append(next(carry_it))
742
+ elif policy == ScanForwardIntermediatesHandlingPolicy.REMOVE_XS:
743
+ fw_intermediates.append(next(xs_it))
744
+ elif (
745
+ policy
746
+ == ScanForwardIntermediatesHandlingPolicy.REMOVE_ADDITIONAL_INPUTS
747
+ ):
748
+ fw_intermediates.append(next(addi_it))
749
+ else:
750
+ raise RuntimeError(f"Unknown policy: {policy}")
751
+
752
+ grad_fw_outputs = (*grad_carry, *grad_y)
753
+
754
+ flat_out = self.hop_partitioned_graph.bw_gm(
755
+ *fw_intermediates,
756
+ *grad_fw_outputs,
757
+ )
758
+
759
+ next_grad_carry, grad_xs, grad_addi = split_into_chunks(
760
+ flat_out, # type: ignore[arg-type]
761
+ [len(self.init), len(self.xs), len(self.additional_inputs)],
762
+ )
763
+
764
+ nonlocal grad_spec
765
+ flat_grads, grad_spec = pytree.tree_flatten(
766
+ (
767
+ next_grad_carry,
768
+ [
769
+ prev + cur
770
+ for prev, cur in zip(
771
+ grad_additional_inputs,
772
+ filter_with_masks(
773
+ grad_addi, additional_inputs_tensor_masks
774
+ ),
775
+ )
776
+ ],
777
+ grad_xs,
778
+ )
779
+ )
780
+ return flat_grads
781
+
782
+ single_step_bw_xs = pytree.tree_map(lambda t: t[0], bw_xs)
783
+ bw_single_step_gm = materialize_as_graph(
784
+ bw_single_step_wrapper,
785
+ tuple(
786
+ pytree.tree_flatten((bw_init, single_step_bw_xs, bw_additional_inputs))[
787
+ 0
788
+ ]
789
+ ),
790
+ )
791
+
792
+ flat_grads = scan_op(
793
+ bw_single_step_gm,
794
+ pytree.tree_flatten(bw_init)[0],
795
+ # TODO: torch.flip copies the tensor, we should optimize it away
796
+ [torch.flip(x, (0,)) for x in pytree.tree_flatten(bw_xs)[0]],
797
+ pytree.tree_flatten(bw_additional_inputs)[0],
798
+ )
799
+ if grad_spec is None:
800
+ raise AssertionError("grad_spec must not be None after scan_op")
801
+ grad_init, grad_additional_inputs, grad_xs = pytree.tree_unflatten(
802
+ flat_grads, grad_spec
803
+ )
804
+ return (
805
+ *grad_init,
806
+ *[torch.flip(elem, (0,)) for elem in grad_xs],
807
+ *fill_none_with_masks(
808
+ grad_additional_inputs, additional_inputs_tensor_masks
809
+ ),
810
+ )
811
+
812
+
813
+ @scan_op.py_autograd_impl
814
+ def scan_autograd(combine_fn, init, xs, additional_inputs):
815
+ with disable_proxy_modes_tracing():
816
+ hop_partitioned_graph: HopPartitionedGraph = (
817
+ HopGraphMinCutPartitioner.create_partitioned_graph(
818
+ combine_fn,
819
+ (*init, *[x[0] for x in xs], *additional_inputs),
820
+ always_recompute_complex_exprs=True,
821
+ )
822
+ )
823
+
824
+ return ScanAutogradOp.apply(
825
+ hop_partitioned_graph,
826
+ len(init),
827
+ len(xs),
828
+ len(additional_inputs),
829
+ *init,
830
+ *xs,
831
+ *additional_inputs,
832
+ )
833
+
834
+
835
+ @scan_op.py_impl(ProxyTorchDispatchMode)
836
+ def scan_proxy_mode(mode, combine_fn, init, xs, additional_inputs):
837
+ return trace_scan(mode, scan_op, combine_fn, init, xs, additional_inputs)
838
+
839
+
840
+ @scan_op.py_impl(FakeTensorMode)
841
+ def scan_fake_tensor_mode(mode, combine_fn, init, xs, additional_inputs):
842
+ with mode:
843
+ scan_length = xs[0].shape[0]
844
+ carry, outputs = _extract_carry_and_out(
845
+ combine_fn(
846
+ *init,
847
+ *[first_slice_copy(inp) for inp in xs],
848
+ *additional_inputs,
849
+ ),
850
+ len(init),
851
+ )
852
+ out = (
853
+ *carry,
854
+ *(stack_y(t, scan_length) for t in outputs),
855
+ )
856
+ return out
857
+
858
+
859
+ @scan_op.py_functionalize_impl
860
+ def scan_functionalize(ctx, combine_fn, init, xs, additional_inputs):
861
+ from torch._higher_order_ops.utils import (
862
+ _check_alias_and_mutation,
863
+ _maybe_run_with_interpreter,
864
+ )
865
+
866
+ unwrapped_xs = ctx.unwrap_tensors(xs)
867
+ unwrapped_init = ctx.unwrap_tensors(init)
868
+ unwrapped_additional_inputs = ctx.unwrap_tensors(additional_inputs)
869
+
870
+ with ctx.redispatch_to_next():
871
+ functional_combine_fn = ctx.functionalize(
872
+ _maybe_run_with_interpreter(combine_fn)
873
+ )
874
+ sample_unwrapped_xs_sliced = [first_slice_copy(inp) for inp in unwrapped_xs]
875
+ sample_inputs = list(
876
+ itertools.chain(
877
+ unwrapped_init,
878
+ sample_unwrapped_xs_sliced,
879
+ unwrapped_additional_inputs,
880
+ )
881
+ )
882
+ pre_dispatch = hasattr(ctx, "mode") and ctx.mode.pre_dispatch
883
+ _check_alias_and_mutation(combine_fn, sample_inputs, "scan", pre_dispatch)
884
+ ret = scan_op(
885
+ functional_combine_fn,
886
+ unwrapped_init,
887
+ unwrapped_xs,
888
+ unwrapped_additional_inputs,
889
+ )
890
+ return ctx.wrap_tensors(ret)
891
+
892
+
893
+ @scan_op.py_impl(torch._C._functorch.TransformType.Vmap)
894
+ def scan_batch_rule(interpreter, combine_fn, init, xs, additional_inputs):
895
+ from torch._functorch.vmap import restore_vmap, unwrap_batched, wrap_batched
896
+
897
+ unbatched_args, in_dims = unwrap_batched(
898
+ (init, xs, additional_inputs), interpreter.level()
899
+ )
900
+ # move to last dim to not interfere with scan's batching
901
+ unbatched_init, unbatched_xs, unbatched_additional_inputs = pytree.tree_map(
902
+ lambda x, bdim: x.movedim(bdim, -1) if bdim is not None else x,
903
+ unbatched_args,
904
+ in_dims,
905
+ )
906
+ after_move_dims = tuple(
907
+ pytree.tree_flatten(
908
+ pytree.tree_map(lambda x: -1 if x is not None else None, in_dims)
909
+ )[0]
910
+ )
911
+
912
+ with interpreter.lower():
913
+ out_dims = None
914
+
915
+ def wrapper(*args):
916
+ nonlocal out_dims
917
+ outputs, per_slice_out_dims = restore_vmap(
918
+ combine_fn,
919
+ after_move_dims,
920
+ interpreter.batch_size(),
921
+ interpreter.randomness(),
922
+ )(*args)
923
+ # Note: outputs are not batched, we just move the batch dim to the end
924
+ # this is to avoid it interfering with scan's batching
925
+ outputs = tuple(
926
+ pytree.tree_map(
927
+ lambda out, out_bdim: out.movedim(out_bdim, -1)
928
+ if out_bdim is not None
929
+ else out,
930
+ outputs,
931
+ per_slice_out_dims,
932
+ )
933
+ )
934
+ out_dims = tuple(
935
+ pytree.tree_map(
936
+ lambda out_bdim: -1 if out_bdim is not None else None,
937
+ per_slice_out_dims,
938
+ )
939
+ )
940
+ return outputs
941
+
942
+ unwrapped_out = scan_op(
943
+ wrapper, unbatched_init, unbatched_xs, unbatched_additional_inputs
944
+ )
945
+
946
+ if out_dims is None:
947
+ raise AssertionError("out_dims must not be None after scan_op")
948
+ batched_out = wrap_batched(unwrapped_out, out_dims, interpreter.level())
949
+ return batched_out
950
+
951
+
952
+ # dense implementation for scan. Used for testing only.
953
+ def _fake_scan(combine_fn, init, xs=None, dim=0, reverse=False):
954
+ carry_leaves, carry_spec = pytree.tree_flatten(init)
955
+ inp_leaves, inp_spec = pytree.tree_flatten(xs)
956
+ if xs is None or len(inp_leaves) == 0:
957
+ return init, []
958
+ result_flat = []
959
+ carry = carry_leaves
960
+ op = reversed if reverse else lambda x: x
961
+
962
+ dummy_carry, dummy_out = combine_fn(
963
+ pytree.tree_unflatten(carry, carry_spec),
964
+ pytree.tree_unflatten(
965
+ [first_slice_copy(elem, dim) for elem in inp_leaves],
966
+ inp_spec,
967
+ ),
968
+ )
969
+ dummy_out_leaves, dummy_out_spec = pytree.tree_flatten(dummy_out)
970
+ num_leaves = len(dummy_out_leaves)
971
+
972
+ for ind in op(range(inp_leaves[0].size(dim))):
973
+ xs = [elem.select(dim, ind) for elem in inp_leaves]
974
+
975
+ carry, y = combine_fn(
976
+ pytree.tree_unflatten(carry, carry_spec),
977
+ pytree.tree_unflatten(xs, inp_spec),
978
+ )
979
+ carry, _ = pytree.tree_flatten(carry)
980
+ y, _ = pytree.tree_flatten(y)
981
+ result_flat.append(y)
982
+
983
+ results = [
984
+ torch.stack([e[leave_ind] for e in op(result_flat)])
985
+ for leave_ind in range(num_leaves)
986
+ ]
987
+ return (
988
+ pytree.tree_unflatten(carry, carry_spec),
989
+ pytree.tree_unflatten(results, dummy_out_spec),
990
+ )
.venv/lib/python3.10/site-packages/torch/_higher_order_ops/schema.py ADDED
@@ -0,0 +1,323 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ from dataclasses import dataclass
3
+ from typing import Any, Optional
4
+
5
+ import torch
6
+ import torch.utils._pytree as pytree
7
+ from torch._library.fake_class_registry import FakeScriptObject
8
+ from torch._library.opaque_object import is_opaque_type
9
+ from torch.fx.node import Target
10
+
11
+
12
+ # Below is an implementation of generating FunctionSchema from example values.
13
+ # This is helpful for generating FunctionSchema for HigherOrderOperator, where
14
+ # we don't have a function to inspect and each call of the higher order operator
15
+ # would have different schema.
16
+ @dataclass(frozen=True, slots=True)
17
+ class HopArgumentInfo:
18
+ # Could give a name to the operand by default it's empty string.
19
+ name: str
20
+ example_value: Any
21
+ # Provide an default_value
22
+ default_value: Any
23
+ # Whether this argument gets mutated in the hop subgraph.
24
+ # For output, this should always be False
25
+ is_mutated: bool
26
+ kw_only: bool
27
+
28
+
29
+ class HopArgumentInfoGen:
30
+ @staticmethod
31
+ def from_example(
32
+ example_value: Any,
33
+ *,
34
+ name: str = "",
35
+ default_value: Optional[Any] = None,
36
+ is_mutated: bool = False,
37
+ kw_only: bool = False,
38
+ ) -> HopArgumentInfo:
39
+ if default_value is not None:
40
+ if type(example_value) is not type(default_value):
41
+ raise AssertionError(
42
+ f"example_value type {type(example_value)} doesn't match default_value type: {type(default_value)}"
43
+ )
44
+
45
+ return HopArgumentInfo(
46
+ name=name,
47
+ example_value=example_value,
48
+ default_value=default_value,
49
+ is_mutated=is_mutated,
50
+ kw_only=kw_only,
51
+ )
52
+
53
+
54
+ class CTypeGen:
55
+ convert_to_base_ty = {
56
+ int: torch._C.IntType.get(),
57
+ float: torch._C.FloatType.get(),
58
+ str: torch._C.StringType.get(),
59
+ bool: torch._C.BoolType.get(),
60
+ }
61
+
62
+ # should return torch._C.JitType but that annotation is busted
63
+ @staticmethod
64
+ def from_example(obj: Any) -> Any:
65
+ import torch
66
+
67
+ if isinstance(obj, torch.fx.GraphModule):
68
+ return torch._C.AnyType.get()
69
+ elif isinstance(obj, torch.SymInt):
70
+ return torch._C.SymIntType.get()
71
+ elif isinstance(obj, torch.SymBool):
72
+ return torch._C.SymBoolType.get()
73
+ elif isinstance(obj, torch.SymFloat):
74
+ return torch._C.FloatType.get()
75
+ elif isinstance(obj, (FakeScriptObject, pytree.TreeSpec)) or is_opaque_type(
76
+ type(obj)
77
+ ):
78
+ return torch._C.PyObjectType.get() # pyrefly: ignore[missing-attribute]
79
+ return torch._C._jit_try_infer_type(obj).type()
80
+
81
+
82
+ class CArgumentGen:
83
+ @staticmethod
84
+ def from_hop_argument_info(
85
+ arg_idx: int, arg_info: HopArgumentInfo, is_output: bool = False
86
+ ) -> Any:
87
+ typ = CTypeGen.from_example(arg_info.example_value)
88
+ if is_output:
89
+ return torch._C.Argument("", typ, None, None, False, None)
90
+
91
+ alias_set = set({f"alias::a{arg_idx}"}) if arg_info.is_mutated else set()
92
+ alias_info = torch._C._AliasInfo(arg_info.is_mutated, alias_set, alias_set) # type: ignore[attr-defined]
93
+ return torch._C.Argument(
94
+ arg_info.name,
95
+ typ,
96
+ None,
97
+ arg_info.default_value,
98
+ arg_info.kw_only,
99
+ alias_info,
100
+ )
101
+
102
+
103
+ class HopSchemaGenerator:
104
+ def __init__(self, hop: torch._ops.HigherOrderOperator):
105
+ self.arg_infos: list[HopArgumentInfo] = []
106
+ self.example_outputs: list[Any] = []
107
+ self.schema_tree_spec: Optional[pytree.TreeSpec] = None
108
+ self.hop = hop
109
+
110
+ def add_arg(
111
+ self,
112
+ name: str,
113
+ example_value: Any,
114
+ default_value: Optional[Any] = None,
115
+ is_mutated: bool = False,
116
+ kw_only: bool = False,
117
+ ) -> None:
118
+ if callable(example_value):
119
+ if not isinstance(
120
+ example_value, (torch.fx.GraphModule, torch._ops.OperatorBase)
121
+ ):
122
+ raise AssertionError(
123
+ "Expect callable to be a GraphModule or an OperatorBase. Please call materialize_as_graph first "
124
+ f"to turn callable arguments {example_value} into a GraphModule."
125
+ )
126
+ _, flat_spec = pytree.tree_flatten(example_value)
127
+ if not flat_spec.is_leaf():
128
+ raise RuntimeError(
129
+ f"example_value {example_value} is not a leaf node. "
130
+ "Please only add flattened inputs to the hop schema. "
131
+ "If you need some structure in the arguments, please"
132
+ "add_arg for flattened args one by one then "
133
+ "call add_schema_tree_spec to register the original pytree "
134
+ " spec of the args."
135
+ )
136
+
137
+ arg_info = HopArgumentInfoGen.from_example(
138
+ example_value=example_value,
139
+ name=name,
140
+ default_value=default_value,
141
+ is_mutated=is_mutated,
142
+ kw_only=kw_only,
143
+ )
144
+ self.arg_infos.append(arg_info)
145
+
146
+ def add_output(self, output: Any) -> None:
147
+ self.example_outputs.append(output)
148
+
149
+ def add_schema_tree_spec(self, *args: Any, **kwargs: Any) -> None:
150
+ """schema tree spec is the tree spec from flattening all inputs to the hop with pytree.tree_flatten
151
+ Since torch.FunctionSchema only have proper mutation/alias support for flattened inputs, we need
152
+ to store the tree spec in order to reconstruct the inputs to the hop.
153
+ """
154
+ self.schema_tree_spec = pytree.tree_flatten((args, kwargs))[1]
155
+
156
+ def gen_schema(self) -> torch._C.FunctionSchema:
157
+ for i, arg_info in enumerate(self.arg_infos):
158
+ arg_spec = pytree.tree_flatten(arg_info.example_value)[1]
159
+ if not arg_spec.is_leaf() and self.schema_tree_spec is None:
160
+ raise RuntimeError(
161
+ f"example_value of arg_infos[{i}] is {arg_info.example_value}, which is not a leaf node. "
162
+ "Please call add_schema_tree_spec to add a schema tree spec first. "
163
+ "Or consider changing the hop's signature to only take flattened arguments."
164
+ )
165
+
166
+ return CFunctionSchemaGen.from_hop_argument_info(
167
+ str(self.hop),
168
+ self.arg_infos,
169
+ HopArgumentInfoGen.from_example(tuple(self.example_outputs), name="out"),
170
+ self.schema_tree_spec,
171
+ )
172
+
173
+
174
+ class CFunctionSchemaGen:
175
+ """
176
+ Note: [HigherOrderOperator schema generation]
177
+ Each invocation of a HigherOrderOperator will have a different schema.
178
+ For example, the schema of torch.cond varies depending on the true_fn and
179
+ false_fn. So we need a way to generate the schema for each invocation of a HOP.
180
+
181
+ We want to enforce the following invariants for HOP's schema:
182
+ 1. Flattened inputs. There should be no pytree structure in it.
183
+ 2. Flattened outputs. Note even if the hop returns a single value, it should be wrapped as a tuple.
184
+ 3. No aliasing. This includes inp-inp aliasing, inp-out aliasing and out-out aliasing.
185
+
186
+ By enforcing these invariants, we could make HOP's schema meets the requirement of schema parser
187
+ and makes hop easier to handle downstream. For example, suppose we have an invoke_quant_test HOP:
188
+
189
+ class GraphModule(torch.nn.Module):
190
+ def forward(self, l_x_, l_y_):
191
+ subgraph_0 = self.subgraph_0
192
+ invoke_quant_test = torch.ops.higher_order.invoke_quant_test(subgraph_0, l_x_, l_y_, scheme = 'nf4');
193
+
194
+ class subgraph_0(torch.nn.Module):
195
+ def forward(self, l_x_, l_y_):
196
+ add_ = l_x_.add_(1)
197
+ matmul = l_x_ @ l_y_
198
+ sin = matmul.sin()
199
+ child = sin.cos()
200
+ child_1 = l_x_ + l_y_
201
+ child_2 = l_x_ - l_y_
202
+ child_3 = l_x_ @ l_y_
203
+ return (child, child_1, child_2, child_3)
204
+
205
+ By encoding the inputs of hop into a list of HopArgumentInfo and output as a single HopArgumentInfo,
206
+ we would get the following schema:
207
+ invoke_quant_test(Any arg0, Tensor(!) arg1, Tensor arg2, str scheme="\\"nf4\\"") -> (Tensor, Tensor, Tensor, Tensor)
208
+ """
209
+
210
+ @staticmethod
211
+ def from_hop_argument_info(
212
+ op_name: str,
213
+ inp_argument_info: list[HopArgumentInfo],
214
+ out_argument_info: HopArgumentInfo,
215
+ schema_tree_spec: Optional[pytree.TreeSpec],
216
+ ) -> Any:
217
+ args = []
218
+ for i, arg_info in enumerate(inp_argument_info):
219
+ args.append(CArgumentGen.from_hop_argument_info(i, arg_info))
220
+
221
+ # NOTE: we want the output to always be a single argument with torch._C.TupleType.
222
+ if not isinstance(out_argument_info.example_value, tuple):
223
+ raise AssertionError(
224
+ f"expect out_argument_info's example_value to be a tuple but got {out_argument_info.example_value}"
225
+ )
226
+ if out_argument_info.is_mutated:
227
+ raise AssertionError(
228
+ "out_argument_info.is_mutated should always be set to False."
229
+ )
230
+ rets = None
231
+ if len(out_argument_info.example_value) == 1:
232
+ rets = [CArgumentGen.from_hop_argument_info(0, out_argument_info, True)]
233
+ else:
234
+ rets = [
235
+ CArgumentGen.from_hop_argument_info(
236
+ i,
237
+ HopArgumentInfoGen.from_example(
238
+ name=f"out{i}",
239
+ example_value=val,
240
+ default_value=None,
241
+ is_mutated=False,
242
+ ),
243
+ is_output=True,
244
+ )
245
+ for i, val in enumerate(out_argument_info.example_value)
246
+ ]
247
+
248
+ return HopSchema(
249
+ op_name,
250
+ "",
251
+ args,
252
+ rets,
253
+ False,
254
+ False,
255
+ schema_tree_spec,
256
+ )
257
+
258
+
259
+ class HopSchema(torch._C.FunctionSchema):
260
+ def __init__(
261
+ self,
262
+ name: str,
263
+ overload_name: str,
264
+ arguments: list[torch._C.Argument],
265
+ returns: list[torch._C.Argument],
266
+ is_vararg: bool,
267
+ is_varret: bool,
268
+ schema_tree_spec: Optional[pytree.TreeSpec],
269
+ ):
270
+ self.tree_spec = schema_tree_spec
271
+ self.is_vararg = is_vararg
272
+ self.is_varret = is_varret
273
+ super().__init__(
274
+ name,
275
+ overload_name,
276
+ arguments,
277
+ returns,
278
+ self.is_vararg,
279
+ self.is_varret,
280
+ )
281
+
282
+ def __deepcopy__(self, memo: Any) -> "HopSchema":
283
+ # Need to additionally copy the tree_spec since
284
+ # it's not a member of torch._C.FunctionSchema
285
+ return HopSchema(
286
+ self.name,
287
+ self.overload_name,
288
+ self.arguments,
289
+ self.returns,
290
+ self.is_vararg,
291
+ self.is_varret,
292
+ copy.deepcopy(self.tree_spec),
293
+ )
294
+
295
+
296
+ def find_hop_schema(
297
+ gm: torch.fx.GraphModule, target: Target
298
+ ) -> list[torch._C.FunctionSchema]:
299
+ schemas = []
300
+ for node in gm.graph.find_nodes(op="call_function", target=target):
301
+
302
+ def _get_example_value(node: torch.fx.Node) -> Any:
303
+ if node.op == "get_attr":
304
+ if not isinstance(node.target, str):
305
+ raise AssertionError(
306
+ f"expected node.target to be str for get_attr, got {type(node.target)}"
307
+ )
308
+ return getattr(gm, node.target)
309
+ else:
310
+ return (
311
+ node.meta["example_value"]
312
+ if "example_value" in node.meta
313
+ else node.meta["val"]
314
+ )
315
+
316
+ fake_args, fake_kwargs = pytree.tree_map_only(
317
+ torch.fx.Node,
318
+ _get_example_value,
319
+ (node.args, node.kwargs),
320
+ )
321
+ schema = node.target.gen_schema(*fake_args, **fake_kwargs)
322
+ schemas.append(schema)
323
+ return schemas
.venv/lib/python3.10/site-packages/torch/_higher_order_ops/strict_mode.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+
3
+ import torch
4
+ import torch._subclasses.functional_tensor
5
+ import torch.utils._pytree as pytree
6
+ from torch._C import DispatchKey
7
+ from torch._functorch.utils import exposed_in
8
+ from torch._higher_order_ops.utils import autograd_not_implemented
9
+ from torch._ops import HigherOrderOperator
10
+ from torch._subclasses.fake_tensor import FakeTensorMode
11
+ from torch.fx.experimental.proxy_tensor import (
12
+ disable_proxy_modes_tracing,
13
+ make_fx,
14
+ ProxyTorchDispatchMode,
15
+ track_tensor_tree,
16
+ )
17
+ from torch.utils._python_dispatch import _get_current_dispatch_mode
18
+
19
+
20
+ @exposed_in("torch")
21
+ def strict_mode(callable, operands):
22
+ if torch.compiler.is_dynamo_compiling():
23
+ return strict_mode_op(callable, operands)
24
+
25
+ from torch._higher_order_ops.utils import setup_compilation_env
26
+
27
+ with setup_compilation_env() as backend:
28
+ return torch.compile(strict_mode_op, backend=backend, fullgraph=True)(
29
+ callable, operands
30
+ )
31
+
32
+
33
+ class StrictMode(HigherOrderOperator):
34
+ def __init__(self):
35
+ super().__init__("strict_mode")
36
+
37
+ def __call__(self, callable, operands):
38
+ # pyrefly: ignore [missing-attribute]
39
+ return super().__call__(callable, operands)
40
+
41
+
42
+ strict_mode_op = StrictMode()
43
+
44
+
45
+ @strict_mode_op.py_impl(DispatchKey.CompositeExplicitAutograd)
46
+ def strict_mode_op_dense(callable, operands):
47
+ mode = _get_current_dispatch_mode()
48
+ if mode is not None:
49
+ raise AssertionError("Mode should never be enabled for CPU/CUDA key")
50
+ return callable(*operands)
51
+
52
+
53
+ strict_mode_op.py_autograd_impl(
54
+ autograd_not_implemented(strict_mode_op, deferred_error=True)
55
+ )
56
+
57
+
58
+ @strict_mode_op.py_impl(ProxyTorchDispatchMode)
59
+ def inner(mode, callable, operands):
60
+ return trace_strict_mode(mode, strict_mode_op, callable, operands)
61
+
62
+
63
+ def trace_strict_mode(mode, strict_mode_op, callable, operands):
64
+ pre_dispatch = getattr(mode, "pre_dispatch", False)
65
+
66
+ with disable_proxy_modes_tracing():
67
+ graph = make_fx(callable, pre_dispatch=pre_dispatch)(*operands)
68
+
69
+ graph_name = mode.tracer.get_fresh_qualname("strict_graph_")
70
+ mode.tracer.root.register_module(graph_name, graph)
71
+
72
+ args = (graph, operands)
73
+
74
+ proxy_args = pytree.tree_map(mode.tracer.unwrap_proxy, args)
75
+
76
+ out_proxy = mode.tracer.create_proxy(
77
+ "call_function", strict_mode_op, proxy_args, {}, name="strict_mode"
78
+ )
79
+
80
+ out = graph(*operands)
81
+ return track_tensor_tree(out, out_proxy, constant=None, tracer=mode.tracer)
82
+
83
+
84
+ @strict_mode_op.py_impl(FakeTensorMode)
85
+ def strict_mode_fake_tensor_mode(mode, callable, operands):
86
+ with mode:
87
+ true_outs = callable(*operands)
88
+ return true_outs
89
+
90
+
91
+ @strict_mode_op.py_functionalize_impl
92
+ def strict_mode_func(ctx, callable, inputs):
93
+ unwrapped_inputs = ctx.unwrap_tensors(inputs)
94
+ with ctx.redispatch_to_next():
95
+ functional_callable = ctx.functionalize(callable)
96
+
97
+ cond_return = strict_mode_op(functional_callable, unwrapped_inputs)
98
+ return ctx.wrap_tensors(cond_return)
.venv/lib/python3.10/site-packages/torch/_higher_order_ops/torchbind.py ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import logging
3
+ from contextlib import contextmanager
4
+
5
+ import torch
6
+ from torch._C import DispatchKey # @manual
7
+ from torch._functorch._aot_autograd.utils import KNOWN_TYPES
8
+ from torch._higher_order_ops.utils import autograd_not_implemented
9
+ from torch._library.fake_class_registry import (
10
+ _is_script_object,
11
+ _ns_and_class_name,
12
+ FakeScriptObject,
13
+ )
14
+ from torch._ops import HigherOrderOperator
15
+ from torch._subclasses.fake_tensor import FakeTensorMode
16
+ from torch.fx.experimental.proxy_tensor import ProxyTorchDispatchMode, track_tensor_tree
17
+ from torch.fx.node import has_side_effect
18
+ from torch.utils import _pytree as pytree
19
+
20
+
21
+ log = logging.getLogger(__name__)
22
+
23
+
24
+ # The call_torchbind operator represents a method invocation on a torchbind
25
+ # object. The calling convention is:
26
+ # call_torchbind(self: ScriptObject, method_name: str, *method_args, **method_kwargs)
27
+ # We do not expect users to write this operator directly. Instead it will be
28
+ # emitted by Dynamo when tracing encounters a torchbind object.
29
+ class CallTorchBind(HigherOrderOperator):
30
+ def __init__(self):
31
+ super().__init__("call_torchbind")
32
+
33
+ def __call__(self, obj, method, *args, **kwargs):
34
+ # pyrefly: ignore [missing-attribute]
35
+ return super().__call__(obj, method, *args, **kwargs)
36
+
37
+ @staticmethod
38
+ def schema(obj, method) -> torch.FunctionSchema:
39
+ """
40
+ Returns the schema of ``CallTorchbind.__call__``.
41
+ """
42
+ if not isinstance(obj, torch._inductor.ir.TorchBindObject):
43
+ raise AssertionError(f"expected obj to be TorchBindObject, got {type(obj)}")
44
+ val = obj.get_real_obj()
45
+ schema = val._get_method(method).schema
46
+ schema_str = str(schema)
47
+ new_schema_str = f"call_torchbind({str(schema.arguments[0].real_type)} {schema.arguments[0].name},"
48
+ first_comma_index = schema_str.find(",")
49
+ if first_comma_index == -1:
50
+ # If no comma is found, find the last closing parenthesis
51
+ first_comma_index = schema_str.rfind(") ->")
52
+ new_schema_str = new_schema_str + " str method" + schema_str[first_comma_index:]
53
+ new_schema = torch._C.parse_schema(new_schema_str)
54
+ return new_schema
55
+
56
+
57
+ call_torchbind = CallTorchBind()
58
+
59
+ # Register this operator as side-effectful with FX.
60
+ # TODO: this is not really sufficient. While passes (hopefully) check
61
+ # Node.is_impure() and make good decisions, we also assume we can execute the
62
+ # graph as many times as we want without changing behavior, which is NOT true of
63
+ # ops that mutate torchbind object state.
64
+ has_side_effect(call_torchbind)
65
+
66
+ _orig_scriptmethod_call = torch.ScriptMethod.__call__
67
+
68
+
69
+ def torchbind_method_redispatch(self, *args, **kwargs):
70
+ if _is_script_object(self.raw_owner):
71
+ return call_torchbind(self.raw_owner, self.name, *args, **kwargs)
72
+ return _orig_scriptmethod_call(self, *args, **kwargs)
73
+
74
+
75
+ @contextmanager
76
+ def enable_torchbind_tracing():
77
+ """Context manager that acts as a feature flag to enable torchbind tracing
78
+ behavior. Once torchbind tracing has been stabilized, we can remove this and
79
+ turn it always on.
80
+ """
81
+ try:
82
+ KNOWN_TYPES.append(torch.ScriptObject)
83
+ torch.ScriptMethod.__call__ = torchbind_method_redispatch # type: ignore[method-assign]
84
+ yield
85
+ finally:
86
+ if KNOWN_TYPES.pop() is not torch.ScriptObject:
87
+ raise AssertionError(
88
+ "Someone else messed with KNOWN_TYPES during tracing, exploding."
89
+ )
90
+ torch.ScriptMethod.__call__ = _orig_scriptmethod_call # type: ignore[method-assign]
91
+
92
+
93
+ @call_torchbind.py_impl(DispatchKey.CompositeExplicitAutograd)
94
+ def call_torchbind_impl(obj, method, *args, **kwargs):
95
+ if isinstance(obj, torch.ScriptObject):
96
+ return _orig_scriptmethod_call(getattr(obj, method), *args, **kwargs)
97
+ elif isinstance(obj, FakeScriptObject):
98
+ return getattr(obj.wrapped_obj, method)(*args, **kwargs)
99
+ else:
100
+ raise RuntimeError(f"Unsupported first arg type {type(obj)} for call_torchbind")
101
+
102
+
103
+ @call_torchbind.py_impl(ProxyTorchDispatchMode)
104
+ def inner(mode, *args, **kwargs):
105
+ proxy_args = pytree.tree_map(mode.tracer.unwrap_proxy, args)
106
+ proxy_kwargs = pytree.tree_map(mode.tracer.unwrap_proxy, kwargs)
107
+
108
+ out_proxy = mode.tracer.create_proxy(
109
+ "call_function",
110
+ call_torchbind,
111
+ proxy_args,
112
+ proxy_kwargs,
113
+ )
114
+ out = call_torchbind(*args, **kwargs)
115
+
116
+ obj, method, *_rest_args = args
117
+ if isinstance(obj, torch.ScriptObject):
118
+ ns, class_name = _ns_and_class_name(
119
+ obj._type().qualified_name() # type: ignore[attr-defined]
120
+ )
121
+ log.warning(
122
+ "Tracing torchbind method %s.%s with real ScriptObject. This may"
123
+ " cause the original object being mutated. If this is not intended,"
124
+ ' You can register a fake class with torch._library.register_fake_class("%s::%s").',
125
+ class_name,
126
+ method,
127
+ ns,
128
+ class_name,
129
+ )
130
+
131
+ ret = track_tensor_tree(out, out_proxy, constant=None, tracer=mode.tracer)
132
+ if "val" not in out_proxy.node.meta:
133
+ if out is not None and not isinstance(out, (int, float, bool)):
134
+ raise AssertionError(
135
+ f"Currently, only these constant dtypes are supported to be returned from torchbind methods, got {type(out)}"
136
+ )
137
+ out_proxy.node.meta["val"] = out
138
+ return ret
139
+
140
+
141
+ # When tracing with fake script object, the call_torchbind op will return a fake tensor
142
+ # When tracing with real script object, the call_torchbind op may return a real tensor,
143
+ # we need to convert it to fake tensor manually. Dynamic shape is supported.
144
+ @call_torchbind.py_impl(FakeTensorMode)
145
+ def call_torchbind_fake(mode, *args, **kwargs):
146
+ with mode:
147
+ out = call_torchbind_impl(*args, **kwargs)
148
+ return pytree.tree_map_only(
149
+ torch.Tensor,
150
+ lambda x: mode.from_tensor(x, static_shapes=True)
151
+ if not isinstance(x, torch._subclasses.fake_tensor.FakeTensor)
152
+ else x,
153
+ out,
154
+ )
155
+
156
+
157
+ call_torchbind.py_autograd_impl(
158
+ autograd_not_implemented(call_torchbind, deferred_error=True)
159
+ )
160
+
161
+
162
+ @call_torchbind.py_functionalize_impl
163
+ def call_torchbind_func(ctx, *args, **kwargs):
164
+ from torch._higher_order_ops.effects import handle_effects
165
+
166
+ return handle_effects(
167
+ ctx.mode._allow_token_discovery, ctx.mode._tokens, call_torchbind, args, kwargs
168
+ )
.venv/lib/python3.10/site-packages/torch/_higher_order_ops/triton_kernel_wrap.py ADDED
@@ -0,0 +1,2207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import collections
2
+ import copy
3
+ import dataclasses
4
+ import functools
5
+ import inspect
6
+ import itertools
7
+ import logging
8
+ import operator
9
+ import threading
10
+ from collections import defaultdict
11
+ from collections.abc import Callable, Sequence
12
+ from typing import Any, Optional, TYPE_CHECKING, Union
13
+ from typing_extensions import Never
14
+
15
+ import sympy
16
+
17
+ import torch.fx as fx
18
+ import torch.utils._pytree as pytree
19
+ from torch import SymInt, Tensor
20
+ from torch._C import DispatchKey
21
+ from torch._higher_order_ops.utils import redirect_to_mode
22
+ from torch._ops import HigherOrderOperator
23
+ from torch._prims_common import clone_preserve_strides
24
+ from torch._subclasses.fake_tensor import FakeTensorMode
25
+ from torch.fx.experimental.proxy_tensor import (
26
+ disable_proxy_modes_tracing,
27
+ ProxyTorchDispatchMode,
28
+ track_tensor_tree,
29
+ )
30
+ from torch.fx.experimental.symbolic_shapes import guard_scalar
31
+ from torch.types import IntLikeType
32
+ from torch.utils.checkpoint import _CachedTorchDispatchMode, _CachingTorchDispatchMode
33
+
34
+
35
+ if TYPE_CHECKING:
36
+ from triton._C.libtriton.ir import (
37
+ module as TritonIRModule,
38
+ operation as TritonIROperation,
39
+ )
40
+
41
+ from torch._dynamo.symbolic_convert import InstructionTranslator
42
+ from torch._dynamo.variables.constant import ConstantVariable
43
+ from torch._dynamo.variables.functions import TritonKernelVariable
44
+ from torch._subclasses.functional_tensor import BaseFunctionalizeAPI
45
+ from torch.fx.proxy import Proxy
46
+ from torch.utils._triton import has_triton
47
+
48
+ TritonMetaParamsType = dict[str, int]
49
+ TritonGridTupleType = tuple[Union[int, sympy.Expr, SymInt], ...]
50
+ TritonGridCallableType = Callable[[TritonMetaParamsType], tuple[int, ...]]
51
+ TritonGridType = Union[TritonGridTupleType, TritonGridCallableType]
52
+
53
+ if has_triton():
54
+ from triton.runtime.autotuner import Autotuner, Config as TritonConfig
55
+ from triton.runtime.jit import JITFunction
56
+ else:
57
+
58
+ class Autotuner: # type: ignore[no-redef]
59
+ pass
60
+
61
+ class JITFunction: # type: ignore[no-redef]
62
+ pass
63
+
64
+ TritonKernelType = Union[Autotuner, JITFunction]
65
+ # mypy specifically complains that TritonAutotunerType is not a valid type if Autotuner is not inside of a Union.
66
+ TritonAutotunerType = Union[Autotuner]
67
+
68
+ log = logging.getLogger("torch._dynamo")
69
+
70
+ # e.g. for a host-side Triton TMA API call ``create_2d_tma_descriptor(ptr, 50, 60, 32, 15, 4)``,
71
+ # the metadata will look like ``("experimental", ([50, 60], [32, 15], 4))``
72
+ TMAExperimentalMetadata = tuple[
73
+ str, # type of TMA (should be "experimental")
74
+ tuple[
75
+ list[IntLikeType], # dims
76
+ list[IntLikeType], # block_dims
77
+ IntLikeType, # element_size
78
+ ],
79
+ ]
80
+
81
+ # e.g. for host-side Triton TMA API call ``TensorDescriptor.from_tensor(ptr, [32, 64])``
82
+ # the metadata will look like ``("stable", ([32, 64],))``
83
+ TMAStableMetadata = tuple[
84
+ str, # type of TMA ("experimental" or "stable")
85
+ tuple[list[IntLikeType],], # block_shape
86
+ ]
87
+
88
+
89
+ def create_tma_experimental_metadata(
90
+ dims: list[IntLikeType],
91
+ block_dims: list[IntLikeType],
92
+ element_size: IntLikeType,
93
+ ) -> TMAExperimentalMetadata:
94
+ return ("experimental", (dims, block_dims, element_size))
95
+
96
+
97
+ def maybe_unpack_tma_experimental_metadata(
98
+ tma_meta: Union[TMAExperimentalMetadata, TMAStableMetadata],
99
+ ) -> Optional[tuple[list[IntLikeType], list[IntLikeType], IntLikeType]]:
100
+ if not tma_meta or len(tma_meta) != 2:
101
+ return None
102
+ if tma_meta[0] == "experimental":
103
+ return tma_meta[1] # type: ignore[return-value]
104
+ return None
105
+
106
+
107
+ def create_tma_stable_metadata(
108
+ block_shape: list[IntLikeType],
109
+ ) -> TMAStableMetadata:
110
+ return ("stable", (block_shape,))
111
+
112
+
113
+ def maybe_unpack_tma_stable_metadata(
114
+ tma_meta: Union[TMAExperimentalMetadata, TMAStableMetadata],
115
+ ) -> Optional[tuple[list[IntLikeType]]]:
116
+ if not tma_meta or len(tma_meta) != 2:
117
+ return None
118
+ if tma_meta[0] == "stable":
119
+ return tma_meta[1] # type: ignore[return-value]
120
+ return None
121
+
122
+
123
+ # TMADescriptorMetadata maps kernel parameter names to the metadata that allows
124
+ # reconstructing TMA descriptors from the underlying tensors (passed as kernel
125
+ # arguments in the fx graph, instead of the TMA descriptors).
126
+ #
127
+ # Since there are two TMA APIs (the old "experimental" API and the new "stable" API),
128
+ # each entry in the dict is a tuple that starts with a string, either "experimental"
129
+ # or "stable". The second entry in the tuple is another tuple, with data that depends
130
+ # on the API type (see TMAExperimentalMetadata and TMAStableMetadata above).
131
+ #
132
+ # These are stored as raw tuples (instead of classes) for ease of serialization.
133
+ TMADescriptorMetadata = dict[
134
+ str, # kernel parameter name
135
+ Union[TMAExperimentalMetadata, TMAStableMetadata],
136
+ ]
137
+
138
+
139
+ ###############################################################################
140
+ # Kernel Side Table
141
+
142
+
143
+ # We cannot put Triton Kernels into the FX graph as the graph nodes
144
+ # do not support arbitrary functions.
145
+ # Use a side table.
146
+ # We use two dicts so that fetching both the kernel and id are O(1)
147
+ class KernelSideTable:
148
+ id_to_kernel: dict[int, "TritonKernelType"] = {}
149
+ kernel_to_id: dict["TritonKernelType", int] = {}
150
+ constant_args: dict[int, dict[str, Any]] = {}
151
+ lock = threading.Lock()
152
+
153
+ # Returns index on the table
154
+ def add_kernel(self, kernel: "TritonKernelType") -> int:
155
+ with self.lock:
156
+ if kernel in self.kernel_to_id:
157
+ return self.kernel_to_id[kernel]
158
+
159
+ idx = len(self.id_to_kernel)
160
+ self.id_to_kernel[idx] = kernel
161
+ self.kernel_to_id[kernel] = idx
162
+ return idx
163
+
164
+ # Returns the triton kernel at the given index
165
+ def get_kernel(self, idx: int) -> "TritonKernelType":
166
+ # No need to lock here as fetching from dict is atomic
167
+ if idx not in self.id_to_kernel:
168
+ raise AssertionError(f"Kernel index {idx} not found in id_to_kernel")
169
+ return self.id_to_kernel[idx]
170
+
171
+ # Not every constant arg can be added to the graph. Use this side table
172
+ # for constant args.
173
+ def add_constant_args(self, args: dict[str, Any]) -> int:
174
+ with self.lock:
175
+ idx = len(self.constant_args)
176
+ self.constant_args[idx] = args
177
+ return idx
178
+
179
+ # Returns the constant args
180
+ def get_constant_args(self, idx: int) -> dict[str, Any]:
181
+ # No need to lock here as fetching from dict is atomic
182
+ if idx not in self.constant_args:
183
+ raise AssertionError(
184
+ f"Constant args index {idx} not found in constant_args"
185
+ )
186
+ return self.constant_args[idx]
187
+
188
+ # Resets the table (only meant to be used in unit tests)
189
+ # This is only safe assuming single threaded execution
190
+ def reset_table(self) -> None:
191
+ self.id_to_kernel = {}
192
+ self.kernel_to_id = {}
193
+ self.constant_args = {}
194
+
195
+
196
+ kernel_side_table = KernelSideTable()
197
+
198
+
199
+ ###############################################################################
200
+ # Mutation Tracker
201
+
202
+
203
+ @dataclasses.dataclass(frozen=True, slots=True)
204
+ class Param:
205
+ idx: int
206
+
207
+
208
+ @dataclasses.dataclass(frozen=True, slots=True)
209
+ class Intermediate:
210
+ idx: int
211
+
212
+ def fake(self) -> bool:
213
+ return self.idx < 0
214
+
215
+
216
+ @dataclasses.dataclass(frozen=True, slots=True)
217
+ class Op:
218
+ name: str
219
+ fn_call_name: Optional[str]
220
+ args: list[Union[Param, Intermediate]]
221
+ ret: Intermediate = dataclasses.field(repr=False)
222
+ # used for scf.yield: see [Note: scf.yield fix-up]
223
+ sub_idx: Optional[int] = None
224
+ # used for tt.elementwise_inline_asm
225
+ # `is_pure = True` assumes the asm block has no side-effects
226
+ is_pure: bool = False
227
+
228
+ def __post_init__(self) -> None:
229
+ if self.name == "tt.call":
230
+ if self.fn_call_name is None:
231
+ raise AssertionError("fn_call_name must not be None for tt.call op")
232
+ else:
233
+ if self.fn_call_name is not None:
234
+ raise AssertionError(
235
+ f"fn_call_name must be None for non-tt.call op, got {self.fn_call_name}"
236
+ )
237
+
238
+
239
+ def generate_ttir(
240
+ kernel: "TritonKernelType",
241
+ kwargs: dict[str, Any],
242
+ tma_descriptor_metadata: TMADescriptorMetadata,
243
+ ) -> tuple["TritonIRModule", list[str]]:
244
+ """
245
+ Uses Triton's internal code generation to create TTIR
246
+ """
247
+ import sympy
248
+ import triton
249
+ import triton.runtime.jit
250
+ from triton.compiler.compiler import ASTSource
251
+ from triton.runtime.autotuner import Autotuner
252
+ from triton.runtime.jit import JITFunction
253
+
254
+ from torch._inductor.utils import (
255
+ get_triton_attrs_descriptor_version,
256
+ triton_version_uses_attrs_dict,
257
+ TritonAttrsDescriptorVersion,
258
+ )
259
+ from torch.utils._triton import has_triton_tensor_descriptor_host_tma
260
+
261
+ triton_version = get_triton_attrs_descriptor_version()
262
+
263
+ import torch._inductor.ir
264
+ from torch._subclasses.fake_tensor import FakeTensor
265
+
266
+ if isinstance(kernel, Autotuner):
267
+ if len(kernel.configs) > 0:
268
+ # If we are autotuning, then it doesn't matter which version gets
269
+ # picked for tracing purposes, so lets pick the first one
270
+ kwargs = {**kwargs, **kernel.configs[0].kwargs}
271
+ kernel = kernel.fn
272
+
273
+ if not isinstance(kernel, JITFunction):
274
+ raise AssertionError(f"Expected kernel to be a JITFunction, got {type(kernel)}")
275
+
276
+ context = triton._C.libtriton.ir.context()
277
+ target = triton.runtime.driver.active.get_current_target()
278
+ backend = triton.compiler.compiler.make_backend(target)
279
+ options = backend.parse_options({})
280
+
281
+ # ignore backend-specific kwargs same way as in the native Triton code
282
+ # https://github.com/triton-lang/triton/blob/a6bb57d6285e723c58e87dd7cba263db6efff789/python/triton/runtime/jit.py#L594-L596
283
+ # why this is important for user-defined Triton kernels on AMD: https://github.com/pytorch/pytorch/issues/140800
284
+ for name in list(kwargs):
285
+ if name not in kernel.arg_names and name in options.__dict__:
286
+ kwargs.pop(name)
287
+
288
+ if len(kwargs) != len(kernel.arg_names):
289
+ raise ValueError(
290
+ "Incorrect number of arguments passed to kernel: "
291
+ f"passed {list(kwargs.keys())}, expected {kernel.arg_names}."
292
+ )
293
+
294
+ # Replace all SymExprs with a regular value for TTIR generation
295
+ # Replace all FakeTensor/TensorBox with real tensors
296
+ # These replacements are needed for triton's type, key and config functions
297
+ ordered_args: dict[str, Any] = {}
298
+ for name in kernel.arg_names:
299
+ a = kwargs[name]
300
+ if isinstance(a, (torch.SymInt, torch.SymFloat, torch.SymBool, sympy.Expr)):
301
+ ordered_args[name] = 2
302
+ elif (
303
+ stable_meta := maybe_unpack_tma_stable_metadata(
304
+ # pyrefly: ignore [bad-argument-type]
305
+ tma_descriptor_metadata.get(name, None)
306
+ )
307
+ ) is not None:
308
+ from triton.tools.tensor_descriptor import TensorDescriptor
309
+
310
+ block_shape = stable_meta[0]
311
+ with torch._C._DisableTorchDispatch():
312
+ # need 16-byte aligned strides
313
+ elements_per_dim = max(1, 16 // a.dtype.itemsize)
314
+ base_tensor = torch.empty(
315
+ [elements_per_dim] * len(block_shape), dtype=a.dtype
316
+ )
317
+
318
+ ordered_args[name] = TensorDescriptor.from_tensor(base_tensor, block_shape)
319
+ elif isinstance(a, (FakeTensor, torch._inductor.ir.TensorBox)):
320
+ with torch._C._DisableTorchDispatch():
321
+ ordered_args[name] = torch.empty(2, dtype=a.dtype)
322
+ else:
323
+ ordered_args[name] = a
324
+
325
+ def is_stable_tensor_descriptor_arg(arg: Any) -> bool:
326
+ if has_triton_tensor_descriptor_host_tma():
327
+ from triton.tools.tensor_descriptor import TensorDescriptor
328
+
329
+ if isinstance(arg, TensorDescriptor):
330
+ return True
331
+ return False
332
+
333
+ def is_tensor_like_arg(arg: Any) -> bool:
334
+ if isinstance(arg, Tensor) or is_stable_tensor_descriptor_arg(arg):
335
+ return True
336
+ return False
337
+
338
+ # Note: one would expect that each input to the triton kernel maps to
339
+ # one input parameter in the TTIR. This is _not_ true for TMA descriptors:
340
+ # one TMA descriptor gets converted into:
341
+ # * one TMA descriptor input
342
+ # * N strides, for a rank-N tensor
343
+ # * N sizes, for a rank-N tensor
344
+ # To account for this, we inject some fake arg names as placeholders for
345
+ # the stride and size parameters.
346
+ def get_tensor_names(name: str, arg: Any) -> list[str]:
347
+ if isinstance(arg, Tensor):
348
+ return [name]
349
+ if is_stable_tensor_descriptor_arg(arg):
350
+ stable_meta = maybe_unpack_tma_stable_metadata(
351
+ tma_descriptor_metadata[name]
352
+ )
353
+ if stable_meta is None:
354
+ raise AssertionError(f"Failed to unpack stable TMA metadata for {name}")
355
+ block_shape = stable_meta[0]
356
+ tensor_rank = len(block_shape)
357
+ names = [name]
358
+ names.extend(name + f" STRIDE PLACEHOLDER {i}" for i in range(tensor_rank))
359
+ names.extend(name + f" SIZE PLACEHOLDER {i}" for i in range(tensor_rank))
360
+ return names
361
+ return []
362
+
363
+ ordered_tensor_names = list(
364
+ itertools.chain.from_iterable(
365
+ get_tensor_names(name, arg) for name, arg in ordered_args.items()
366
+ )
367
+ )
368
+
369
+ def _get_specialization(args): # type: ignore[no-untyped-def]
370
+ # Support multiple triton versions.
371
+ # This code basically copies JITFunction.run() logic to get the attrs to construct an ASTSource.
372
+ if triton_version == TritonAttrsDescriptorVersion.V1_COMPILER:
373
+ return kernel._get_config(*args)
374
+ elif triton_version in {
375
+ TritonAttrsDescriptorVersion.V2_BACKENDS,
376
+ TritonAttrsDescriptorVersion.V3_BACKENDS_TUPLE,
377
+ }:
378
+ from triton.backends.compiler import AttrsDescriptor # noqa: F401
379
+
380
+ target = triton.runtime.driver.active.get_current_target()
381
+ backend_ = triton.compiler.compiler.make_backend(target)
382
+
383
+ return backend_.get_attrs_descriptor(args, kernel.params)
384
+ else:
385
+ if (
386
+ get_triton_attrs_descriptor_version()
387
+ != TritonAttrsDescriptorVersion.V4_DICT
388
+ ):
389
+ raise AssertionError(
390
+ f"Expected Triton attrs descriptor version V4_DICT, "
391
+ f"got {get_triton_attrs_descriptor_version()}"
392
+ )
393
+ # specialize_impl switched to create_specialize_impl in https://github.com/triton-lang/triton/pull/6099
394
+ if hasattr(triton.runtime.jit, "create_specialize_impl"):
395
+ try:
396
+ # Latest versions of Triton take specialize_extra as an arg to create_specialize_impl
397
+ specialize_impl = triton.runtime.jit.create_specialize_impl(
398
+ specialize_extra=backend.get_arg_specialization
399
+ )
400
+ except TypeError: # Unknown arg `specialize_extra`
401
+ # Older versions of Triton take specialize_extra as an arg to specialize_impl
402
+ specialize_impl = functools.partial(
403
+ triton.runtime.jit.create_specialize_impl(),
404
+ specialize_extra=backend.get_arg_specialization,
405
+ )
406
+ # create_specialize_impl is removed in https://github.com/triton-lang/triton/pull/7771
407
+ # switch to native_specialize_impl instead
408
+ elif hasattr(triton.runtime.jit, "native_specialize_impl"):
409
+ from triton.backends import BaseBackend
410
+ from triton.runtime.jit import native_specialize_impl
411
+
412
+ def _native_specialize_impl(
413
+ arg: Any,
414
+ is_const: bool = False,
415
+ specialize_value: bool = True,
416
+ align: bool = True,
417
+ ) -> Callable:
418
+ return native_specialize_impl(
419
+ BaseBackend, arg, is_const, specialize_value, align
420
+ )
421
+
422
+ specialize_impl = _native_specialize_impl
423
+ else:
424
+ from triton.runtime.jit import specialize_impl as specialize_impl_orig
425
+
426
+ specialize_impl = functools.partial(
427
+ specialize_impl_orig,
428
+ specialize_extra=backend.get_arg_specialization,
429
+ )
430
+
431
+ from triton._utils import find_paths_if, get_iterable_path
432
+
433
+ # logic is copied from: binder = create_function_from_signature(self.signature, self.params, backend)
434
+ attrvals = []
435
+ for arg, kp in zip(args, kernel.params):
436
+ if kp.is_constexpr:
437
+ attrvals.append(arg)
438
+ else:
439
+ spec = specialize_impl(
440
+ arg,
441
+ is_const=kp.is_const,
442
+ specialize_value=not kp.do_not_specialize,
443
+ align=not kp.do_not_specialize_on_alignment,
444
+ )
445
+ # pyrefly: ignore [unsupported-operation]
446
+ attrvals.append(spec[1])
447
+
448
+ attrs = find_paths_if(attrvals, lambda _, x: isinstance(x, str))
449
+ attrs = {
450
+ k: backend.parse_attr(get_iterable_path(attrvals, k)) for k in attrs
451
+ }
452
+ return attrs
453
+
454
+ specialization = _get_specialization(ordered_args.values())
455
+ constants = {
456
+ name: arg for name, arg in ordered_args.items() if not is_tensor_like_arg(arg)
457
+ }
458
+
459
+ if (mangle_type := getattr(triton.runtime.jit, "mangle_type", None)) is not None:
460
+
461
+ def get_signature_value(idx: int, arg: Any) -> str:
462
+ if kernel.params[idx].is_constexpr:
463
+ return "constexpr"
464
+ # pyrefly: ignore [not-callable]
465
+ return mangle_type(arg)
466
+
467
+ else:
468
+
469
+ def get_signature_value(idx: int, arg: Any) -> str:
470
+ return kernel._type_of(kernel.key_of(arg))
471
+
472
+ if triton_version_uses_attrs_dict():
473
+ # In newer versions of Triton, the signature includes constexpr args
474
+ signature = {
475
+ name: get_signature_value(i, arg)
476
+ for i, (name, arg) in enumerate(ordered_args.items())
477
+ }
478
+ else:
479
+ # In older versions of Triton, the signature does not include constexpr args
480
+ constexprs = [p.num for p in kernel.params if p.is_constexpr]
481
+ signature = {
482
+ name: get_signature_value(i, arg)
483
+ for i, (name, arg) in enumerate(ordered_args.items())
484
+ if i not in constexprs
485
+ }
486
+
487
+ triton._C.libtriton.ir.load_dialects(context)
488
+ backend.load_dialects(context)
489
+
490
+ src = ASTSource(kernel, signature, constants, specialization)
491
+
492
+ # Triton changes ASTSource.make_ir to take 3/4 arguments. Handle
493
+ # backward compatibility here.
494
+ make_ir_sig_params = len(inspect.signature(src.make_ir).parameters)
495
+ get_codegen_implementation_sig_params = len(
496
+ inspect.signature(backend.get_codegen_implementation).parameters
497
+ )
498
+ if make_ir_sig_params == 2:
499
+ ttir_module = src.make_ir(options, context)
500
+ elif make_ir_sig_params == 3:
501
+ codegen_fns = backend.get_codegen_implementation()
502
+
503
+ ttir_module = src.make_ir(options, codegen_fns, context)
504
+ elif make_ir_sig_params == 4:
505
+ codegen_args = [options] if get_codegen_implementation_sig_params == 1 else []
506
+
507
+ codegen_fns = backend.get_codegen_implementation(*codegen_args)
508
+ module_map = backend.get_module_map()
509
+
510
+ ttir_module = src.make_ir(options, codegen_fns, module_map, context)
511
+ else:
512
+ codegen_args = [options] if get_codegen_implementation_sig_params == 1 else []
513
+
514
+ codegen_fns = backend.get_codegen_implementation(*codegen_args)
515
+ module_map = backend.get_module_map()
516
+
517
+ ttir_module = src.make_ir(target, options, codegen_fns, module_map, context)
518
+ if not ttir_module.verify():
519
+ raise RuntimeError("Verification for TTIR module has failed")
520
+
521
+ return ttir_module, ordered_tensor_names
522
+
523
+
524
+ def ttir_to_functions(
525
+ ttir_module: "TritonIRModule",
526
+ ) -> dict[str, dict[Intermediate, list[Op]]]:
527
+ """
528
+ Walk the `ttir_module` bottom up to mine the `functions` from
529
+ the structured MLIR entities representing the Triton kernel
530
+ (mlir::Operation, mlir::Block, mlir::Region).
531
+ """
532
+ functions: dict[str, dict[Intermediate, list[Op]]] = {}
533
+
534
+ # block id --> op result (Intermediate) --> one or more ops
535
+ op_stack: dict[int, dict[Intermediate, list[Op]]] = defaultdict(
536
+ lambda: defaultdict(list)
537
+ )
538
+ region_id_to_block_ids: dict[int, list[int]] = defaultdict(list)
539
+ block_id_to_block_arg_ids: dict[int, list[int]] = {}
540
+ replacements: dict[int, Union[Intermediate, Param]] = {}
541
+ reindex_map: dict[int, int] = {}
542
+ next_fake_intermediate = 0
543
+
544
+ def reindex(idx: int) -> int:
545
+ if idx not in reindex_map:
546
+ reindex_map[idx] = len(reindex_map)
547
+ return reindex_map[idx]
548
+
549
+ def mlir_to_functions(op: "TritonIROperation") -> None:
550
+ name: str = op.get_name()
551
+ if name == "builtin.module":
552
+ # this wraps all tt.func ops
553
+ return
554
+
555
+ operand_ids: list[int] = [
556
+ reindex(op.get_operand(i).id()) for i in range(op.get_num_operands())
557
+ ]
558
+ result_ids: list[int] = [
559
+ reindex(op.get_result(i).id()) for i in range(op.get_num_results())
560
+ ]
561
+
562
+ child_block_ids: list[int] = []
563
+ for i in [op.get_region(i).id() for i in range(op.get_num_regions())]:
564
+ # as the walk is bottom-up, the region_id_to_block_ids[i]
565
+ # must be populated by the time we process the enclosing op
566
+ child_block_ids.extend(region_id_to_block_ids[i])
567
+
568
+ parent_block_id = -1
569
+ parent_block = op.get_block()
570
+ if parent_block is not None:
571
+ parent_block_id = parent_block.id()
572
+ if parent_block_id not in block_id_to_block_arg_ids:
573
+ block_id_to_block_arg_ids[parent_block_id] = []
574
+ for i in range(parent_block.get_num_arguments()):
575
+ block_id_to_block_arg_ids[parent_block_id].append(
576
+ reindex(parent_block.get_argument(i).id()),
577
+ )
578
+ # the region info is collected via ops' parent blocks to be
579
+ # used later when the region's encloding op is traversed
580
+ parent_region = parent_block.get_parent()
581
+ if parent_region is not None:
582
+ region_id_to_block_ids[parent_region.id()].append(parent_block_id)
583
+
584
+ nonlocal next_fake_intermediate
585
+
586
+ if name == "tt.func":
587
+ # for function ops: gather and inline
588
+ # the ops from all child blocks
589
+ fn_ops = defaultdict(list)
590
+ for child_block_id in child_block_ids:
591
+ for result, block_fn_ops in op_stack.pop(child_block_id).items():
592
+ for block_fn_op in block_fn_ops:
593
+ fn_ops[result].append(block_fn_op)
594
+
595
+ # replace the corresponding Intermediates in the
596
+ # child op args with the function args (Params)
597
+ for i, idx in enumerate(block_id_to_block_arg_ids[child_block_ids[0]]):
598
+ replacements[idx] = Param(i)
599
+
600
+ for fn_op_list in fn_ops.values():
601
+ for fn_op in fn_op_list:
602
+ for i in range(len(fn_op.args)):
603
+ arg = fn_op.args[i]
604
+ seen = set() # to break cycles
605
+ # there can be transitive replacements, but likely
606
+ # no cycles (we keep the `seen` set just in case)
607
+ while (
608
+ isinstance(arg, Intermediate)
609
+ and arg.idx in replacements
610
+ and arg.idx not in seen
611
+ ):
612
+ seen.add(arg.idx)
613
+ arg = fn_op.args[i] = replacements[arg.idx]
614
+
615
+ # next function capture starts
616
+ # with empty replacements
617
+ replacements.clear()
618
+
619
+ fn_name = op.get_str_attr("sym_name")
620
+ functions[fn_name] = fn_ops
621
+ elif child_block_ids:
622
+ if name in {"scf.if", "scf.for", "scf.while", "tt.reduce", "tt.scan"}:
623
+ # for blocked ops: inline the enclosed ops into
624
+ # the parent block + rewire the last op in each
625
+ # child block to return the block result
626
+ return_ops = []
627
+ for block_id in child_block_ids:
628
+ if name == "scf.for":
629
+ # example:
630
+ # %result = scf.for %iv = %lb to %ub step %step iter_args(%arg = %init) -> (i32) ...
631
+ # block args: 2 (%iv, %arg)
632
+ # op operands: 4 (%lb, %ub, %step, %init)
633
+ # `%arg` is mapping to `%init`
634
+ for i, idx in enumerate(block_id_to_block_arg_ids[block_id]):
635
+ if i == 0:
636
+ next_fake_intermediate -= 1
637
+ replacements[idx] = Intermediate(next_fake_intermediate)
638
+ else:
639
+ replacements[idx] = Intermediate(operand_ids[i + 2])
640
+ elif name == "scf.while":
641
+ # example:
642
+ # %3:3 = scf.while (%arg2 = %1, %arg3 = %2, %arg4 = %c0_i32_8) ...
643
+ # block args: 3 (%arg2, %arg3, %arg4)
644
+ # op operands: 3 (%1, %2, %c0_i32_8)
645
+ # `%arg2` is mapping to `%1`, `%arg3` is mapping to `%2`, ...
646
+ for i, idx in enumerate(block_id_to_block_arg_ids[block_id]):
647
+ replacements[idx] = Intermediate(operand_ids[i])
648
+ elif name == "scf.if":
649
+ # the scf block args are ignored by the pass. but, as they
650
+ # may be used as operands of the ops inside the block
651
+ # (and nested blocks inlined in the current block by now),
652
+ # they are replaced by new fake Intermediates to avoid "this
653
+ # operand is not returned by any other op in the fn" error
654
+ # in the downstream analysis
655
+ for idx in block_id_to_block_arg_ids[block_id]:
656
+ next_fake_intermediate -= 1
657
+ replacements[idx] = Intermediate(next_fake_intermediate)
658
+ else:
659
+ if name not in ("tt.reduce", "tt.scan"):
660
+ raise AssertionError(
661
+ f"Expected op name to be 'tt.reduce' or 'tt.scan', got {name}"
662
+ )
663
+ # wire the block arguments to the op arguments
664
+ num_operands = len(operand_ids)
665
+ block_arg_ids = block_id_to_block_arg_ids[block_id]
666
+ if len(block_arg_ids) != 2 * num_operands:
667
+ raise AssertionError(
668
+ f"{name} is expected to have twice as "
669
+ "many block arguments as op arguments: "
670
+ f"{operand_ids=}, {block_arg_ids=}."
671
+ )
672
+ for i, idx in enumerate(block_arg_ids):
673
+ # for a tt.reduce/tt.scan op with N arguments, the block
674
+ # arguments comprise N reduced values followed by
675
+ # N current values corresponding to the N op args
676
+ replacements[idx] = Intermediate(
677
+ operand_ids[i % num_operands]
678
+ )
679
+
680
+ if block_id in op_stack:
681
+ block_ops = op_stack.pop(block_id)
682
+ if not block_ops:
683
+ continue
684
+ last_ret, last_ops = block_ops.popitem()
685
+ if all(
686
+ op.name
687
+ in ("scf.yield", "tt.reduce.return", "tt.scan.return")
688
+ for op in last_ops
689
+ ):
690
+ # if last_ops are all return ops, treat them separately
691
+ return_ops.extend(last_ops)
692
+ else:
693
+ # otherwise, return last_ops to the block
694
+ block_ops[last_ret] = last_ops
695
+ for op_result, child_ops in block_ops.items():
696
+ op_stack[parent_block_id][op_result].extend(child_ops)
697
+
698
+ scf_results = [Intermediate(idx) for idx in result_ids]
699
+
700
+ if return_ops and all(
701
+ (op.name == "scf.yield" and len(result_ids) == len(op.args))
702
+ for op in return_ops
703
+ ):
704
+ # [Note: scf.yield fix-up]
705
+ #
706
+ # TL;DR: if our scf.yield takes N args, then we'll create N scf.yield ops to handle each of the
707
+ # args.
708
+ #
709
+ # **Context**:
710
+ # During mutation analysis, the analysis pass will identify mutating ops (e.g. tt.store)
711
+ # and then DFS upwards towards the parameters of the function. Specifically, the analysis pass
712
+ # looks at the mutated arg in tt.store; then looks for its source ops; and then recurses on the
713
+ # arguments to each of the source ops.
714
+ #
715
+ # In the case of scf.if/scf.for, we may have multiple return ops, each passed as an arg
716
+ # to scf.yield:
717
+ #
718
+ # %18:2 = scf.if %... -> (!tt.ptr<f32>, !tt.ptr<f32>) {
719
+ # ...
720
+ # scf.yield %1, %2
721
+ # } else {
722
+ # scf.yield %3, %4
723
+ # }
724
+ #
725
+ # And for each of the returns of the scf.if, we'd naively assign the source op of each of the
726
+ # return values to be the scf.yields. But the scf.yields take _all_ the returns as arguments.
727
+ # Therefore, if _any_ of the return values of the scf.if are mutated, then the analysis pass
728
+ # would mark _all_ of the yield args as mutated.
729
+ #
730
+ # **Solution**:
731
+ # For the purposes of this analysis pass, we create N yield ops - one for each
732
+ # return-val/yield-arg. In the example above, we'll have two scf.yield's for each branch of the
733
+ # scf.if.
734
+
735
+ for return_op in return_ops:
736
+ for i, (scf_result, yield_arg) in enumerate(
737
+ zip(scf_results, return_op.args)
738
+ ):
739
+ sub_yield_op = Op(
740
+ return_op.name,
741
+ return_op.fn_call_name,
742
+ [yield_arg],
743
+ return_op.ret,
744
+ sub_idx=i,
745
+ )
746
+ op_stack[parent_block_id][scf_result].append(sub_yield_op)
747
+
748
+ else:
749
+ for scf_result in scf_results:
750
+ for return_op in return_ops:
751
+ op_stack[parent_block_id][scf_result].append(return_op)
752
+ else:
753
+ raise RuntimeError(
754
+ f"Unknown blocked function: {name}. Can't capture the TTIR."
755
+ )
756
+ else:
757
+ callee = None
758
+ if name == "tt.call":
759
+ callee = op.get_flat_symbol_ref_attr("callee")
760
+ args: list[Union[Param, Intermediate]] = [
761
+ Intermediate(operand) for operand in operand_ids
762
+ ]
763
+ block_ops = op_stack[parent_block_id]
764
+
765
+ is_pure = False
766
+ # Handle the case for tt.elementwise_inline_asm to set `is_pure` for mutation analysis
767
+ if name == "tt.elementwise_inline_asm":
768
+ is_pure = op.get_bool_attr("pure")
769
+
770
+ if result_ids:
771
+ for result_id in result_ids:
772
+ res = Intermediate(result_id)
773
+ block_ops[res].append(Op(name, callee, args, res, is_pure=is_pure))
774
+ else:
775
+ next_fake_intermediate -= 1
776
+ fake_res = Intermediate(next_fake_intermediate)
777
+ block_ops[fake_res].append(
778
+ Op(name, callee, args, fake_res, is_pure=is_pure)
779
+ )
780
+
781
+ ttir_module.walk(mlir_to_functions)
782
+
783
+ return functions
784
+
785
+
786
+ class MemoizeWithCycleCheck:
787
+ fn: Callable[..., Any]
788
+ cache: dict[tuple[Any], Any]
789
+
790
+ def __init__(self, fn: Callable[..., Any]) -> None:
791
+ self.fn = fn
792
+ self.reset()
793
+
794
+ def __call__(
795
+ self,
796
+ functions: dict[str, dict[Intermediate, list[Op]]],
797
+ fn_name: str,
798
+ *args: Any,
799
+ ) -> list[bool]:
800
+ key: tuple[Any, ...] = (fn_name, *args)
801
+ if key not in self.cache:
802
+ self.cache[key] = None
803
+ self.cache[key] = self.fn(functions, fn_name, *args)
804
+ if self.cache[key] is None:
805
+ raise RuntimeError("Recursion is not supported")
806
+ return self.cache[key]
807
+
808
+ def reset(self) -> None:
809
+ self.cache = {}
810
+
811
+
812
+ @MemoizeWithCycleCheck
813
+ def get_tma_stores(
814
+ functions: dict[str, dict[Intermediate, list[Op]]], fn_name: str
815
+ ) -> set[Union[Intermediate, Param]]:
816
+ """
817
+ Identifies all intermediates and parameters that are written to by a
818
+ `tt.experimental_descriptor_store`. It tracks only the specific values
819
+ written to via experimental_descriptor_store and the input values to
820
+ `tt.reinterpret_tensor_descriptor` used to construct the direct inputs
821
+ to tt.experimental_descriptor_store - not any recursive values
822
+ used to construct those values.
823
+
824
+ For example: for
825
+ tt.reinterpret_tensor_descriptor(Intermediate(idx=0), ...)
826
+ Intermediate(idx=1) = tt.experimental_descriptor_store(Intermediate(idx=0), ...)
827
+ this function will return [Intermediate(idx=0), Intermediate(idx=1)],
828
+
829
+ However
830
+ Intermediate(idx=4) = arith.addptr(Intermediate(idx=2), Intermediate(idx=3))
831
+ Intermediate(idx=5) = tt.experimental_descriptor_store(Intermediate(idx=4), ...)
832
+ tt.experimental_descriptor_store(Intermediate(idx=5), ...)
833
+ this function will mark only idx=4 and idx=5 (but not idx=2 or idx=3)
834
+
835
+ If an intermediate/parameter is passed into a function and is written to
836
+ via experimental_descriptor_store within that function, the argument to the
837
+ function will also be marked.
838
+ """
839
+
840
+ result: set[Union[Intermediate, Param]] = set()
841
+
842
+ ops = functions[fn_name]
843
+ for op_list in ops.values():
844
+ for op in op_list:
845
+ if op.name == "tt.call":
846
+ if op.fn_call_name not in functions:
847
+ raise AssertionError(
848
+ f"Function {op.fn_call_name} not found in functions for TMA stores"
849
+ )
850
+ # pyrefly: ignore [bad-argument-type]
851
+ tma_stores = get_tma_stores(functions, op.fn_call_name)
852
+ for i, inp in enumerate(op.args):
853
+ if Param(idx=i) in tma_stores:
854
+ result.add(inp)
855
+ elif op.name == "tt.experimental_descriptor_store":
856
+ if len(op.args) < 1:
857
+ raise AssertionError(
858
+ f"tt.experimental_descriptor_store expected at least 1 arg, got {len(op.args)}"
859
+ )
860
+ result.add(op.args[0])
861
+ elif op.name == "tt.descriptor_store":
862
+ if len(op.args) < 1:
863
+ raise AssertionError(
864
+ f"tt.descriptor_store expected at least 1 arg, got {len(op.args)}"
865
+ )
866
+ result.add(op.args[0])
867
+
868
+ for val in list(result):
869
+ if val in ops:
870
+ if not isinstance(val, Intermediate):
871
+ continue
872
+ for op in ops[val]:
873
+ if op.name == "tt.reinterpret_tensor_descriptor":
874
+ if len(op.args) < 1:
875
+ raise AssertionError(
876
+ "tt.reinterpret_tensor_descriptor expected at least 1 arg, "
877
+ f"got {len(op.args)}"
878
+ )
879
+ result.add(op.args[0])
880
+
881
+ return result
882
+
883
+
884
+ @MemoizeWithCycleCheck
885
+ def analyze_kernel_mutations(
886
+ functions: dict[str, dict[Intermediate, list[Op]]], fn_name: str, num_args: int
887
+ ) -> list[bool]:
888
+ """
889
+ Analyzes the graph to detect all sinks from a predefined list of sinks
890
+ by using triton's MemWrite trait list. NOTE: What if triton exposed this?
891
+ From each sink, it traverses the CFG backwards to identify all the input
892
+ pointers that are mutated.
893
+ """
894
+ # Name of mutation op to mutated parameter indices
895
+ # List from Triton Github include/triton/Dialect/Triton/IR/TritonOps.td
896
+ # All the OPs that have MemWrite trait.
897
+ # What if Triton exposed this?
898
+ MUTATION_OPS = {
899
+ "tt.store": [0],
900
+ "tt.atomic_cas": [0],
901
+ "tt.atomic_rmw": [0],
902
+ "tt.experimental_descriptor_store": [0],
903
+ "tt.experimental_tensormap_create": [0],
904
+ "tt.descriptor_store": [0],
905
+ }
906
+ # Ops that we want to bail out on
907
+ UNKNOWN_OPS = {"tt.elementwise_inline_asm"}
908
+
909
+ stack: list[Union[Param, Intermediate]] = []
910
+ visited = set()
911
+ ops = functions[fn_name]
912
+ tma_stores = get_tma_stores(functions, fn_name)
913
+
914
+ for op_list in ops.values():
915
+ for op in op_list:
916
+ # If we encounter an operation with effects that cannot be reliably analyzed
917
+ # (e.g. `tt.elementwise_inline_asm`), we assume it does not mutate any input parameters.
918
+ if op.name in UNKNOWN_OPS:
919
+ if op.name == "tt.elementwise_inline_asm" and op.is_pure:
920
+ continue
921
+ raise RuntimeError(
922
+ f"ttir analysis hit an op we do not know how to analyze: {op.name}"
923
+ )
924
+
925
+ if op.name == "tt.experimental_tensormap_create":
926
+ # Note: this is how we implement experimental_descriptor_store mutation analysis.
927
+ # for on-device TMA.
928
+ # experimental_tensormap_store(a, b, ...) stores b to the location specified
929
+ # by descriptor in the memory of a.
930
+ # To track this, we first find all the intermediates/params to which we store via
931
+ # experimental_tensormap_store (get_tma_stores, called above). Then, during this
932
+ # analysis we wait to find the corresponding experimental_tensormap_create (if it
933
+ # exists), at which point we will mark the global_ptr as mutated (as done below).
934
+ if len(op.args) < 2:
935
+ raise AssertionError(
936
+ f"tt.experimental_tensormap_create expected at least 2 args, "
937
+ f"got {len(op.args)}"
938
+ )
939
+ if op.args[0] in tma_stores:
940
+ stack.append(op.args[1])
941
+
942
+ if op.name == "tt.call":
943
+ if op.fn_call_name not in functions:
944
+ raise AssertionError(
945
+ f"Function {op.fn_call_name} not found in functions dict"
946
+ )
947
+ mutations = analyze_kernel_mutations(
948
+ functions,
949
+ # pyrefly: ignore [bad-argument-type]
950
+ op.fn_call_name,
951
+ len(op.args),
952
+ )
953
+ stack.extend(arg for arg, mutated in zip(op.args, mutations) if mutated)
954
+ else:
955
+ stack.extend(op.args[idx] for idx in MUTATION_OPS.get(op.name, []))
956
+
957
+ # The following is an iterative DFS algorithm
958
+ mutated = [False] * num_args
959
+ while stack:
960
+ arg = stack.pop()
961
+ if arg in visited:
962
+ continue
963
+
964
+ visited.add(arg)
965
+
966
+ if isinstance(arg, Param):
967
+ if arg.idx >= num_args:
968
+ # This is an argument defined in the kernel, not passed in
969
+ continue
970
+ mutated[arg.idx] = True
971
+ elif isinstance(arg, Intermediate) and not arg.fake():
972
+ for op in ops[arg]:
973
+ # Skip arguments to load
974
+ if op.name != "tt.load":
975
+ stack.extend(op.args)
976
+ return mutated
977
+
978
+
979
+ def identify_mutated_tensors(
980
+ kernel: "TritonKernelType",
981
+ kwargs: dict[str, Any],
982
+ tma_descriptor_metadata: TMADescriptorMetadata,
983
+ ) -> list[str]:
984
+ """
985
+ Given a triton kernel and the arguments for this kernel, this function
986
+ 1) Retrieves the TTIR converted version of the kernel from Triton's API.
987
+ 2) Parses the TTIR and creates a control flow graph
988
+ 3) Analyzes the graph to detect all input tensor mutations
989
+ """
990
+
991
+ ttir_module = None
992
+ functions = None
993
+ try:
994
+ ttir_module, ordered_tensor_names = generate_ttir(
995
+ kernel, kwargs, tma_descriptor_metadata
996
+ )
997
+
998
+ # extract functions from TTIR using MLIR bindings exposed by Triton code
999
+ functions = ttir_to_functions(ttir_module)
1000
+
1001
+ if functions is None:
1002
+ raise AssertionError("ttir_to_functions returned None")
1003
+ kernel_name = next(iter(functions.keys()))
1004
+ # Triton codegen modifies the name
1005
+ # pyrefly: ignore [missing-attribute]
1006
+ kernel_fn_name = kernel.fn.__name__
1007
+ if kernel_fn_name not in kernel_name:
1008
+ raise AssertionError(
1009
+ f"Kernel name {kernel_fn_name} not found in TTIR kernel name {kernel_name}"
1010
+ )
1011
+ # Reset the cache between top level invocations
1012
+ # The cache for analyze kernel mutations is mainly used for cycle
1013
+ # detection, so each top level invocation needs a clean cache
1014
+ analyze_kernel_mutations.reset()
1015
+ get_tma_stores.reset()
1016
+ mutations = analyze_kernel_mutations(
1017
+ functions, kernel_name, len(ordered_tensor_names)
1018
+ )
1019
+
1020
+ return [
1021
+ ordered_tensor_names[i] for i, mutated in enumerate(mutations) if mutated
1022
+ ]
1023
+ except Exception:
1024
+ import torch._inductor.ir
1025
+
1026
+ log.warning(
1027
+ "Encountered an exception in identify_mutated_tensors, assuming every input is mutated",
1028
+ exc_info=True,
1029
+ )
1030
+ if ttir_module is not None:
1031
+ log.debug("TTIR:\n%s", str(ttir_module))
1032
+ if functions is not None:
1033
+ log.debug("functions:")
1034
+ for name, fn in functions.items():
1035
+ log.debug("===\t%s\t===", name)
1036
+ for ret, ops in fn.items():
1037
+ log.debug("%s\t=>\t%s", ret, ops)
1038
+ return [
1039
+ key
1040
+ for key, value in kwargs.items()
1041
+ if isinstance(value, (Tensor, torch._inductor.ir.TensorBox))
1042
+ ]
1043
+
1044
+
1045
+ ###############################################################################
1046
+ # Triton Kernel Wrappers
1047
+
1048
+
1049
+ # Used for wrapping a Triton Kernel
1050
+ class TritonKernelWrapperMutation(HigherOrderOperator):
1051
+ def __init__(self) -> None:
1052
+ super().__init__("triton_kernel_wrapper_mutation", cacheable=True)
1053
+
1054
+ def __call__(
1055
+ self,
1056
+ kernel_idx: int,
1057
+ constant_args_idx: int,
1058
+ grid: list["TritonGridType"],
1059
+ tma_descriptor_metadata: TMADescriptorMetadata,
1060
+ kwargs: dict[str, Any],
1061
+ ) -> Any:
1062
+ # pyrefly: ignore [missing-attribute]
1063
+ return super().__call__(
1064
+ kernel_idx=kernel_idx,
1065
+ constant_args_idx=constant_args_idx,
1066
+ grid=grid,
1067
+ tma_descriptor_metadata=tma_descriptor_metadata,
1068
+ kwargs=kwargs,
1069
+ )
1070
+
1071
+
1072
+ triton_kernel_wrapper_mutation = TritonKernelWrapperMutation()
1073
+
1074
+
1075
+ # Used for wrapping a Triton Kernel in a functional manner
1076
+ class TritonKernelWrapperFunctional(HigherOrderOperator):
1077
+ def __init__(self) -> None:
1078
+ super().__init__("triton_kernel_wrapper_functional", cacheable=True)
1079
+
1080
+ def __call__(
1081
+ self,
1082
+ kernel_idx: int,
1083
+ constant_args_idx: int,
1084
+ grid: list["TritonGridType"],
1085
+ tma_descriptor_metadata: TMADescriptorMetadata,
1086
+ kwargs: dict[str, Any],
1087
+ tensors_to_clone: list[str],
1088
+ ) -> dict[str, Any]:
1089
+ # pyrefly: ignore [missing-attribute]
1090
+ return super().__call__(
1091
+ kernel_idx=kernel_idx,
1092
+ constant_args_idx=constant_args_idx,
1093
+ grid=grid,
1094
+ tma_descriptor_metadata=tma_descriptor_metadata,
1095
+ kwargs=kwargs,
1096
+ tensors_to_clone=tensors_to_clone,
1097
+ )
1098
+
1099
+
1100
+ triton_kernel_wrapper_functional = TritonKernelWrapperFunctional()
1101
+
1102
+
1103
+ def get_kernel(kernel_idx: int) -> "TritonKernelType":
1104
+ return kernel_side_table.get_kernel(kernel_idx)
1105
+
1106
+
1107
+ @triton_kernel_wrapper_mutation.py_impl(DispatchKey.CompositeExplicitAutograd)
1108
+ def triton_kernel_wrapper_mutation_dense(
1109
+ *,
1110
+ kernel_idx: int,
1111
+ constant_args_idx: int,
1112
+ grid: list["TritonGridType"],
1113
+ tma_descriptor_metadata: TMADescriptorMetadata,
1114
+ kwargs: dict[str, Any],
1115
+ ) -> None:
1116
+ from torch._inductor.codegen.wrapper import user_defined_kernel_grid_fn_code
1117
+
1118
+ kernel = kernel_side_table.get_kernel(kernel_idx)
1119
+ constant_args = kernel_side_table.get_constant_args(constant_args_idx)
1120
+
1121
+ if len(grid) == 1:
1122
+ grid_fn = grid[0]
1123
+ else:
1124
+ fn_name, code = user_defined_kernel_grid_fn_code(
1125
+ # pyrefly: ignore [missing-attribute]
1126
+ kernel.fn.__name__,
1127
+ # pyrefly: ignore [missing-attribute]
1128
+ kernel.configs,
1129
+ grid,
1130
+ )
1131
+ namespace: dict[str, Any] = {}
1132
+ exec(code, namespace)
1133
+ grid_fn = namespace[fn_name]
1134
+
1135
+ if tma_descriptor_metadata:
1136
+ # as we need to launch the kernel here, we "unwrap" the
1137
+ # tma_descriptor_metadata, create the TMA descriptors
1138
+ # from it, and replace the tensors in the kwargs by the
1139
+ # corresponding TMA descriptors before launching
1140
+ kwargs = kwargs.copy()
1141
+ for k, v in tma_descriptor_metadata.items():
1142
+ tensor = kwargs[k]
1143
+ if (exp_meta := maybe_unpack_tma_experimental_metadata(v)) is not None:
1144
+ from triton.tools.experimental_descriptor import ( # noqa: F401
1145
+ create_1d_tma_descriptor,
1146
+ create_2d_tma_descriptor,
1147
+ )
1148
+
1149
+ dims, block_dims, element_size = exp_meta
1150
+ create_tma_descriptor = (
1151
+ create_1d_tma_descriptor
1152
+ if len(dims) == 1
1153
+ else create_2d_tma_descriptor
1154
+ )
1155
+ kwargs[k] = create_tma_descriptor(
1156
+ tensor.data_ptr(),
1157
+ *dims,
1158
+ *block_dims,
1159
+ element_size,
1160
+ )
1161
+ else:
1162
+ stable_meta = maybe_unpack_tma_stable_metadata(v)
1163
+ if stable_meta is None:
1164
+ raise AssertionError(
1165
+ f"Failed to unpack stable TMA metadata for key {k}"
1166
+ )
1167
+ from triton.tools.tensor_descriptor import TensorDescriptor
1168
+
1169
+ block_shape = stable_meta[0]
1170
+
1171
+ kwargs[k] = TensorDescriptor.from_tensor(tensor, block_shape)
1172
+
1173
+ # move as many positional arguments from dicts to args as we
1174
+ # can to circumvent the bug with the kwargs and pre_/post_hook:
1175
+ # https://github.com/triton-lang/triton/issues/5082
1176
+ # TODO: remove this when the Triton issue above is fixed
1177
+ args = []
1178
+ # copy kwargs and constant_args here to
1179
+ # avoid mutating the original inputs
1180
+ kwargs = kwargs.copy()
1181
+ constant_args = constant_args.copy()
1182
+ # pyrefly: ignore [missing-attribute]
1183
+ for name in kernel.arg_names:
1184
+ if name in kwargs:
1185
+ args.append(kwargs.pop(name))
1186
+ elif name in constant_args:
1187
+ args.append(constant_args.pop(name))
1188
+ else:
1189
+ break
1190
+
1191
+ # pyrefly: ignore [bad-index, index-error]
1192
+ kernel[grid_fn](*args, **kwargs, **constant_args)
1193
+
1194
+
1195
+ @triton_kernel_wrapper_mutation.py_impl(FakeTensorMode)
1196
+ def triton_kernel_wrapper_mutation_fake_tensor_mode(
1197
+ mode: FakeTensorMode,
1198
+ *,
1199
+ kernel_idx: int,
1200
+ constant_args_idx: int,
1201
+ grid: list["TritonGridType"],
1202
+ tma_descriptor_metadata: TMADescriptorMetadata,
1203
+ kwargs: dict[str, Any],
1204
+ ) -> None:
1205
+ with mode:
1206
+ return None
1207
+
1208
+
1209
+ @triton_kernel_wrapper_mutation.py_impl(DispatchKey.Meta)
1210
+ def _(
1211
+ *,
1212
+ kernel_idx: int,
1213
+ constant_args_idx: int,
1214
+ grid: list["TritonGridType"],
1215
+ tma_descriptor_metadata: TMADescriptorMetadata,
1216
+ kwargs: dict[str, Any],
1217
+ ) -> None:
1218
+ return None
1219
+
1220
+
1221
+ def trace_triton_kernel_wrapper(
1222
+ proxy_mode: ProxyTorchDispatchMode,
1223
+ func_overload: Callable[..., Any],
1224
+ node_args: dict[str, Any],
1225
+ ) -> Optional[dict[str, Any]]:
1226
+ with disable_proxy_modes_tracing():
1227
+ out = func_overload(**node_args)
1228
+
1229
+ proxy_args = pytree.tree_map(
1230
+ proxy_mode.tracer.unwrap_proxy, # type: ignore[union-attr]
1231
+ node_args,
1232
+ )
1233
+ out_proxy = proxy_mode.tracer.create_proxy(
1234
+ "call_function",
1235
+ func_overload,
1236
+ (),
1237
+ proxy_args,
1238
+ name=func_overload.__name__ + "_proxy",
1239
+ )
1240
+
1241
+ ret = track_tensor_tree(out, out_proxy, constant=None, tracer=proxy_mode.tracer)
1242
+ return ret
1243
+
1244
+
1245
+ @triton_kernel_wrapper_mutation.py_impl(ProxyTorchDispatchMode)
1246
+ def triton_kernel_wrapper_mutation_proxy_torch_dispatch_mode(
1247
+ mode: ProxyTorchDispatchMode,
1248
+ *,
1249
+ kernel_idx: int,
1250
+ constant_args_idx: int,
1251
+ grid: list["TritonGridType"],
1252
+ tma_descriptor_metadata: TMADescriptorMetadata,
1253
+ kwargs: dict[str, Any],
1254
+ ) -> None:
1255
+ trace_triton_kernel_wrapper(
1256
+ mode,
1257
+ triton_kernel_wrapper_mutation,
1258
+ {
1259
+ "kernel_idx": kernel_idx,
1260
+ "constant_args_idx": constant_args_idx,
1261
+ "grid": grid,
1262
+ "tma_descriptor_metadata": tma_descriptor_metadata,
1263
+ "kwargs": kwargs,
1264
+ },
1265
+ )
1266
+
1267
+ return None
1268
+
1269
+
1270
+ def get_mutated_tensors(
1271
+ kernel_idx: int,
1272
+ constant_args_idx: int,
1273
+ kwargs: dict[str, Any],
1274
+ tma_descriptor_metadata: TMADescriptorMetadata,
1275
+ ) -> list[str]:
1276
+ kernel = kernel_side_table.get_kernel(kernel_idx)
1277
+ constant_args = kernel_side_table.get_constant_args(constant_args_idx)
1278
+ return identify_mutated_tensors(
1279
+ kernel, {**kwargs, **constant_args}, tma_descriptor_metadata
1280
+ )
1281
+
1282
+
1283
+ @triton_kernel_wrapper_mutation.py_functionalize_impl
1284
+ def triton_kernel_wrapper_mutation_functionalize(
1285
+ ctx: "BaseFunctionalizeAPI",
1286
+ kernel_idx: int,
1287
+ constant_args_idx: int,
1288
+ grid: list["TritonGridType"],
1289
+ tma_descriptor_metadata: TMADescriptorMetadata,
1290
+ kwargs: dict[str, Any],
1291
+ ) -> None:
1292
+ unwrapped_kwargs = ctx.unwrap_tensors(kwargs) # type: ignore[arg-type]
1293
+ # TODO(oulgen): Preexisting bug, if two kernel inputs are views of each
1294
+ # other, and one gets mutated in kernel, and later another gets mutated,
1295
+ # they are no longer equal. Fix this by graph breaking on this condition
1296
+ # earlier in dynamo.
1297
+ tensors_to_clone = get_mutated_tensors(
1298
+ kernel_idx, constant_args_idx, unwrapped_kwargs, tma_descriptor_metadata
1299
+ )
1300
+ with ctx.redispatch_to_next():
1301
+ unwrapped_outputs = triton_kernel_wrapper_functional(
1302
+ kernel_idx=kernel_idx,
1303
+ constant_args_idx=constant_args_idx,
1304
+ grid=grid,
1305
+ tma_descriptor_metadata=tma_descriptor_metadata,
1306
+ kwargs=unwrapped_kwargs,
1307
+ tensors_to_clone=tensors_to_clone,
1308
+ )
1309
+
1310
+ if not set(unwrapped_outputs.keys()).issubset(set(kwargs.keys())):
1311
+ raise AssertionError(
1312
+ f"Output keys {set(unwrapped_outputs.keys())} not subset of input keys {set(kwargs.keys())}"
1313
+ )
1314
+ for key, output_arg in unwrapped_outputs.items():
1315
+ if not isinstance(output_arg, Tensor):
1316
+ continue
1317
+ input_arg = kwargs[key]
1318
+ if not isinstance(input_arg, Tensor):
1319
+ raise AssertionError(
1320
+ f"Expected input_arg for key {key} to be a Tensor, got {type(input_arg)}"
1321
+ )
1322
+
1323
+ ctx.replace(input_arg, output_arg)
1324
+ # indicate that above replace is hidden from autograd
1325
+ ctx.mark_mutation_hidden_from_autograd(input_arg)
1326
+ ctx.commit_update(input_arg)
1327
+ ctx.sync(input_arg)
1328
+ return None
1329
+
1330
+
1331
+ @triton_kernel_wrapper_functional.py_impl(DispatchKey.CompositeExplicitAutograd)
1332
+ def triton_kernel_wrapper_functional_dense(
1333
+ *,
1334
+ kernel_idx: int,
1335
+ constant_args_idx: int,
1336
+ grid: list["TritonGridType"],
1337
+ tma_descriptor_metadata: TMADescriptorMetadata,
1338
+ kwargs: dict[str, Any],
1339
+ tensors_to_clone: list[str],
1340
+ ) -> dict[str, Any]:
1341
+ # TODO(oulgen): For performance reasons, we want to ensure that these
1342
+ # `clone_preserve_strides` calls are never executed at runtime
1343
+ # (inductor should always optimize them away).
1344
+ # Requires https://github.com/pytorch/pytorch/issues/109240
1345
+ kwargs = {
1346
+ key: (clone_preserve_strides(val) if key in tensors_to_clone else val)
1347
+ for key, val in kwargs.items()
1348
+ }
1349
+ triton_kernel_wrapper_mutation(
1350
+ kernel_idx=kernel_idx,
1351
+ constant_args_idx=constant_args_idx,
1352
+ grid=grid,
1353
+ tma_descriptor_metadata=tma_descriptor_metadata,
1354
+ kwargs=kwargs,
1355
+ )
1356
+ return {key: val for key, val in kwargs.items() if key in tensors_to_clone}
1357
+
1358
+
1359
+ @triton_kernel_wrapper_functional.py_impl(FakeTensorMode)
1360
+ def triton_kernel_wrapper_functional_fake_tensor_mode(
1361
+ mode: FakeTensorMode,
1362
+ *,
1363
+ kernel_idx: int,
1364
+ constant_args_idx: int,
1365
+ grid: list["TritonGridType"],
1366
+ tma_descriptor_metadata: TMADescriptorMetadata,
1367
+ kwargs: dict[str, Any],
1368
+ tensors_to_clone: list[str],
1369
+ ) -> dict[str, Any]:
1370
+ # TODO(oulgen): For performance reasons, we want to ensure that these
1371
+ # `clone_preserve_strides` calls are never executed at runtime
1372
+ # (inductor should always optimize them away).
1373
+ # Requires https://github.com/pytorch/pytorch/issues/109240
1374
+ with mode:
1375
+ return {
1376
+ key: clone_preserve_strides(val)
1377
+ for key, val in kwargs.items()
1378
+ if key in tensors_to_clone
1379
+ }
1380
+
1381
+
1382
+ @triton_kernel_wrapper_functional.py_impl(ProxyTorchDispatchMode)
1383
+ def triton_kernel_wrapper_functional_proxy_torch_dispatch_mode(
1384
+ mode: ProxyTorchDispatchMode,
1385
+ *,
1386
+ kernel_idx: int,
1387
+ constant_args_idx: int,
1388
+ grid: list["TritonGridType"],
1389
+ tma_descriptor_metadata: TMADescriptorMetadata,
1390
+ kwargs: dict[str, Any],
1391
+ tensors_to_clone: list[str],
1392
+ ) -> dict[str, Any]:
1393
+ ret = trace_triton_kernel_wrapper(
1394
+ mode,
1395
+ triton_kernel_wrapper_functional,
1396
+ {
1397
+ "kernel_idx": kernel_idx,
1398
+ "constant_args_idx": constant_args_idx,
1399
+ "grid": grid,
1400
+ "tma_descriptor_metadata": tma_descriptor_metadata,
1401
+ "kwargs": kwargs,
1402
+ "tensors_to_clone": tensors_to_clone,
1403
+ },
1404
+ )
1405
+ if ret is None:
1406
+ raise AssertionError("trace_triton_kernel_wrapper returned None")
1407
+ return ret
1408
+
1409
+
1410
+ @triton_kernel_wrapper_functional.py_functionalize_impl
1411
+ def triton_kernel_wrapper_functional_functionalize(
1412
+ ctx: "BaseFunctionalizeAPI",
1413
+ kernel_idx: int,
1414
+ constant_args_idx: int,
1415
+ grid: list["TritonGridType"],
1416
+ tma_descriptor_metadata: TMADescriptorMetadata,
1417
+ kwargs: dict[str, Any],
1418
+ tensors_to_clone: list[str],
1419
+ ) -> dict[str, Any]:
1420
+ unwrapped_kwargs = ctx.unwrap_tensors(kwargs) # type: ignore[arg-type]
1421
+ with ctx.redispatch_to_next():
1422
+ outputs = triton_kernel_wrapper_functional(
1423
+ kernel_idx=kernel_idx,
1424
+ constant_args_idx=constant_args_idx,
1425
+ grid=grid,
1426
+ tma_descriptor_metadata=tma_descriptor_metadata,
1427
+ kwargs=unwrapped_kwargs,
1428
+ tensors_to_clone=tensors_to_clone,
1429
+ )
1430
+ return ctx.wrap_tensors(outputs) # type: ignore[return-value,arg-type]
1431
+
1432
+
1433
+ triton_kernel_wrapper_mutation.fallthrough(DispatchKey.PythonDispatcher) # type: ignore[attr-defined]
1434
+ triton_kernel_wrapper_mutation.fallthrough(DispatchKey.PythonTLSSnapshot) # type: ignore[attr-defined]
1435
+ triton_kernel_wrapper_mutation.fallthrough(DispatchKey.ADInplaceOrView)
1436
+ triton_kernel_wrapper_mutation.fallthrough(DispatchKey.BackendSelect)
1437
+ triton_kernel_wrapper_mutation.fallthrough(DispatchKey.AutocastCPU) # type: ignore[attr-defined]
1438
+ triton_kernel_wrapper_mutation.fallthrough(DispatchKey.AutocastCUDA) # type: ignore[attr-defined]
1439
+ triton_kernel_wrapper_mutation.fallthrough(DispatchKey.AutogradCUDA)
1440
+ triton_kernel_wrapper_mutation.fallthrough(DispatchKey.AutogradCPU)
1441
+
1442
+ triton_kernel_wrapper_functional.fallthrough(DispatchKey.PythonDispatcher) # type: ignore[attr-defined]
1443
+ triton_kernel_wrapper_functional.fallthrough(DispatchKey.PythonTLSSnapshot) # type: ignore[attr-defined]
1444
+ triton_kernel_wrapper_functional.fallthrough(DispatchKey.ADInplaceOrView)
1445
+ triton_kernel_wrapper_functional.fallthrough(DispatchKey.BackendSelect)
1446
+ triton_kernel_wrapper_functional.fallthrough(DispatchKey.AutocastCPU) # type: ignore[attr-defined]
1447
+ triton_kernel_wrapper_functional.fallthrough(DispatchKey.AutocastCUDA) # type: ignore[attr-defined]
1448
+ triton_kernel_wrapper_functional.fallthrough(DispatchKey.AutogradCUDA)
1449
+ triton_kernel_wrapper_functional.fallthrough(DispatchKey.AutogradCUDA)
1450
+ triton_kernel_wrapper_functional.fallthrough(DispatchKey.AutogradCPU)
1451
+
1452
+ # Adds SAC support for triton ops
1453
+ redirect_to_mode(triton_kernel_wrapper_mutation, _CachingTorchDispatchMode)
1454
+ redirect_to_mode(triton_kernel_wrapper_mutation, _CachedTorchDispatchMode)
1455
+
1456
+ ###############################################################################
1457
+ # The "TritonHOPifier": a class that transforms a call to a triton kernel into
1458
+ # a call to the triton_kernel_wrapper_mutation HOP.
1459
+
1460
+
1461
+ class TritonHOPifier:
1462
+ """Orchestrator for converting a user-defined triton kernel into a call
1463
+ to the triton_kernel_wrapper_mutation HOP.
1464
+
1465
+ It has two main use cases.
1466
+
1467
+ 1. When Dynamo sees a triton kernel, it wraps it into a TritonKernelVariable
1468
+ and uses the TritonHOPifier to convert calls to the TritonKernelVariable
1469
+ into a call to the HOP.
1470
+
1471
+ 2. In order to capture a user-defined triton kernel while performing
1472
+ tracing (via make_fx or non-strict export), a user must annotate their
1473
+ triton kernel with the `wrap_triton` decorator. The decorator uses
1474
+ TritonHOPifier to convert calls to the triton kernel into a call
1475
+ to the HOP (which can then be traced).
1476
+
1477
+ Because Dynamo has its own calling conventions for e.g. invoking a user-defined function
1478
+ TritonHOPifier is an abstract class that can be overridden by its subclasses.
1479
+ """
1480
+
1481
+ def raise_unsupported(self, msg: str) -> Never:
1482
+ raise NotImplementedError("abstract method")
1483
+
1484
+ def is_callable(self, maybe_callable: Any) -> bool:
1485
+ raise NotImplementedError("abstract method")
1486
+
1487
+ def get_value(self, val: Any) -> Any:
1488
+ raise NotImplementedError("abstract method")
1489
+
1490
+ def call_grid( # type: ignore[no-untyped-def]
1491
+ self,
1492
+ grid,
1493
+ meta,
1494
+ tx,
1495
+ ) -> Union[tuple[Union[int, sympy.Expr, SymInt], ...], tuple["Proxy", ...]]:
1496
+ raise NotImplementedError("abstract method")
1497
+
1498
+ def wrap_user_defined_obj(
1499
+ self,
1500
+ user_obj: Any,
1501
+ tx: Optional["InstructionTranslator"],
1502
+ variable: Optional[
1503
+ Union["TritonKernelVariable", "TraceableTritonKernelWrapper"]
1504
+ ],
1505
+ name: str,
1506
+ ) -> Any:
1507
+ raise NotImplementedError("abstract method")
1508
+
1509
+ def call_user_defined_fn(
1510
+ self,
1511
+ user_fn: Callable[..., Any],
1512
+ args: list,
1513
+ kwargs: dict,
1514
+ tx: Optional["InstructionTranslator"],
1515
+ variable: Optional[
1516
+ Union["TritonKernelVariable", "TraceableTritonKernelWrapper"]
1517
+ ],
1518
+ ) -> Any:
1519
+ raise NotImplementedError("abstract method")
1520
+
1521
+ def maybe_unpack_configs(
1522
+ self, configs: list["TritonConfig"], tx: Optional["InstructionTranslator"]
1523
+ ) -> list["TritonConfig"]:
1524
+ raise NotImplementedError("abstract method")
1525
+
1526
+ def maybe_unpack_heuristic_result(self, result: Any) -> Any:
1527
+ raise NotImplementedError("abstract method")
1528
+
1529
+ @staticmethod
1530
+ def do_prune_configs( # type: ignore[no-untyped-def]
1531
+ autotuner: "TritonAutotunerType",
1532
+ early_config_prune: Optional[Callable],
1533
+ perf_model: Optional[Callable],
1534
+ top_k: float,
1535
+ configs: list,
1536
+ named_args: dict,
1537
+ kwargs: dict,
1538
+ ) -> list["TritonConfig"]:
1539
+ # Reimplement autotuner.prune_configs(...) here
1540
+ # see: https://github.com/triton-lang/triton/blob/e57b46897191b3b3061c78d0d60e58e94be565b6/python/triton/runtime/autotuner.py # noqa: E501,B950
1541
+ # We do this to avoid calling prune_configs, which in turn calls early_config_prune and perf_model
1542
+ # These are both user-defined functions which can contain side effects, so we want to sandbox them in Dynamo
1543
+
1544
+ if early_config_prune:
1545
+ configs = early_config_prune(configs, named_args, **kwargs)
1546
+
1547
+ if perf_model:
1548
+ # we assert top_k is a float before calling this
1549
+ if isinstance(top_k, float) and top_k <= 1.0:
1550
+ top_k = int(len(configs) * top_k)
1551
+ elif not isinstance(top_k, int):
1552
+ """
1553
+ Slice index must be an integer, SupportsIndex or None
1554
+ """
1555
+ raise TypeError(
1556
+ "Error while pruning configs, top_k must be either 1) a float <= 1.0 or 2) an int"
1557
+ )
1558
+ if len(configs) > top_k:
1559
+ est_timing = [
1560
+ (
1561
+ config,
1562
+ float(
1563
+ perf_model(**named_args, **kwargs, **config.all_kwargs())
1564
+ ),
1565
+ )
1566
+ for config in configs
1567
+ ]
1568
+ configs = [
1569
+ config[0]
1570
+ for config in sorted(est_timing, key=operator.itemgetter(1))[:top_k]
1571
+ ]
1572
+ return configs
1573
+
1574
+ def call_HOP( # type: ignore[no-untyped-def]
1575
+ self,
1576
+ variable,
1577
+ grids,
1578
+ combined_args: dict[str, Any],
1579
+ tx,
1580
+ ) -> Optional["ConstantVariable"]:
1581
+ raise NotImplementedError("abstract method")
1582
+
1583
+ def check_grid( # type: ignore[no-untyped-def]
1584
+ self, grid
1585
+ ) -> Union[tuple[Union[int, sympy.Expr, SymInt], ...], tuple["Proxy", ...]]:
1586
+ raise NotImplementedError("abstract method")
1587
+
1588
+ def init_variable(
1589
+ self,
1590
+ variable: Union["TraceableTritonKernelWrapper", "TritonKernelVariable"],
1591
+ kernel: "TritonKernelType",
1592
+ kernel_idx: Optional[int],
1593
+ grid: Optional["TritonGridType"],
1594
+ ) -> None:
1595
+ from triton.runtime.autotuner import Autotuner
1596
+
1597
+ if kernel is None:
1598
+ raise AssertionError("kernel cannot be None")
1599
+
1600
+ variable.kernel = kernel
1601
+ variable.kernel_idx = kernel_side_table.add_kernel(kernel)
1602
+
1603
+ if kernel_idx is not None and variable.kernel_idx != kernel_idx:
1604
+ raise AssertionError(
1605
+ f"kernel_idx mismatch: expected {kernel_idx}, got {variable.kernel_idx}"
1606
+ )
1607
+
1608
+ # pyrefly: ignore [bad-assignment]
1609
+ variable.grid = grid
1610
+
1611
+ if isinstance(kernel, Autotuner):
1612
+ import torch
1613
+ import torch._dynamo
1614
+
1615
+ # We only support configs, keys, and restore_value arguments
1616
+ # of triton.autotune. Make sure other arguments are defaulted.
1617
+ defaults = inspect.signature(Autotuner.__init__).parameters
1618
+ # Newer version of triton change attribute name from warmup to num_warmup and rep to num_rep.
1619
+ # The call to get_first_attr is to maintain backward-compatibility.
1620
+
1621
+ def defaults_ok(
1622
+ attr: str, alternates: tuple[str, ...], values: tuple[Any, ...]
1623
+ ) -> bool:
1624
+ if attr not in defaults:
1625
+ return True
1626
+ value = torch._dynamo.utils.get_first_attr(kernel, attr, *alternates)
1627
+ if value == defaults[attr].default:
1628
+ return True
1629
+ return value in values
1630
+
1631
+ if (
1632
+ not torch._inductor.config.unsafe_ignore_unsupported_triton_autotune_args
1633
+ and (
1634
+ not defaults_ok("num_warmups", ("warmup",), (25, None))
1635
+ or not defaults_ok("num_reps", ("rep",), (100, None))
1636
+ or not defaults_ok("use_cuda_graph", (), (False,))
1637
+ )
1638
+ ):
1639
+ self.raise_unsupported(
1640
+ "Only configs, keys, restore_value, and reset_to_zero are supported for triton.autotune"
1641
+ )
1642
+ if (
1643
+ not torch._inductor.config.unsafe_ignore_unsupported_triton_autotune_args
1644
+ and (
1645
+ # pre_hook requires running arbitrary code at runtime, which we cannot handle at this time
1646
+ # https://github.com/pytorch/pytorch/issues/139059
1647
+ # we can't support pre_hook or post_hook in user defined triton kernels at the moment,
1648
+ # as they require the ability to execute code at runtime (AOTI can't support this)
1649
+ (
1650
+ hasattr(kernel, "user_defined_pre_hook")
1651
+ and kernel.user_defined_pre_hook is not False
1652
+ )
1653
+ or (
1654
+ hasattr(kernel, "user_defined_post_hook")
1655
+ and kernel.user_defined_post_hook is not False
1656
+ )
1657
+ or (
1658
+ # Check Config passed to autotuner in configs
1659
+ any(cfg.pre_hook is not None for cfg in kernel.configs)
1660
+ )
1661
+ )
1662
+ ):
1663
+ self.raise_unsupported(
1664
+ "pre_hook and post_hook are not supported in triton.Autotune or triton.Config"
1665
+ )
1666
+
1667
+ def call_getitem(
1668
+ self,
1669
+ variable: Union["TritonKernelVariable", "TraceableTritonKernelWrapper"],
1670
+ args: Sequence[Any],
1671
+ ) -> Union["TritonKernelVariable", "TraceableTritonKernelWrapper"]:
1672
+ # __getitem__ should only be called if we don't already have a grid
1673
+ # Only grid needs to be passed
1674
+ if variable.grid is not None or len(args) != 1:
1675
+ self.raise_unsupported(
1676
+ "Triton kernels should be called with only a single grid"
1677
+ )
1678
+
1679
+ return type(variable)(
1680
+ kernel=variable.kernel,
1681
+ kernel_idx=variable.kernel_idx,
1682
+ grid=args[0],
1683
+ )
1684
+
1685
+ def call_run(
1686
+ self,
1687
+ variable: Union["TritonKernelVariable", "TraceableTritonKernelWrapper"],
1688
+ args: Sequence[Any],
1689
+ kwargs: dict[str, Any],
1690
+ tx: Optional["InstructionTranslator"],
1691
+ ) -> Optional["ConstantVariable"]:
1692
+ if "grid" not in kwargs:
1693
+ self.raise_unsupported("Triton kernel requires to be called with a grid")
1694
+ grid = kwargs.pop("grid")
1695
+ kwargs.pop("warmup", None)
1696
+ # rewrite kernel.run(*args, grid=grid) to kernel[grid](*args)
1697
+ return self.call_triton_kernel(
1698
+ type(variable)(
1699
+ kernel=variable.kernel, kernel_idx=variable.kernel_idx, grid=grid
1700
+ ),
1701
+ args,
1702
+ kwargs,
1703
+ tx,
1704
+ )
1705
+
1706
+ def call_triton_kernel(
1707
+ self,
1708
+ variable: Union["TritonKernelVariable", "TraceableTritonKernelWrapper"],
1709
+ args: Sequence[Any],
1710
+ kwargs: dict[str, Any],
1711
+ tx: Optional["InstructionTranslator"],
1712
+ ) -> Optional["ConstantVariable"]:
1713
+ from triton import JITFunction
1714
+ from triton.runtime.autotuner import autotune, Autotuner, Config, Heuristics
1715
+
1716
+ # Check if num_ctas is in kwargs
1717
+ if "num_ctas" in kwargs:
1718
+ self.raise_unsupported(
1719
+ "Passing num_ctas directly to the Triton kernel is not supported. "
1720
+ "Please use a Config in @triton.autotune instead."
1721
+ )
1722
+
1723
+ # Make sure the kernel has a grid
1724
+ if variable.grid is None:
1725
+ self.raise_unsupported("Triton kernels should always be called with a grid")
1726
+
1727
+ # raise an exception if there are multiple @triton.autotune decorators
1728
+ iter_kernel = variable.kernel
1729
+ autotuner_count = 0
1730
+ while not isinstance(iter_kernel, JITFunction):
1731
+ if isinstance(iter_kernel, Autotuner):
1732
+ autotuner_count += 1
1733
+ if autotuner_count > 1:
1734
+ self.raise_unsupported(
1735
+ "Passing multiple @triton.autotune decorators is not supported. "
1736
+ "Please use a single @triton.autotune decorator instead."
1737
+ )
1738
+
1739
+ iter_kernel = iter_kernel.fn
1740
+
1741
+ # Process the @triton.heuristics decorator:
1742
+ # - We know there is only 1 autotuner decorator here
1743
+ # - We can apply the heuristic to all triton.Configs in the order that the decorators appear
1744
+ # This way, when the config is selected, the heuristics have already been applied.
1745
+ # - Decorators that appear *before* the autotuner are already processed correctly
1746
+ if isinstance(variable.kernel, Autotuner) and isinstance(
1747
+ variable.kernel.fn, Heuristics
1748
+ ):
1749
+ # unwrap the heuristics decorator, we don't need it anymore
1750
+ # variable.kernel ==> Autotuner
1751
+ # variable.kernel.fn ==> Heuristics
1752
+ # ...
1753
+ # There can be arbitrarily many heuristics wrappers here!
1754
+ # ...
1755
+ # variable.kernel.fn ==> JITFunction
1756
+
1757
+ # Copy the configs, we are going to be modifying them
1758
+ new_configs = copy.deepcopy(variable.kernel.configs)
1759
+
1760
+ named_args = dict(zip(variable.kernel.arg_names, args))
1761
+
1762
+ # Iterate through all of the heuristics wrappers that come after the autotune wrapper
1763
+ iter_kernel = variable.kernel.fn
1764
+ while isinstance(iter_kernel, Heuristics):
1765
+ # For each config, apply the heuristic fn(s)
1766
+ for config_idx in range(len(new_configs)):
1767
+ for kwarg_key, heuristic_fn in iter_kernel.values.items():
1768
+ # Run heuristics on the combined configs + kwargs
1769
+ heuristic_result = self.call_user_defined_fn(
1770
+ heuristic_fn,
1771
+ [
1772
+ {
1773
+ **named_args,
1774
+ **kwargs,
1775
+ **new_configs[config_idx].__dict__["kwargs"],
1776
+ },
1777
+ ],
1778
+ {},
1779
+ tx,
1780
+ variable,
1781
+ )
1782
+
1783
+ # Update the kwargs in each config
1784
+ # maybe_unpack_heuristic_result raises unsupported if the value is non-constant
1785
+ new_configs[config_idx].__dict__["kwargs"][kwarg_key] = (
1786
+ self.maybe_unpack_heuristic_result(heuristic_result)
1787
+ )
1788
+
1789
+ iter_kernel = iter_kernel.fn
1790
+ if not isinstance(iter_kernel, JITFunction):
1791
+ raise AssertionError(
1792
+ f"Expected iter_kernel to be a JITFunction, got {type(iter_kernel)}"
1793
+ )
1794
+ prune_configs_by = {
1795
+ "perf_model": variable.kernel.perf_model,
1796
+ "early_config_prune": variable.kernel.early_config_prune,
1797
+ "configs_top_k": variable.kernel.configs_top_k,
1798
+ }
1799
+ new_kernel = autotune(
1800
+ configs=new_configs, key=[], prune_configs_by=prune_configs_by
1801
+ )(iter_kernel)
1802
+ # create a new variable to contain the new (wrapped) kernel;
1803
+ # skip kernel_idx to get a new record in the kernel side table
1804
+ new_var = type(variable)(new_kernel, None, variable.grid)
1805
+ return self.call_triton_kernel(new_var, args, kwargs, tx)
1806
+
1807
+ SPECIAL_CONFIG_NAMES = {
1808
+ "num_warps",
1809
+ "num_stages",
1810
+ "num_ctas",
1811
+ "num_consumer_groups",
1812
+ "num_buffers_warp_spec",
1813
+ "num_cpu_threads",
1814
+ }
1815
+
1816
+ # move special config names to configs out of kwargs
1817
+ special_kwargs = {}
1818
+ for name in SPECIAL_CONFIG_NAMES:
1819
+ if name in kwargs:
1820
+ # remove special kwargs from `kwargs`
1821
+ val = kwargs.pop(name)
1822
+ special_kwargs[name] = self.get_value(val)
1823
+
1824
+ if special_kwargs:
1825
+ if isinstance(variable.kernel, Autotuner):
1826
+ # if there is Autotuner already, set
1827
+ # special kwargs to each of its configs
1828
+ new_configs = copy.deepcopy(variable.kernel.configs)
1829
+ for config in new_configs:
1830
+ config.__dict__.update(special_kwargs)
1831
+ prune_configs_by = {
1832
+ "perf_model": variable.kernel.perf_model,
1833
+ "early_config_prune": variable.kernel.early_config_prune,
1834
+ "configs_top_k": variable.kernel.configs_top_k,
1835
+ }
1836
+
1837
+ new_kernel = autotune(
1838
+ configs=new_configs, key=[], prune_configs_by=prune_configs_by
1839
+ )(variable.kernel.fn)
1840
+ else:
1841
+ # if there is no Autotuner, wrap the kernel into a
1842
+ # new one with a single config with special kwargs
1843
+ new_config = Config(kwargs={}, **special_kwargs)
1844
+
1845
+ new_kernel = autotune(configs=[new_config], key=[])(variable.kernel)
1846
+
1847
+ # create a new variable to contain the new (wrapped) kernel;
1848
+ # skip kernel_idx to get a new record in the kernel side table
1849
+ new_var = type(variable)(new_kernel, None, variable.grid)
1850
+ return self.call_triton_kernel(new_var, args, kwargs, tx)
1851
+
1852
+ if isinstance(variable.kernel, Autotuner):
1853
+ special_param_names = []
1854
+ for name in SPECIAL_CONFIG_NAMES:
1855
+ if name in variable.kernel.fn.arg_names:
1856
+ special_param_names.append(name)
1857
+
1858
+ if special_param_names:
1859
+ # If the Triton kernel has SPECIAL_CONFIG_NAMES in parameters, those should
1860
+ # be passed from the kernel configs: the behavior of Triton runtime is that
1861
+ # those values get folded into the kernel arguments iff there are parameters
1862
+ # with the same name. Normally the values of those parameters are defined
1863
+ # outside the `kwargs` part of the autotuning configs. Here we move them to
1864
+ # the `kwargs` part (if they're absent there) to facilitate passing them as
1865
+ # arguments to the kernel downstream.
1866
+ updated = False
1867
+ new_configs = copy.deepcopy(variable.kernel.configs)
1868
+ for config in new_configs:
1869
+ for name in special_param_names:
1870
+ if name not in config.__dict__["kwargs"]:
1871
+ if name not in config.__dict__:
1872
+ raise AssertionError(
1873
+ f"{name} must be in autotuning configs to be used "
1874
+ "as a kernel parameter"
1875
+ )
1876
+ config.__dict__["kwargs"][name] = config.__dict__[name]
1877
+ updated = True
1878
+
1879
+ if updated:
1880
+ prune_configs_by = {
1881
+ "perf_model": variable.kernel.perf_model,
1882
+ "early_config_prune": variable.kernel.early_config_prune,
1883
+ "configs_top_k": variable.kernel.configs_top_k,
1884
+ }
1885
+
1886
+ new_kernel = autotune(
1887
+ configs=new_configs, prune_configs_by=prune_configs_by, key=[]
1888
+ )(variable.kernel.fn)
1889
+ new_var = type(variable)(new_kernel, None, variable.grid)
1890
+ return self.call_triton_kernel(new_var, args, kwargs, tx)
1891
+
1892
+ # These are the default values in upstream Triton
1893
+ # see: https://github.com/triton-lang/triton/blob/e57b46897191b3b3061c78d0d60e58e94be565b6/python/triton/runtime/autotuner.py # noqa: E501,B950
1894
+ default_perf_model = None
1895
+ default_early_config_prune = None
1896
+
1897
+ # run prune_configs_by
1898
+ if isinstance(variable.kernel, Autotuner) and (
1899
+ variable.kernel.perf_model != default_perf_model
1900
+ or variable.kernel.early_config_prune != default_early_config_prune
1901
+ ):
1902
+ # Prune the configs
1903
+ named_args = dict(zip(variable.kernel.arg_names, args))
1904
+
1905
+ # The source information is important here so the guards are installed correctly
1906
+
1907
+ wrapped_early_configs_prune = self.wrap_user_defined_obj(
1908
+ variable.kernel.early_config_prune,
1909
+ tx,
1910
+ variable,
1911
+ "early_config_prune",
1912
+ )
1913
+
1914
+ wrapped_perf_model = self.wrap_user_defined_obj(
1915
+ variable.kernel.perf_model, tx, variable, "perf_model"
1916
+ )
1917
+
1918
+ wrapped_configs_top_k = self.wrap_user_defined_obj(
1919
+ variable.kernel.configs_top_k, tx, variable, "configs_top_k"
1920
+ )
1921
+
1922
+ wrapped_configs = self.wrap_user_defined_obj(
1923
+ variable.kernel.configs, tx, variable, "configs"
1924
+ )
1925
+
1926
+ pruned_configs = self.call_user_defined_fn(
1927
+ self.do_prune_configs,
1928
+ [
1929
+ variable,
1930
+ wrapped_early_configs_prune,
1931
+ wrapped_perf_model,
1932
+ wrapped_configs_top_k,
1933
+ wrapped_configs,
1934
+ named_args,
1935
+ kwargs,
1936
+ ],
1937
+ {},
1938
+ tx,
1939
+ variable,
1940
+ )
1941
+
1942
+ pruned_configs = self.maybe_unpack_configs(pruned_configs, tx)
1943
+
1944
+ # after pruning the configs, create a new autotuner object with
1945
+ # these configs and recurse.
1946
+ new_kernel = autotune(configs=pruned_configs, key=[])(variable.kernel.fn)
1947
+ # create a new variable to contain the new (wrapped) kernel;
1948
+ # skip kernel_idx to get a new record in the kernel side table
1949
+ new_var = type(variable)(new_kernel, None, variable.grid)
1950
+ return self.call_triton_kernel(new_var, args, kwargs, tx)
1951
+
1952
+ # Both for grid's meta as well as for the kernel, we need combined
1953
+ # args and kwargs combined and normalized
1954
+
1955
+ combined_args_raw = {**dict(zip(variable.kernel.arg_names, args)), **kwargs}
1956
+
1957
+ # precompute the grid for the kernel
1958
+ configs = (
1959
+ [config.kwargs for config in variable.kernel.configs]
1960
+ if isinstance(variable.kernel, Autotuner)
1961
+ else [{}]
1962
+ )
1963
+ grids = []
1964
+ for config_args in configs:
1965
+ # If the grid is a function, then lets execute it and convert it to
1966
+ # a list
1967
+ grid = variable.grid
1968
+ if grid is None:
1969
+ raise AssertionError("grid cannot be None at this point")
1970
+ if self.is_callable(grid):
1971
+ # Populate the special "meta" argument to call the grid function
1972
+ meta = {**combined_args_raw, **config_args}
1973
+ grid = self.call_grid(grid, meta, tx) # type: ignore[arg-type]
1974
+ grids.append(self.check_grid(grid))
1975
+
1976
+ for i in range(len(grids)):
1977
+ if not isinstance(grids[i], tuple):
1978
+ self.raise_unsupported("Only tuple grids are supported")
1979
+ # inductor expects all grids to be 3-tuple so lets make it
1980
+ if len(grids[i]) == 1:
1981
+ grids[i] = (grids[i][0], 1, 1)
1982
+ elif len(grids[i]) == 2:
1983
+ grids[i] = (grids[i][0], grids[i][1], 1)
1984
+ elif len(grids[i]) > 3:
1985
+ self.raise_unsupported("Grid can have at most rank 3")
1986
+
1987
+ if len(grids) == 0:
1988
+ raise AssertionError("grids cannot be empty")
1989
+ if isinstance(variable.kernel, JITFunction):
1990
+ constexprs = [p.num for p in variable.kernel.params if p.is_constexpr]
1991
+ arg_names = [p.name for p in variable.kernel.params]
1992
+ else:
1993
+ # If we are looking at an @triton.autotune decorator, the nested function should be a JITFunction
1994
+ # This is because we don't support @triton.heuristics or nested @triton.autotune decorators yet
1995
+ if not isinstance(variable.kernel, Autotuner):
1996
+ raise AssertionError(
1997
+ f"Expected variable.kernel to be an Autotuner, got {type(variable.kernel)}"
1998
+ )
1999
+ constexprs = [p.num for p in variable.kernel.fn.params if p.is_constexpr]
2000
+ arg_names = [p.name for p in variable.kernel.fn.params]
2001
+
2002
+ for idx, arg_name in enumerate(arg_names):
2003
+ if idx in constexprs:
2004
+ if arg_name in combined_args_raw:
2005
+ # [Note: Specialize tl.constexpr args in user-defined triton kernels]
2006
+ # This arg is marked as tl.constexpr. That means that triton will recompile every time
2007
+ # this value changes.
2008
+ # https://github.com/pytorch/pytorch/issues/136504
2009
+ # One option is to correctly pass the symints in so that the symbolic expressions are defined
2010
+ # when the triton code is being executed.
2011
+ # But since triton will have to recompile either way, we instead just specialize on the value.
2012
+ #
2013
+ # Depending on the type of `variable` we might expect different types for the symbolic args:
2014
+ # either SymNodeVariables (for TritonKernelVariables) or SymInts (TracingTritonKernelWrapper)
2015
+ combined_args_raw[arg_name] = variable.specialize_symbolic(
2016
+ combined_args_raw[arg_name]
2017
+ )
2018
+ return self.call_HOP(variable, grids, combined_args_raw, tx)
2019
+
2020
+
2021
+ ###############################################################################
2022
+ # Helpers for wrap_triton API that makes a user-defined triton kernel traceable into
2023
+ # a graph via make_fx or non-strict export (coming soon)
2024
+
2025
+
2026
+ class TracingTritonHOPifier(TritonHOPifier):
2027
+ def raise_unsupported(self, msg: str) -> Never:
2028
+ raise RuntimeError(msg)
2029
+
2030
+ def is_callable(self, maybe_callable: Any) -> bool:
2031
+ return callable(maybe_callable)
2032
+
2033
+ def get_value(self, val: Any) -> Any:
2034
+ return val
2035
+
2036
+ def call_grid(
2037
+ self,
2038
+ grid: "TritonGridCallableType",
2039
+ meta: "TritonMetaParamsType",
2040
+ tx: None,
2041
+ ) -> tuple[Union[int, sympy.Expr, SymInt], ...]:
2042
+ if tx is not None:
2043
+ raise AssertionError("tx must be None for TracingTritonHOPifier")
2044
+ if not isinstance(meta, dict):
2045
+ raise AssertionError(f"meta must be a dict, got {type(meta)}")
2046
+ if not callable(grid):
2047
+ raise AssertionError(f"grid must be callable, got {type(grid)}")
2048
+ return grid(meta)
2049
+
2050
+ def wrap_user_defined_obj(
2051
+ self,
2052
+ user_obj: Any,
2053
+ tx: Optional["InstructionTranslator"],
2054
+ variable: Optional[
2055
+ Union["TritonKernelVariable", "TraceableTritonKernelWrapper"]
2056
+ ],
2057
+ name: str,
2058
+ ) -> Any:
2059
+ if tx is not None:
2060
+ raise AssertionError("tx must be None for TracingTritonHOPifier")
2061
+ return user_obj
2062
+
2063
+ def call_user_defined_fn(
2064
+ self,
2065
+ user_fn: Callable[..., Any],
2066
+ args: list,
2067
+ kwargs: dict,
2068
+ tx: Optional["InstructionTranslator"],
2069
+ variable: Optional[
2070
+ Union["TritonKernelVariable", "TraceableTritonKernelWrapper"]
2071
+ ],
2072
+ ) -> Any:
2073
+ if not isinstance(args, list):
2074
+ raise AssertionError(f"args must be a list, got {type(args)}")
2075
+ if not isinstance(kwargs, dict):
2076
+ raise AssertionError(f"kwargs must be a dict, got {type(kwargs)}")
2077
+ if not callable(user_fn):
2078
+ raise AssertionError(f"user_fn must be callable, got {type(user_fn)}")
2079
+ return user_fn(*args, **kwargs)
2080
+
2081
+ def maybe_unpack_configs(
2082
+ self, configs: list["TritonConfig"], tx: Optional["InstructionTranslator"]
2083
+ ) -> list["TritonConfig"]:
2084
+ if not isinstance(configs, list):
2085
+ raise AssertionError(f"configs must be a list, got {type(configs)}")
2086
+ return configs
2087
+
2088
+ def maybe_unpack_heuristic_result(self, result: Any) -> Any:
2089
+ return result
2090
+
2091
+ def check_grid(
2092
+ self,
2093
+ grid: "TritonGridType",
2094
+ ) -> tuple[Union[int, sympy.Expr, SymInt], ...]:
2095
+ if not isinstance(grid, collections.abc.Sequence):
2096
+ raise RuntimeError(
2097
+ "wrap_triton can only handle grids that resolve to Sequence[int]."
2098
+ )
2099
+ # normalize to tuple
2100
+ return tuple(grid)
2101
+
2102
+ def store_non_graphable_args(
2103
+ self,
2104
+ combined_args: dict[str, Any],
2105
+ ) -> tuple[dict, int]:
2106
+ """
2107
+ Some args cannot be stored in the FX graph.
2108
+ Put them in the side table.
2109
+ """
2110
+
2111
+ def is_graphable(val: Any) -> bool:
2112
+ return isinstance(val, (fx.node.base_types, fx.Node))
2113
+
2114
+ non_graphable_args = {
2115
+ k: v for k, v in combined_args.items() if not is_graphable(v)
2116
+ }
2117
+ graphable_args = {k: v for k, v in combined_args.items() if is_graphable(v)}
2118
+
2119
+ constant_args_idx = kernel_side_table.add_constant_args(non_graphable_args)
2120
+
2121
+ return graphable_args, constant_args_idx
2122
+
2123
+ def call_HOP(
2124
+ self,
2125
+ variable: "TraceableTritonKernelWrapper",
2126
+ grids: list["TritonGridTupleType"],
2127
+ combined_args: dict[str, Any],
2128
+ tx: None,
2129
+ ) -> None:
2130
+ if tx is not None:
2131
+ raise AssertionError("tx must be None for TracingTritonHOPifier")
2132
+ if not isinstance(variable, TraceableTritonKernelWrapper):
2133
+ raise AssertionError(
2134
+ f"Expected TraceableTritonKernelWrapper, got {type(variable)}"
2135
+ )
2136
+
2137
+ graphable_args, constant_args_idx = self.store_non_graphable_args(combined_args)
2138
+
2139
+ if not isinstance(variable.kernel_idx, int):
2140
+ raise AssertionError(
2141
+ f"kernel_idx must be an int, got {type(variable.kernel_idx)}"
2142
+ )
2143
+ return triton_kernel_wrapper_mutation(
2144
+ kernel_idx=variable.kernel_idx,
2145
+ constant_args_idx=constant_args_idx,
2146
+ grid=grids, # type: ignore[arg-type]
2147
+ # TMA descriptor capturing not yet
2148
+ # supported in non-dynamo tracing
2149
+ tma_descriptor_metadata={},
2150
+ kwargs=graphable_args,
2151
+ )
2152
+
2153
+
2154
+ tracing_triton_hopifier_singleton = TracingTritonHOPifier()
2155
+
2156
+
2157
+ class TraceableTritonKernelWrapper:
2158
+ kernel: "TritonKernelType"
2159
+ kernel_idx: Optional[int]
2160
+ grid: Optional["TritonGridType"]
2161
+
2162
+ def __init__(
2163
+ self,
2164
+ kernel: "TritonKernelType",
2165
+ kernel_idx: Optional[int],
2166
+ grid: Optional["TritonGridType"],
2167
+ ) -> None:
2168
+ self.kernel = None
2169
+ self.grid = None
2170
+ tracing_triton_hopifier_singleton.init_variable(self, kernel, kernel_idx, grid)
2171
+ if self.kernel is None:
2172
+ raise AssertionError("kernel was not initialized properly")
2173
+
2174
+ def __getitem__(self, *args: Sequence[Any]) -> "TraceableTritonKernelWrapper":
2175
+ return tracing_triton_hopifier_singleton.call_getitem(self, args) # type: ignore[return-value]
2176
+
2177
+ def run(self, *args: Sequence[Any], **kwargs: dict[str, Any]) -> Any:
2178
+ from torch._library.triton import is_wrap_triton_enabled
2179
+
2180
+ if is_wrap_triton_enabled():
2181
+ return tracing_triton_hopifier_singleton.call_run(self, args, kwargs, None)
2182
+ else:
2183
+ if self.kernel is None:
2184
+ raise AssertionError("kernel cannot be None")
2185
+ # pyrefly: ignore [missing-attribute]
2186
+ return self.kernel.run(*args, **kwargs)
2187
+
2188
+ def __call__(self, *args: Sequence[Any], **kwargs: dict[str, Any]) -> Any:
2189
+ from torch._library.triton import is_wrap_triton_enabled
2190
+
2191
+ if is_wrap_triton_enabled():
2192
+ return tracing_triton_hopifier_singleton.call_triton_kernel(
2193
+ self, args, kwargs, None
2194
+ )
2195
+ else:
2196
+ if self.kernel is None:
2197
+ raise AssertionError("kernel cannot be None")
2198
+ # pyrefly: ignore [bad-index, index-error]
2199
+ return self.kernel[self.grid](*args, **kwargs)
2200
+
2201
+ def specialize_symbolic(self, arg: Sequence[Any]) -> Any:
2202
+ import torch
2203
+
2204
+ # See [Note: Specialize tl.constexpr args in user-defined triton kernels]
2205
+ if isinstance(arg, (torch.SymInt, torch.SymBool, torch.SymFloat)):
2206
+ return guard_scalar(arg)
2207
+ return arg
.venv/lib/python3.10/site-packages/torch/_higher_order_ops/utils.py ADDED
@@ -0,0 +1,1339 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import contextlib
3
+ import functools
4
+ from collections.abc import Callable, Iterable, Mapping, Sequence
5
+ from contextlib import AbstractContextManager, contextmanager, ExitStack, nullcontext
6
+ from dataclasses import dataclass
7
+ from typing import Any, Optional, overload, TypeVar, Union
8
+
9
+ import torch
10
+ import torch.fx.traceback as fx_traceback
11
+ import torch.utils._pytree as pytree
12
+ from torch._dispatch.python import suspend_functionalization
13
+ from torch._guards import detect_fake_mode
14
+ from torch._higher_order_ops.schema import HopSchema
15
+ from torch._library.fake_class_registry import FakeScriptObject
16
+ from torch._library.opaque_object import is_opaque_type
17
+ from torch._ops import HigherOrderOperator, OperatorBase, OpOverload
18
+ from torch._subclasses.fake_tensor import FakeTensor
19
+ from torch._subclasses.functional_tensor import (
20
+ disable_functional_mode,
21
+ FunctionalTensor,
22
+ )
23
+ from torch.fx.experimental.proxy_tensor import (
24
+ _temp_remove_metadata_torch_function_mode,
25
+ disable_proxy_modes_tracing,
26
+ make_fx,
27
+ )
28
+ from torch.fx.passes.runtime_assert import insert_deferred_runtime_asserts
29
+ from torch.fx.passes.shape_prop import _extract_tensor_metadata, TensorMetadata
30
+ from torch.multiprocessing.reductions import StorageWeakRef
31
+
32
+
33
+ @dataclass
34
+ class UnsupportedAliasMutationException(RuntimeError):
35
+ reason: str
36
+
37
+
38
+ def autograd_not_implemented_inner(
39
+ operator: OperatorBase, delayed_error: bool, *args: Any, **kwargs: Any
40
+ ) -> Any:
41
+ """If autograd is enabled and any of the arguments require grad this will either
42
+ raise an error or return a DelayedError depending on the value of delayed.
43
+
44
+ Args:
45
+ operator: The Operator to call with the *args and **kwargs with
46
+ op_name: The name of the Operator
47
+ delayed_error: If True, return a DelayedError instead of raising an error
48
+ args: The flattened operands to the Operator
49
+ kwargs: The keyword arguments to the Operator
50
+
51
+ Raises:
52
+ RuntimeError: If autograd is enabled and any of the arguments to the Operator
53
+ """
54
+ with torch._C._AutoDispatchBelowAutograd():
55
+ result = operator(*args, **kwargs)
56
+ flat_operands = pytree.arg_tree_leaves(*args)
57
+ if torch.is_grad_enabled() and any(
58
+ f.requires_grad for f in flat_operands if isinstance(f, torch.Tensor)
59
+ ):
60
+ if delayed_error:
61
+ err_fn = torch._C._functions.DelayedError(
62
+ f"Autograd not implemented for {str(operator)}",
63
+ 1,
64
+ )
65
+
66
+ def fake_requires_grad(tensor):
67
+ if torch.is_floating_point(tensor) or torch.is_complex(tensor):
68
+ tensor = tensor.detach()
69
+ tensor.requires_grad = True
70
+ return tensor
71
+
72
+ return pytree.tree_map_only(
73
+ torch.Tensor, lambda x: err_fn(fake_requires_grad(x)), result
74
+ )
75
+ else:
76
+ raise RuntimeError(f"Autograd not implemented for {str(operator)}")
77
+ return result
78
+
79
+
80
+ def autograd_not_implemented(op: OperatorBase, deferred_error: bool) -> Callable:
81
+ def inner(*args, **kwargs):
82
+ return autograd_not_implemented_inner(op, deferred_error, *args, **kwargs)
83
+
84
+ return inner
85
+
86
+
87
+ def _maybe_run_with_interpreter(fn):
88
+ maybe_interpreted_fn = fn
89
+ if isinstance(fn, torch.fx.GraphModule) and fx_traceback.has_preserved_node_meta():
90
+ # Running graph with interpreter is needed for propagating the stack_trace
91
+ def graph_with_interpreter(*args):
92
+ with fx_traceback.preserve_node_meta():
93
+ return torch.fx.Interpreter(fn).run(*args)
94
+
95
+ maybe_interpreted_fn = graph_with_interpreter
96
+ return maybe_interpreted_fn
97
+
98
+
99
+ def _maybe_compile_and_run_fn(fn, *args):
100
+ if not torch.compiler.is_dynamo_compiling():
101
+ with setup_compilation_env() as backend: # type: ignore[attr-defined]
102
+ return torch.compile(fn, backend=backend, fullgraph=True)(*args)
103
+ else:
104
+ return fn(*args)
105
+
106
+
107
+ def reenter_make_fx(fn, subgraph_decomp_table=None):
108
+ from torch.fx.experimental.proxy_tensor import _CURRENT_MAKE_FX_TRACER
109
+
110
+ @functools.wraps(fn)
111
+ def wrapped(*args):
112
+ if _CURRENT_MAKE_FX_TRACER is None:
113
+ raise AssertionError(
114
+ "Cannot reenter make_fx when we're not under a make_fx tracing session"
115
+ )
116
+ if subgraph_decomp_table is None:
117
+ gm = _CURRENT_MAKE_FX_TRACER.trace_subgraph(
118
+ _maybe_run_with_interpreter(fn), *args
119
+ )
120
+ else:
121
+ gm = _CURRENT_MAKE_FX_TRACER.trace_subgraph_custom_decomp(
122
+ _maybe_run_with_interpreter(fn), subgraph_decomp_table, *args
123
+ )
124
+
125
+ return gm
126
+
127
+ return wrapped
128
+
129
+
130
+ def _maybe_reenter_make_fx(fn, subgraph_decomp_table=None):
131
+ from torch.fx.experimental.proxy_tensor import _CURRENT_MAKE_FX_TRACER
132
+
133
+ if _CURRENT_MAKE_FX_TRACER is not None:
134
+ return reenter_make_fx(fn, subgraph_decomp_table=subgraph_decomp_table)
135
+ else:
136
+
137
+ def _maybe_make_fx_with_fake_mode(fn):
138
+ @functools.wraps(fn)
139
+ def wrapped(*args):
140
+ from torch._guards import detect_fake_mode
141
+
142
+ fake_mode = detect_fake_mode(args)
143
+ if fake_mode is None:
144
+ # we creaeta a fake_mode here to make sure we could
145
+ # trace the graph with data-dependent calls e.g. .item()
146
+ return make_fx(
147
+ fn,
148
+ tracing_mode="fake",
149
+ decomposition_table=subgraph_decomp_table,
150
+ )(*args)
151
+ # Tracing with real if all inputs have been fakfied
152
+ return make_fx(fn, decomposition_table=subgraph_decomp_table)(*args)
153
+
154
+ return wrapped
155
+
156
+ return _maybe_make_fx_with_fake_mode(fn)
157
+
158
+
159
+ def check_meta_consistency(
160
+ lhs_list: list[Union[torch.Tensor, torch.SymInt, int]],
161
+ rhs_list: list[Union[torch.Tensor, torch.SymInt, int]],
162
+ lhs_name: str,
163
+ rhs_name: str,
164
+ include_contiguity: bool = True,
165
+ ) -> None:
166
+ def diff_meta_pairs(
167
+ lhs_list: list[Union[torch.Tensor, torch.SymInt, int]],
168
+ rhs_list: list[Union[torch.Tensor, torch.SymInt, int]],
169
+ ) -> list[str]:
170
+ def diff_meta(
171
+ lhs: Union[torch.Tensor, torch.SymInt, int],
172
+ rhs: Union[torch.Tensor, torch.SymInt, int],
173
+ ) -> str:
174
+ if isinstance(lhs, torch.Tensor) and isinstance(rhs, torch.Tensor):
175
+ return ", ".join(
176
+ diff_tensor_meta(
177
+ _extract_tensor_metadata(
178
+ lhs, include_contiguity=include_contiguity
179
+ ),
180
+ _extract_tensor_metadata(
181
+ rhs, include_contiguity=include_contiguity
182
+ ),
183
+ check_grad=False,
184
+ )
185
+ )
186
+ else:
187
+
188
+ def _both_int_types(lhs, rhs):
189
+ return isinstance(lhs, (int, torch.SymInt)) and isinstance(
190
+ rhs, (int, torch.SymInt)
191
+ )
192
+
193
+ def _both_tensor(lhs, rhs):
194
+ return isinstance(lhs, torch.Tensor) and isinstance(
195
+ rhs, torch.Tensor
196
+ )
197
+
198
+ if not _both_int_types(lhs, rhs) and not _both_tensor(lhs, rhs):
199
+ return f"type: {lhs} vs {rhs}"
200
+
201
+ return ""
202
+
203
+ # Manually check the device of lhs and rhs as this field is currently not part of TensorMetadata
204
+ def diff_device(
205
+ lhs: Union[torch.Tensor, torch.SymInt, int],
206
+ rhs: Union[torch.Tensor, torch.SymInt, int],
207
+ ) -> str:
208
+ if isinstance(lhs, torch.Tensor) and isinstance(rhs, torch.Tensor):
209
+ if (
210
+ rhs.device.type == lhs.device.type
211
+ and rhs.device.index == lhs.device.index
212
+ ):
213
+ return ""
214
+ else:
215
+ return "device"
216
+ return ""
217
+
218
+ if len(lhs_list) != len(rhs_list):
219
+ raise torch._dynamo.exc.UncapturedHigherOrderOpError(
220
+ f"Expected {lhs_name} and {rhs_name} to have same number of outputs but got lhs:{lhs_list} and rhs:{rhs_list}"
221
+ )
222
+ all_diffs = []
223
+ for i, (lhs, rhs) in enumerate(zip(lhs_list, rhs_list)):
224
+ if diff := diff_meta(lhs, rhs):
225
+ all_diffs.append(
226
+ f"pair[{i}] differ in {diff}, where lhs is {lhs} and rhs is {rhs}"
227
+ )
228
+ if diff := diff_device(lhs, rhs):
229
+ all_diffs.append(
230
+ f"pair[{i}] differ in {diff}, where lhs is {lhs} and rhs is {rhs}"
231
+ )
232
+ return all_diffs
233
+
234
+ if all_diffs := diff_meta_pairs(lhs_list, rhs_list):
235
+ diff_str = "\n".join(all_diffs)
236
+ raise torch._dynamo.exc.UncapturedHigherOrderOpError(
237
+ f"Expected {lhs_name} and {rhs_name} to have same metadata but found:\n{diff_str}"
238
+ )
239
+
240
+
241
+ # Thread-local flag to indicate we're inside HOP internal compilation
242
+ import threading
243
+
244
+
245
+ _hop_compile_tls = threading.local()
246
+
247
+
248
+ def _in_hop_compile() -> bool:
249
+ return getattr(_hop_compile_tls, "in_hop_compile", False)
250
+
251
+
252
+ @contextmanager
253
+ def setup_compilation_env():
254
+ """
255
+ Context manager that sets up proper environment and backend when invoking torch.compile
256
+ inside torch.export region or inside HOP.
257
+ """
258
+ from torch._dynamo.backends.debugging import (
259
+ make_eager_backend_with_torch_function_modes,
260
+ )
261
+ from torch._dynamo.backends.registry import lookup_backend
262
+ from torch.fx.experimental.proxy_tensor import (
263
+ _temp_remove_pre_dispatch_torch_function_mode,
264
+ )
265
+
266
+ old_in_hop_compile = getattr(_hop_compile_tls, "in_hop_compile", False)
267
+ _hop_compile_tls.in_hop_compile = True
268
+ try:
269
+ with (
270
+ _set_compilation_env(),
271
+ torch._dynamo.utils.disable_cache_limit(),
272
+ _temp_remove_pre_dispatch_torch_function_mode() as pre_dispatch_mode,
273
+ _temp_remove_metadata_torch_function_mode() as metadata_mode,
274
+ ):
275
+ modes = [
276
+ mode for mode in (pre_dispatch_mode, metadata_mode) if mode is not None
277
+ ]
278
+ if modes:
279
+ yield make_eager_backend_with_torch_function_modes(modes)
280
+ else:
281
+ yield lookup_backend("eager")
282
+ finally:
283
+ _hop_compile_tls.in_hop_compile = old_in_hop_compile
284
+
285
+
286
+ @contextmanager
287
+ def _set_compilation_env():
288
+ _old_is_tracing = torch.fx._symbolic_trace._is_fx_tracing_flag
289
+ _old_allow_empty_graphs = torch._dynamo.config.allow_empty_graphs
290
+ _old_capture_scalar_outputs = torch._dynamo.config.capture_scalar_outputs
291
+ # The issue is tracked in https://github.com/pytorch/pytorch/issues/144360: when dynamo finds
292
+ # the top-level frame produces no graph, the default behavior is to fallback to eager.
293
+ # Then when it encounters an inner function, it will try to trace that function again, which is unnecessary.
294
+ # For while_loop, during inspecting the inner call, we trace into the python dispathcer
295
+ # logic, which is not tracable as of today. So the proper fix can be either 1. allow dispatch
296
+ # logic to be dynamo tracable or 2. fixing https://github.com/pytorch/pytorch/issues/144360.
297
+ # but it exposes some bugs in existing tests so we have to have a temporary flag to control
298
+ # the behavior, which allows dynamo to store an empty graph for a frame without falling back to eager
299
+ try:
300
+ # We need to turn off the is_fx_tracing_flag. Remove this flag check from dyanmo
301
+ # once we are confident fx tracing works with dynamo.
302
+ torch.fx._symbolic_trace._is_fx_tracing_flag = False
303
+ # pyrefly: ignore [bad-assignment]
304
+ torch._dynamo.config.allow_empty_graphs = True
305
+ torch._dynamo.config.capture_scalar_outputs = True
306
+ yield
307
+ finally:
308
+ torch.fx._symbolic_trace._is_fx_tracing_flag = _old_is_tracing
309
+ torch._dynamo.config.allow_empty_graphs = _old_allow_empty_graphs
310
+ torch._dynamo.config.capture_scalar_outputs = _old_capture_scalar_outputs
311
+
312
+
313
+ # The invariant here is that we always trace the branch with fake tensor
314
+ def _maybe_fake_tracing(fn, inputs: list[Any], pre_dispatch):
315
+ fake_mode_det = detect_fake_mode(inputs)
316
+ fake_mode: AbstractContextManager = nullcontext()
317
+ tracing_mode = "fake"
318
+ if fake_mode_det is not None:
319
+ fake_mode = fake_mode_det
320
+ tracing_mode = "real"
321
+
322
+ # Note: we need to turn off proxy tensor mode to avoid tracing infra
323
+ # code that happens in make_fx e.g. we now call as_strided when wrapping tensor
324
+ # as fake tensor.
325
+ with fake_mode, disable_proxy_modes_tracing():
326
+ gm = make_fx(
327
+ fn,
328
+ tracing_mode=tracing_mode,
329
+ pre_dispatch=pre_dispatch,
330
+ _error_on_data_dependent_ops=False,
331
+ )(*inputs)
332
+ if not isinstance(fake_mode, nullcontext) and fake_mode.shape_env is not None: # type: ignore[attr-defined]
333
+ insert_deferred_runtime_asserts(
334
+ gm,
335
+ fake_mode.shape_env, # type: ignore[attr-defined]
336
+ "hoo_maybe_fake_tracing",
337
+ export=True, # type: ignore[attr-defined]
338
+ )
339
+ return gm
340
+
341
+
342
+ def potential_input_alias_or_mutation(gm, inputs, pre_dispatch=False):
343
+ try:
344
+ gm = _maybe_fake_tracing(gm, inputs, pre_dispatch)
345
+ except UnsupportedAliasMutationException:
346
+ # this can happen when nested cond_op is
347
+ # functionalized
348
+ return True
349
+ except Exception as e:
350
+ raise e
351
+
352
+ example_inputs = [
353
+ ph.meta.get("val", None) for ph in gm.graph.find_nodes(op="placeholder")
354
+ ]
355
+ (
356
+ inp_inp_alias_map,
357
+ inp_out_alias_map,
358
+ out_out_alias_map,
359
+ inp_mutation,
360
+ ) = check_input_alias_and_mutation(gm, example_inputs)
361
+ return (inp_inp_alias_map, inp_out_alias_map, out_out_alias_map), inp_mutation
362
+
363
+
364
+ def analyze_potential_input_alias_or_mutation(name, aliases, input_mutations):
365
+ if any(len(a) > 0 for a in aliases):
366
+ # TODO: Investigate here further which node is exactly aliasing
367
+ raise RuntimeError(
368
+ f"{name} where aliases appear. "
369
+ + f"In particular, these inputs \
370
+ {set(el for el_map in aliases if len(el_map.keys()) > 0 for el in el_map)} " # noqa: C401
371
+ + "get aliased. Please ensure that this doesn't happen."
372
+ )
373
+ if len(input_mutations):
374
+ # TODO: Investigate here further which node is exactly mutating the inputs
375
+ raise RuntimeError(
376
+ f"{name} where the inputs are mutated. "
377
+ + f"In particular, these nodes are mutating the inputs \
378
+ {set(el for el in input_mutations)}." # noqa: C401
379
+ + "Please ensure that this doesn't happen."
380
+ )
381
+
382
+
383
+ def _has_potential_branch_input_mutation(gm, inputs, pre_dispatch=False):
384
+ (
385
+ (_, _, _),
386
+ inp_mutation,
387
+ ) = potential_input_alias_or_mutation(gm, inputs, pre_dispatch)
388
+
389
+ return len(inp_mutation) > 0
390
+
391
+
392
+ def has_potential_input_alias_or_mutation(gm, inputs, pre_dispatch=False):
393
+ (
394
+ (
395
+ inp_inp_alias_map,
396
+ inp_out_alias_map,
397
+ out_out_alias_map,
398
+ ),
399
+ inp_mutation,
400
+ ) = potential_input_alias_or_mutation(gm, inputs, pre_dispatch)
401
+ return (
402
+ any(
403
+ (
404
+ len(inp_inp_alias_map) > 0,
405
+ len(inp_out_alias_map) > 0,
406
+ len(out_out_alias_map) > 0,
407
+ )
408
+ ),
409
+ len(inp_mutation) > 0,
410
+ )
411
+
412
+
413
+ def _collect_fake_inputs(inputs):
414
+ from torch._subclasses.fake_tensor import FakeTensor
415
+
416
+ # Get the example values of the inputs.
417
+ inputs_fake: list[Union[FakeTensor, torch.Tensor, int]] = []
418
+ for inp in inputs:
419
+ if isinstance(inp, (torch.fx.proxy.Proxy, torch.fx.node.Node)):
420
+ inp = inp.node if isinstance(inp, torch.fx.proxy.Proxy) else inp
421
+ if hasattr(inp, "meta"):
422
+ val = inp.meta["example_value"]
423
+ if isinstance(val, torch.Tensor):
424
+ if torch._C._functorch.is_batchedtensor(
425
+ val
426
+ ) or torch._C._functorch.is_functionaltensor(val):
427
+ # This case is for batched or functional tensors
428
+ # Unwrap the tensors
429
+ while torch._C._functorch.is_batchedtensor(
430
+ val
431
+ ) or torch._C._functorch.is_functionaltensor(val):
432
+ val = torch._C._functorch.get_unwrapped(val)
433
+ if not isinstance(val, FakeTensor):
434
+ raise AssertionError(
435
+ f"Expected FakeTensor after unwrapping, got {type(val)}"
436
+ )
437
+ inputs_fake.append(val)
438
+ else:
439
+ # This is the standard case of a TensorVariable
440
+ if not isinstance(val, FakeTensor):
441
+ raise AssertionError(
442
+ f"Expected FakeTensor, got {type(val)}"
443
+ )
444
+ inputs_fake.append(val)
445
+ else:
446
+ # This case is for SymInts and other non-Tensor elements
447
+ if isinstance(val, torch.Tensor):
448
+ raise AssertionError(f"Expected non-Tensor, got {type(val)}")
449
+ inputs_fake.append(val)
450
+ else:
451
+ # This case is for ints
452
+ if not isinstance(inp, int):
453
+ raise AssertionError(f"Expected int, got {type(inp)}")
454
+ inputs_fake.append(inp)
455
+
456
+ return inputs_fake
457
+
458
+
459
+ def _check_alias_and_mutation(graph_module, inputs_fake, name, pre_dispatch):
460
+ aliases, inp_mutation = has_potential_input_alias_or_mutation(
461
+ graph_module, inputs_fake, pre_dispatch=pre_dispatch
462
+ )
463
+ if aliases:
464
+ raise RuntimeError(f"{name} might be aliasing the input or the output!") # noqa: F541
465
+ if inp_mutation:
466
+ raise RuntimeError(f"{name} might be modifying the input!") # noqa: F541
467
+
468
+
469
+ def unique_graph_id(proxy_mode, prefix):
470
+ """Returns a unique name and id for a graph to be added to a proxy_mode tracer"""
471
+ # There are probably better ways - I know that create_arg has some self incrementing name
472
+ # magic to it, but since we explicitly have to get the name for register_module,
473
+ # I was not sure how to do that. This kinda simulates it.
474
+ return unique_graph_name_with_root(proxy_mode.tracer.root, prefix)
475
+
476
+
477
+ def unique_graph_name_with_root(
478
+ root: torch.fx.GraphModule, prefix: str
479
+ ) -> tuple[int, str]:
480
+ next_name = None
481
+ i = 0
482
+ # pyrefly: ignore [bad-assignment]
483
+ while not next_name:
484
+ candidate = f"{prefix}_{i}"
485
+ if hasattr(root, candidate):
486
+ i += 1
487
+ else:
488
+ next_name = candidate
489
+ return i, next_name
490
+
491
+
492
+ def _from_fun(t):
493
+ from torch._functorch.aot_autograd import from_fun
494
+
495
+ if isinstance(t, torch.Tensor):
496
+ if t.dtype != torch.bool:
497
+ return torch.empty_strided(
498
+ t.size(),
499
+ t.stride(),
500
+ dtype=t.dtype,
501
+ requires_grad=t.requires_grad,
502
+ device=t.device,
503
+ )
504
+ else:
505
+ # clone of a functional tensor produces a functional tensor
506
+ # but we want to avoid it so we clone a non-functional version
507
+ maybe_unfunc_t = t
508
+ if isinstance(t, FunctionalTensor):
509
+ torch._sync(t)
510
+ maybe_unfunc_t = from_fun(t)
511
+ elif torch._is_functional_tensor(t):
512
+ # need to handle both types of functionalization here:
513
+ # these are the tensors that came from the user,
514
+ # which could be either FunctionalTensorWrapper or FunctionalTensor
515
+ torch._sync(t)
516
+ maybe_unfunc_t = torch._from_functional_tensor(t)
517
+ # pyrefly: ignore[missing-attribute]
518
+ return maybe_unfunc_t.clone()
519
+ return t
520
+
521
+
522
+ def clone_outputs_aliasing_inputs(args):
523
+ input_storage = {
524
+ StorageWeakRef(arg._typed_storage())
525
+ for arg in args
526
+ if isinstance(arg, torch.Tensor)
527
+ }
528
+
529
+ def maybe_clone(t):
530
+ if (
531
+ isinstance(t, torch.Tensor)
532
+ and StorageWeakRef(t._typed_storage()) in input_storage
533
+ ):
534
+ return t.clone()
535
+ return t
536
+
537
+ return maybe_clone
538
+
539
+
540
+ def prepare_fw_with_masks(fn):
541
+ def fw_with_masks(*args):
542
+ fw_out = fn(*args)
543
+ return fw_out, [
544
+ bool(isinstance(ret, torch.Tensor) and ret.requires_grad) for ret in fw_out
545
+ ]
546
+
547
+ return fw_with_masks
548
+
549
+
550
+ def prepare_fw_with_masks_all_requires_grad(fn):
551
+ def fw_with_masks(*args):
552
+ fw_out = fn(*args)
553
+ # Note [force all outputs to be require grad]
554
+ # Instead of using the original fn, we set the output of original
555
+ # fn to all require grad. This is consistent with the behavior
556
+ # of autograd.Function, where if any one of the inputs requires grad
557
+ # all output will be require grad. This also makes the downstream
558
+ # require_gradness reasoning much easier.
559
+ if pytree.tree_any_only(torch.Tensor, lambda t: t.requires_grad, args):
560
+ fw_out = pytree.tree_map_only(
561
+ torch.Tensor,
562
+ lambda x: x.requires_grad_(True) if x.dtype.is_floating_point else x,
563
+ fw_out,
564
+ )
565
+
566
+ def _query_requires_grad(t: torch.Tensor) -> bool:
567
+ if torch._is_functional_tensor(t):
568
+ t = torch._from_functional_tensor(t)
569
+ return t.requires_grad
570
+
571
+ return fw_out, pytree.tree_map_only(torch.Tensor, _query_requires_grad, fw_out)
572
+
573
+ return fw_with_masks
574
+
575
+
576
+ # This function replaces None gradients with all-zero gradients.
577
+ # `None` gradients are problematic for CUDA graphs. Those gradients are
578
+ # replaced with an all-zero tensor for better optimization
579
+ def unmask_none_gradients(grads, operands):
580
+ allowed_types = (torch.Tensor, int, torch.SymInt)
581
+ if not all(isinstance(o, allowed_types) for o in operands):
582
+ raise AssertionError(
583
+ f"operands can only be of {allowed_types} but got {[type(o) for o in operands]}"
584
+ )
585
+
586
+ unmasked_grads = []
587
+ for g, o in zip(grads, operands):
588
+ if g is not None:
589
+ unmasked_grads.append(g)
590
+ else:
591
+ # In case the operand is an int or a torch.SymInt, return None
592
+ # This can happen for lifted_arguments. E.g., the shapes of a dynamic tensor are lifted and passed
593
+ # as additional arguments
594
+ unmasked_grads.append(
595
+ torch.zeros_like(o) if isinstance(o, torch.Tensor) else None
596
+ )
597
+
598
+ return unmasked_grads
599
+
600
+
601
+ def _maybe_fake_prop_ignore_unbacked(fn, args):
602
+ with ExitStack() as ctx_stack:
603
+ if (fake_mode := detect_fake_mode(args)) is not None:
604
+ ctx_stack.enter_context(fake_mode)
605
+ if fake_mode.shape_env is not None:
606
+ ctx_stack.enter_context(
607
+ fake_mode.shape_env.ignore_fresh_unbacked_symbols()
608
+ )
609
+ return fn(*args)
610
+
611
+
612
+ def redirect_to_mode(hop: OperatorBase, mode):
613
+ """Utility for redispatching HOP to underlying mode
614
+
615
+ Args:
616
+ hop: The HOP to redispatch
617
+ mode: The mode to redispatch to
618
+
619
+ Returns:
620
+ A decorated function that implements the HOP for the given mode
621
+ """
622
+
623
+ @hop.py_impl(mode)
624
+ def impl(mode, *args, **kwargs):
625
+ return mode.__torch_dispatch__(hop, [], args, kwargs)
626
+
627
+ return impl
628
+
629
+
630
+ # TODO: The parameter use_output_and_grad_bw is required because some operations
631
+ # that utilize this function, such as the while_loop, may require (grad, fwd_outputs)
632
+ def create_fw_bw_graph(fn, use_output_and_grad_bw, fw_inputs, fw_outputs):
633
+ from torch._functorch.aot_autograd import AOTConfig, create_joint
634
+
635
+ # Note:[HOP create fw_bw graph] We create "clean" environments for make_fx by suspending all dispatch keys
636
+ # between Autograd and Python key. Currently, we only suspend functionalization but more can be
637
+ # added when required. Will encounter two problems if we don't suspend functionalization:
638
+ #
639
+ # 1. make_fx fails to capture operations on input: the inputs are wrapped as _to_functional_tensor_wrapper,
640
+ # but they will be unwrapped before entering ProxyTorchDispatchMode as part of the dispatching.
641
+ # However, it's the outside wrapper that tracer creates proxies for. This casuses tracer fail to
642
+ # fetch the proxy for the inputs and fail to capture any operations on them.
643
+ #
644
+ # 2. make_fx fails to capture output: the outputs after ProxyTorchDispatchMode are further
645
+ # wrapped as FunctionalTensorWrapper in Functionalize key after return. However, the tracer
646
+ # only associates the inner tensor with proxy in ProxyTorchDispatchMode. Therefore,
647
+ # when creating the output node, it fails to associate the wrapped tensor with its proxy.
648
+ # Instead, it will create _tensor_constant as output.
649
+
650
+ dummy_aot_config = AOTConfig(
651
+ fw_compiler=None, # type: ignore[arg-type]
652
+ bw_compiler=None, # type: ignore[arg-type]
653
+ partition_fn=None, # type: ignore[arg-type]
654
+ decompositions={},
655
+ num_params_buffers=0,
656
+ aot_id=0,
657
+ keep_inference_input_mutations=False,
658
+ )
659
+
660
+ example_grad = [_from_fun(out) for out in fw_outputs]
661
+ num_grads = len(example_grad)
662
+ fw_graph = _maybe_reenter_make_fx(fn)(*fw_inputs)
663
+
664
+ def joint_fn(*joint_operands_grads):
665
+ if use_output_and_grad_bw:
666
+ grads = joint_operands_grads[0]
667
+ inputs = joint_operands_grads[1][-1:]
668
+ else:
669
+ grads = joint_operands_grads[:num_grads]
670
+ inputs = joint_operands_grads[num_grads:]
671
+
672
+ joint = create_joint(prepare_fw_with_masks(fn), aot_config=dummy_aot_config)
673
+ _, grads = joint(
674
+ list(inputs),
675
+ [grad for grad in grads if grad is not None and grad.requires_grad],
676
+ )
677
+
678
+ # Unmask None gradients to all-zero gradients
679
+ unmasked_grads = unmask_none_gradients(grads, inputs)
680
+
681
+ # In order to keep map functional for backward graph,
682
+ # we clone outputs that are aliasing inputs
683
+ maybe_clone = clone_outputs_aliasing_inputs(joint_operands_grads)
684
+
685
+ return pytree.tree_map(maybe_clone, unmasked_grads)
686
+
687
+ if use_output_and_grad_bw:
688
+ example_xs_out = list(fw_inputs) + list(fw_outputs)
689
+ joint_graph = _maybe_reenter_make_fx(joint_fn)(
690
+ (list(example_grad), list(example_xs_out))
691
+ )
692
+ else:
693
+ example_xs_out = list(fw_inputs)
694
+ joint_graph = _maybe_reenter_make_fx(joint_fn)(
695
+ *(list(example_grad) + list(example_xs_out))
696
+ )
697
+
698
+ return fw_graph, joint_graph
699
+
700
+
701
+ def _unstack_pytree(xs):
702
+ flat_xs, inspec = pytree.tree_flatten(xs)
703
+ if not all(isinstance(xs, torch.Tensor) for xs in flat_xs):
704
+ raise RuntimeError(f"Leaves of xs must be Tensor {flat_xs}")
705
+
706
+ if not all(xs.shape[0] == flat_xs[0].shape[0] for xs in flat_xs):
707
+ raise RuntimeError(
708
+ f"Leaves of xs must have same leading dimension size {[xs.shape for xs in flat_xs]}"
709
+ )
710
+
711
+ a = zip(*flat_xs)
712
+
713
+ pytrees = [pytree.tree_unflatten(tuple, inspec) for tuple in a]
714
+ return pytrees
715
+
716
+
717
+ def _stack_pytree(pytrees):
718
+ flat_out = []
719
+ out_spec = None
720
+ for pt in pytrees:
721
+ flat_pt, out_spec = pytree.tree_flatten(pt)
722
+ flat_out.append(flat_pt)
723
+ if out_spec is None:
724
+ raise AssertionError("out_spec cannot be None")
725
+ b = zip(*flat_out)
726
+ stacked_out = []
727
+ for leaves in b:
728
+ if all(isinstance(leaf, torch.Tensor) for leaf in leaves):
729
+ stacked_out.append(torch.stack(leaves))
730
+ elif all(leaf is None for leaf in leaves):
731
+ # Backward graph can return None output when forward inputs doesn't require grad.
732
+ # When we eagerly execute backward graph, we need to call _stack_pytree on its output,
733
+ # therefore we need to deal with None output.
734
+ stacked_out.append(None) # type: ignore[arg-type]
735
+ else:
736
+ raise RuntimeError(f"Cannot stack {leaves}.")
737
+ return pytree.tree_unflatten(stacked_out, out_spec)
738
+
739
+
740
+ # We cannot call save_for_backward for symints. This helper function
741
+ # can be used to save symints as direct attributes of ctx in autograd.Function.
742
+ #
743
+ # For example, if args = (x, y, s0, z, s1),
744
+ # save_values_for_backward will partition the args into two lists, and a bookkeeping list pos:
745
+ # partitioned_args[0] = (x, y, z)
746
+ # partitioned_args[1] = (s0, s1)
747
+ # pos = (0, 0, 1, 0, 1)
748
+ # pos list keeps track of which partition the args
749
+ # is partitioned into in order to recover it in saved_values.
750
+ #
751
+ # In saved_values, we can recover the original args by:
752
+ # iterating over the pos list and pop one item from the front of partitioned_args[pos[i]].
753
+ # We use t_idx and s_idx to keep track of the next index of the item we are going to pop for the two lists.
754
+ def save_values_for_backward(ctx, args):
755
+ if not all(
756
+ isinstance(arg, (torch.Tensor, torch.SymInt, int, type(None), FakeScriptObject))
757
+ or is_opaque_type(type(arg))
758
+ for arg in args
759
+ ):
760
+ raise AssertionError(f"Invalid arg types in {args}")
761
+ partitioned_args: list[Any] = [[], []]
762
+ pos = []
763
+ for arg in args:
764
+ idx = 0 if isinstance(arg, torch.Tensor) else 1
765
+ partitioned_args[idx].append(arg)
766
+ pos.append(idx)
767
+
768
+ if hasattr(ctx, "non_tensor_args"):
769
+ raise AssertionError("ctx already has non_tensor_args attribute.")
770
+ if hasattr(ctx, "pos"):
771
+ raise AssertionError("ctx already has pos attribute.")
772
+ ctx.save_for_backward(*partitioned_args[0])
773
+ ctx.non_tensor_args = partitioned_args[1]
774
+ ctx.pos = pos
775
+
776
+
777
+ def saved_values(ctx):
778
+ args = []
779
+ t_idx = 0
780
+ s_idx = 0
781
+ saved_tensors = ctx.saved_tensors
782
+ for p in ctx.pos:
783
+ if p == 0:
784
+ args.append(saved_tensors[t_idx])
785
+ t_idx += 1
786
+ else:
787
+ args.append(ctx.non_tensor_args[s_idx])
788
+ s_idx += 1
789
+ if t_idx + s_idx != len(ctx.pos):
790
+ raise AssertionError(
791
+ f"t_idx ({t_idx}) + s_idx ({s_idx}) != len(ctx.pos) ({len(ctx.pos)})"
792
+ )
793
+ return tuple(args)
794
+
795
+
796
+ def split_into_chunks(iterable: Sequence[Any], chunk_sizes: list[int]) -> list[Any]:
797
+ if sum(chunk_sizes) != len(iterable):
798
+ raise AssertionError(
799
+ f"the sum of all chunks ({sum(chunk_sizes)}) needs to match the length of the iterable ({len(iterable)})."
800
+ )
801
+ elements = []
802
+ idx = 0
803
+ for size in chunk_sizes:
804
+ elements.append(iterable[idx : idx + size])
805
+ idx += size
806
+ return elements
807
+
808
+
809
+ def _clone_aliasing_output(inputs: Sequence[Any], outputs: Sequence[Any]):
810
+ # For tensors whose grad is None, create zero tensors as gradients
811
+ # This invariant is useful for cudagraph.
812
+
813
+ # Elimitate input-output, output-output aliasing
814
+ seen_input_storages = {
815
+ StorageWeakRef(t._typed_storage())
816
+ for t in inputs
817
+ if isinstance(t, torch.Tensor)
818
+ }
819
+ seen_output_storages = set()
820
+ final_outputs = []
821
+ for out in outputs:
822
+ if isinstance(out, torch.Tensor):
823
+ out_storage = StorageWeakRef(out._typed_storage())
824
+ if (
825
+ out_storage in seen_input_storages
826
+ or out_storage in seen_output_storages
827
+ ):
828
+ out = out.clone()
829
+ seen_output_storages.add(StorageWeakRef(out._typed_storage()))
830
+ final_outputs.append(out)
831
+ return final_outputs
832
+
833
+
834
+ def create_bw_fn(
835
+ fn: Callable, args: tuple[Any, ...], return_fw_outputs: bool = False
836
+ ) -> Callable:
837
+ """
838
+ For a fn that accepts flat inputs and returns flat outputs:
839
+ fw_out = fn(*args),
840
+ this function returns:
841
+ grad_args = bw_fn(*args_and_grad_output)
842
+ with the following invariants:
843
+ 1. args + fw_out has an 1-1 correspondence to args_and_grad_output
844
+ 2. grad_args has an 1-1 corresponsence to args
845
+ 3. for tensor arg whose requires_grad is False, its corresponding grad in
846
+ grad_args will be a zero tensor with the same shape.
847
+ """
848
+
849
+ from torch._functorch.aot_autograd import AOTConfig, create_joint
850
+
851
+ # pyrefly: ignore [missing-module-attribute]
852
+ from torch._higher_order_ops.utils import prepare_fw_with_masks_all_requires_grad
853
+
854
+ dummy_aot_config = AOTConfig(
855
+ fw_compiler=None, # type: ignore[arg-type]
856
+ bw_compiler=None, # type: ignore[arg-type]
857
+ partition_fn=None, # type: ignore[arg-type]
858
+ decompositions={},
859
+ num_params_buffers=0,
860
+ aot_id=0,
861
+ keep_inference_input_mutations=False,
862
+ )
863
+ n_primals = len(args)
864
+
865
+ bw_fn = create_joint(
866
+ prepare_fw_with_masks_all_requires_grad(fn), aot_config=dummy_aot_config
867
+ )
868
+
869
+ def flat_fn(*args_and_grad_outs):
870
+ primals = args_and_grad_outs[:n_primals]
871
+ tangents = args_and_grad_outs[n_primals:]
872
+ fw_outs, grad_args = bw_fn(primals, tangents)
873
+ if len(args) != len(grad_args):
874
+ raise AssertionError(
875
+ f"Expected {len(args)} grad_args, got {len(grad_args)}"
876
+ )
877
+
878
+ # For tensors whose grad is None, create zero tensors as gradients
879
+ # This invariant is useful for cudagraph.
880
+ grad_args = [
881
+ torch.zeros_like(arg)
882
+ if isinstance(arg, torch.Tensor) and grad is None
883
+ else grad
884
+ for grad, arg in zip(grad_args, primals)
885
+ ]
886
+
887
+ final_grads = _clone_aliasing_output(args_and_grad_outs, grad_args)
888
+ if return_fw_outputs:
889
+ return *fw_outs, *final_grads
890
+ return final_grads
891
+
892
+ return flat_fn
893
+
894
+
895
+ def get_dummy_aot_autograd_config():
896
+ from torch._functorch.aot_autograd import AOTConfig
897
+
898
+ return AOTConfig(
899
+ fw_compiler=None, # type: ignore[arg-type]
900
+ bw_compiler=None, # type: ignore[arg-type]
901
+ partition_fn=None, # type: ignore[arg-type]
902
+ decompositions={},
903
+ num_params_buffers=0,
904
+ aot_id=0,
905
+ keep_inference_input_mutations=False,
906
+ )
907
+
908
+
909
+ # Slices off the first element of a given dimension
910
+ def first_slice_copy(t: torch.Tensor, dim: int = 0) -> torch.Tensor:
911
+ return torch.select_copy(t, dim, 0)
912
+
913
+
914
+ # Returns a mask whether a list element is a tensor or not
915
+ def get_tensor_mask(tensor_list: Iterable[Any]) -> list[bool]:
916
+ return [bool(isinstance(v, torch.Tensor)) for v in tensor_list]
917
+
918
+
919
+ def mask_list(
920
+ mask: list[bool], inp: list[Any], other: Optional[list[Any]] = None
921
+ ) -> list[Any]:
922
+ # Masks elements on an `inp` list.
923
+ # If other is None, then the elements of the `inp` list where the mask is False are removed
924
+ # If other is not None, then the elements of the `inp` list where the mask is False are
925
+ # replaced with the elements of the `other` list
926
+ if len(mask) != len(inp):
927
+ raise AssertionError(
928
+ f"The length of the mask ({len(mask)}) needs to be identical to the length of the input ({len(inp)})"
929
+ )
930
+ if other is not None:
931
+ if len(inp) != len(other):
932
+ raise AssertionError(
933
+ f"If an input and an other list is provided, they need to have the same length ({len(inp)} != {len(other)})"
934
+ )
935
+ return [i if m else o for m, i, o in zip(mask, inp, other)]
936
+ else:
937
+ return [i for m, i in zip(mask, inp) if m]
938
+
939
+
940
+ def first_slice_copy_with_grad(li: Iterable[Any]) -> list[Any]:
941
+ # First_slice_copy does not keep the original requires_grad flag,
942
+ # but we need it for materialize_as_graph
943
+ # in order to compute the correct gradients
944
+ # The reason why first_slice_copy doesn't keep requires_grad flag is
945
+ # because it's called in torch.autograd.Function.backward/forward.
946
+ slc = [first_slice_copy(x).requires_grad_(x.requires_grad) for x in li]
947
+ return slc
948
+
949
+
950
+ # Reports the difference between meta of two tensors in a string
951
+ def diff_tensor_meta(
952
+ meta1: TensorMetadata, meta2: TensorMetadata, check_grad=True
953
+ ) -> list[str]:
954
+ from torch.fx.experimental.symbolic_shapes import GuardOnDataDependentSymNode
955
+
956
+ pair_diffs = []
957
+ for meta_name in TensorMetadata._fields:
958
+ if not check_grad and meta_name == "requires_grad":
959
+ continue
960
+ val1 = getattr(meta1, meta_name)
961
+ val2 = getattr(meta2, meta_name)
962
+ try:
963
+ if val1 != val2:
964
+ pair_diffs.append(f"'{meta_name}: {val1} vs {val2}'")
965
+ except GuardOnDataDependentSymNode:
966
+ pair_diffs.append(f"'{meta_name}: {val1} vs {val2}'")
967
+ continue
968
+ return pair_diffs
969
+
970
+
971
+ # Note [lifted arg types in hop]
972
+ # For dynamoed hops, we automatically lift the free symbols in tensors as arguments.
973
+ # This has implications for the types of lifted args for different dispatch keys:
974
+ # 1. functionalization, FakeTensorMode, ProxyTorchDispatchMode, Autograd need to support torch.Symint
975
+ # lifted args because it's on the path of torch.compile(dynamic=True).
976
+ # 2. functionalization, FakeTensorMode, ProxyTorchDispatchMode, Autograd, CompositeExplicitAutograd need
977
+ # to support int arguments. In the eager run case, we re-trace the subgraph in AutogradKey, so inner
978
+ # hops may receive int inputs from the shape of outer tensor inputs.
979
+ # However, CompositeExplicitAutograd won't receive SymInt inputs because it only accepts real tensor inputs.
980
+ def validate_subgraph_args_types(lifted_args: Union[tuple[Any, ...], list[Any]]):
981
+ allowed_types = (torch.Tensor, int, torch.SymInt)
982
+ if not all(
983
+ isinstance(arg, (torch.Tensor, int, torch.SymInt)) for arg in lifted_args
984
+ ):
985
+ raise AssertionError(
986
+ f"{lifted_args} can only be of {allowed_types} but got {tuple(type(arg) for arg in lifted_args)}"
987
+ )
988
+
989
+
990
+ # TODO: Return a more detailed information as to which node
991
+ # causes a mutation or an alias. This may requires a per operator tensor version checking
992
+ def check_input_alias_and_mutation(
993
+ gm: torch.fx.GraphModule,
994
+ fake_args: list[FakeTensor],
995
+ ) -> tuple[dict[int, int], dict[int, int], dict[int, int], list[int]]:
996
+ (
997
+ inp_inp_alias_map,
998
+ inp_out_alias_map,
999
+ out_out_alias_map,
1000
+ mutated_inputs,
1001
+ ) = check_input_alias_and_mutation_return_outputs(gm)[:-1]
1002
+ # pyrefly: ignore [bad-return]
1003
+ return inp_inp_alias_map, inp_out_alias_map, out_out_alias_map, mutated_inputs
1004
+
1005
+
1006
+ def _tensor_storage(t) -> StorageWeakRef:
1007
+ return StorageWeakRef(t._typed_storage())
1008
+
1009
+
1010
+ def check_input_alias_and_mutation_return_outputs(
1011
+ gm: torch.fx.GraphModule,
1012
+ ) -> tuple[
1013
+ dict[int, int],
1014
+ dict[int, int],
1015
+ dict[int, int],
1016
+ list[int],
1017
+ Union[tuple[Any, ...], list[Any]],
1018
+ ]:
1019
+ def _get_example_value(n):
1020
+ if not isinstance(n, torch.fx.Node):
1021
+ return n
1022
+ else:
1023
+ return n.meta["val"] if "val" in n.meta else n.meta["example_value"]
1024
+
1025
+ fake_args = [
1026
+ _get_example_value(n)
1027
+ for n in gm.graph.find_nodes(op="placeholder")
1028
+ if isinstance(n, torch.fx.Node) and "val" in n.meta
1029
+ ]
1030
+ outputs = [
1031
+ _get_example_value(n)
1032
+ for n in pytree.tree_flatten(gm.graph.find_nodes(op="output")[0].args[0])[0]
1033
+ ]
1034
+
1035
+ # We need to analyze the original fake_args to detect
1036
+ # inp-inp alias.
1037
+ inp_storage_map = {
1038
+ _tensor_storage(inp): i
1039
+ for i, inp in enumerate(fake_args)
1040
+ if isinstance(inp, torch.Tensor)
1041
+ }
1042
+ out_storage_map = {
1043
+ _tensor_storage(out): i
1044
+ for i, out in enumerate(outputs)
1045
+ if isinstance(out, torch.Tensor)
1046
+ }
1047
+ inp_inp_alias_map = {
1048
+ i: inp_storage_map[_tensor_storage(inp)]
1049
+ for i, inp in enumerate(fake_args)
1050
+ if isinstance(inp, torch.Tensor) and inp_storage_map[_tensor_storage(inp)] != i
1051
+ }
1052
+ out_out_alias_map = {
1053
+ i: out_storage_map[_tensor_storage(out)]
1054
+ for i, out in enumerate(outputs)
1055
+ if isinstance(out, torch.Tensor) and out_storage_map[_tensor_storage(out)] != i
1056
+ }
1057
+ inp_out_alias_map = {
1058
+ i: out_storage_map[_tensor_storage(inp)]
1059
+ for i, inp in enumerate(fake_args)
1060
+ if isinstance(inp, torch.Tensor) and _tensor_storage(inp) in out_storage_map
1061
+ }
1062
+ mutated_inputs = []
1063
+ for node in gm.graph.nodes:
1064
+ if node.op == "call_function" and isinstance(
1065
+ node.target, torch._ops.OpOverload
1066
+ ):
1067
+ for arg_node, arg_schema in zip(node.args, node.target._schema.arguments):
1068
+ if arg_schema.is_write:
1069
+ arg_val = _get_example_value(arg_node)
1070
+ if not isinstance(arg_val, torch.Tensor):
1071
+ raise AssertionError(
1072
+ f"Expected arg_val to be a Tensor, got {type(arg_val)}"
1073
+ )
1074
+ if _tensor_storage(arg_val) in inp_storage_map:
1075
+ mutated_inputs.append(inp_storage_map[_tensor_storage(arg_val)])
1076
+
1077
+ return (
1078
+ inp_inp_alias_map,
1079
+ inp_out_alias_map,
1080
+ out_out_alias_map,
1081
+ mutated_inputs,
1082
+ outputs,
1083
+ )
1084
+
1085
+
1086
+ registered_hop_fake_fns: dict[torch._ops.OpOverload, Callable] = {}
1087
+
1088
+
1089
+ F = TypeVar("F", bound=Callable)
1090
+
1091
+
1092
+ @overload
1093
+ def register_fake(hop, fn: None = None) -> Callable[[F], F]: ...
1094
+
1095
+
1096
+ @overload
1097
+ def register_fake(hop, fn: F) -> F: ...
1098
+
1099
+
1100
+ def register_fake(hop, fn=None):
1101
+ """
1102
+ Register a fake function for a HOP. This is conceptually equivalent of the
1103
+ register_fake utility for the custom ops. The registered function is called
1104
+ inside the fake_tensor _dispatch_impl.
1105
+ """
1106
+ if hop in registered_hop_fake_fns:
1107
+ raise AssertionError(f"hop {hop} already registered in registered_hop_fake_fns")
1108
+
1109
+ def register(func: F) -> F:
1110
+ from torch._subclasses.fake_tensor import FakeTensorMode
1111
+
1112
+ redirect_to_mode(hop, FakeTensorMode)
1113
+
1114
+ registered_hop_fake_fns[hop] = func
1115
+ return func
1116
+
1117
+ if fn is None:
1118
+ return register
1119
+ return register(fn)
1120
+
1121
+
1122
+ class FunctionalizeCtxWrapper:
1123
+ """
1124
+ This is a dummy wrapper to facilitate fake tensor caching.
1125
+
1126
+ For AOT Dispatcher metadata collection pass, HOPs go from functionalization
1127
+ key to fake tensor key. The functionalization key wraps the subgraphs in a
1128
+ function, which changes from call to call even though the subgraph might
1129
+ still be same.
1130
+
1131
+ To enable fake tensor caching, we just wrap the ctx and subgraph in this
1132
+ class and then use the subgraph as the hash.
1133
+ """
1134
+
1135
+ # Prevents PYTORCH_TEST_WITH_DYNAMO=1 test failures
1136
+ @torch._disable_dynamo
1137
+ def __init__(self, ctx, subgraph):
1138
+ self.ctx = ctx
1139
+ self.subgraph = subgraph
1140
+
1141
+ def __hash__(self):
1142
+ return id(self.subgraph)
1143
+
1144
+ def __repr__(self):
1145
+ return f"FunctionalizeCtxWrapper on subgraph {self.subgraph})"
1146
+
1147
+ def __call__(self, *args, **kwargs):
1148
+ if isinstance(self.subgraph, torch.fx.GraphModule):
1149
+ # Running graph with interpreter is needed for propagating the stack_trace
1150
+ with fx_traceback.preserve_node_meta():
1151
+ return self.ctx.functionalize(torch.fx.Interpreter(self.subgraph).run)(
1152
+ *args, **kwargs
1153
+ )
1154
+ return self.ctx.functionalize(self.subgraph)(*args, **kwargs)
1155
+
1156
+
1157
+ # A wrapper over HigherOrderOperator that also carries its schema
1158
+ class HopInstance:
1159
+ def __init__(self, op: HigherOrderOperator, schema: HopSchema):
1160
+ if not isinstance(op, HigherOrderOperator):
1161
+ raise AssertionError(f"Expected HigherOrderOperator, got {type(op)}")
1162
+ self._op = op
1163
+ # Using "_" to be consistent with how we access _schema of OpOverload
1164
+ self._schema = schema
1165
+
1166
+ def __call__(self, *args, **kwargs):
1167
+ return self._op(*args, **kwargs)
1168
+
1169
+ @staticmethod
1170
+ def create(hop: HigherOrderOperator, *args, **kwargs):
1171
+ return HopInstance(hop, hop.gen_schema(*args, **kwargs))
1172
+
1173
+
1174
+ # This call_op can be used to call a HopInstance with
1175
+ # flat args and kwargs. We need to make use of the hop's schema's tree_spec
1176
+ # to unflatten the args and kwargs before calling the hop.
1177
+ def call_op(op: Union[OpOverload, HopInstance], args, kwargs):
1178
+ if isinstance(op, OpOverload):
1179
+ return op(*args, **kwargs)
1180
+
1181
+ if not isinstance(op, HopInstance):
1182
+ raise AssertionError(f"Expected HopInstance, got {type(op)}")
1183
+ schema = op._schema
1184
+ bound_args = list(args)
1185
+ bound_kwargs = {}
1186
+ for arg in schema.arguments[len(bound_args) :]:
1187
+ if arg.name not in kwargs:
1188
+ raise AssertionError(f"arg {arg.name} not in kwargs: {kwargs}")
1189
+ val = kwargs[arg.name]
1190
+ if not arg.kwarg_only:
1191
+ bound_args.append(val)
1192
+ else:
1193
+ bound_kwargs[arg.name] = val
1194
+
1195
+ if schema.tree_spec is not None:
1196
+ if len(bound_args) != len(schema.arguments) or len(bound_kwargs) != 0:
1197
+ raise AssertionError(
1198
+ f"Expected {len(schema.arguments)} bound_args and 0 bound_kwargs, "
1199
+ f"got {len(bound_args)} and {len(bound_kwargs)}"
1200
+ )
1201
+ args, kwargs = pytree.tree_unflatten(bound_args, schema.tree_spec)
1202
+ return op(*args, **kwargs)
1203
+ else:
1204
+ if len(bound_args) + len(bound_kwargs) != len(schema.arguments):
1205
+ raise AssertionError(
1206
+ f"Expected {len(schema.arguments)} total args, "
1207
+ f"got {len(bound_args)} + {len(bound_kwargs)}"
1208
+ )
1209
+ return op(*bound_args, **bound_kwargs)
1210
+
1211
+
1212
+ def materialize_as_graph(
1213
+ fn: Callable,
1214
+ args: tuple[Any, ...],
1215
+ include_key_set: Optional[torch._C.DispatchKeySet] = None,
1216
+ exclude_key_set: Optional[torch._C.DispatchKeySet] = None,
1217
+ force_enable_grad=False,
1218
+ subgraph_decomp_table: Optional[Mapping[OpOverload, Callable]] = None,
1219
+ ) -> torch.fx.GraphModule:
1220
+ if include_key_set is None:
1221
+ include_key_set = torch._C._dispatch_tls_local_include_set()
1222
+ if exclude_key_set is None:
1223
+ exclude_key_set = torch._C._dispatch_tls_local_exclude_set()
1224
+
1225
+ @torch._dynamo.disable(recursive=True, reason=None)
1226
+ def _materialize_as_graph_inner():
1227
+ with suspend_functionalization(), disable_functional_mode():
1228
+ with disable_proxy_modes_tracing():
1229
+ unfunc_t = [_from_fun(arg) for arg in args]
1230
+
1231
+ with contextlib.ExitStack() as stack:
1232
+ stack.enter_context(
1233
+ torch.utils._python_dispatch._disable_current_modes()
1234
+ )
1235
+ stack.enter_context(
1236
+ torch._C._ForceDispatchKeyGuard(include_key_set, exclude_key_set),
1237
+ )
1238
+ if force_enable_grad:
1239
+ stack.enter_context(torch.enable_grad())
1240
+ # fake_mode is needed because parent tracer's fake_mode might
1241
+ # be None but the associated inputs have fake mode or there
1242
+ # is a global tracing context with fake mode. We nneed to
1243
+ # make sure the fake mode when tracing subgraph is consistent.
1244
+ if fake_mode := detect_fake_mode(unfunc_t):
1245
+ stack.enter_context(fake_mode)
1246
+ return _maybe_reenter_make_fx(
1247
+ fn, subgraph_decomp_table=subgraph_decomp_table
1248
+ )(*unfunc_t)
1249
+
1250
+ gm = _materialize_as_graph_inner()
1251
+ if gm is None:
1252
+ raise AssertionError("materialize_as_graph returned None")
1253
+ return gm
1254
+
1255
+
1256
+ def materialize_callable_in_args(op: HopInstance, args, kwargs):
1257
+ schema = op._schema
1258
+ hop = op._op
1259
+ flat_args, flat_spec = pytree.tree_flatten((args, kwargs))
1260
+
1261
+ def wrapped_fn(*flat_args):
1262
+ return call_op(op, args, kwargs)
1263
+
1264
+ # We need to trace the higher order op in order to materilaize the callable inputs that
1265
+ # are a callable (e.g. after functionalization key)
1266
+ gm = reenter_make_fx(wrapped_fn)(*flat_args)
1267
+ hop_node = gm.graph.find_nodes(op="call_function", target=hop)[0]
1268
+ arg_proxies = pytree.tree_leaves((hop_node.args, hop_node.kwargs))
1269
+ if not isinstance(schema, torch._C.FunctionSchema) or len(arg_proxies) != len(
1270
+ schema.arguments
1271
+ ):
1272
+ raise AssertionError(
1273
+ f"Expected FunctionSchema with {len(arg_proxies)} arguments"
1274
+ )
1275
+
1276
+ # call_op preserves ordering of proxies via schema
1277
+ materialized_args = []
1278
+ for i, proxy in enumerate(arg_proxies):
1279
+ if (
1280
+ isinstance(proxy, torch.fx.Node)
1281
+ and proxy.op == "get_attr"
1282
+ and isinstance(getattr(gm, proxy.target), torch.fx.GraphModule) # type: ignore[arg-type]
1283
+ ):
1284
+ if not callable(flat_args[i]):
1285
+ raise AssertionError(
1286
+ f"Expected flat_args[{i}] to be callable for {schema}"
1287
+ )
1288
+ materialized_args.append(getattr(gm, proxy.target)) # type: ignore[arg-type]
1289
+ else:
1290
+ materialized_args.append(flat_args[i])
1291
+
1292
+ return pytree.tree_unflatten(materialized_args, flat_spec)
1293
+
1294
+
1295
+ def has_user_subclass(args, allowed_subclasses):
1296
+ """Check if any tensor arguments are user subclasses.
1297
+
1298
+ This is used to determine if tensor subclasses should get a chance to run
1299
+ their own implementation first before falling back to the default implementation.
1300
+
1301
+ Args:
1302
+ args: Arguments to check (will be flattened with pytree)
1303
+ allowed_subclasses: Tuple of allowed subclass types
1304
+
1305
+ Returns:
1306
+ True if user tensor subclasses are found, False otherwise
1307
+ """
1308
+ flat_args, _ = pytree.tree_flatten(args)
1309
+
1310
+ val = any(
1311
+ isinstance(a, torch.Tensor)
1312
+ and type(a) is not torch.Tensor
1313
+ and not isinstance(a, allowed_subclasses)
1314
+ for a in flat_args
1315
+ )
1316
+ return val
1317
+
1318
+
1319
+ def _has_gen_schema(op: HigherOrderOperator):
1320
+ # There is an InvokeQuant argument we cannot gen_schema.
1321
+ if op is torch.ops.higher_order.invoke_quant_packed:
1322
+ return False
1323
+ method = "gen_schema"
1324
+ return hasattr(type(op), method) and getattr(type(op), method) is not getattr(
1325
+ HigherOrderOperator, method
1326
+ )
1327
+
1328
+
1329
+ def filter_with_masks(data: list[Optional[torch.Tensor]], masks: list[bool]):
1330
+ if len(data) != len(masks):
1331
+ raise AssertionError(
1332
+ f"data length ({len(data)}) != masks length ({len(masks)})"
1333
+ )
1334
+ return [item for item, keep in zip(data, masks) if keep]
1335
+
1336
+
1337
+ def fill_none_with_masks(data: list[Optional[torch.Tensor]], masks: list[bool]):
1338
+ data_iter = iter(data)
1339
+ return [next(data_iter) if kept else None for kept in masks]
.venv/lib/python3.10/site-packages/torch/_higher_order_ops/while_loop.py ADDED
@@ -0,0 +1,954 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import contextlib
3
+ import functools
4
+ from collections.abc import Callable
5
+ from typing import Union
6
+
7
+ import torch
8
+ import torch.utils._pytree as pytree
9
+ from torch._C import DispatchKey
10
+ from torch._higher_order_ops.utils import (
11
+ _maybe_run_with_interpreter,
12
+ autograd_not_implemented,
13
+ check_input_alias_and_mutation_return_outputs,
14
+ check_meta_consistency,
15
+ fill_none_with_masks,
16
+ filter_with_masks,
17
+ materialize_as_graph,
18
+ reenter_make_fx,
19
+ validate_subgraph_args_types,
20
+ )
21
+ from torch._ops import HigherOrderOperator
22
+ from torch._subclasses.fake_tensor import FakeTensorMode
23
+ from torch.fx.experimental.proxy_tensor import (
24
+ disable_proxy_modes_tracing,
25
+ ProxyTorchDispatchMode,
26
+ track_tensor_tree,
27
+ )
28
+
29
+
30
+ class WhileLoopOp(HigherOrderOperator):
31
+ def __init__(self) -> None:
32
+ super().__init__("while_loop")
33
+
34
+ def __call__(
35
+ self,
36
+ cond_fn: Callable,
37
+ body_fn: Callable,
38
+ carried_inputs: tuple[Union[torch.Tensor, int, float, bool]],
39
+ additional_inputs: tuple[Union[torch.Tensor, torch.SymInt, int], ...],
40
+ /,
41
+ ):
42
+ if not isinstance(carried_inputs, (tuple, list)):
43
+ raise RuntimeError(
44
+ f"carried_inputs must be a tuple or list, got {type(carried_inputs)}"
45
+ )
46
+ if not isinstance(additional_inputs, (tuple, list)):
47
+ raise RuntimeError(
48
+ f"additional_inputs must be a tuple or list, got {type(additional_inputs)}"
49
+ )
50
+
51
+ validate_subgraph_args_types(carried_inputs)
52
+ validate_subgraph_args_types(additional_inputs)
53
+ # pyrefly: ignore [missing-attribute]
54
+ return super().__call__(cond_fn, body_fn, carried_inputs, additional_inputs)
55
+
56
+ # pyrefly: ignore [bad-override]
57
+ def gen_schema(self, cond_fn, body_fn, carried_inputs, additional_inputs):
58
+ from torch._higher_order_ops.schema import HopSchemaGenerator
59
+ from torch._higher_order_ops.utils import materialize_as_graph
60
+
61
+ all_inputs = carried_inputs + additional_inputs
62
+
63
+ cond_gm: torch.fx.GraphModule = (
64
+ cond_fn
65
+ if isinstance(cond_fn, torch.fx.GraphModule)
66
+ else materialize_as_graph(cond_fn, all_inputs)
67
+ )
68
+ body_gm: torch.fx.GraphModule = (
69
+ body_fn
70
+ if isinstance(body_fn, torch.fx.GraphModule)
71
+ else materialize_as_graph(body_fn, all_inputs)
72
+ )
73
+
74
+ def _find_example_value(n, real_inp):
75
+ if "val" in n.meta:
76
+ return n.meta["val"]
77
+ elif "example_value" in n.meta:
78
+ return n.meta["example_value"]
79
+ else:
80
+ if isinstance(real_inp, torch.Tensor):
81
+ raise AssertionError(
82
+ "expected non-Tensor real_inp when no val/example_value in meta, got Tensor"
83
+ )
84
+ return real_inp
85
+
86
+ (
87
+ _,
88
+ _,
89
+ _,
90
+ body_mutated_inputs,
91
+ body_outputs,
92
+ ) = check_input_alias_and_mutation_return_outputs(body_gm)
93
+
94
+ (
95
+ _,
96
+ _,
97
+ _,
98
+ cond_mutated_inputs,
99
+ _,
100
+ ) = check_input_alias_and_mutation_return_outputs(cond_gm)
101
+
102
+ mutated_inputs = set(body_mutated_inputs) | set(cond_mutated_inputs)
103
+
104
+ schema_gen = HopSchemaGenerator(self)
105
+ schema_gen.add_arg("cond_fn", cond_gm)
106
+ schema_gen.add_arg("body_fn", body_gm)
107
+
108
+ for idx, arg in enumerate(carried_inputs):
109
+ schema_gen.add_arg(
110
+ f"carried_input{idx}", arg, is_mutated=idx in mutated_inputs
111
+ )
112
+
113
+ for idx, arg in enumerate(additional_inputs):
114
+ additional_idx = len(carried_inputs) + idx
115
+ schema_gen.add_arg(
116
+ f"additional_input{idx}",
117
+ arg,
118
+ is_mutated=additional_idx in mutated_inputs,
119
+ )
120
+
121
+ for out in body_outputs:
122
+ schema_gen.add_output(out)
123
+
124
+ schema_gen.add_schema_tree_spec(
125
+ cond_fn, body_fn, carried_inputs, additional_inputs
126
+ )
127
+ return schema_gen.gen_schema()
128
+
129
+
130
+ while_loop_op = WhileLoopOp()
131
+
132
+
133
+ def while_loop(cond_fn, body_fn, carried_inputs):
134
+ r"""
135
+ Run ``body_fn(*carried_inputs)`` while ``cond_fn(*carried_inputs)`` returns
136
+ a True scalar tensor. Returns the output of body_fn or initial
137
+ carried_inputs.
138
+
139
+ .. warning::
140
+
141
+ `torch.while_loop` is a prototype feature in PyTorch. It has limited support for input and output types and
142
+ doesn't support training currently. Please look forward to a more stable implementation in a future version of PyTorch.
143
+ Read more about feature classification at: https://pytorch.org/blog/pytorch-feature-classification-changes/#prototype
144
+
145
+ `while_loop` is a structured control flow operator. It preserves the loop semantic across the torch.compile and torch.export.
146
+
147
+ `while_loop` is equivalent to the following::
148
+
149
+ def while_loop(cond_fn, body_fn, carried_inputs):
150
+ val = carried_inputs
151
+ while cond_fn(*val):
152
+ val = body_fn(*val)
153
+ return val
154
+
155
+ Args:
156
+ cond_fn (Callable): A callable function that returns a boolean Scalar tensor or a python boolean.
157
+
158
+ body_fn (Callable): A callable function that takes the same inputs as `cond_fn` and returns a tuple of tensors or ints
159
+
160
+ carried_inputs (Tuple of possibly nested dict/list/tuple of tensors or ints): A tuple of inputs to cond_fn and body_fn.
161
+ It's also the initial value of states that are carried across iterations. Note that when pass an integer as carry,
162
+ the corresponding return of while_loop will be another int with unknown values because we don't know how many
163
+ iterations while_loop will run.
164
+
165
+ Example 1::
166
+
167
+ def cond_fn(iter, x):
168
+ return iter.sum() < 10
169
+
170
+
171
+ def body_fn(iter, x):
172
+ return iter + 1, x.sin()
173
+
174
+
175
+ while_loop(cond_fn, body_fn, (torch.zeros(1), torch.randn(3, 4)))
176
+
177
+ Example 2::
178
+
179
+ def cond_fn(int_iter, x):
180
+ return 2 * int_iter < x.shape[0]
181
+
182
+
183
+ def body_fn(int_iter, x):
184
+ return int_iter + 1, x + int_iter
185
+
186
+
187
+ while_loop(cond_fn, body_fn, (0, torch.randn(3, 4)))
188
+
189
+ Restrictions:
190
+
191
+ - body_fn must return tensors or int with the same metadata (e.g.shape, dtype) as inputs.
192
+
193
+ - body_fn and cond_fn must not in-place mutate the carried_inputs. A clone before the mutation is required.
194
+
195
+ - body_fn and cond_fn must not mutate python variables (e.g. list/dict) created outside of the body_fn.
196
+
197
+ - body_fn and cond_fn's output cannot alias any of the inputs. A clone is required.
198
+
199
+ .. warning::
200
+
201
+ Temporal Limitations:
202
+
203
+ - 'while_loop' only supports **inference** right now. Autograd will be supported in the future.
204
+
205
+ """
206
+
207
+ # Currently, additional_inputs is not a user-facing input. It will be automatically set in dynamo.
208
+ # parameters and buffers accessed in cond_fn or body_fn or tensor closures will become additional_inputs.
209
+ additional_inputs: tuple = ()
210
+
211
+ # The reason we flatten the output before calling into dynamo is that
212
+ # we want to create a consistent input ordering for cond_fn and body_fn.
213
+ # and we also want to the input ordering matches the output ordering.
214
+ # Also see NOTE: [why we cannot use "automatic" for while_loop]
215
+ # Construct flat cond_fn and flat_body_fn, which takes flattened inputs
216
+ flat_inputs, in_spec = pytree.tree_flatten((carried_inputs, additional_inputs))
217
+
218
+ def flat_cond_fn(*flat_args):
219
+ carried, additional = pytree.tree_unflatten(flat_args, in_spec)
220
+ return cond_fn(*carried, *additional)
221
+
222
+ def flat_body_fn(*flat_args):
223
+ carried, additional = pytree.tree_unflatten(flat_args, in_spec)
224
+ return body_fn(*carried, *additional)
225
+
226
+ if torch.compiler.is_dynamo_compiling():
227
+ return while_loop_op(flat_cond_fn, flat_body_fn, tuple(flat_inputs), tuple())
228
+
229
+ def _validate_input(cond_fn, body_fn, carried_inputs):
230
+ from torch._higher_order_ops.utils import validate_subgraph_args_types
231
+
232
+ if not callable(cond_fn) or not callable(body_fn):
233
+ raise RuntimeError("Expect cond_fn and body_fn to be callable.")
234
+
235
+ validate_subgraph_args_types(flat_inputs)
236
+
237
+ if not pytree.tree_all(
238
+ lambda t: isinstance(t, (torch.Tensor, torch.SymInt, int)), carried_inputs
239
+ ):
240
+ raise RuntimeError(
241
+ "Expect carried_inputs to be a tuple of possibly nested dict/list/tuple that only"
242
+ f"consists of tensor or int leaves, but got {carried_inputs}."
243
+ )
244
+
245
+ _validate_input(cond_fn, body_fn, carried_inputs)
246
+
247
+ # Dynamo is expecting a callable with "__code__" attribute.
248
+ # We cannot directly pass cond_op to it. So we wrap it in a dummy function.
249
+ def _while_loop_op_wrapper(*args, **kwargs):
250
+ return while_loop_op(*args, **kwargs)
251
+
252
+ from torch._higher_order_ops.utils import setup_compilation_env
253
+
254
+ with setup_compilation_env() as backend:
255
+ return torch.compile(_while_loop_op_wrapper, backend=backend, fullgraph=True)(
256
+ flat_cond_fn, flat_body_fn, tuple(flat_inputs), tuple()
257
+ )
258
+
259
+
260
+ @while_loop_op.py_impl(DispatchKey.CompositeExplicitAutograd)
261
+ def while_loop_dense(
262
+ cond_fn, body_fn, carried_inputs, additional_inputs, stack_output=False
263
+ ):
264
+ carried_vals = carried_inputs
265
+
266
+ def _validate_cond_output(pred):
267
+ if (
268
+ isinstance(pred, torch.Tensor)
269
+ and pred.size() == torch.Size([])
270
+ and pred.dtype == torch.bool
271
+ ) or isinstance(pred, bool):
272
+ return
273
+ else:
274
+ raise RuntimeError(
275
+ f"cond_fn must return a boolean scalar tensor or a boolean but got {pred}"
276
+ )
277
+
278
+ if not isinstance(carried_inputs, (tuple, list)):
279
+ raise RuntimeError(
280
+ f"carried_inputs must be a tuple or list but got {type(carried_inputs)}"
281
+ )
282
+
283
+ # Check condition and set up flag
284
+ should_loop = cond_fn(*carried_vals, *additional_inputs)
285
+ _validate_cond_output(should_loop)
286
+
287
+ if not should_loop:
288
+ if stack_output:
289
+ return tuple(
290
+ val.unsqueeze(0).clone() if isinstance(val, torch.Tensor) else val
291
+ for val in carried_vals
292
+ )
293
+ else:
294
+ return tuple(
295
+ val.clone() if isinstance(val, torch.Tensor) else val
296
+ for val in carried_vals
297
+ )
298
+
299
+ outputs: list[list[torch.Tensor]] = [[] for _ in carried_vals]
300
+
301
+ while should_loop:
302
+ out = body_fn(*carried_vals, *additional_inputs)
303
+ if stack_output:
304
+ for i, o in enumerate(out):
305
+ outputs[i].append(o)
306
+
307
+ if not isinstance(out, tuple):
308
+ raise AssertionError(f"body_fn should return a tuple but got {type(out)}")
309
+ if len(out) != len(carried_inputs):
310
+ raise AssertionError(
311
+ f"body_fn should return the same number of elements as carried_inputs, got {len(out)} vs {len(carried_inputs)}"
312
+ )
313
+ carried_vals = out
314
+
315
+ should_loop = cond_fn(*carried_vals, *additional_inputs)
316
+
317
+ if stack_output:
318
+ outs: list[torch.Tensor] = []
319
+ for out in outputs:
320
+ outs.append(torch.stack(out, dim=0))
321
+ return tuple(outs)
322
+
323
+ return carried_vals
324
+
325
+
326
+ @while_loop_op.py_autograd_impl
327
+ def while_loop_autograd(cond_fn, body_fn, operands, additional_inputs):
328
+ return WhileLoopAutogradOp.apply(
329
+ cond_fn,
330
+ body_fn,
331
+ len(operands),
332
+ len(additional_inputs),
333
+ *operands,
334
+ *additional_inputs,
335
+ )
336
+
337
+
338
+ def _find_or_create_fake_mode() -> FakeTensorMode:
339
+ from torch.fx.experimental.symbolic_shapes import ShapeEnv
340
+
341
+ fake_mode = torch._guards.detect_fake_mode()
342
+ if fake_mode is None:
343
+ fake_mode = FakeTensorMode(shape_env=ShapeEnv())
344
+
345
+ return fake_mode
346
+
347
+
348
+ def _create_unbacked_symint(
349
+ fake_mode: FakeTensorMode, ignore_fresh_unbacked_symbols: bool
350
+ ) -> torch.SymInt:
351
+ if fake_mode is None or fake_mode.shape_env is None:
352
+ raise AssertionError("Must provide a fake_mode with shape_env.")
353
+ ctx = (
354
+ contextlib.nullcontext()
355
+ if not ignore_fresh_unbacked_symbols
356
+ else fake_mode.shape_env.ignore_fresh_unbacked_symbols()
357
+ )
358
+ with ctx:
359
+ return fake_mode.shape_env.create_unbacked_symint()
360
+
361
+
362
+ @while_loop_op.py_impl(ProxyTorchDispatchMode)
363
+ def while_loop_tracing(
364
+ mode,
365
+ cond_fn,
366
+ body_fn,
367
+ carried_inputs,
368
+ additional_inputs,
369
+ stack_output=False,
370
+ ):
371
+ op = while_loop_stack_output_op if stack_output else while_loop_op
372
+
373
+ def _trace_while_loop(
374
+ proxy_mode, op, cond_fn, body_fn, carried_inputs, additional_inputs
375
+ ):
376
+ # NOTE [unspecialize int carry with unbacked symints]
377
+ # When we support int carry, we'll also need to support int output of body_fn because.
378
+ # previous iteration's output is next iteration's input and they must match.
379
+ # For carries, when we start tracing while_loop, they can be
380
+ # - constants e.g. (0, [1, 3])
381
+ # - backed symints (x.shape[0], [x.shape[1] + x.stride[1], x.shape[2]])
382
+ # - unbacked symints e.g. (u0, [u0 + u1, u2])
383
+ # We choose the most conservative design: in all cases, we create new unbacked symints to trace the
384
+ # subgraph. It's possible to do some analysis on initial carry and the output of first
385
+ # iteration to determine a better range for the output unbacked symbol e.g. when input is an unbacked
386
+ # symint >= 0 before the while_loop but in general this is difficult because we don't know
387
+ # the number of iterations. Users would have to re-constrain the unbacked symint in subgraph if needed.
388
+ #
389
+ # For output of fake cond_fn, it could be constant bool or SymBool (e.g. return x.shape[0] < 4,
390
+ # where x.shape[0] can be either static of dynamic). In the case of constant bool, we should do a
391
+ # specialization (NYI).
392
+
393
+ # For output of fake body_fn, it could be all three types though from user's point of view,
394
+ # they're all integers e.g.
395
+
396
+ # init_carry = (0, s0, u1, t)
397
+ # def body_fn(u0, s0, u1, t):
398
+ # ...
399
+ # return (t.shape[0], t.shape[1], t.shape[2], y + 1)
400
+ #
401
+ # It may seem that a constant output isn't possible: users shouldn't write a while_loop
402
+ # that always return 0. But it could be that a shape is not set as dynamic properly (e.g.
403
+ # automatic dynamic hasn't been triggered).
404
+ #
405
+ # For this reason, we treat int, symint outputs in the same way:
406
+ # - they can match against any of int, symint carry
407
+ # - we unspecialize them with new unbacked symints in fake while_loop
408
+ # Similarly, we could do some analysis to refine the output ranges but it's easier to start with
409
+ # fresh unbacked symints. One surprising case can be: an input unbacked symint is constrained by
410
+ # users to be >= 0 (either before while_loop or inside body_fn) and it increments by 1 in each
411
+ # iteration. Ideally, we should know that the final output is >= 0 but we didn't constrain the
412
+ # unbacked symint output of subgraph as of today because this requires a smart range analysis.
413
+ fake_mode: FakeTensorMode = _find_or_create_fake_mode()
414
+
415
+ def _unspecialize_carried_inputs(x):
416
+ if isinstance(x, (int, torch.SymInt)):
417
+ return _create_unbacked_symint(
418
+ fake_mode, ignore_fresh_unbacked_symbols=True
419
+ )
420
+ # Note: [unspecialize constant tensor carry]
421
+ # We need to disable constant specialization for tensor inputs that become loop carries.
422
+ # Here's the problem: when a user creates a constant tensor e.g. torch.tensor(0), PyTorch calls aten.lift_fresh_copy
423
+ # to create a safe copy (avoiding aliasing issues), which creates a FakeTensor with constant=True.
424
+ # But when this FakeTensor becomes a loop carry, we have a problem:
425
+ # - Operations like .item() will read the constant value and bake it into the traced code
426
+ # - This is incorrect because carry variables change between loop iterations
427
+ # - The traced code would use the wrong constant value for all iterations
428
+ # Solution: We clone the constant tensors and mark the cloned tensor as non-constant so they won't
429
+ # be specialized to fixed values during tracing body_fn or cond_fn.
430
+ elif isinstance(x, torch.Tensor):
431
+ x = x.clone()
432
+ if hasattr(x, "constant") and x.constant is not None:
433
+ # pyrefly: ignore [missing-attribute]
434
+ x.constant = None
435
+ return x
436
+
437
+ with disable_proxy_modes_tracing():
438
+ unspecialized_carried_inputs = pytree.tree_map_only(
439
+ (int, torch.SymInt, torch.Tensor),
440
+ # For temporarily created unbacked symints, we don't need to bind them to any proxy
441
+ lambda x: _unspecialize_carried_inputs(x),
442
+ carried_inputs,
443
+ )
444
+
445
+ def produce_graph(fn):
446
+ cloned_carried_inputs = pytree.tree_map_only(
447
+ torch.Tensor, lambda x: x.clone(), unspecialized_carried_inputs
448
+ )
449
+ return reenter_make_fx(fn)(*cloned_carried_inputs, *additional_inputs)
450
+
451
+ cond_graph = produce_graph(cond_fn)
452
+ body_graph = produce_graph(body_fn)
453
+
454
+ next_name = None
455
+ i = 0
456
+ # pyrefly: ignore [bad-assignment]
457
+ while not next_name:
458
+ candidate = f"while_loop_cond_graph_{i}"
459
+ if hasattr(proxy_mode.tracer.root, candidate):
460
+ i += 1
461
+ else:
462
+ next_name = candidate
463
+ cond_graph_name = next_name
464
+ body_graph_name = f"while_loop_body_graph_{i}"
465
+ if hasattr(proxy_mode.tracer.root, body_graph_name):
466
+ raise AssertionError(
467
+ f"proxy_mode.tracer.root already has attribute {body_graph_name}"
468
+ )
469
+
470
+ proxy_mode.tracer.root.register_module(cond_graph_name, cond_graph)
471
+ proxy_mode.tracer.root.register_module(body_graph_name, body_graph)
472
+
473
+ args = (cond_graph, body_graph, carried_inputs, additional_inputs)
474
+
475
+ proxy_args = pytree.tree_map(proxy_mode.tracer.unwrap_proxy, args)
476
+
477
+ out_proxy = proxy_mode.tracer.create_proxy(
478
+ "call_function", op, proxy_args, {}, name=op._name
479
+ )
480
+
481
+ out = op(
482
+ cond_graph, body_graph, unspecialized_carried_inputs, additional_inputs
483
+ )
484
+ return track_tensor_tree(
485
+ out, out_proxy, constant=None, tracer=proxy_mode.tracer
486
+ )
487
+
488
+ return _trace_while_loop(
489
+ mode,
490
+ op,
491
+ cond_fn,
492
+ body_fn,
493
+ carried_inputs,
494
+ additional_inputs,
495
+ )
496
+
497
+
498
+ @while_loop_op.py_impl(FakeTensorMode)
499
+ def while_loop_fake_tensor_mode(
500
+ mode, cond_fn, body_fn, carried_inputs, additional_inputs, stack_output=False
501
+ ):
502
+ with mode:
503
+ # NOTE: [Handling unback symints in subgraph of while_loop]
504
+ # The idea is that the scope of unbacked symints are limited to the subgraph.
505
+ #
506
+ # We're implementing the fake tensor mode of while_loop operator.
507
+ # and we run body_fn once to get an fake output.
508
+ # Let's first consider the case that unbacked symints are tensor shapes:
509
+ #
510
+ # Case 1:
511
+ # if the unbacked symints is local to the subgraph e.g.
512
+ # def body_fn(it, x):
513
+ # nz = x.nonzero()
514
+ # return it+1. nz.sum()
515
+ # we can just ignore the newly created unbacked symints because it has
516
+ # no effect on the output of while_loop and it's tracked when we tracing.
517
+ # the subgraph.
518
+ #
519
+ # Case 2:
520
+ # if the unbacked symints are shape of output of while_loop e.g.
521
+ # def body_fn(it, x):
522
+ # nz = x.nonzero()
523
+ # return it+1, nz
524
+ # This will fail the shape check because in each iteration, the carried_input's shape
525
+ # must match the output shape as nz.shape contains newly allocated unbacked symint, this
526
+ # won't match the carried_input's shape.
527
+ #
528
+ # Case 3:
529
+ # if the unbacked symints are shape of carried_inputs e.g.
530
+ # nz = a.nonzero()
531
+ # body_fn(it, nz):
532
+ # return it+1. nz.sin() + 1,
533
+ # There's no new unbacked symints allocated in subgraph, so we're safe.
534
+ with mode.shape_env.ignore_fresh_unbacked_symbols():
535
+ # body_fn return output with the same pytree and tensor meta data as carried_inputs
536
+ # so we could just return the output after one iteration.
537
+ body_outs = body_fn(*carried_inputs, *additional_inputs)
538
+ check_meta_consistency(
539
+ carried_inputs,
540
+ body_outs,
541
+ "carried_inputs",
542
+ "body_output",
543
+ include_contiguity=False,
544
+ )
545
+
546
+ if stack_output:
547
+ n_iter = _create_unbacked_symint(mode, ignore_fresh_unbacked_symbols=False)
548
+ if not all(isinstance(x, torch.Tensor) for x in carried_inputs):
549
+ raise AssertionError(
550
+ f"all carried_inputs must be tensors for stack_output, got {[type(x) for x in carried_inputs]}"
551
+ )
552
+ fake_outputs = tuple(
553
+ out.clone()
554
+ .unsqueeze(0)
555
+ .repeat((n_iter,) + tuple(1 for _ in range(out.dim())))
556
+ for out in body_outs
557
+ )
558
+ return pytree.tree_map_only(
559
+ (int, torch.SymInt),
560
+ # For while_loop's unbacked symint output, we want them to be bound
561
+ # to the proxy of while_loop's output.
562
+ lambda _: _create_unbacked_symint(
563
+ mode, ignore_fresh_unbacked_symbols=False
564
+ ),
565
+ fake_outputs,
566
+ )
567
+
568
+ # See NOTE [unspecialize int carry with unbacked symints]
569
+ return pytree.tree_map_only(
570
+ (int, torch.SymInt),
571
+ # For while_loop's unbacked symint output, we want them to be bound
572
+ # to the proxy of while_loop's output.
573
+ lambda _: _create_unbacked_symint(
574
+ mode, ignore_fresh_unbacked_symbols=False
575
+ ),
576
+ body_outs,
577
+ )
578
+
579
+
580
+ @while_loop_op.py_functionalize_impl
581
+ def while_loop_func(
582
+ ctx, cond_fn, body_fn, carried_inputs, additional_inputs, stack_output=False
583
+ ):
584
+ from torch._higher_order_ops.utils import _check_alias_and_mutation
585
+
586
+ op = while_loop_stack_output_op if stack_output else while_loop_op
587
+
588
+ unwrapped_carried_inputs = ctx.unwrap_tensors(carried_inputs)
589
+ unwrapped_additional_inputs = ctx.unwrap_tensors(additional_inputs)
590
+ unwrapped_inputs = unwrapped_carried_inputs + unwrapped_additional_inputs
591
+ with ctx.redispatch_to_next():
592
+ functional_cond_fn = ctx.functionalize(_maybe_run_with_interpreter(cond_fn))
593
+ functional_body_fn = ctx.functionalize(_maybe_run_with_interpreter(body_fn))
594
+ pre_dispatch = hasattr(ctx, "mode") and ctx.mode.pre_dispatch
595
+ for fn, fn_name in [
596
+ (cond_fn, "cond_fn"),
597
+ (body_fn, "body_fn"),
598
+ ]:
599
+ _check_alias_and_mutation(fn, unwrapped_inputs, fn_name, pre_dispatch)
600
+ ret = op(
601
+ functional_cond_fn,
602
+ functional_body_fn,
603
+ unwrapped_carried_inputs,
604
+ unwrapped_additional_inputs,
605
+ )
606
+ return ctx.wrap_tensors(ret)
607
+
608
+
609
+ class WhileLoopStackOutputOp(HigherOrderOperator):
610
+ """
611
+ while_loop_stack_output is a variant of while_loop that returns a stack of outputs.
612
+ Its semantic can be illurated using python code as:
613
+ def while_loop_stack_output(cond_fn, body_fn, carried_inputs, additional_inputs):
614
+ outs = []
615
+ while cond_fn(*carried_inputs, *additional_inputs):
616
+ out = body_fn(*carried_inputs, *additional_inputs)
617
+ outs.append(out)
618
+ return torch.stack(outs)
619
+
620
+ It's useful for supporting autograd of while_loop.
621
+ """
622
+
623
+ def __init__(self) -> None:
624
+ super().__init__("while_loop_stack_output")
625
+
626
+ def __call__(
627
+ self,
628
+ cond_fn: Callable,
629
+ body_fn: Callable,
630
+ carried_inputs: tuple[Union[torch.Tensor, int, float, bool]],
631
+ additional_inputs: tuple[Union[torch.Tensor, torch.SymInt, int], ...],
632
+ /,
633
+ ):
634
+ if not isinstance(carried_inputs, (tuple, list)):
635
+ raise RuntimeError(
636
+ f"carried_inputs must be a tuple or list, got {type(carried_inputs)}"
637
+ )
638
+ if not isinstance(additional_inputs, (tuple, list)):
639
+ raise RuntimeError(
640
+ f"additional_inputs must be a tuple or list, got {type(additional_inputs)}"
641
+ )
642
+
643
+ validate_subgraph_args_types(carried_inputs)
644
+ validate_subgraph_args_types(additional_inputs)
645
+ # pyrefly: ignore [missing-attribute]
646
+ return super().__call__(cond_fn, body_fn, carried_inputs, additional_inputs)
647
+
648
+
649
+ # Note [while_loop autograd]
650
+ # Consider wthe following while_loop that can be visualized as:
651
+ # additional_inputs
652
+ # ┌─────┬─────┼─────┬─────┐
653
+ # | | | | |
654
+ # ↓ ↓ ↓ ↓ ↓
655
+ # x ──→ y0 ─→ y1 ─→ y2 ─→ y3 ─→ y4
656
+ #
657
+ # The bacwkard can be visualized as follows:
658
+ #
659
+ # g_additional_inputs
660
+ # ┌──────┬──────┼──────┬──────┐
661
+ # | | | | |
662
+ # | | | | |
663
+ # gx <── gy0 <─ gy1 <─ gy2 <─ gy3 <─ gy4
664
+ #
665
+ # We can compute gx using chain rule:
666
+ #
667
+ # gx = gy0 * bw(y0, x),
668
+ #
669
+ # where gy0 denotes the gradient of loss with respect to y0, and bw(y0, x) denotes the gradient of y0 with
670
+ # respect to x. Note that bw can be computed from forward body_fn easily using torch.autograd.grad.
671
+ # We could substitute the unknowns gy0, gy1, ..., with chain rule until gy4:
672
+ #
673
+ # gx = gy1 * bw(y1, y0) * bw(y0, x)
674
+ # = gy2 * bw(y2, y1) * bw(y1, y0) * bw(y0, x)
675
+ # = ...
676
+ # = gy4 * bw(y4, y3) * bw(y3, y2) * bw(y2, y1) * bw(y1, y0) * bw(y0, x)
677
+ #
678
+ # since gy4 is the graient of the final output, which is given as the backward input, we've got a formula
679
+ # to compute gx. A abbr for the formula is: gy4 * bw43210x
680
+ #
681
+ # In a similar way, we can compute g_additional_inputs using chain rule:
682
+ #
683
+ # g_additional_inputs = gy0 * bw(y0, addi) + gy1 * bw(y1, addi) + gy2 * bw(y2, addi) + ... + gy4 * bw(y4, addi)
684
+ #
685
+ # Notice that gy0 = gy4 * bw43210, gy1 = gy4 * bw4321 etc, we now also get a formula for g_additional_inputs.
686
+ #
687
+ # Implementation:
688
+ # The idea of implementation is to construct a while_loop to calculate both gx and g_additional_inputs.
689
+ # Specifically, we can implement the backward of while_loop with as follows:
690
+ #
691
+ # def cond_fn(idx, grad_carries, grad_additional_inputs, fw_additional_inputs, fw_inps):
692
+ # return idx < fw_inps.size(0)
693
+ #
694
+ # def body_fn(idx, grad_carries, grad_additional_inputs, fw_additional_inputs, fw_inps):
695
+ # reversed_idx = fw_inps.size(0) - 1 - idx
696
+ # next_grad_carry, next_grad_additional_inputs = bw(fw_inps[reversed_idx], fw_additional_inputs, grad_carries)
697
+ # return idx + 1, next_grad_carry, next_grad_additional_inputs + grad_additional_inputs
698
+ #
699
+ # idx = 0
700
+ # init_grad_carries = grads
701
+ # init_grad_additional_inputs = torch.zeros_like(g_additional_inputs)
702
+ # fw_inps = torch.cat([ctx.fw_carried_inputs, fw_outputs[:-1]])
703
+ # while_loop(cond_fn, body_fn, (idx, init_grad_carries, init_grad_additional_inputs,), (fw_additional_inputs, fw_inps))
704
+
705
+
706
+ class WhileLoopAutogradOp(torch.autograd.Function):
707
+ @staticmethod
708
+ # pyrefly: ignore [bad-override]
709
+ def forward(
710
+ ctx,
711
+ cond_fn,
712
+ body_fn,
713
+ num_carried_inputs,
714
+ num_additional_inputs,
715
+ *carries_and_inputs,
716
+ ):
717
+ from torch._higher_order_ops.scan import split_into_chunks
718
+
719
+ carries, additional_inputs = split_into_chunks(
720
+ carries_and_inputs, [num_carried_inputs, num_additional_inputs]
721
+ )
722
+ with torch._C._AutoDispatchBelowAutograd():
723
+ fw_outputs = while_loop_stack_output_op(
724
+ cond_fn, body_fn, carries, additional_inputs
725
+ )
726
+
727
+ if hasattr(ctx, "fw_cond_fn"):
728
+ raise AssertionError("ctx already has fw_cond_fn attribute")
729
+ if hasattr(ctx, "fw_body_fn"):
730
+ raise AssertionError("ctx already has fw_body_fn attribute")
731
+ if hasattr(ctx, "carries"):
732
+ raise AssertionError("ctx already has carries attribute")
733
+ if hasattr(ctx, "additional_inputs"):
734
+ raise AssertionError("ctx already has additional_inputs attribute")
735
+ if hasattr(ctx, "fw_outputs"):
736
+ raise AssertionError("ctx already has fw_outputs attribute")
737
+ ctx.fw_cond_fn = cond_fn
738
+ ctx.fw_body_fn = body_fn
739
+ ctx.carries = carries
740
+ ctx.additional_inputs = additional_inputs
741
+ ctx.fw_outputs = fw_outputs
742
+ loop_count = None
743
+ # pyrefly: ignore [bad-assignment]
744
+ for out in fw_outputs:
745
+ if isinstance(out, torch.Tensor):
746
+ if loop_count is not None:
747
+ if out.size(0) != loop_count:
748
+ raise AssertionError(
749
+ f"inconsistent loop_count: expected {loop_count}, got {out.size(0)}"
750
+ )
751
+ else:
752
+ loop_count = out.size(0)
753
+ if loop_count is None:
754
+ raise AssertionError(
755
+ "loop_count must not be None after processing fw_outputs"
756
+ )
757
+
758
+ # Remove the loop_count from pending_fresh_unbacked_symbols
759
+ # because it's not part of forward output and it's impossible
760
+ # to bind it to a proxy in forward graph anyways.
761
+ if (
762
+ isinstance(loop_count, torch.SymInt)
763
+ and (shape_env := loop_count.node.shape_env)
764
+ and loop_count in shape_env.pending_fresh_unbacked_symbols
765
+ ):
766
+ shape_env.pending_fresh_unbacked_symbols.remove(loop_count)
767
+
768
+ # Even when body function is not executed, we clone and unsqueeze the input
769
+ # to avoid the aliasing, therefore loop_count is always >= 1
770
+ torch._check(loop_count >= 1)
771
+ # We snapshot the dispatch keys in forward for materializing the
772
+ # the bw_graph in backward.
773
+ ctx._fw_include_key_set = torch._C._dispatch_tls_local_include_set()
774
+ ctx._fw_exclude_key_set = torch._C._dispatch_tls_local_exclude_set()
775
+ if len(fw_outputs) <= 0:
776
+ raise AssertionError("fw_outputs shouldn't be empty")
777
+ # Only the last of the output fw_outputs need to be returned
778
+ return tuple(ckp[-1] for ckp in fw_outputs)
779
+
780
+ @staticmethod
781
+ def backward(ctx, *grads):
782
+ from torch._higher_order_ops.cond import create_bw_fn
783
+ from torch._higher_order_ops.scan import split_into_chunks
784
+
785
+ # set up single step bw fn
786
+ bw_body_fn = create_bw_fn(ctx.fw_body_fn, ctx.carries + ctx.additional_inputs)
787
+ # Note [Handle inputs that're not differentiable]
788
+ # When a forward input is non-differentiable e.g. a symint or an integer tensor, their gradients
789
+ # will be None. However, we don't want to return None in the subgraph because this complicates the
790
+ # inductor codegen, where we need to do a non-uniform treatment for None and tensors.
791
+ # So we set up masks and filter the None gradients so that only tensors are returned from each step.
792
+ carries_tensor_masks = [
793
+ bool(isinstance(t, torch.Tensor) and t.dtype.is_floating_point)
794
+ for t in ctx.carries
795
+ ]
796
+ additional_inputs_tensor_masks = [
797
+ bool(isinstance(t, torch.Tensor) and t.dtype.is_floating_point)
798
+ for t in ctx.additional_inputs
799
+ ]
800
+
801
+ init_idx = torch.zeros((), dtype=torch.int64)
802
+ init_grad_carries = filter_with_masks(grads, carries_tensor_masks) # type: ignore[arg-type]
803
+ init_grad_additional_inputs = tuple(
804
+ torch.zeros_like(t)
805
+ for need_keep, t in zip(
806
+ additional_inputs_tensor_masks, ctx.additional_inputs
807
+ )
808
+ if need_keep
809
+ )
810
+ # We need to the forward inputs to each iteration to compute the backward
811
+ # which is the concatenation of first iteraiton input i.e. ctx.carries and all iterations's
812
+ # output except the last iteration.
813
+ fw_carries = [
814
+ torch.cat([carry.unsqueeze(0), carries[:-1]])
815
+ for carry, carries in zip(ctx.carries, ctx.fw_outputs)
816
+ ]
817
+ for fw_carry, carry in zip(fw_carries, ctx.carries):
818
+ fw_carry.requires_grad_(carry.requires_grad)
819
+
820
+ _, spec = pytree.tree_flatten(
821
+ (
822
+ init_idx,
823
+ init_grad_carries,
824
+ init_grad_additional_inputs,
825
+ ctx.fw_outputs,
826
+ ctx.additional_inputs,
827
+ )
828
+ )
829
+
830
+ def cond_fn(*flat_args):
831
+ (
832
+ idx,
833
+ grad_carries,
834
+ grad_additional_inputs,
835
+ fw_carries,
836
+ additional_inputs,
837
+ ) = pytree.tree_unflatten(flat_args, spec)
838
+ if not isinstance(fw_carries[0], torch.Tensor):
839
+ raise AssertionError(
840
+ f"expected fw_carries[0] to be torch.Tensor, got {type(fw_carries[0])}"
841
+ )
842
+ # excluding the last iteration's output
843
+ return idx < fw_carries[0].size(0)
844
+
845
+ def body_fn(*flat_args):
846
+ (
847
+ idx,
848
+ grad_carries,
849
+ grad_additional_inputs,
850
+ fw_carries,
851
+ additional_inputs,
852
+ ) = pytree.tree_unflatten(flat_args, spec)
853
+ reversed_idx = fw_carries[0].size(0) - idx - 1
854
+ selected_fw_carries = [
855
+ ckp.select(0, reversed_idx.item()) for ckp in fw_carries
856
+ ]
857
+ cur_grad_carries, cur_grad_additional_inputs = split_into_chunks(
858
+ bw_body_fn(*selected_fw_carries, *additional_inputs, *grad_carries),
859
+ [len(ctx.carries), len(ctx.additional_inputs)],
860
+ )
861
+ if not all(isinstance(t, torch.Tensor) for t in cur_grad_carries):
862
+ raise AssertionError(
863
+ f"all cur_grad_carries must be tensors, got {[type(t) for t in cur_grad_carries]}"
864
+ )
865
+ cur_grad_carries_tensors = filter_with_masks(
866
+ cur_grad_carries, carries_tensor_masks
867
+ )
868
+ cur_grad_additional_inputs_tensors = filter_with_masks(
869
+ cur_grad_additional_inputs, additional_inputs_tensor_masks
870
+ )
871
+ return (
872
+ idx + 1,
873
+ *cur_grad_carries_tensors,
874
+ *(
875
+ cur_grad + grad
876
+ for cur_grad, grad in zip(
877
+ cur_grad_additional_inputs_tensors, grad_additional_inputs
878
+ )
879
+ ),
880
+ )
881
+
882
+ args_single_step_bw = (
883
+ init_idx,
884
+ *init_grad_carries,
885
+ *init_grad_additional_inputs,
886
+ *fw_carries,
887
+ *ctx.additional_inputs,
888
+ )
889
+
890
+ cond_gm = materialize_as_graph(
891
+ cond_fn,
892
+ args_single_step_bw,
893
+ ctx._fw_include_key_set,
894
+ ctx._fw_exclude_key_set,
895
+ force_enable_grad=True,
896
+ )
897
+
898
+ body_gm = materialize_as_graph(
899
+ body_fn,
900
+ args_single_step_bw,
901
+ ctx._fw_include_key_set,
902
+ ctx._fw_exclude_key_set,
903
+ force_enable_grad=True,
904
+ )
905
+
906
+ _, final_grad_carries, final_grad_additional_inputs = split_into_chunks(
907
+ while_loop_op(
908
+ # pyrefly: ignore [bad-argument-type]
909
+ cond_gm,
910
+ # pyrefly: ignore [bad-argument-type]
911
+ body_gm,
912
+ # pyrefly: ignore [bad-argument-type]
913
+ (
914
+ init_idx,
915
+ *init_grad_carries,
916
+ *init_grad_additional_inputs,
917
+ ),
918
+ (*fw_carries, *ctx.additional_inputs),
919
+ ),
920
+ [1, len(init_grad_carries), len(init_grad_additional_inputs)],
921
+ )
922
+ return (
923
+ None,
924
+ None,
925
+ None,
926
+ None,
927
+ *fill_none_with_masks(final_grad_carries, carries_tensor_masks),
928
+ *fill_none_with_masks(
929
+ final_grad_additional_inputs, additional_inputs_tensor_masks
930
+ ),
931
+ )
932
+
933
+
934
+ while_loop_stack_output_op = WhileLoopStackOutputOp()
935
+
936
+ while_loop_stack_output_op.py_impl(DispatchKey.CompositeExplicitAutograd)(
937
+ functools.partial(while_loop_dense, stack_output=True)
938
+ )
939
+
940
+ while_loop_stack_output_op.py_impl(ProxyTorchDispatchMode)(
941
+ functools.partial(while_loop_tracing, stack_output=True)
942
+ )
943
+
944
+ while_loop_stack_output_op.py_impl(FakeTensorMode)(
945
+ functools.partial(while_loop_fake_tensor_mode, stack_output=True)
946
+ )
947
+
948
+ while_loop_stack_output_op.py_functionalize_impl(
949
+ functools.partial(while_loop_func, stack_output=True)
950
+ )
951
+
952
+ while_loop_stack_output_op.py_autograd_impl(
953
+ autograd_not_implemented(while_loop_stack_output_op, deferred_error=True)
954
+ )
.venv/lib/python3.10/site-packages/torch/_higher_order_ops/wrap.py ADDED
@@ -0,0 +1,394 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import inspect
3
+ import itertools
4
+ import logging
5
+ from typing import Any, Optional
6
+
7
+ import torch
8
+ import torch.utils._pytree as pytree
9
+ from torch._C import DispatchKey
10
+ from torch._higher_order_ops.utils import (
11
+ redirect_to_mode,
12
+ reenter_make_fx,
13
+ register_fake,
14
+ )
15
+ from torch._logging import warning_once
16
+ from torch._ops import HigherOrderOperator
17
+ from torch.fx import GraphModule
18
+ from torch.fx.experimental.proxy_tensor import ProxyTorchDispatchMode, track_tensor_tree
19
+ from torch.types import _dtype
20
+ from torch.utils._debug_mode import DebugMode
21
+ from torch.utils.checkpoint import _CachedTorchDispatchMode, _CachingTorchDispatchMode
22
+
23
+
24
+ log = logging.getLogger(__name__)
25
+
26
+ uid = itertools.count(1)
27
+
28
+
29
+ # Used for testing the HigherOrderOperator mechanism
30
+ class Wrap(HigherOrderOperator):
31
+ def __init__(self) -> None:
32
+ super().__init__("wrap")
33
+
34
+ def __call__(self, func, *args, **kwargs):
35
+ # Dynamo already traces the body of HigherOrderOp beforehand when it
36
+ # so no need to trace into it.
37
+ import torch._dynamo # noqa: F401
38
+ from torch._dynamo import disable
39
+
40
+ @disable
41
+ def wrapper():
42
+ result = func(*args, **kwargs)
43
+ return result
44
+
45
+ return wrapper()
46
+
47
+
48
+ wrap = Wrap()
49
+
50
+
51
+ class InductorCompiledCode(HigherOrderOperator):
52
+ """
53
+ Defines a HOP for wrapping inductor compiled functions as a callable.
54
+ When used with torch.compile via "wrap_inductor_compiled_regions",
55
+ this HOP will automatically be wrapped and redirect various torch dispatch modes.
56
+ """
57
+
58
+ def __init__(self) -> None:
59
+ super().__init__("inductor_compiled_code")
60
+
61
+ def __call__(self, func, *args, **kwargs):
62
+ # pyrefly: ignore [missing-attribute]
63
+ return super().__call__(func, *args, **kwargs)
64
+
65
+
66
+ inductor_compiled_code = InductorCompiledCode()
67
+ inductor_compiled_code.fallthrough(DispatchKey.AutogradCPU)
68
+ inductor_compiled_code.fallthrough(DispatchKey.AutogradCUDA)
69
+
70
+
71
+ @inductor_compiled_code.py_impl(DispatchKey.CompositeExplicitAutograd)
72
+ def inductor_compiled_code_impl(func, inputs):
73
+ return func(inputs)
74
+
75
+
76
+ redirect_to_mode(inductor_compiled_code, DebugMode)
77
+ redirect_to_mode(inductor_compiled_code, _CachingTorchDispatchMode)
78
+ redirect_to_mode(inductor_compiled_code, _CachedTorchDispatchMode)
79
+
80
+
81
+ @register_fake(inductor_compiled_code)
82
+ def inductor_compiled_code_fake(func, inputs):
83
+ raise RuntimeError(
84
+ "Inductor compiled code cannot be run with FakeTensor inputs. "
85
+ "This can happen when torch.compile is called inside a FakeTensorMode. "
86
+ "Consider using backend='eager' or backend='aot_eager' instead."
87
+ )
88
+
89
+
90
+ class WrapWithSetGradEnabled(HigherOrderOperator):
91
+ def __init__(self) -> None:
92
+ super().__init__("wrap_with_set_grad_enabled")
93
+
94
+ def __call__(self, enable_grad, wrapped_func, *args, **kwargs):
95
+ # Dynamo already traces the body of HigherOrderOp beforehand when it
96
+ # so no need to trace into it.
97
+ import torch._dynamo # noqa: F401
98
+ from torch._dynamo import disable
99
+
100
+ @disable
101
+ def wrapper():
102
+ prev = torch.is_grad_enabled()
103
+ torch.set_grad_enabled(enable_grad)
104
+ res = wrapped_func(*args, **kwargs)
105
+ torch.set_grad_enabled(prev)
106
+ return res
107
+
108
+ return wrapper()
109
+
110
+
111
+ wrap_with_set_grad_enabled = WrapWithSetGradEnabled()
112
+
113
+
114
+ class WrapWithAutocast(HigherOrderOperator):
115
+ def __init__(self):
116
+ super().__init__("wrap_with_autocast")
117
+
118
+ def __call__(
119
+ self,
120
+ device_type: str,
121
+ dtype: Optional[_dtype],
122
+ enabled: bool,
123
+ cache_enabled: Optional[bool],
124
+ wrapped_func,
125
+ *args,
126
+ **kwargs,
127
+ ):
128
+ # Dynamo already traces the body of HigherOrderOp beforehand when it
129
+ # so no need to trace into it.
130
+ import torch._dynamo # noqa: F401
131
+ from torch._dynamo import disable
132
+
133
+ @disable
134
+ def wrapper():
135
+ with torch.autocast(device_type, dtype, enabled, cache_enabled):
136
+ return wrapped_func(*args, **kwargs)
137
+
138
+ return wrapper()
139
+
140
+
141
+ wrap_with_autocast = WrapWithAutocast()
142
+
143
+
144
+ # This HOP allows you to bypass dynamo tracing of the wrapper function while
145
+ # still tracing the inner function.
146
+ # Takes two callables: The first, `wrapper_fn`, accepts `inner_fn` and returns a
147
+ # callable with the same signature. The second is the `inner_fn` itself. Any
148
+ # extra *args and **kwargs are forwarded to `wrapper_fn(inner_fn)` when it is
149
+ # executed.
150
+ class DynamoBypassingWrapper(HigherOrderOperator):
151
+ def __init__(self):
152
+ super().__init__("dynamo_bypassing_wrapper")
153
+
154
+ def __call__(
155
+ self,
156
+ wrapper_fn_or_key,
157
+ inner_fn,
158
+ *args,
159
+ **kwargs,
160
+ ):
161
+ # Dynamo already traces the body of HigherOrderOp beforehand when it
162
+ # so no need to trace into it.
163
+ import torch._dynamo # noqa: F401
164
+ from torch._dynamo import disable
165
+
166
+ is_compiling = isinstance(wrapper_fn_or_key, str)
167
+ if is_compiling:
168
+ if not isinstance(inner_fn, torch.fx.GraphModule):
169
+ raise AssertionError(
170
+ f"expected inner_fn to be torch.fx.GraphModule, got {type(inner_fn)}"
171
+ )
172
+ wrapper_fn = inner_fn.meta[wrapper_fn_or_key]
173
+ else:
174
+ wrapper_fn = wrapper_fn_or_key
175
+
176
+ @disable
177
+ def wrapper():
178
+ return wrapper_fn(inner_fn)(*args, **kwargs)
179
+
180
+ return wrapper()
181
+
182
+
183
+ dynamo_bypassing_wrapper = DynamoBypassingWrapper()
184
+
185
+
186
+ class WrapActivationCheckpoint(HigherOrderOperator):
187
+ """
188
+ This operator is used to wrap torch.utils.checkpoint. This avoids
189
+ TorchDynamo to look into saved tensor hooks and directly passes the control
190
+ to AOT Autograd, which is ok with tracing saved tensor hooks. As a result of
191
+ AOT tracing torch.utils.checkpoint code, we have a backward graph with
192
+ recomputed forward nodes.
193
+
194
+ However, we might deprecate this operator soon. The difficulty arises in the
195
+ functionalization of rng ops. Today, there are two different
196
+ functionalization of rng ops - one at AOT autograd and other at Inductor.
197
+ And they are difficult to map to each other. The rng states also complicate
198
+ pattern matching in Inductor. Due to the ease of implementation, we are
199
+ currently inclined towards functionalization at Inductor level, which means
200
+ that duplication/recomputation is done as a compiler pass in the
201
+ partitioners. See TagActivationCheckpoint for more information.
202
+ """
203
+
204
+ def __init__(self) -> None:
205
+ super().__init__("wrap_activation_checkpoint", cacheable=False)
206
+
207
+ def __call__(self, function, *args, **kwargs):
208
+ # use_reentrant is set to False because this op is going to be traced.
209
+ # And we ensure that AOT Autograd traces through the non reentrant
210
+ # version of checkpointing.
211
+ import torch.fx.traceback as fx_traceback
212
+ from torch.fx import Interpreter
213
+
214
+ kwargs["use_reentrant"] = False
215
+ kwargs["preserve_rng_state"] = False
216
+ # Using interpreter allows preservation of metadata through torch.compile stack.
217
+ with fx_traceback.preserve_node_meta():
218
+ from torch.utils.checkpoint import checkpoint
219
+
220
+ return checkpoint(Interpreter(function).run, *args, **kwargs)
221
+
222
+
223
+ wrap_activation_checkpoint = WrapActivationCheckpoint()
224
+
225
+
226
+ class TagActivationCheckpoint(HigherOrderOperator):
227
+ """
228
+ This operator is supposed to be used only with torch.compile stack. This
229
+ accepts a Fx graph module which needs to be checkpointed. This operator adds
230
+ "recomputable" tag to the nodes of the Fx graph that should be recomputed.
231
+
232
+ The goal is to:
233
+ 1. Avoid using Dynamo to trace through saved tensor hooks.
234
+ 2. For selective checkpointing case, let AOTAutograd trace through
235
+ saved tensor hooks but has special logic with TorchDispatchMode to override
236
+ the usual saved_tensor_hooks fn logic in order to tag the nodes.
237
+ 3. Rely on the partitioners to actually duplicate the nodes.
238
+ This sits well in the torch.compile stack, because by the time graph
239
+ reaches partitioner, inductor has already run its functionalization of rng
240
+ ops (by setting fixed seed for each random op, see `replace_random_passes`).
241
+ Therefore, the duplication of nodes, by design, respects the rng states in
242
+ the forward and recomputed forward in backward.
243
+ """
244
+
245
+ def __init__(self) -> None:
246
+ super().__init__("tag_activation_checkpoint", cacheable=True)
247
+
248
+ @staticmethod
249
+ def divide_kwargs(kwargs):
250
+ """
251
+ checkpoint fn can have mixed kwargs between checkpointed fn and
252
+ checkpoint fn itself. For example
253
+ >> def gn(x, y, z=None):
254
+ >> a = torch.matmul(x, y)
255
+ >> if z is not None:
256
+ >> return torch.matmul(a, z)
257
+ >> return a
258
+ >> def fn(x, y, z):
259
+ >> return torch.cos(checkpoint(gn, x, y, use_reentrant=False, z=z))
260
+ In the above case, z belongs to checkpointed function gn, but
261
+ use_reentrant belongs to the checkpoint function. This function splits
262
+ the kwargs into checkpoint_kwargs and gmod_kwargs (or
263
+ checkpointed_fn_kwargs).
264
+ We do sorting to ensure same graph from run to run for better
265
+ debuggability. It is not required for correctness.
266
+ """
267
+ from torch.utils.checkpoint import checkpoint
268
+
269
+ ckpt_signature = inspect.signature(checkpoint)
270
+ checkpoint_keys = set()
271
+ for name in ckpt_signature.parameters:
272
+ if name in ("function", "args", "kwargs"):
273
+ continue
274
+ checkpoint_keys.add(name)
275
+
276
+ # `preserve_rng_state` is not a regular kwarg
277
+ checkpoint_keys.add("preserve_rng_state")
278
+
279
+ checkpoint_kwargs = {
280
+ name: kwargs[name] for name in kwargs if name in checkpoint_keys
281
+ }
282
+ gmod_kwargs = {
283
+ name: kwargs[name] for name in kwargs if name not in checkpoint_keys
284
+ }
285
+ return checkpoint_kwargs, gmod_kwargs
286
+
287
+ @staticmethod
288
+ def tag_nodes(gmod, is_sac):
289
+ from torch.utils.checkpoint import CheckpointPolicy
290
+
291
+ unique_graph_id = next(uid)
292
+ for node in gmod.graph.nodes:
293
+ if node.op in ("call_function", "call_method", "call_module"):
294
+ node.meta["ac_graph_id"] = unique_graph_id
295
+ if is_sac:
296
+ # For selective checkpointing, we will populate this tag later in _CachingTorchDispatchMode.
297
+ node.meta["recompute"] = None
298
+ else:
299
+ # Under vanilla activation checkpointing, all nodes should be recomputed.
300
+ node.meta["recompute"] = CheckpointPolicy.PREFER_RECOMPUTE
301
+ return gmod
302
+
303
+ def __call__(self, gmod, *args, **kwargs):
304
+ dispatch_key_set = torch._ops._compute_keyset(
305
+ args, kwargs, self.non_fallthrough_keys
306
+ )
307
+ dispatch_key = dispatch_key_set.highestPriorityTypeId()
308
+ if dispatch_key == torch._C.DispatchKey.PreDispatch:
309
+ # pyrefly: ignore [missing-attribute]
310
+ return super().__call__(gmod, *args, **kwargs)
311
+
312
+ return tag_activation_checkpoint_impl(gmod, *args, **kwargs)
313
+
314
+
315
+ tag_activation_checkpoint = TagActivationCheckpoint()
316
+
317
+
318
+ def tag_activation_checkpoint_impl(gmod, *args, **kwargs):
319
+ import torch.fx.traceback as fx_traceback
320
+ from torch.fx import Interpreter
321
+
322
+ if "_checkpoint_context_fn" in gmod.meta:
323
+ warning_once(
324
+ log,
325
+ """
326
+ Detected that context_fn is passed to torch.utils.checkpoint under torch.compile.
327
+ Please make sure the checkpointed region does not contain in-place ops (e.g. torch.relu_).
328
+ """,
329
+ )
330
+ # use_reentrant is set to False because this op is going to be traced.
331
+ # And we ensure that AOT Autograd traces through the non reentrant
332
+ # version of checkpointing.
333
+ kwargs["use_reentrant"] = False
334
+ # preserve_rng_state is set to False because we want to prevent AOTAutograd from tracing through
335
+ # `torch.random.fork_rng` op (which is not supported yet under CUDA).
336
+ # This doesn't mean that we don't preserve RNG state. Instead, we will always preserve RNG state
337
+ # regardless of this flag (by doing RNG functionalization via `replace_random_passes` in Inductor
338
+ # instead of in AOTAutograd).
339
+ kwargs["preserve_rng_state"] = False
340
+ kwargs["context_fn"] = gmod.meta["_checkpoint_context_fn"]
341
+ # We first tag all nodes as "recompute" in this graph, and then we undo the "recompute" tag
342
+ # for specific nodes in _CachingTorchDispatchMode in torch/utils/checkpoint.py.
343
+ gmod = TagActivationCheckpoint.tag_nodes(gmod, is_sac=True)
344
+ # Using interpreter allows preservation of metadata through torch.compile stack.
345
+ with fx_traceback.preserve_node_meta():
346
+ from torch.utils.checkpoint import checkpoint
347
+
348
+ return checkpoint(Interpreter(gmod).run, *args, **kwargs)
349
+ else:
350
+ gmod = TagActivationCheckpoint.tag_nodes(gmod, is_sac=False)
351
+ # Using interpreter allows preservation of metadata through torch.compile stack.
352
+ # TODO: We want to use the same `checkpoint(Interpreter(gmod).run, *args, **kwargs)` here
353
+ # as the `context_fn != None` case, but that depends on in-place op support in TorchDispatchMode + torch.compile.
354
+ # (for details on in-place op issue, run `test_compile_selective_checkpoint_inplace_op` unit test)
355
+ with fx_traceback.preserve_node_meta():
356
+ return Interpreter(gmod).run(*args)
357
+
358
+
359
+ @tag_activation_checkpoint.py_impl(ProxyTorchDispatchMode)
360
+ def proxy_mode_key(
361
+ proxy_mode: ProxyTorchDispatchMode,
362
+ gmod: GraphModule,
363
+ *args: Any,
364
+ **kwargs: Any,
365
+ ) -> tuple[torch.Tensor]:
366
+ import torch.fx.traceback as fx_traceback
367
+ from torch.fx import Interpreter
368
+
369
+ if not proxy_mode.pre_dispatch:
370
+ raise AssertionError(
371
+ "post-dispatch mode should have inlined in the Autograd key"
372
+ )
373
+ example_out = tag_activation_checkpoint(gmod, *args, **kwargs)
374
+ proxy_args = pytree.tree_map(proxy_mode.tracer.unwrap_proxy, args) # type: ignore[union-attr]
375
+ proxy_kwargs = pytree.tree_map(proxy_mode.tracer.unwrap_proxy, kwargs) # type: ignore[union-attr]
376
+ qualname = proxy_mode.tracer.get_fresh_qualname("wrap_body") # type: ignore[union-attr]
377
+
378
+ # TODO (tmanlaibaatar) don't we need flat_apply here??
379
+ # Dynamo already traced the gmod body without kwargs
380
+ flat_args, _ = pytree.tree_flatten(args)
381
+ with fx_traceback.preserve_node_meta():
382
+ gmod_aten = reenter_make_fx(Interpreter(gmod).run)(*flat_args)
383
+ gmod_aten.meta["_checkpoint_context_fn"] = gmod.meta["_checkpoint_context_fn"]
384
+ proxy_mode.tracer.root.register_module(qualname, gmod_aten) # type: ignore[union-attr]
385
+ proxy_gmod = proxy_mode.tracer.unwrap_proxy(gmod_aten) # type: ignore[union-attr, call-overload]
386
+ out_proxy = proxy_mode.tracer.create_proxy(
387
+ "call_function",
388
+ tag_activation_checkpoint,
389
+ (proxy_gmod, *proxy_args),
390
+ proxy_kwargs,
391
+ )
392
+ return track_tensor_tree(
393
+ example_out, out_proxy, constant=None, tracer=proxy_mode.tracer
394
+ )
.venv/lib/python3.10/site-packages/torch/_inductor/analysis/__init__.py ADDED
File without changes
.venv/lib/python3.10/site-packages/torch/_inductor/analysis/device_info.py ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ from dataclasses import dataclass
3
+ from typing import Optional, Union
4
+
5
+ import torch
6
+
7
+
8
+ log = logging.getLogger(__name__)
9
+
10
+
11
+ @dataclass(frozen=True)
12
+ class DeviceInfo:
13
+ """
14
+ Theoretical Numbers from data sheet. If two numbers are given, Tensor/Matrix Core vs not,
15
+ then the higher number is reported. Sparsity is not considered.
16
+
17
+
18
+ Bandwidth numbers are tricky, because there are platform differences that may not show up in the profiler trace.
19
+ For example,
20
+ """
21
+
22
+ tops: dict[Union[torch.dtype, str], float]
23
+ dram_bw_gbs: float
24
+ dram_gb: float
25
+
26
+
27
+ # Indexing is based on `torch.cuda.get_device_name()`
28
+ # TODO investigate profiler support for tf32 and allow device to report correct number when it's turned on.
29
+ _device_mapping: dict[str, DeviceInfo] = {
30
+ # Source:
31
+ # @lint-ignore https://www.nvidia.com/en-us/data-center/h100/
32
+ "NVIDIA H100": DeviceInfo(
33
+ tops={
34
+ torch.float64: 67.0,
35
+ torch.float32: 67.5,
36
+ "torch.tf32": 156.0,
37
+ torch.bfloat16: 1979.0,
38
+ torch.float16: 1979.0,
39
+ torch.float8_e8m0fnu: 3958.0,
40
+ torch.float8_e8m0fnu: 3958.0,
41
+ torch.float8_e4m3fnuz: 3958.0,
42
+ torch.float8_e5m2: 3958.0,
43
+ torch.float8_e5m2fnuz: 3958.0,
44
+ torch.float8_e8m0fnu: 3958.0,
45
+ torch.int8: 3958.0,
46
+ },
47
+ dram_bw_gbs=3350,
48
+ dram_gb=80,
49
+ ),
50
+ # Source:
51
+ # @lint-ignore https://www.nvidia.com/content/dam/en-zz/Solutions/Data-Center/a100/pdf/
52
+ # nvidia-a100-datasheet-us-nvidia-1758950-r4-web.pdf
53
+ "NVIDIA A100": DeviceInfo(
54
+ tops={
55
+ torch.float64: 19.5,
56
+ torch.float32: 19.5,
57
+ torch.bfloat16: 312.5,
58
+ torch.float16: 312.5,
59
+ # Not in datasheet: float8
60
+ torch.int8: 624.0,
61
+ "torch.tf32": 156.0,
62
+ },
63
+ dram_bw_gbs=2039.0,
64
+ dram_gb=80.0,
65
+ ),
66
+ # Source:
67
+ # @lint-ignore https://resources.nvidia.com/en-us-gpu-resources/l4-tensor-datasheet
68
+ "NVIDIA L4": DeviceInfo(
69
+ tops={
70
+ # This is a guess, not in datasheet
71
+ torch.float64: 15.1,
72
+ torch.float32: 30.3,
73
+ "torch.tf32": 120.0,
74
+ torch.bfloat16: 242.0,
75
+ torch.float16: 242.0,
76
+ torch.float8_e8m0fnu: 485.0,
77
+ torch.float8_e8m0fnu: 485.0,
78
+ torch.float8_e4m3fnuz: 485.0,
79
+ torch.float8_e5m2: 485.0,
80
+ torch.float8_e5m2fnuz: 485.0,
81
+ torch.float8_e8m0fnu: 485.0,
82
+ torch.int8: 485.0,
83
+ },
84
+ dram_bw_gbs=3350,
85
+ dram_gb=24,
86
+ ),
87
+ # Source:
88
+ # @lint-ignore https://www.amd.com/content/dam/amd/en/documents\
89
+ # /instinct-tech-docs/product-briefs/amd-instinct-mi350x-gpu-brochure.pdf
90
+ "AMD MI350X": DeviceInfo(
91
+ tops={
92
+ torch.float64: 72.1,
93
+ torch.float32: 144.2,
94
+ # not specified, fall back to float32 numbers
95
+ "torch.tf32": 144.2,
96
+ torch.bfloat16: 2309.6,
97
+ torch.float16: 2309.6,
98
+ torch.float8_e8m0fnu: 4614.0,
99
+ torch.float8_e8m0fnu: 4614.0,
100
+ torch.float8_e4m3fnuz: 4614.0,
101
+ torch.float8_e5m2: 4614.0,
102
+ torch.float8_e5m2fnuz: 4614.0,
103
+ torch.float8_e8m0fnu: 4614.0,
104
+ torch.int8: 4614.0,
105
+ },
106
+ dram_bw_gbs=8000.0,
107
+ dram_gb=288.0,
108
+ ),
109
+ # Source:
110
+ # @lint-ignore https://www.amd.com/content/dam/amd/en/documents\
111
+ # /instinct-tech-docs/data-sheets/amd-instinct-mi300a-data-sheet.pdf
112
+ "AMD MI300A": DeviceInfo(
113
+ tops={
114
+ torch.float64: 122.6,
115
+ torch.float32: 122.6,
116
+ "torch.tf32": 490.3,
117
+ torch.bfloat16: 980.6,
118
+ torch.float16: 980.6,
119
+ torch.float8_e8m0fnu: 1961.2,
120
+ torch.float8_e8m0fnu: 1961.2,
121
+ torch.float8_e4m3fnuz: 1961.2,
122
+ torch.float8_e5m2: 1961.2,
123
+ torch.float8_e5m2fnuz: 1961.2,
124
+ torch.float8_e8m0fnu: 1961.2,
125
+ torch.int8: 1961.2,
126
+ },
127
+ dram_bw_gbs=5300.0,
128
+ dram_gb=128.0,
129
+ ),
130
+ # Source:
131
+ # @lint-ignore https://www.amd.com/content/dam/amd/en/documents/\
132
+ # instinct-tech-docs/data-sheets/amd-instinct-mi300x-data-sheet.pdf
133
+ "AMD MI300X": DeviceInfo(
134
+ tops={
135
+ torch.float64: 163.4,
136
+ torch.float32: 163.4,
137
+ "torch.tf32": 653.7,
138
+ torch.bfloat16: 1307.4,
139
+ torch.float16: 1307.4,
140
+ torch.float8_e8m0fnu: 2614.9,
141
+ torch.float8_e8m0fnu: 2614.9,
142
+ torch.float8_e4m3fnuz: 2614.9,
143
+ torch.float8_e5m2: 2614.9,
144
+ torch.float8_e5m2fnuz: 2614.9,
145
+ torch.float8_e8m0fnu: 2614.9,
146
+ torch.int8: 2614.9,
147
+ },
148
+ dram_bw_gbs=5300.0,
149
+ dram_gb=192.0,
150
+ ),
151
+ # Source:
152
+ # @lint-ignore https://www.amd.com/content/dam/amd/\
153
+ # en/documents/instinct-business-docs/product-briefs/instinct-mi210-brochure.pdf
154
+ "AMD MI210X": DeviceInfo(
155
+ tops={
156
+ torch.float64: 45.3,
157
+ torch.float32: 45.3,
158
+ # not specified, fall back to float32 numbers
159
+ "torch.tf32": 45.3,
160
+ torch.bfloat16: 181.0,
161
+ torch.float16: 181.0,
162
+ # not specified, fall back to float16 numbers
163
+ torch.float8_e8m0fnu: 181.0,
164
+ torch.float8_e8m0fnu: 181.0,
165
+ torch.float8_e4m3fnuz: 181.0,
166
+ torch.float8_e5m2: 181.0,
167
+ torch.float8_e5m2fnuz: 181.0,
168
+ torch.float8_e8m0fnu: 181.0,
169
+ torch.int8: 181.0,
170
+ },
171
+ # pcie4.0x16
172
+ dram_bw_gbs=1600.0,
173
+ dram_gb=64.0,
174
+ ),
175
+ }
176
+ _device_mapping["AMD INSTINCT MI350X"] = _device_mapping["AMD MI350X"]
177
+ _device_mapping["AMD INSTINCT MI300X"] = _device_mapping["AMD MI300X"]
178
+ _device_mapping["AMD INSTINCT MI210X"] = _device_mapping["AMD MI210X"]
179
+
180
+
181
+ def lookup_device_info(name: str) -> Optional[DeviceInfo]:
182
+ """
183
+ Problem: when diffing profiles between amd and nvidia, we don't have access to the device information
184
+ of the other one. Also, since the analysis is static, we should be able to do it on another device unrelated
185
+ to the recorded device. Therefore, _device_mapping statically contains the information for lots of devices.
186
+ If one is missing, please run DeviceInfo.get_device_info() and add it to _device_mapping.
187
+ name (str): name of the device to lookup. Should map onto torch.cuda.get_device_name().
188
+ """
189
+ return _device_mapping.get(name)
190
+
191
+
192
+ def datasheet_tops(dtype: torch.dtype, is_tf32: bool = False) -> Optional[float]:
193
+ """
194
+ Get the theoretical TFLOPS of the device for a given dtype. This can throw an exception if the device
195
+ is not in the datasheet list above.
196
+ """
197
+ name: Optional[str] = torch.cuda.get_device_name()
198
+ if name is None:
199
+ log.info("No device found, returning None")
200
+ return None
201
+ device_info = lookup_device_info(name)
202
+ if device_info is None:
203
+ log_str = f"Device {name} not in datasheet, returning None"
204
+ log.info(log_str)
205
+ return None
206
+ if dtype not in device_info.tops:
207
+ log.info(
208
+ "Device %s does not have a datasheet entry for %s, returning None",
209
+ name,
210
+ dtype,
211
+ )
212
+ return None
213
+
214
+ return device_info.tops[
215
+ "torch.tf32" if dtype == torch.float32 and is_tf32 else dtype
216
+ ]
.venv/lib/python3.10/site-packages/torch/_inductor/analysis/profile_analysis.py ADDED
@@ -0,0 +1,823 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import logging
3
+ import math
4
+ from collections import defaultdict
5
+ from collections.abc import Callable
6
+ from dataclasses import dataclass
7
+ from typing import Any, Optional, Union
8
+
9
+ import torch
10
+ from torch._inductor.analysis.device_info import DeviceInfo, lookup_device_info
11
+ from torch._inductor.utils import tabulate_2d, zip_dicts
12
+ from torch.utils import _pytree as pytree
13
+ from torch.utils._ordered_set import OrderedSet
14
+ from torch.utils.flop_counter import flop_registry
15
+
16
+
17
+ log = logging.getLogger(__name__)
18
+
19
+
20
+ ATEN_PREFIX = "aten::"
21
+
22
+
23
+ @dataclass
24
+ class ProfileEvent:
25
+ category: str
26
+ key: str
27
+ self_device_time_ms: float
28
+ # the benchmark is run multiple times and we average the count across all the
29
+ # runs. It should be an integer but define a float just in case.
30
+ count: float
31
+
32
+
33
+ # adapters convert the json trace into a format that works with flops_counter
34
+ ArgsType = tuple[tuple[Any, ...], dict[Any, Any]]
35
+ AdapterType = Callable[[tuple[Any, ...], tuple[Any, ...]], ArgsType]
36
+ adapters_map: dict[str, AdapterType] = {}
37
+
38
+
39
+ def parse_list(lst: str) -> list[int]:
40
+ lst = lst.replace("[", "").replace("]", "")
41
+ substrings = lst.split(",")
42
+
43
+ return [int(substring.strip()) for substring in substrings]
44
+
45
+
46
+ def register_adapter(
47
+ aten: Union[str, list[str]],
48
+ ) -> Callable[
49
+ [AdapterType],
50
+ AdapterType,
51
+ ]:
52
+ def decorator(func: AdapterType) -> AdapterType:
53
+ # pyrefly: ignore [unknown-name]
54
+ global _adapters_map
55
+
56
+ if isinstance(aten, str):
57
+ adapters_map[aten] = func
58
+ else:
59
+ for at in aten:
60
+ adapters_map[at] = func
61
+ return func
62
+
63
+ return decorator
64
+
65
+
66
+ @register_adapter(["_slow_conv2d_forward"])
67
+ def _slow_conv2d_adapter(
68
+ shapes: tuple[Any, ...], concrete: tuple[Any, ...]
69
+ ) -> tuple[tuple[Any], dict[Any, Any]]:
70
+ tmp = list(shapes)
71
+ tmp.append(False)
72
+ tmp2 = list(concrete)
73
+ if len(tmp2) < 5:
74
+ raise ParseException("slow conv2d has less than 5 concrete inputs")
75
+ tmp2[3] = tmp2[4]
76
+ return conv_adapter(tuple(tmp), tuple(tmp2))
77
+
78
+
79
+ @register_adapter(
80
+ ["convolution", "_convolution", "cudnn_convolution", "convolution_overrideable"]
81
+ )
82
+ def conv_adapter(
83
+ shapes: tuple[Any, ...], concrete: tuple[Any, ...]
84
+ ) -> tuple[tuple[Any], dict[Any, Any]]:
85
+ tmp = list(shapes)
86
+ if len(tmp) == 4:
87
+ transposed = False
88
+ elif len(tmp) > 6:
89
+ transposed = bool(tmp[6])
90
+ tmp[6] = transposed
91
+ else:
92
+ raise ParseException(f"Convolution has the wrong number of inputs: {len(tmp)}")
93
+
94
+ kwargs: dict[Any, Any] = {}
95
+ if not transposed:
96
+ # calculate output shape if not transposed.
97
+ def conv_out_dims(x: int, kernel: int, stride: int) -> int:
98
+ return (x - kernel) // stride + 1
99
+
100
+ stride = parse_list(concrete[3])
101
+ inp = shapes[0]
102
+ w = shapes[1]
103
+ out_x_y = [conv_out_dims(*args) for args in zip(inp[2:], w[2:], stride)]
104
+ out = [inp[0], w[0]] + out_x_y # we only need the xy values
105
+ kwargs["out_val"] = out
106
+
107
+ return tuple(tmp), kwargs
108
+
109
+
110
+ def default_adapter(
111
+ shapes: tuple[Any], concrete: tuple[Any]
112
+ ) -> tuple[tuple[Any], dict[Any, Any]]:
113
+ return shapes, {}
114
+
115
+
116
+ @register_adapter("addmm")
117
+ def addmm_adapter(
118
+ shapes: tuple[Any], concrete: tuple[Any]
119
+ ) -> tuple[tuple[Any], dict[Any, Any]]:
120
+ tmp = list(shapes)[:3]
121
+ return tuple(tmp), {}
122
+
123
+
124
+ @register_adapter("bmm")
125
+ def bmm_adapter(
126
+ shapes: tuple[Any], concrete: tuple[Any]
127
+ ) -> tuple[tuple[Any], dict[Any, Any]]:
128
+ tmp = list(shapes)
129
+ return tuple(tmp[:2]), {}
130
+
131
+
132
+ @register_adapter("baddbmm")
133
+ def baddbmm_adapter(
134
+ shapes: tuple[Any], concrete: tuple[Any]
135
+ ) -> tuple[tuple[Any], dict[Any, Any]]:
136
+ tmp = list(shapes)[:3]
137
+ return tuple(tmp), {}
138
+
139
+
140
+ @register_adapter("mm")
141
+ def mm_adapter(
142
+ shapes: tuple[Any], concrete: tuple[Any]
143
+ ) -> tuple[tuple[Any], dict[Any, Any]]:
144
+ return shapes, {}
145
+
146
+
147
+ def _parse_kernel_name(name: str) -> Optional[str]:
148
+ """
149
+ parse the name of the kernel from the event name.
150
+ """
151
+ if name.startswith(ATEN_PREFIX):
152
+ return name[len(ATEN_PREFIX) :]
153
+ elif "conv" in name:
154
+ return "convolution"
155
+ elif "addmm" in name:
156
+ return "addmm"
157
+ elif "bmm" in name:
158
+ return "bmm"
159
+ elif "baddbmm" in name:
160
+ return "baddbmm"
161
+ elif "_mm" in name:
162
+ return "mm"
163
+ else:
164
+ return None
165
+
166
+
167
+ def _calculate_flops(event: dict[str, Any]) -> int:
168
+ """
169
+ This function has to parse the kernel name, which is error prone. There doesn't seem to be another solution that
170
+ will support all the different backends that can generate kernels, so make sure to update this function when new
171
+ ops and backends are desired.
172
+ """
173
+ name = event["name"]
174
+ if "kernel_flop" in event["args"] and event["args"]["kernel_flop"] != 0:
175
+ return event["args"]["kernel_flop"]
176
+ op_name = _parse_kernel_name(name)
177
+ if op_name is None:
178
+ return 0
179
+
180
+ op_obj = getattr(torch.ops.aten, op_name, None)
181
+ if op_obj is None or op_obj not in flop_registry:
182
+ return 0
183
+
184
+ flop_function = flop_registry[op_obj]
185
+
186
+ if "Input Dims" not in event["args"] or "Concrete Inputs" not in event["args"]:
187
+ return 0
188
+ input_shapes = event["args"]["Input Dims"]
189
+ concrete = event["args"]["Concrete Inputs"]
190
+ if op_name in adapters_map:
191
+ try:
192
+ args, kwargs = adapters_map[op_name](input_shapes, concrete)
193
+ except ParseException as e:
194
+ msg = f"Failed to parse {op_name} with {e}"
195
+ log.warning(msg)
196
+ return 0
197
+ else:
198
+ try:
199
+ args, kwargs = default_adapter(input_shapes, concrete)
200
+ except ParseException as e:
201
+ msg = f"Failed to parse {op_name} with {e}"
202
+ log.warning(msg)
203
+ return 0
204
+ return flop_function(*args, **kwargs)
205
+
206
+
207
+ def _get_size_from_string(type_string: str) -> int:
208
+ if not hasattr(torch, type_string):
209
+ return 1
210
+ else:
211
+ return getattr(torch, type_string).itemsize
212
+
213
+
214
+ def _default_estimate_gb(event: dict[str, Any]) -> float:
215
+ sizes_and_types = zip(event["args"]["Input Dims"], event["args"]["Input type"])
216
+ bw = 0
217
+ for size, typ in sizes_and_types:
218
+ isize = _get_size_from_string(typ)
219
+ bw += isize * math.prod(pytree.tree_flatten(size)[0])
220
+ return bw / 1e9
221
+
222
+
223
+ def _estimate_gb(event: dict[str, Any]) -> float:
224
+ """
225
+ Our best effort to estimate the gb, should be refactored soon with MemoryCounter.
226
+ """
227
+ name = event["name"]
228
+ if "kernel_num_gb" in event["args"] and event["args"]["kernel_num_gb"] != 0:
229
+ return event["args"]["kernel_num_gb"]
230
+ if "Input type" not in event["args"] or "Input Dims" not in event["args"]:
231
+ return 0
232
+ op_name = _parse_kernel_name(name)
233
+ if op_name is None:
234
+ return _default_estimate_gb(event)
235
+
236
+ op_obj = getattr(torch.ops.aten, op_name, None)
237
+ if op_obj is None:
238
+ return _default_estimate_gb(event)
239
+
240
+ if "Input Dims" not in event["args"] or "Concrete Inputs" not in event["args"]:
241
+ return _default_estimate_gb(event)
242
+ input_shapes = event["args"]["Input Dims"]
243
+
244
+ # NOTE these will be refactored into a similar object to FlopCounter soon
245
+ def mm_formula(M: int, N: int, K: int, size: int) -> int:
246
+ return 2 * (M * K + N * K + M * N) * size
247
+
248
+ if op_name == "addmm":
249
+ add_in_size = math.prod(pytree.tree_flatten(input_shapes[0])[0])
250
+ add_type_size = _get_size_from_string(event["args"]["Input type"][0])
251
+ M = input_shapes[1][0]
252
+ N = input_shapes[1][1]
253
+ assert input_shapes[1][1] == input_shapes[2][0]
254
+ K = input_shapes[2][1]
255
+ mul_type_size = _get_size_from_string(event["args"]["Input type"][1])
256
+ return (mm_formula(M, N, K, mul_type_size) + add_in_size * add_type_size) / 1e9
257
+ elif op_name == "mm":
258
+ M = input_shapes[0][0]
259
+ N = input_shapes[0][1]
260
+ assert input_shapes[0][1] == input_shapes[1][0]
261
+ K = input_shapes[1][1]
262
+ type_size = _get_size_from_string(event["args"]["Input type"][0])
263
+ return mm_formula(M, N, K, type_size) / 1e9
264
+ elif op_name == "baddbmm":
265
+ add_in_size = math.prod(pytree.tree_flatten(input_shapes[0])[0])
266
+ add_type_size = _get_size_from_string(event["args"]["Input type"][0])
267
+ B = input_shapes[0][0]
268
+ M = input_shapes[1][1]
269
+ N = input_shapes[1][2]
270
+ K = input_shapes[2][2]
271
+ mul_type_size = _get_size_from_string(event["args"]["Input type"][1])
272
+ return (
273
+ B * mm_formula(M, N, K, mul_type_size) + add_in_size * add_type_size
274
+ ) / 1e9
275
+ elif op_name == "bmm":
276
+ add_in_size = math.prod(pytree.tree_flatten(input_shapes[0])[0])
277
+ add_type_size = _get_size_from_string(event["args"]["Input type"][0])
278
+ B = input_shapes[0][0]
279
+ M = input_shapes[0][1]
280
+ N = input_shapes[0][2]
281
+ K = input_shapes[1][2]
282
+ mul_type_size = _get_size_from_string(event["args"]["Input type"][1])
283
+ return (
284
+ B * mm_formula(M, N, K, mul_type_size) + add_in_size * add_type_size
285
+ ) / 1e9
286
+ elif op_name in [
287
+ "convolution",
288
+ "_convolution",
289
+ "cudnn_convolution",
290
+ "_slow_conv2d_forward",
291
+ ]:
292
+ concrete = event["args"]["Concrete Inputs"]
293
+
294
+ def conv_out_dim(x: int, kernel: int, stride: int) -> int:
295
+ return (x - kernel) // stride + 1
296
+
297
+ stride = parse_list(
298
+ concrete[3] if op_name != "_slow_conv2d_forward" else concrete[4]
299
+ )
300
+ inp = input_shapes[0]
301
+ w = input_shapes[1]
302
+ out_x_y = [conv_out_dim(*args) for args in zip(inp[2:], w[2:], stride)]
303
+ out = [inp[0], w[0]] + out_x_y
304
+ # each output element reads in * w * w chunk
305
+ input_reads = out[0] * out[1] * out[2] * out[3] * inp[1] * w[2] * w[3]
306
+ # Assume weights are in cache, so only read once
307
+ weight_reads = w[0] * w[1] * w[2] * w[3]
308
+ return (input_reads + weight_reads) / 1e9
309
+
310
+ return _default_estimate_gb(event)
311
+
312
+
313
+ def _create_extern_mapping(
314
+ data: dict[str, Any],
315
+ ) -> defaultdict[int, list[dict[str, Any]]]:
316
+ """
317
+ compute a mapping from external ids to non kernels, which contain the information we need to estimate flops etc
318
+ """
319
+ extern_mapping: defaultdict[int, list[dict[str, Any]]] = defaultdict(list)
320
+ for event in data["traceEvents"]:
321
+ if (
322
+ "args" not in event
323
+ or "External id" not in event["args"]
324
+ or event["cat"] != "cpu_op"
325
+ ):
326
+ continue
327
+ if len(extern_mapping[event["args"]["External id"]]) > 0:
328
+ raise ParseException("duplicate external id in event")
329
+ extern_mapping[event["args"]["External id"]].append(event)
330
+ return extern_mapping
331
+
332
+
333
+ def _augment_trace_helper(data: dict[str, Any]) -> dict[str, Any]:
334
+ extern_mapping = _create_extern_mapping(data)
335
+
336
+ for event in data["traceEvents"]:
337
+ if "cat" not in event or event["cat"] != "kernel":
338
+ continue
339
+ if "args" not in event:
340
+ raise ParseException(f"kernel has no args: {event}")
341
+ if "External id" not in event["args"]:
342
+ event_str = f"kernel has no External id: {event}"
343
+ log.info(event_str)
344
+ continue
345
+
346
+ external_op = extern_mapping[event["args"]["External id"]][0]
347
+ flops = _calculate_flops(external_op)
348
+ if flops == 0:
349
+ flops = _calculate_flops(event)
350
+ external_op["args"]["kernel_flop"] = flops
351
+ external_op["args"]["kernel_num_gb"] = _estimate_gb(external_op)
352
+ event["args"]["kernel_flop"] = external_op["args"]["kernel_flop"]
353
+ event["args"]["kernel_num_gb"] = external_op["args"]["kernel_num_gb"]
354
+ return data
355
+
356
+
357
+ _dtype_map = {
358
+ "float": torch.float,
359
+ "float32": torch.float,
360
+ "int": torch.int,
361
+ "int8": torch.int8,
362
+ "int16": torch.int16,
363
+ "int32": torch.int,
364
+ "long": torch.long,
365
+ "long int": torch.long,
366
+ "bfloat16": torch.bfloat16,
367
+ "float16": torch.float16,
368
+ "float64": torch.double,
369
+ }
370
+
371
+
372
+ @dataclass(frozen=True)
373
+ class KernelStats:
374
+ flops: int
375
+ bw: float
376
+ latency: float # us
377
+ achieved_flops: float
378
+ achieved_bandwidth: float
379
+
380
+
381
+ KernelNameMap = defaultdict[str, OrderedSet[KernelStats]]
382
+
383
+
384
+ @dataclass(frozen=False)
385
+ class Device:
386
+ name: str
387
+ index: int
388
+ info: Optional[DeviceInfo]
389
+ stats: KernelNameMap
390
+
391
+ def __repr__(self) -> str:
392
+ return f"Device({self.name}, {self.index}): {self.info}"
393
+
394
+
395
+ DeviceMap = dict[int, Device]
396
+ Table = tuple[list[str], dict[str, list[str]]]
397
+
398
+
399
+ class JsonProfile:
400
+ _devices: DeviceMap
401
+
402
+ def __init__(
403
+ self,
404
+ path: str,
405
+ benchmark_name: Optional[str] = None,
406
+ dtype: Optional[Union[torch.dtype, str]] = None,
407
+ ):
408
+ """
409
+ Convenience class for running common operations on chrome/perfetto json traces.
410
+ """
411
+ self.path = path
412
+ with open(path) as f:
413
+ self.data = json.load(f)
414
+ self.events = self.data["traceEvents"]
415
+ self.benchmark_name = benchmark_name
416
+ if dtype is None:
417
+ self.dtype = None
418
+ elif isinstance(dtype, torch.dtype):
419
+ # pyrefly: ignore [bad-assignment]
420
+ self.dtype = dtype
421
+ else:
422
+ # pyrefly: ignore [bad-assignment]
423
+ self.dtype = _dtype_map.get(dtype)
424
+ self._create_devices()
425
+
426
+ def convert_dtype(self, event: dict[str, Any]) -> Optional[torch.dtype]:
427
+ """
428
+ Each op has a list of dtypes for each input arg. We need to convert these into a single dtype for flop estimation.
429
+ Issues:
430
+ - converting the strings to concrete torch.dtypes
431
+ - What if we have float32, float, float16 all in the inputs? Our choice is to use the largest buffer dtype.
432
+ """
433
+
434
+ if (
435
+ "Input Dims" not in event["args"]
436
+ or "Input type" not in event["args"]
437
+ or "Concrete Inputs" not in event["args"]
438
+ ):
439
+ if "bfloat16" in event["name"]:
440
+ return torch.bfloat16
441
+ elif "float16" in event["name"]:
442
+ return torch.float16
443
+ else:
444
+ return None
445
+
446
+ input_sizes = event["args"]["Input Dims"]
447
+ input_types = event["args"]["Input type"]
448
+ concrete_inputs = event["args"]["Concrete Inputs"]
449
+ assert len(input_sizes) == len(input_types)
450
+ assert len(input_types) == len(concrete_inputs)
451
+
452
+ if len(input_sizes) == 0:
453
+ raise RuntimeError("Empty input_sizes and input_types")
454
+
455
+ biggest_size = 0
456
+ biggest_index = 0
457
+ for i in range(len(input_sizes)):
458
+ if concrete_inputs[i] != "":
459
+ # concrete inputs are usually small tensors, so we can just skip
460
+ continue
461
+ my_size = input_sizes[i]
462
+ total_size = sum(parse_list(my_size))
463
+ if total_size > biggest_size:
464
+ biggest_size = total_size
465
+ biggest_index = i
466
+ ret_type = input_types[biggest_index]
467
+ if ret_type in _dtype_map:
468
+ return _dtype_map[ret_type]
469
+ raise RuntimeError(f"Unknown type: {ret_type}. Please add to _dtype_map.")
470
+
471
+ def _create_devices(self) -> None:
472
+ self._devices = {}
473
+ for dev in self.data["deviceProperties"]:
474
+ name = dev["name"]
475
+ device_info = lookup_device_info(name)
476
+
477
+ if device_info is None:
478
+ log.info(
479
+ "Unsupported device in profile: %s, please consider contributing to _device_mapping.",
480
+ name,
481
+ )
482
+ self._devices[dev["id"]] = Device(
483
+ name, dev["id"], device_info, defaultdict(OrderedSet)
484
+ )
485
+
486
+ def calculate_flops(self, event: dict[str, Any]) -> int:
487
+ return _calculate_flops(event)
488
+
489
+ def estimate_gb(self, event: dict[str, Any]) -> float:
490
+ return _estimate_gb(event)
491
+
492
+ def augment_trace(self) -> None:
493
+ self.data = _augment_trace_helper(self.data)
494
+
495
+ def _compute_stats(self) -> None:
496
+ """populates the name -> stats map"""
497
+ for event in self.events:
498
+ if "cat" not in event or "args" not in event or event["cat"] != "kernel":
499
+ continue
500
+ if "device" not in event["args"]:
501
+ continue
502
+ dev_tmp = event["args"]["device"]
503
+ if dev_tmp not in self._devices:
504
+ continue
505
+ dev = self._devices[event["args"]["device"]]
506
+
507
+ dur = event["dur"] # us
508
+ if "kernel_flop" in event["args"]:
509
+ assert dur != 0
510
+ # 1,000,000us/s * flop / us
511
+ op_flops = event["args"]["kernel_flop"] / (dur / 1e6)
512
+ else:
513
+ op_flops = 0
514
+
515
+ if "kernel_num_gb" in event["args"]:
516
+ assert dur != 0
517
+ # 1,000,000us/s * gb = gb/s
518
+ op_gbps = event["args"]["kernel_num_gb"] / (dur / 1e6)
519
+ else:
520
+ op_gbps = 0
521
+
522
+ if dev.info is not None:
523
+ dtype = self.convert_dtype(event) or self.dtype
524
+ if dtype is None:
525
+ raise RuntimeError(
526
+ "dtype is not found on tensor and default dtype is not set"
527
+ )
528
+ achieved_flops = 100 * op_flops / (1e12 * dev.info.tops[dtype])
529
+ achieved_bandwidth = 100 * op_gbps / dev.info.dram_bw_gbs
530
+ else:
531
+ achieved_flops = 0
532
+ achieved_bandwidth = 0
533
+
534
+ if "name" not in event["args"]:
535
+ continue
536
+ dev.stats[event["name"]].add(
537
+ KernelStats(
538
+ flops=op_flops,
539
+ bw=op_gbps,
540
+ latency=dur,
541
+ achieved_bandwidth=achieved_bandwidth,
542
+ achieved_flops=achieved_flops,
543
+ )
544
+ )
545
+
546
+ def _create_single_table(self, dev: Device) -> Table:
547
+ """Create a table with the devices mapped to indices."""
548
+ headers = [
549
+ "Kernel Name",
550
+ "Kernel Count",
551
+ "FLOPS",
552
+ "Kernel Reads (GB)",
553
+ "Dur (us)",
554
+ "Achieved FLOPS %",
555
+ "Achieved Bandwidth %",
556
+ ]
557
+ rows: dict[str, list[str]] = {}
558
+
559
+ def safe_div_format(x: float, y: float) -> str:
560
+ if y == 0:
561
+ return "0.0"
562
+ return f"{x / y:.4f}"
563
+
564
+ for kernel_name, stats_set in dev.stats.items():
565
+ ker_count = 0
566
+ flops = 0
567
+ flops_count = 0
568
+ achieved_flops = 0.0
569
+ bw = 0.0
570
+ bw_count = 0
571
+ achieved_bandwidth = 0.0
572
+ latency = 0.0
573
+ for stats in stats_set:
574
+ if stats.flops != 0:
575
+ flops += stats.flops
576
+ achieved_flops += stats.achieved_flops
577
+ flops_count += 1
578
+ if stats.bw != 0:
579
+ bw += stats.bw
580
+ achieved_bandwidth += stats.achieved_bandwidth
581
+ bw_count += 1
582
+ latency += stats.latency
583
+ ker_count += 1
584
+ assert ker_count != 0
585
+ rows[kernel_name] = [
586
+ str(ker_count),
587
+ safe_div_format(flops, flops_count),
588
+ safe_div_format(bw, bw_count),
589
+ safe_div_format(latency, ker_count),
590
+ safe_div_format(achieved_flops, flops_count),
591
+ safe_div_format(achieved_bandwidth, bw_count),
592
+ ]
593
+
594
+ return headers, rows
595
+
596
+ def _create_tables(self, devs: DeviceMap) -> dict[int, Table]:
597
+ return {idx: self._create_single_table(dev) for idx, dev in devs.items()}
598
+
599
+ def _combine_tables(
600
+ self, table1: Table, table1_name: str, table2: Table, table2_name: str
601
+ ) -> Table:
602
+ new_headers = (
603
+ ["Kernel Name"]
604
+ + [f"{table1_name} {head}" for head in table1[0][1:]]
605
+ + [f"{table2_name} {head}" for head in table2[0][1:]]
606
+ )
607
+ t1_length = len(table1[0][1:])
608
+ t2_length = len(table2[0][1:])
609
+ new_rows = {}
610
+
611
+ for key, row1, row2 in zip_dicts(
612
+ table1[1],
613
+ table2[1],
614
+ d1_default=["Empty"] * t1_length,
615
+ d2_default=["Empty"] * t2_length,
616
+ ):
617
+ assert row1 is not None
618
+ assert row2 is not None
619
+ new_rows[key] = row1 + row2
620
+ return new_headers, new_rows
621
+
622
+ def report(
623
+ self, other: Optional["JsonProfile"] = None, name_limit: int = 40
624
+ ) -> str:
625
+ def create_ret(
626
+ table_headers: list[str], table_rows: dict[str, list[str]]
627
+ ) -> str:
628
+ table_flattened = [
629
+ [kernel_name[:name_limit], *kernel_vals]
630
+ for kernel_name, kernel_vals in table_rows.items()
631
+ ]
632
+ return tabulate_2d(table_flattened, headers=table_headers)
633
+
634
+ if other is not None:
635
+ self._compute_stats()
636
+ other._compute_stats()
637
+
638
+ self_tables = self._create_tables(self._devices)
639
+ other_tables = self._create_tables(other._devices)
640
+
641
+ self_name = (
642
+ self.benchmark_name if self.benchmark_name is not None else "Table 1"
643
+ )
644
+ other_name = (
645
+ other.benchmark_name if other.benchmark_name is not None else "Table 2"
646
+ )
647
+
648
+ ret = []
649
+ assert self._devices.keys() == other._devices.keys()
650
+ for device_idx, t1, t2 in zip_dicts(
651
+ self_tables, other_tables, d1_default=None, d2_default=None
652
+ ):
653
+ assert t1 is not None
654
+ assert t2 is not None
655
+ table_headers, table_rows = self._combine_tables(
656
+ t1, self_name, t2, other_name
657
+ )
658
+ tab_string = create_ret(table_headers, table_rows)
659
+ # pyrefly: ignore [bad-argument-type]
660
+ ret.append(f"{self._devices[device_idx]}:\n{tab_string}")
661
+ return "\n".join(ret)
662
+ self._compute_stats()
663
+
664
+ self_tables = self._create_tables(self._devices)
665
+
666
+ ret = []
667
+ for idx, table in self_tables.items():
668
+ table_headers, table_rows = table
669
+ tab_string = create_ret(table_headers, table_rows)
670
+ # pyrefly: ignore [bad-argument-type]
671
+ ret.append(f"{self._devices[idx]}:\n{tab_string}")
672
+ return "\n".join(ret)
673
+
674
+ def dump(self, out: str) -> None:
675
+ with open(out, "w") as f:
676
+ json.dump(self.data, f)
677
+
678
+ def combine_with(self, other: "JsonProfile") -> "JsonProfile":
679
+ """
680
+ Combine this profile with another profile by merging their trace events.
681
+ Returns a new JsonProfile object with combined data.
682
+ """
683
+ # Create a new combined data structure
684
+ combined_data = {
685
+ "traceEvents": self.data["traceEvents"] + other.data["traceEvents"],
686
+ "deviceProperties": self.data.get("deviceProperties", []),
687
+ }
688
+
689
+ # Merge device properties, avoiding duplicates
690
+ other_device_props = other.data.get("deviceProperties", [])
691
+ existing_device_ids = OrderedSet(
692
+ [dev["id"] for dev in combined_data["deviceProperties"]]
693
+ )
694
+
695
+ for device_prop in other_device_props:
696
+ if device_prop["id"] not in existing_device_ids:
697
+ combined_data["deviceProperties"].append(device_prop)
698
+
699
+ # Copy any other top-level properties from the first profile
700
+ for key, value in self.data.items():
701
+ if key not in combined_data:
702
+ combined_data[key] = value
703
+
704
+ import os
705
+
706
+ # Create a temporary file to write the combined data
707
+ import tempfile
708
+
709
+ with tempfile.NamedTemporaryFile(
710
+ mode="w", suffix=".json", delete=False
711
+ ) as tmp_file:
712
+ json.dump(combined_data, tmp_file)
713
+ tmp_path = tmp_file.name
714
+
715
+ try:
716
+ # Create new JsonProfile from the combined data
717
+ combined_profile = JsonProfile(
718
+ tmp_path,
719
+ benchmark_name=f"{self.benchmark_name or 'Profile1'}_+_{other.benchmark_name or 'Profile2'}",
720
+ dtype=self.dtype or other.dtype,
721
+ )
722
+ return combined_profile
723
+ finally:
724
+ # Clean up temporary file
725
+ os.unlink(tmp_path)
726
+
727
+
728
+ class ParseException(RuntimeError):
729
+ pass
730
+
731
+
732
+ def main() -> None:
733
+ """
734
+ Main function for the profile analysis script.
735
+ """
736
+ import argparse
737
+
738
+ parser = argparse.ArgumentParser()
739
+ parser.add_argument(
740
+ "--diff",
741
+ nargs=5,
742
+ metavar=(
743
+ "input_file1",
744
+ "name1",
745
+ "input_file2",
746
+ "name2",
747
+ "dtype",
748
+ ),
749
+ help="Two json traces to compare with, specified as <file1> <name1> <file2> <name2> <dtype>",
750
+ )
751
+ parser.add_argument(
752
+ "--name_limit",
753
+ type=int,
754
+ help="the maximum name size in the final report",
755
+ )
756
+ parser.add_argument(
757
+ "--augment_trace",
758
+ "-a",
759
+ nargs=3,
760
+ metavar=("input_file", "output_file", "dtype"),
761
+ help="Augment a trace with inductor meta information. Provide input and output file paths.",
762
+ )
763
+ parser.add_argument(
764
+ "--analysis",
765
+ nargs=2,
766
+ metavar=("input_file", "dtype"),
767
+ help="Run analysis on a single trace, specified as <file> <dtype>",
768
+ )
769
+ parser.add_argument(
770
+ "--combine",
771
+ nargs="+",
772
+ metavar=("input_files", "output_file"),
773
+ help="Combine multiple profiles into a single profile by merging trace events. Specify as <input_file1> \
774
+ <input_file2> [input_file3 ...] <output_file>. The last argument is the output file, all preceding arguments are \
775
+ input files to combine.",
776
+ )
777
+ args = parser.parse_args()
778
+
779
+ if args.diff:
780
+ p1 = JsonProfile(args.diff[0], args.diff[1], dtype=args.diff[4])
781
+ p1.augment_trace()
782
+ p2 = JsonProfile(args.diff[2], args.diff[3], dtype=args.diff[4])
783
+ p2.augment_trace()
784
+ if args.name_limit:
785
+ print(p1.report(p2, name_limit=args.name_limit))
786
+ else:
787
+ print(p1.report(p2))
788
+ if args.analysis:
789
+ p1 = JsonProfile(
790
+ args.analysis[0],
791
+ dtype=args.analysis[1],
792
+ )
793
+ p1.augment_trace()
794
+ if args.name_limit:
795
+ print(p1.report(name_limit=args.name_limit))
796
+ else:
797
+ print(p1.report())
798
+ if args.augment_trace:
799
+ p = JsonProfile(args.augment_trace[0], dtype=args.augment_trace[2])
800
+ p.augment_trace()
801
+ p.dump(args.augment_trace[1])
802
+ if args.combine:
803
+ input_files = args.combine[:-1] # All arguments except the last one
804
+ output_file = args.combine[-1] # Last argument is the output file
805
+
806
+ if len(input_files) < 2:
807
+ print("Error: At least 2 input files are required for combining")
808
+ return
809
+
810
+ # Load the first profile
811
+ combined = JsonProfile(input_files[0], dtype=None)
812
+
813
+ # Iteratively combine with all other profiles
814
+ for input_file in input_files[1:]:
815
+ profile = JsonProfile(input_file, dtype=None)
816
+ combined = combined.combine_with(profile)
817
+
818
+ combined.dump(output_file)
819
+ print(f"Successfully combined {', '.join(input_files)} into {output_file}")
820
+
821
+
822
+ if __name__ == "__main__":
823
+ main()
.venv/lib/python3.10/site-packages/torch/_inductor/compile_worker/__init__.py ADDED
File without changes
.venv/lib/python3.10/site-packages/torch/_inductor/compile_worker/__main__.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import argparse
3
+ import base64
4
+ import functools
5
+ import importlib
6
+ import logging
7
+ import os
8
+ import sys
9
+ from typing import TypeVar
10
+
11
+ from torch._inductor.async_compile import pre_fork_setup
12
+ from torch._inductor.codecache import torch_key
13
+ from torch._inductor.compile_worker.subproc_pool import (
14
+ SubprocKind,
15
+ SubprocMain,
16
+ SubprocPickler,
17
+ )
18
+ from torch._inductor.compile_worker.utils import _async_compile_initializer
19
+ from torch._inductor.runtime.compile_tasks import _set_triton_ptxas_path
20
+
21
+
22
+ _T = TypeVar("_T")
23
+
24
+
25
+ log = logging.getLogger(__name__)
26
+
27
+ _set_triton_ptxas_path()
28
+
29
+ try:
30
+ import triton
31
+
32
+ assert triton is not None # preload in parent
33
+ except ImportError:
34
+ pass
35
+
36
+
37
+ def _lookup_and_create_type(base: type[_T], qname: str) -> _T:
38
+ """
39
+ Given a base type and qualified name: import & lookup that name, check
40
+ that it's of the given type and then instantiate it.
41
+ """
42
+ pkg, name = qname.rsplit(".", 1)
43
+ mod = importlib.import_module(pkg)
44
+ ty = getattr(mod, name)
45
+ if not issubclass(ty, base):
46
+ raise TypeError(f"Type {ty} is not a subtype of {base}")
47
+ return ty()
48
+
49
+
50
+ def main():
51
+ try:
52
+ parser = argparse.ArgumentParser()
53
+ parser.add_argument(
54
+ "--pickler", type=functools.partial(_lookup_and_create_type, SubprocPickler)
55
+ )
56
+ parser.add_argument("--kind", type=SubprocKind)
57
+ parser.add_argument("--workers", type=int)
58
+ parser.add_argument("--parent", type=int)
59
+ parser.add_argument("--read-fd", type=int)
60
+ parser.add_argument("--write-fd", type=int)
61
+ parser.add_argument("--torch-key", type=str)
62
+ args = parser.parse_args()
63
+ if os.getppid() != args.parent:
64
+ sys.exit(0)
65
+ read_fd = os.fdopen(args.read_fd, "rb")
66
+ write_fd = os.fdopen(args.write_fd, "wb")
67
+
68
+ pre_fork_setup()
69
+
70
+ torch_key.set(base64.b64decode(args.torch_key.encode("utf-8"))) # type: ignore[attr-defined]
71
+
72
+ _async_compile_initializer(args.parent)
73
+
74
+ SubprocMain(args.pickler, args.kind, args.workers, read_fd, write_fd).main()
75
+ except Exception:
76
+ log.exception("Uncaught exception in compile_worker subprocess")
77
+
78
+
79
+ if __name__ == "__main__":
80
+ main()
.venv/lib/python3.10/site-packages/torch/_inductor/compile_worker/subproc_pool.py ADDED
@@ -0,0 +1,496 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import base64
2
+ import functools
3
+ import itertools
4
+ import logging
5
+ import multiprocessing
6
+ import os
7
+ import pickle
8
+ import struct
9
+ import subprocess
10
+ import sys
11
+ import threading
12
+ import traceback
13
+ import typing
14
+ from collections.abc import Callable
15
+ from concurrent.futures import Future, ProcessPoolExecutor
16
+ from concurrent.futures.process import BrokenProcessPool
17
+ from enum import Enum, IntEnum
18
+ from typing import Any, IO, Optional, TypeVar
19
+ from typing_extensions import Never, ParamSpec
20
+
21
+ # _thread_safe_fork is needed because the subprocesses in the pool can read
22
+ # justknobs, e.g., in the Triton compiler. For internal, the import installs
23
+ # functionality to destroy singletons before forking and re-enable them after.
24
+ import torch._thread_safe_fork # noqa: F401
25
+ from torch._inductor import config
26
+ from torch._inductor.codecache import torch_key
27
+ from torch._inductor.compile_worker.timer import Timer
28
+ from torch._inductor.compile_worker.tracked_process_pool import (
29
+ TrackedProcessPoolExecutor,
30
+ )
31
+ from torch._inductor.compile_worker.utils import _async_compile_initializer
32
+ from torch._inductor.utils import get_ld_library_path, python_subprocess_env
33
+ from torch._utils_internal import find_compile_subproc_binary
34
+ from torch.monitor import _WaitCounter, _WaitCounterTracker
35
+
36
+
37
+ log = logging.getLogger(__name__)
38
+
39
+ _P = ParamSpec("_P")
40
+ _T = TypeVar("_T")
41
+
42
+
43
+ class MsgHeader(IntEnum):
44
+ ERROR = 0
45
+ SHUTDOWN = 1
46
+ QUIESCE = 2
47
+ WAKEUP = 3
48
+ JOB = 4
49
+
50
+
51
+ def _pack_msg(msg_header: MsgHeader, job_id: int, length: int) -> bytes:
52
+ return struct.pack("nnn", int(msg_header), job_id, length)
53
+
54
+
55
+ def _unpack_msg(data: bytes) -> tuple[MsgHeader, int, int]:
56
+ if not data:
57
+ return MsgHeader.ERROR, -1, -1
58
+ msg_header, job_id, length = struct.unpack("nnn", data)
59
+ return MsgHeader(msg_header), job_id, length
60
+
61
+
62
+ msg_bytes = len(_pack_msg(MsgHeader.JOB, 0, 0))
63
+
64
+
65
+ def _send_msg(
66
+ write_pipe: IO[bytes], msg_header: MsgHeader, job_id: int = -1, data: bytes = b""
67
+ ) -> None:
68
+ length = len(data)
69
+ write_pipe.write(_pack_msg(msg_header, job_id, length))
70
+ if length > 0:
71
+ write_pipe.write(data)
72
+ write_pipe.flush()
73
+
74
+
75
+ def _recv_msg(read_pipe: IO[bytes]) -> tuple[MsgHeader, int, bytes]:
76
+ msg_header, job_id, length = _unpack_msg(read_pipe.read(msg_bytes))
77
+ data = read_pipe.read(length) if length > 0 else b""
78
+ return msg_header, job_id, data
79
+
80
+
81
+ class _SubprocExceptionInfo:
82
+ """
83
+ Carries exception info from subprocesses across the wire. traceback
84
+ objects are not pickleable, so we store the trace as a string and
85
+ use it for the message in the exception thrown in the main process.
86
+ """
87
+
88
+ def __init__(self, details: str) -> None:
89
+ self.details = details
90
+
91
+
92
+ class SubprocException(Exception):
93
+ """
94
+ Thrown when a job in a subprocess raises an Exception.
95
+ """
96
+
97
+ def __init__(self, details: str, name: str = "<unknown>") -> None:
98
+ self.details = details
99
+ super().__init__(
100
+ f"An exception occurred in a subprocess:\n\nName={name}\n{details}"
101
+ )
102
+
103
+ def with_name(self, name: str) -> "SubprocException":
104
+ return SubprocException(self.details, name)
105
+
106
+
107
+ class SubprocPickler:
108
+ """
109
+ Allows a caller to provide a custom pickler for passing data with the
110
+ subprocess.
111
+ """
112
+
113
+ def dumps(self, obj: object) -> bytes:
114
+ return pickle.dumps(obj, pickle.HIGHEST_PROTOCOL)
115
+
116
+ def loads(self, data: bytes) -> object:
117
+ return pickle.loads(data)
118
+
119
+
120
+ class SubprocKind(Enum):
121
+ FORK = "fork"
122
+ SPAWN = "spawn"
123
+
124
+
125
+ class SubprocPool:
126
+ """
127
+ Mimic a concurrent.futures.ProcessPoolExecutor, but wrap it in
128
+ a subprocess.Popen() to try to avoid issues with forking/spawning
129
+ """
130
+
131
+ def __init__(
132
+ self,
133
+ nprocs: int,
134
+ pickler: Optional[SubprocPickler] = None,
135
+ kind: SubprocKind = SubprocKind.FORK,
136
+ quiesce: bool = False,
137
+ ) -> None:
138
+ entry = os.path.join(os.path.dirname(__file__), "__main__.py")
139
+ self.pickler = pickler or SubprocPickler()
140
+ self.kind = kind
141
+
142
+ subproc_read_fd, write_fd = os.pipe()
143
+ read_fd, subproc_write_fd = os.pipe()
144
+ self.write_pipe = os.fdopen(write_fd, "wb")
145
+ self.read_pipe = os.fdopen(read_fd, "rb")
146
+ torch_key_str = base64.b64encode(torch_key()).decode("utf-8")
147
+
148
+ cmd = [
149
+ sys.executable,
150
+ entry,
151
+ ]
152
+ if (binary := find_compile_subproc_binary()) is not None:
153
+ cmd = [binary]
154
+
155
+ args = [
156
+ f"--pickler={self.pickler.__class__.__module__}.{self.pickler.__class__.__name__}",
157
+ f"--kind={self.kind.value}",
158
+ f"--workers={nprocs}",
159
+ f"--parent={os.getpid()}",
160
+ f"--read-fd={str(subproc_read_fd)}",
161
+ f"--write-fd={str(subproc_write_fd)}",
162
+ f"--torch-key={torch_key_str}",
163
+ ]
164
+ cmd.extend(args)
165
+ log_path = None
166
+ self.log_file = None
167
+
168
+ if config.worker_suppress_logging:
169
+ log_path = os.devnull
170
+ log.info("Suppressing compile worker output due to config")
171
+ else:
172
+ log_path = config.torchinductor_worker_logpath
173
+ if not log_path:
174
+ log_path = config.get_worker_log_path()
175
+
176
+ if log_path:
177
+ # pyrefly: ignore [bad-assignment]
178
+ self.log_file = open(log_path, "w") # noqa:SIM115
179
+
180
+ self.process = subprocess.Popen(
181
+ cmd,
182
+ env={
183
+ **python_subprocess_env(),
184
+ # Safeguard against creating a SubprocPool in the subprocess.
185
+ "TORCH_WARM_POOL": "0",
186
+ # Some internal usages need a modified LD_LIBRARY_PATH.
187
+ "LD_LIBRARY_PATH": get_ld_library_path(),
188
+ },
189
+ pass_fds=(subproc_read_fd, subproc_write_fd),
190
+ stdout=self.log_file,
191
+ stderr=self.log_file,
192
+ )
193
+ self.write_lock = threading.Lock()
194
+ self.read_thread = threading.Thread(
195
+ target=self._read_thread, name="InductorSubproc", daemon=True
196
+ )
197
+
198
+ self.futures_lock = threading.Lock()
199
+ self.pending_futures: dict[int, Future[Any]] = {}
200
+ # The pending waitcounter, is used to indicate the time when we have any specific job running.
201
+ self.pending_waitcounters: dict[int, Any] = {}
202
+ self.job_id_count = itertools.count()
203
+
204
+ # The running waitcounter indicates the time when the SubProcPool object exists.
205
+ self.running = True
206
+ self.running_waitcounter = _WaitCounter(
207
+ "pytorch.wait_counter.subproc_pool.running"
208
+ ).guard()
209
+ self.running_waitcounter.__enter__()
210
+
211
+ # The quiesce waitcounter indicates when the job is in a quiesced state.
212
+ self.quiesce_waitcounter: Optional[_WaitCounterTracker] = None
213
+
214
+ # Firstjob is used to capture the time from when the firstjob is queued, to when the first job is done.
215
+ self.firstjob = True
216
+ self.firstjob_id: Optional[int] = None
217
+ self.firstjob_waitcounter = _WaitCounter(
218
+ "pytorch.wait_counter.subproc_pool.first_job"
219
+ ).guard()
220
+
221
+ if quiesce:
222
+ self.timer: Optional[Timer] = Timer(
223
+ config.quiesce_async_compile_time, self.quiesce
224
+ )
225
+ else:
226
+ self.timer = None
227
+
228
+ # Start thread last to ensure all member variables are initialized
229
+ # before any access.
230
+ self.read_thread.start()
231
+
232
+ def submit(
233
+ self, job_fn: Callable[_P, _T], *args: _P.args, **kwargs: _P.kwargs
234
+ ) -> Future[_T]:
235
+ if args or kwargs:
236
+ # pyrefly: ignore [bad-assignment]
237
+ job_fn = functools.partial(job_fn, *args, **kwargs)
238
+ job_data = self.pickler.dumps(job_fn)
239
+ future: Future[_T]
240
+ with self.futures_lock:
241
+ job_id = next(self.job_id_count)
242
+ self.pending_futures[job_id] = future = Future()
243
+ self.pending_waitcounters[job_id] = _WaitCounter(
244
+ "pytorch.wait_counter.subproc_pool.job"
245
+ ).guard()
246
+ self.pending_waitcounters[job_id].__enter__()
247
+ if self.quiesce_waitcounter:
248
+ self.firstjob = True
249
+ self.quiesce_waitcounter.__exit__()
250
+ self.quiesce_waitcounter = None
251
+ # This can be entered from either quiesce wakeup, or from startup.
252
+ if self.firstjob:
253
+ self.firstjob_id = job_id
254
+ self.firstjob_waitcounter.__enter__()
255
+ self.firstjob = False
256
+ future.set_running_or_notify_cancel()
257
+ self._send(MsgHeader.JOB, job_id, job_data)
258
+ return future
259
+
260
+ def _send(self, msg_header: MsgHeader, job_id: int = -1, data: bytes = b"") -> None:
261
+ with self.write_lock:
262
+ if not self.running:
263
+ raise RuntimeError("Attempting to use a closed pool")
264
+ _send_msg(self.write_pipe, msg_header, job_id, data)
265
+
266
+ def _read_thread(self) -> None:
267
+ while True:
268
+ data = b""
269
+ job_id = -1
270
+ try:
271
+ msg_header, job_id, data = _recv_msg(self.read_pipe)
272
+ except Exception:
273
+ # Something went wrong during the read. There's no way we have a
274
+ # valid msg.
275
+ log.exception("failure in subproc_pool._recv_msg")
276
+ msg_header = MsgHeader.ERROR
277
+
278
+ if msg_header != MsgHeader.JOB:
279
+ # read_pipe returned None or got exception
280
+ if self.running:
281
+ log.warning("SubprocPool unclean exit")
282
+ self.running = False
283
+ self.running_waitcounter.__exit__()
284
+ self.read_pipe.close()
285
+ # Cancel all the pending futures.
286
+ self.shutdown()
287
+ return
288
+
289
+ try:
290
+ result = self.pickler.loads(data)
291
+ except Exception as e:
292
+ # Something went wrong unpickling. We have a job_id so just
293
+ # notify that particular future and continue on.
294
+ log.exception("unpickle failure in SubprocPool._read_thread")
295
+ result = e
296
+
297
+ with self.futures_lock:
298
+ if not self.running:
299
+ return
300
+ if self.timer:
301
+ self.timer.record_call()
302
+ if isinstance(result, _SubprocExceptionInfo):
303
+ # An exception occurred in the submitted job
304
+ self.pending_futures[job_id].set_exception(
305
+ SubprocException(result.details)
306
+ )
307
+ elif isinstance(result, Exception):
308
+ # An exception occurred in some of our subprocess machinery.
309
+ self.pending_futures[job_id].set_exception(result)
310
+ else:
311
+ self.pending_futures[job_id].set_result(result)
312
+
313
+ self.pending_waitcounters[job_id].__exit__()
314
+ del self.pending_waitcounters[job_id]
315
+ if self.firstjob_id == job_id:
316
+ self.firstjob_waitcounter.__exit__()
317
+
318
+ del self.pending_futures[job_id]
319
+
320
+ def quiesce(self) -> None:
321
+ self._send(MsgHeader.QUIESCE)
322
+ if self.quiesce_waitcounter is None:
323
+ self.quiesce_waitcounter = _WaitCounter(
324
+ "pytorch.wait_counter.subproc_pool.quiesced"
325
+ ).guard()
326
+ self.quiesce_waitcounter.__enter__()
327
+
328
+ def wakeup(self) -> None:
329
+ self._send(MsgHeader.WAKEUP)
330
+
331
+ def shutdown(self) -> None:
332
+ try:
333
+ with self.write_lock:
334
+ if not self.running:
335
+ return
336
+ if self.timer:
337
+ self.timer.quit()
338
+ self.running = False
339
+ self.running_waitcounter.__exit__()
340
+ _send_msg(self.write_pipe, MsgHeader.SHUTDOWN)
341
+ self.write_pipe.close()
342
+ self.process.wait(300)
343
+ if self.log_file:
344
+ self.log_file.close()
345
+ except OSError:
346
+ log.warning("Ignored OSError in pool shutdown", exc_info=True)
347
+ finally:
348
+ with self.futures_lock:
349
+ for future in self.pending_futures.values():
350
+ if not future.cancel():
351
+ future.set_exception(RuntimeError("SubprocPool closed"))
352
+ self.pending_futures.clear()
353
+
354
+
355
+ class SubprocMain:
356
+ """Communicates with a SubprocPool in the parent process, called by __main__.py"""
357
+
358
+ def __init__(
359
+ self,
360
+ pickler: SubprocPickler,
361
+ kind: SubprocKind,
362
+ nprocs: int,
363
+ read_pipe: IO[bytes],
364
+ write_pipe: IO[bytes],
365
+ ) -> None:
366
+ self.pickler = pickler
367
+ self.kind = kind
368
+ self.read_pipe = read_pipe
369
+ self.write_pipe = write_pipe
370
+ self.write_lock = threading.Lock()
371
+ self.nprocs = nprocs
372
+ self.pool: Optional[ProcessPoolExecutor] = None
373
+ self.running = True
374
+
375
+ def main(self) -> None:
376
+ while True:
377
+ msg_header, job_id, data = _recv_msg(self.read_pipe)
378
+ if msg_header == MsgHeader.JOB:
379
+ self.submit(job_id, data)
380
+ elif msg_header == MsgHeader.WAKEUP:
381
+ self._start_pool()
382
+ elif msg_header == MsgHeader.QUIESCE:
383
+ self._quiesce()
384
+ else:
385
+ return self._shutdown()
386
+
387
+ def _quiesce(self) -> None:
388
+ if self.pool is not None:
389
+ self.pool.shutdown(wait=False)
390
+ self.pool = None
391
+
392
+ def _shutdown(self) -> None:
393
+ with self.write_lock:
394
+ self.running = False
395
+ try:
396
+ _send_msg(self.write_pipe, MsgHeader.SHUTDOWN)
397
+ self.write_pipe.close()
398
+ except BrokenPipeError:
399
+ pass # parent process already shutdown
400
+ self.read_pipe.close()
401
+ self._quiesce()
402
+
403
+ def submit(self, job_id: int, data: bytes) -> None:
404
+ while self.running:
405
+ try:
406
+ self._submit_inner(job_id, data)
407
+ return
408
+ except BrokenProcessPool:
409
+ # If any subprocess in the pool crashes, we get a BrokenProcessPool
410
+ # exception and the whole pool becomes unusable. Handle crashes by
411
+ # recreating the pool and resubmitting.
412
+ self.pool = None
413
+
414
+ def _submit_inner(self, job_id: int, data: bytes) -> None:
415
+ def callback(fut: Future[Any]) -> None:
416
+ if not self.running:
417
+ return
418
+ try:
419
+ result = fut.result()
420
+ except Exception as e:
421
+ log.exception("Error in subprocess")
422
+ result = self.pickler.dumps(e)
423
+ assert isinstance(result, bytes)
424
+ with self.write_lock:
425
+ if self.running:
426
+ _send_msg(self.write_pipe, MsgHeader.JOB, job_id, result)
427
+ return
428
+
429
+ self._start_pool()
430
+ assert self.pool is not None
431
+
432
+ future = self.pool.submit(
433
+ functools.partial(SubprocMain.do_job, self.pickler, data)
434
+ )
435
+ future.add_done_callback(callback)
436
+
437
+ def _start_pool(self) -> None:
438
+ if self.pool is not None:
439
+ return
440
+
441
+ self.pool = TrackedProcessPoolExecutor(
442
+ self.nprocs,
443
+ mp_context=multiprocessing.get_context(self.kind.value),
444
+ initializer=functools.partial(_async_compile_initializer, os.getpid()),
445
+ )
446
+ multiprocessing.util.Finalize(
447
+ None, self.pool.shutdown, exitpriority=sys.maxsize
448
+ )
449
+ _warm_process_pool(self.pool, self.nprocs)
450
+
451
+ @staticmethod
452
+ def do_job(pickler: SubprocPickler, data: bytes) -> bytes:
453
+ # do the pickle/unpickle in the sub-subproc
454
+ job = typing.cast(Callable[[], object], pickler.loads(data))
455
+
456
+ try:
457
+ result = job()
458
+ except Exception:
459
+ result = _SubprocExceptionInfo(traceback.format_exc())
460
+ return pickler.dumps(result)
461
+
462
+
463
+ AnyPool = typing.Union[ProcessPoolExecutor, SubprocPool]
464
+
465
+
466
+ def _warm_process_pool(pool: ProcessPoolExecutor, n: int) -> None:
467
+ # We have to fork processes for compiler workers, but the more memory and other resources that are loaded, the
468
+ # slower the os.fork time is, quite drastically. It also holds the GIL so we can't put it on another thread.
469
+
470
+ # Examples:
471
+ # A simple x + x + x script: 10ms seconds in the middle of the program, 2ms at startup
472
+ # tf_efficientnet_b0 benchmark: 50ms! in the middle of the program , 3ms at startup
473
+
474
+ # So we want to start the workers early when it is still cheap, and also to allow the workers to get
475
+ # ready before we have work for them.
476
+
477
+ # ProcessPoolExecutor also does not launch the workers until it finds a point when all the workers are idle.
478
+ # But if we waited until then fork time will be long and we will be waiting for the processes to initialize.
479
+
480
+ # We force them to start here with some YOLOing of the internal methods.
481
+
482
+ if hasattr(pool, "_start_queue_management_thread"):
483
+ pool._start_queue_management_thread()
484
+ else:
485
+ for _ in range(n):
486
+ pool._adjust_process_count()
487
+ if hasattr(pool, "_start_executor_manager_thread"):
488
+ pool._start_executor_manager_thread()
489
+
490
+
491
+ class TestException(RuntimeError):
492
+ pass
493
+
494
+
495
+ def raise_testexc() -> Never:
496
+ raise TestException
.venv/lib/python3.10/site-packages/torch/_inductor/compile_worker/timer.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections.abc import Callable
2
+ from threading import Lock, Thread
3
+ from time import monotonic, sleep
4
+ from typing import Optional, Union
5
+
6
+
7
+ class Timer:
8
+ """
9
+ This measures how long we have gone since last receiving an event and if it is greater than a set interval, calls a function.
10
+ """
11
+
12
+ def __init__(
13
+ self,
14
+ duration: Union[int, float], # Duration in seconds
15
+ call: Callable[[], None], # Function to call when we expire
16
+ ) -> None:
17
+ # We don't start the background thread until we actually get an event.
18
+ self.background_thread: Optional[Thread] = None
19
+ self.last_called: Optional[float] = None
20
+ self.duration = duration
21
+ self.sleep_time = duration / 2
22
+ self.call = call
23
+ self.exit = False
24
+
25
+ self.lock = Lock()
26
+
27
+ def record_call(self) -> None:
28
+ with self.lock:
29
+ if self.background_thread is None:
30
+ self.background_thread = Thread(
31
+ target=self.check, daemon=True, name="subproc_worker_timer"
32
+ )
33
+ self.background_thread.start()
34
+ self.last_called = monotonic()
35
+
36
+ def quit(self) -> None:
37
+ with self.lock:
38
+ self.exit = True
39
+
40
+ def check(self) -> None:
41
+ while True:
42
+ # We have to be sensitive on checking here, to avoid too much impact on cpu
43
+ sleep(self.sleep_time)
44
+ with self.lock:
45
+ if self.exit:
46
+ return
47
+ assert self.last_called is not None
48
+ if self.last_called + self.duration >= monotonic():
49
+ continue
50
+ self.last_called = None
51
+ self.background_thread = None
52
+
53
+ # Releasing lock in case self.call() takes a very long time or is reentrant
54
+ self.call()
55
+ return
.venv/lib/python3.10/site-packages/torch/_inductor/compile_worker/tracked_process_pool.py ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import atexit
2
+ import concurrent
3
+ import dataclasses
4
+ import logging
5
+ import threading
6
+ from collections.abc import Callable
7
+ from concurrent.futures import Future, ProcessPoolExecutor
8
+ from dataclasses import dataclass
9
+ from multiprocessing.context import BaseContext
10
+ from time import time
11
+ from typing import Any, Optional, TypeVar
12
+ from typing_extensions import ParamSpec
13
+
14
+ # _thread_safe_fork is needed because the subprocesses in the pool can read
15
+ # justknobs, e.g., in the Triton compiler. For internal, the import installs
16
+ # functionality to destroy singletons before forking and re-enable them after.
17
+ import torch._thread_safe_fork # noqa: F401
18
+
19
+
20
+ _P = ParamSpec("_P")
21
+ _R = TypeVar("_R")
22
+
23
+
24
+ log = logging.getLogger(__name__)
25
+
26
+
27
+ @dataclass
28
+ class _QueueStats:
29
+ # Mapping from id(future) -> start time
30
+ pending: dict[int, float] = dataclasses.field(default_factory=dict)
31
+ timing: list[float] = dataclasses.field(default_factory=list)
32
+ enqueue_count: int = 0
33
+ dequeue_count: int = 0
34
+ max_queue_depth: int = 0
35
+ pool_count: int = 0
36
+
37
+
38
+ # The queue statistics tracked by TrackedProcessPoolExecutor. Always grab
39
+ # _queue_stats_lock before touching.
40
+ _queue_stats = _QueueStats()
41
+ _queue_stats_lock = threading.Lock()
42
+
43
+
44
+ class TrackedProcessPoolExecutor(ProcessPoolExecutor):
45
+ def __init__(
46
+ self,
47
+ max_workers: Optional[int] = None,
48
+ mp_context: Optional[BaseContext] = None,
49
+ initializer: Optional[Callable[[], object]] = None,
50
+ ) -> None:
51
+ with _queue_stats_lock:
52
+ _queue_stats.pool_count += 1
53
+ super().__init__(max_workers, mp_context, initializer)
54
+
55
+ def _record_dequeue(self, f: Future[Any]) -> None:
56
+ now = time()
57
+ with _queue_stats_lock:
58
+ stats = _queue_stats
59
+ if (start_time := stats.pending.pop(id(f), None)) is None:
60
+ return
61
+ stats.dequeue_count += 1
62
+ duration = now - start_time
63
+ stats.timing.append(duration)
64
+
65
+ def _record_enqueue(self, f: Future[Any]) -> None:
66
+ # Monkeypatch the set_running_or_notify_cancel so we can track when the Future moves out of PENDING.
67
+ saved_running_or_notify_cancel = f.set_running_or_notify_cancel
68
+
69
+ def set_running_or_notify_cancel() -> Any:
70
+ self._record_dequeue(f)
71
+ return saved_running_or_notify_cancel()
72
+
73
+ now = time()
74
+ with _queue_stats_lock:
75
+ stats = _queue_stats
76
+ stats.pending[id(f)] = now
77
+ stats.enqueue_count += 1
78
+ stats.max_queue_depth = max(stats.max_queue_depth, len(stats.pending))
79
+ f.set_running_or_notify_cancel = set_running_or_notify_cancel # type: ignore[method-assign]
80
+
81
+ if f._state != concurrent.futures._base.PENDING:
82
+ self._record_dequeue(f)
83
+
84
+ def submit(
85
+ self, fn: Callable[_P, _R], /, *args: _P.args, **kwargs: _P.kwargs
86
+ ) -> Future[_R]:
87
+ # pyrefly: ignore [bad-argument-type]
88
+ f = super().submit(fn, *args, **kwargs)
89
+ self._record_enqueue(f)
90
+ return f
91
+
92
+
93
+ @atexit.register
94
+ def _queue_stats_report() -> None:
95
+ stats = _queue_stats
96
+ if stats.pool_count == 0:
97
+ return
98
+
99
+ timing = stats.timing
100
+ timing.sort()
101
+
102
+ log.info("AsyncCompile Metrics:")
103
+ log.info(" Pools %s", stats.pool_count)
104
+ log.info(
105
+ " Items %d enqueued / %d dequeued", stats.enqueue_count, stats.dequeue_count
106
+ )
107
+ log.info(" Max Queue Depth: %d", stats.max_queue_depth)
108
+ n = len(timing)
109
+ if n > 0:
110
+ log.info(" Longest queue time: %0.2fs", timing[-1])
111
+ log.info(" P50: %0.2fs", timing[n // 2])
112
+ if n >= 20:
113
+ log.info(" P95: %0.2fs", timing[n * 95 // 100])
.venv/lib/python3.10/site-packages/torch/_inductor/compile_worker/utils.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import signal
3
+ from threading import Thread
4
+ from time import sleep
5
+ from typing import Optional
6
+
7
+
8
+ _IN_TOPLEVEL_PROCESS = True
9
+
10
+
11
+ def in_toplevel_process() -> bool:
12
+ global _IN_TOPLEVEL_PROCESS
13
+ return _IN_TOPLEVEL_PROCESS
14
+
15
+
16
+ # If this process dies abnormally (e.g. segfault)
17
+ # it will not shut down the workers. Instead,
18
+ # the workers will have their parent reassigned to the
19
+ # init process. This launches a separate thread to
20
+ # watch for the worker getting reassigned,
21
+ # and cleans it up in this case.
22
+ #
23
+ # This function cannot be an inner function since otherwise mp_context="spawn" would
24
+ # not work for ProcessPoolExecutor since inner functions cannot be pickled.
25
+ def _async_compile_initializer(orig_ppid: int) -> None:
26
+ import torch._C
27
+
28
+ def run() -> None:
29
+ while True:
30
+ sleep(60)
31
+ if orig_ppid != os.getppid():
32
+ os.kill(os.getpid(), signal.SIGKILL)
33
+
34
+ global _watchdog_thread, _original_parent
35
+ _original_parent = orig_ppid
36
+ _watchdog_thread = Thread(target=run, daemon=True)
37
+ _watchdog_thread.start()
38
+ # Ignore Ctrl-C (i.e. SIGINT) sent to pool workers to avoid meaningless log spam.
39
+ signal.signal(signal.SIGINT, signal.SIG_IGN)
40
+
41
+ # Install a crash handler to print out the stacktrace for SEGV
42
+ torch._C._initCrashHandler()
43
+
44
+ # Set a bit to distinguish async_compile subprocesses from the toplevel process.
45
+ global _IN_TOPLEVEL_PROCESS
46
+ _IN_TOPLEVEL_PROCESS = False
47
+
48
+
49
+ _watchdog_thread: Optional[Thread] = None
50
+ _original_parent: Optional[int] = None
51
+
52
+
53
+ def has_parent_changed() -> bool:
54
+ return _original_parent != os.getppid()
.venv/lib/python3.10/site-packages/torch/_inductor/fx_passes/serialized_patterns/__init__.py ADDED
File without changes
.venv/lib/python3.10/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_1.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: ignore-errors
2
+
3
+ # noqa: F401, E501
4
+ # This is an auto-generated file. Please do not modify it by hand.
5
+ # To re-generate, run:
6
+ # cd ~/pytorch && python torchgen/fuse/gen_patterns.py
7
+
8
+ import torch
9
+ import torch._inductor
10
+ import operator
11
+
12
+ aten = torch.ops.aten
13
+ prims = torch.ops.prims
14
+
15
+ from torch._inductor.pattern_matcher import (
16
+ Arg,
17
+ CallFunction,
18
+ CallFunctionVarArgs,
19
+ CallMethod,
20
+ CallMethodVarArgs,
21
+ CallModule,
22
+ CallModuleVarArgs,
23
+ ExclusiveKeywordArg,
24
+ Ignored,
25
+ KeywordArg,
26
+ ListOf,
27
+ MultiOutputPattern,
28
+ PatternExpr,
29
+ RepeatedExpr,
30
+ _TargetArgsExpr,
31
+ _TargetExpr,
32
+ _TargetExprVarArgs,
33
+ )
34
+ expand_default = CallFunction(aten.expand.default, KeywordArg('query'), Ignored())
35
+ view_default = CallFunction(aten.view.default, expand_default, Ignored(), _users=2)
36
+ permute_default = CallFunction(aten.permute.default, KeywordArg('key'), Ignored())
37
+ expand_default_1 = CallFunction(aten.expand.default, permute_default, Ignored())
38
+ view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored(), _users=2)
39
+ bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1)
40
+ view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored())
41
+ div_Tensor = CallFunction(aten.div.Tensor, view_default_2, KeywordArg('inv_scale'), _users=2)
42
+ amax_default = CallFunction(aten.amax.default, div_Tensor, Ignored(), True)
43
+ sub_Tensor = CallFunction(aten.sub.Tensor, div_Tensor, amax_default)
44
+ exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2)
45
+ sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True)
46
+ div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList, _users=3)
47
+ expand_default_2 = CallFunction(aten.expand.default, div_Tensor_1, Ignored())
48
+ view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored(), _users=2)
49
+ expand_default_3 = CallFunction(aten.expand.default, KeywordArg('value'), Ignored())
50
+ view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored(), _users=2)
51
+ bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4)
52
+ view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored())
53
+ neg_default = CallFunction(aten.neg.default, div_Tensor_1)
54
+ view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2)
55
+ permute_default_1 = CallFunction(aten.permute.default, view_default_4, Ignored())
56
+ bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_1)
57
+ view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored())
58
+ mul_Tensor = CallFunction(aten.mul.Tensor, view_default_7, div_Tensor_1, _users=2)
59
+ sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor, Ignored(), True)
60
+ fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor)
61
+ div_Tensor_2 = CallFunction(aten.div.Tensor, fma_default, KeywordArg('inv_scale'))
62
+ view_default_8 = CallFunction(aten.view.default, div_Tensor_2, Ignored(), _users=2)
63
+ permute_default_2 = CallFunction(aten.permute.default, view_default_1, Ignored())
64
+ bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_2)
65
+ view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored())
66
+ permute_default_3 = CallFunction(aten.permute.default, view_default, Ignored())
67
+ bmm_default_4 = CallFunction(aten.bmm.default, permute_default_3, view_default_8)
68
+ view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored())
69
+ permute_default_4 = CallFunction(aten.permute.default, view_default_10, Ignored())
70
+ permute_default_5 = CallFunction(aten.permute.default, view_default_3, Ignored())
71
+ bmm_default_5 = CallFunction(aten.bmm.default, permute_default_5, view_default_6)
72
+ view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored())
73
+ _sfdp_pattern_1_training = MultiOutputPattern([view_default_5,
74
+ view_default_9,
75
+ permute_default_4,
76
+ view_default_11,
77
+ None
78
+ ])
79
+
80
+
81
+ expand_default = CallFunction(aten.expand.default, KeywordArg('query'), Ignored())
82
+ view_default = CallFunction(aten.view.default, expand_default, Ignored())
83
+ permute_default = CallFunction(aten.permute.default, KeywordArg('key'), Ignored())
84
+ expand_default_1 = CallFunction(aten.expand.default, permute_default, Ignored())
85
+ view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored())
86
+ bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1)
87
+ view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored())
88
+ div_Tensor = CallFunction(aten.div.Tensor, view_default_2, KeywordArg('inv_scale'), _users=2)
89
+ amax_default = CallFunction(aten.amax.default, div_Tensor, Ignored(), True)
90
+ sub_Tensor = CallFunction(aten.sub.Tensor, div_Tensor, amax_default)
91
+ exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2)
92
+ sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True)
93
+ div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList)
94
+ expand_default_2 = CallFunction(aten.expand.default, div_Tensor_1, Ignored())
95
+ view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored())
96
+ expand_default_3 = CallFunction(aten.expand.default, KeywordArg('value'), Ignored())
97
+ view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored())
98
+ bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4)
99
+ _sfdp_pattern_1_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0)
100
+
101
+
102
+ expand_default = CallFunction(aten.expand.default, KeywordArg('query'), Ignored())
103
+ view_default = CallFunction(aten.view.default, expand_default, Ignored(), _users=2)
104
+ permute_default = CallFunction(aten.permute.default, KeywordArg('key'), Ignored())
105
+ expand_default_1 = CallFunction(aten.expand.default, permute_default, Ignored())
106
+ view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored(), _users=2)
107
+ bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1)
108
+ view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored())
109
+ div_Tensor = CallFunction(aten.div.Tensor, view_default_2, KeywordArg('inv_scale'))
110
+ convert_element_type_default = CallFunction(prims.convert_element_type.default, div_Tensor, Ignored(), _users=2)
111
+ amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True)
112
+ sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default)
113
+ exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2)
114
+ sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True)
115
+ div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList)
116
+ convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor_1, Ignored(), _users=2)
117
+ expand_default_2 = CallFunction(aten.expand.default, convert_element_type_default_1, Ignored())
118
+ view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored(), _users=2)
119
+ expand_default_3 = CallFunction(aten.expand.default, KeywordArg('value'), Ignored())
120
+ view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored(), _users=2)
121
+ bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4)
122
+ view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored())
123
+ convert_element_type_default_2 = CallFunction(prims.convert_element_type.default, convert_element_type_default_1, Ignored(), _users=2)
124
+ neg_default = CallFunction(aten.neg.default, convert_element_type_default_2)
125
+ view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2)
126
+ permute_default_1 = CallFunction(aten.permute.default, view_default_4, Ignored())
127
+ bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_1)
128
+ view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored())
129
+ convert_element_type_default_3 = CallFunction(prims.convert_element_type.default, view_default_7, Ignored())
130
+ mul_Tensor = CallFunction(aten.mul.Tensor, convert_element_type_default_3, convert_element_type_default_2, _users=2)
131
+ sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor, Ignored(), True)
132
+ fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor)
133
+ convert_element_type_default_4 = CallFunction(prims.convert_element_type.default, fma_default, Ignored())
134
+ div_Tensor_2 = CallFunction(aten.div.Tensor, convert_element_type_default_4, KeywordArg('inv_scale'))
135
+ view_default_8 = CallFunction(aten.view.default, div_Tensor_2, Ignored(), _users=2)
136
+ permute_default_2 = CallFunction(aten.permute.default, view_default_1, Ignored())
137
+ bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_2)
138
+ view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored())
139
+ permute_default_3 = CallFunction(aten.permute.default, view_default, Ignored())
140
+ bmm_default_4 = CallFunction(aten.bmm.default, permute_default_3, view_default_8)
141
+ view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored())
142
+ permute_default_4 = CallFunction(aten.permute.default, view_default_10, Ignored())
143
+ permute_default_5 = CallFunction(aten.permute.default, view_default_3, Ignored())
144
+ bmm_default_5 = CallFunction(aten.bmm.default, permute_default_5, view_default_6)
145
+ view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored())
146
+ _sfdp_pattern_1_half_training = MultiOutputPattern([view_default_5,
147
+ view_default_9,
148
+ permute_default_4,
149
+ view_default_11,
150
+ None
151
+ ])
152
+
153
+
154
+ expand_default = CallFunction(aten.expand.default, KeywordArg('query'), Ignored())
155
+ view_default = CallFunction(aten.view.default, expand_default, Ignored())
156
+ permute_default = CallFunction(aten.permute.default, KeywordArg('key'), Ignored())
157
+ expand_default_1 = CallFunction(aten.expand.default, permute_default, Ignored())
158
+ view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored())
159
+ bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1)
160
+ view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored())
161
+ div_Tensor = CallFunction(aten.div.Tensor, view_default_2, KeywordArg('inv_scale'))
162
+ convert_element_type_default = CallFunction(prims.convert_element_type.default, div_Tensor, Ignored(), _users=2)
163
+ amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True)
164
+ sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default)
165
+ exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2)
166
+ sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True)
167
+ div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList)
168
+ convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor_1, Ignored())
169
+ expand_default_2 = CallFunction(aten.expand.default, convert_element_type_default_1, Ignored())
170
+ view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored())
171
+ expand_default_3 = CallFunction(aten.expand.default, KeywordArg('value'), Ignored())
172
+ view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored())
173
+ bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4)
174
+ _sfdp_pattern_1_half_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0)
.venv/lib/python3.10/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_10.py ADDED
@@ -0,0 +1,205 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: ignore-errors
2
+
3
+ # noqa: F401, E501
4
+ # This is an auto-generated file. Please do not modify it by hand.
5
+ # To re-generate, run:
6
+ # cd ~/pytorch && python torchgen/fuse/gen_patterns.py
7
+
8
+ import torch
9
+ import torch._inductor
10
+ import operator
11
+
12
+ aten = torch.ops.aten
13
+ prims = torch.ops.prims
14
+
15
+ from torch._inductor.pattern_matcher import (
16
+ Arg,
17
+ CallFunction,
18
+ CallFunctionVarArgs,
19
+ CallMethod,
20
+ CallMethodVarArgs,
21
+ CallModule,
22
+ CallModuleVarArgs,
23
+ ExclusiveKeywordArg,
24
+ Ignored,
25
+ KeywordArg,
26
+ ListOf,
27
+ MultiOutputPattern,
28
+ PatternExpr,
29
+ RepeatedExpr,
30
+ _TargetArgsExpr,
31
+ _TargetExpr,
32
+ _TargetExprVarArgs,
33
+ )
34
+ permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored())
35
+ div_Tensor = CallFunction(aten.div.Tensor, permute_default, Ignored())
36
+ expand_default = CallFunction(aten.expand.default, div_Tensor, Ignored())
37
+ clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format)
38
+ view_default = CallFunction(aten.view.default, clone_default, Ignored(), _users=2)
39
+ permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored())
40
+ permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored())
41
+ expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored())
42
+ clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format)
43
+ view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored(), _users=2)
44
+ bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1)
45
+ view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored(), _users=2)
46
+ amax_default = CallFunction(aten.amax.default, view_default_2, Ignored(), True)
47
+ sub_Tensor = CallFunction(aten.sub.Tensor, view_default_2, amax_default)
48
+ exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2)
49
+ sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True)
50
+ div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList, _users=3)
51
+ convert_element_type_default = CallFunction(prims.convert_element_type.default, div_Tensor_1, Ignored())
52
+ expand_default_2 = CallFunction(aten.expand.default, convert_element_type_default, Ignored())
53
+ view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored(), _users=2)
54
+ permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored())
55
+ expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored())
56
+ clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format)
57
+ view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored(), _users=2)
58
+ bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4)
59
+ view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored())
60
+ neg_default = CallFunction(aten.neg.default, div_Tensor_1)
61
+ view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2)
62
+ permute_default_4 = CallFunction(aten.permute.default, view_default_4, Ignored())
63
+ bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_4)
64
+ convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, bmm_default_2, Ignored())
65
+ view_default_7 = CallFunction(aten.view.default, convert_element_type_default_1, Ignored())
66
+ convert_element_type_default_2 = CallFunction(prims.convert_element_type.default, view_default_7, Ignored())
67
+ mul_Tensor = CallFunction(aten.mul.Tensor, convert_element_type_default_2, div_Tensor_1, _users=2)
68
+ sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor, Ignored(), True)
69
+ fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor)
70
+ view_default_8 = CallFunction(aten.view.default, fma_default, Ignored(), _users=2)
71
+ permute_default_5 = CallFunction(aten.permute.default, view_default_1, Ignored())
72
+ bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_5)
73
+ view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored())
74
+ div_Tensor_2 = CallFunction(aten.div.Tensor, view_default_9, Ignored())
75
+ permute_default_6 = CallFunction(aten.permute.default, div_Tensor_2, Ignored())
76
+ permute_default_7 = CallFunction(aten.permute.default, view_default, Ignored())
77
+ bmm_default_4 = CallFunction(aten.bmm.default, permute_default_7, view_default_8)
78
+ view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored())
79
+ permute_default_8 = CallFunction(aten.permute.default, view_default_10, Ignored())
80
+ permute_default_9 = CallFunction(aten.permute.default, permute_default_8, Ignored())
81
+ permute_default_10 = CallFunction(aten.permute.default, view_default_3, Ignored())
82
+ bmm_default_5 = CallFunction(aten.bmm.default, permute_default_10, view_default_6)
83
+ view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored())
84
+ permute_default_11 = CallFunction(aten.permute.default, view_default_11, Ignored())
85
+ _sfdp_pattern_10_training = MultiOutputPattern([view_default_5,
86
+ permute_default_6,
87
+ permute_default_9,
88
+ permute_default_11
89
+ ])
90
+
91
+
92
+ permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored())
93
+ div_Tensor = CallFunction(aten.div.Tensor, permute_default, Ignored())
94
+ expand_default = CallFunction(aten.expand.default, div_Tensor, Ignored())
95
+ clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format)
96
+ view_default = CallFunction(aten.view.default, clone_default, Ignored())
97
+ permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored())
98
+ permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored())
99
+ expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored())
100
+ clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format)
101
+ view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored())
102
+ bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1)
103
+ view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored(), _users=2)
104
+ amax_default = CallFunction(aten.amax.default, view_default_2, Ignored(), True)
105
+ sub_Tensor = CallFunction(aten.sub.Tensor, view_default_2, amax_default)
106
+ exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2)
107
+ sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True)
108
+ div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList)
109
+ convert_element_type_default = CallFunction(prims.convert_element_type.default, div_Tensor_1, Ignored())
110
+ expand_default_2 = CallFunction(aten.expand.default, convert_element_type_default, Ignored())
111
+ view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored())
112
+ permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored())
113
+ expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored())
114
+ clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format)
115
+ view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored())
116
+ bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4)
117
+ _sfdp_pattern_10_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0)
118
+
119
+
120
+ permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored())
121
+ div_Tensor = CallFunction(aten.div.Tensor, permute_default, Ignored())
122
+ expand_default = CallFunction(aten.expand.default, div_Tensor, Ignored())
123
+ clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format)
124
+ view_default = CallFunction(aten.view.default, clone_default, Ignored(), _users=2)
125
+ permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored())
126
+ permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored())
127
+ expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored())
128
+ clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format)
129
+ view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored(), _users=2)
130
+ bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1)
131
+ view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored())
132
+ convert_element_type_default = CallFunction(prims.convert_element_type.default, view_default_2, Ignored(), _users=2)
133
+ amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True)
134
+ sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default)
135
+ exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2)
136
+ sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True)
137
+ div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList, _users=3)
138
+ convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor_1, Ignored())
139
+ expand_default_2 = CallFunction(aten.expand.default, convert_element_type_default_1, Ignored())
140
+ view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored(), _users=2)
141
+ permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored())
142
+ expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored())
143
+ clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format)
144
+ view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored(), _users=2)
145
+ bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4)
146
+ view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored())
147
+ neg_default = CallFunction(aten.neg.default, div_Tensor_1)
148
+ view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2)
149
+ permute_default_4 = CallFunction(aten.permute.default, view_default_4, Ignored())
150
+ bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_4)
151
+ view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored())
152
+ convert_element_type_default_2 = CallFunction(prims.convert_element_type.default, view_default_7, Ignored())
153
+ mul_Tensor = CallFunction(aten.mul.Tensor, convert_element_type_default_2, div_Tensor_1, _users=2)
154
+ sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor, Ignored(), True)
155
+ fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor)
156
+ convert_element_type_default_3 = CallFunction(prims.convert_element_type.default, fma_default, Ignored())
157
+ view_default_8 = CallFunction(aten.view.default, convert_element_type_default_3, Ignored(), _users=2)
158
+ permute_default_5 = CallFunction(aten.permute.default, view_default_1, Ignored())
159
+ bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_5)
160
+ view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored())
161
+ div_Tensor_2 = CallFunction(aten.div.Tensor, view_default_9, Ignored())
162
+ permute_default_6 = CallFunction(aten.permute.default, div_Tensor_2, Ignored())
163
+ permute_default_7 = CallFunction(aten.permute.default, view_default, Ignored())
164
+ bmm_default_4 = CallFunction(aten.bmm.default, permute_default_7, view_default_8)
165
+ view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored())
166
+ permute_default_8 = CallFunction(aten.permute.default, view_default_10, Ignored())
167
+ permute_default_9 = CallFunction(aten.permute.default, permute_default_8, Ignored())
168
+ permute_default_10 = CallFunction(aten.permute.default, view_default_3, Ignored())
169
+ bmm_default_5 = CallFunction(aten.bmm.default, permute_default_10, view_default_6)
170
+ view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored())
171
+ permute_default_11 = CallFunction(aten.permute.default, view_default_11, Ignored())
172
+ _sfdp_pattern_10_half_training = MultiOutputPattern([view_default_5,
173
+ permute_default_6,
174
+ permute_default_9,
175
+ permute_default_11
176
+ ])
177
+
178
+
179
+ permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored())
180
+ div_Tensor = CallFunction(aten.div.Tensor, permute_default, Ignored())
181
+ expand_default = CallFunction(aten.expand.default, div_Tensor, Ignored())
182
+ clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format)
183
+ view_default = CallFunction(aten.view.default, clone_default, Ignored())
184
+ permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored())
185
+ permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored())
186
+ expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored())
187
+ clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format)
188
+ view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored())
189
+ bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1)
190
+ view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored())
191
+ convert_element_type_default = CallFunction(prims.convert_element_type.default, view_default_2, Ignored(), _users=2)
192
+ amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True)
193
+ sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default)
194
+ exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2)
195
+ sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True)
196
+ div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList)
197
+ convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor_1, Ignored())
198
+ expand_default_2 = CallFunction(aten.expand.default, convert_element_type_default_1, Ignored())
199
+ view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored())
200
+ permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored())
201
+ expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored())
202
+ clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format)
203
+ view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored())
204
+ bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4)
205
+ _sfdp_pattern_10_half_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0)
.venv/lib/python3.10/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_11.py ADDED
@@ -0,0 +1,204 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: ignore-errors
2
+
3
+ # noqa: F401, E501
4
+ # This is an auto-generated file. Please do not modify it by hand.
5
+ # To re-generate, run:
6
+ # cd ~/pytorch && python torchgen/fuse/gen_patterns.py
7
+
8
+ import torch
9
+ import torch._inductor
10
+ import operator
11
+
12
+ aten = torch.ops.aten
13
+ prims = torch.ops.prims
14
+
15
+ from torch._inductor.pattern_matcher import (
16
+ Arg,
17
+ CallFunction,
18
+ CallFunctionVarArgs,
19
+ CallMethod,
20
+ CallMethodVarArgs,
21
+ CallModule,
22
+ CallModuleVarArgs,
23
+ ExclusiveKeywordArg,
24
+ Ignored,
25
+ KeywordArg,
26
+ ListOf,
27
+ MultiOutputPattern,
28
+ PatternExpr,
29
+ RepeatedExpr,
30
+ _TargetArgsExpr,
31
+ _TargetExpr,
32
+ _TargetExprVarArgs,
33
+ )
34
+ permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored())
35
+ expand_default = CallFunction(aten.expand.default, permute_default, Ignored())
36
+ clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format)
37
+ view_default = CallFunction(aten.view.default, clone_default, Ignored(), _users=2)
38
+ permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored())
39
+ permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored())
40
+ expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored())
41
+ clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format)
42
+ view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored(), _users=2)
43
+ bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1)
44
+ view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored())
45
+ div_Tensor = CallFunction(aten.div.Tensor, view_default_2, KeywordArg('inv_scale'), _users=2)
46
+ amax_default = CallFunction(aten.amax.default, div_Tensor, Ignored(), True)
47
+ sub_Tensor = CallFunction(aten.sub.Tensor, div_Tensor, amax_default)
48
+ exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2)
49
+ sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True)
50
+ div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList, _users=3)
51
+ expand_default_2 = CallFunction(aten.expand.default, div_Tensor_1, Ignored())
52
+ view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored(), _users=2)
53
+ permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored())
54
+ expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored())
55
+ clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format)
56
+ view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored(), _users=2)
57
+ bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4)
58
+ view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored())
59
+ neg_default = CallFunction(aten.neg.default, div_Tensor_1)
60
+ view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2)
61
+ permute_default_4 = CallFunction(aten.permute.default, view_default_4, Ignored())
62
+ bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_4)
63
+ view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored())
64
+ mul_Tensor = CallFunction(aten.mul.Tensor, view_default_7, div_Tensor_1, _users=2)
65
+ sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor, Ignored(), True)
66
+ fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor)
67
+ div_Tensor_2 = CallFunction(aten.div.Tensor, fma_default, KeywordArg('inv_scale'))
68
+ view_default_8 = CallFunction(aten.view.default, div_Tensor_2, Ignored(), _users=2)
69
+ permute_default_5 = CallFunction(aten.permute.default, view_default_1, Ignored())
70
+ bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_5)
71
+ view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored())
72
+ permute_default_6 = CallFunction(aten.permute.default, view_default_9, Ignored())
73
+ permute_default_7 = CallFunction(aten.permute.default, view_default, Ignored())
74
+ bmm_default_4 = CallFunction(aten.bmm.default, permute_default_7, view_default_8)
75
+ view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored())
76
+ permute_default_8 = CallFunction(aten.permute.default, view_default_10, Ignored())
77
+ permute_default_9 = CallFunction(aten.permute.default, permute_default_8, Ignored())
78
+ permute_default_10 = CallFunction(aten.permute.default, view_default_3, Ignored())
79
+ bmm_default_5 = CallFunction(aten.bmm.default, permute_default_10, view_default_6)
80
+ view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored())
81
+ permute_default_11 = CallFunction(aten.permute.default, view_default_11, Ignored())
82
+ _sfdp_pattern_11_training = MultiOutputPattern([view_default_5,
83
+ permute_default_6,
84
+ permute_default_9,
85
+ permute_default_11,
86
+ None
87
+ ])
88
+
89
+
90
+ permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored())
91
+ expand_default = CallFunction(aten.expand.default, permute_default, Ignored())
92
+ clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format)
93
+ view_default = CallFunction(aten.view.default, clone_default, Ignored())
94
+ permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored())
95
+ permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored())
96
+ expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored())
97
+ clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format)
98
+ view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored())
99
+ bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1)
100
+ view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored())
101
+ div_Tensor = CallFunction(aten.div.Tensor, view_default_2, KeywordArg('inv_scale'), _users=2)
102
+ amax_default = CallFunction(aten.amax.default, div_Tensor, Ignored(), True)
103
+ sub_Tensor = CallFunction(aten.sub.Tensor, div_Tensor, amax_default)
104
+ exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2)
105
+ sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True)
106
+ div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList)
107
+ expand_default_2 = CallFunction(aten.expand.default, div_Tensor_1, Ignored())
108
+ view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored())
109
+ permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored())
110
+ expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored())
111
+ clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format)
112
+ view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored())
113
+ bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4)
114
+ _sfdp_pattern_11_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0)
115
+
116
+
117
+ permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored())
118
+ expand_default = CallFunction(aten.expand.default, permute_default, Ignored())
119
+ clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format)
120
+ view_default = CallFunction(aten.view.default, clone_default, Ignored(), _users=2)
121
+ permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored())
122
+ permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored())
123
+ expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored())
124
+ clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format)
125
+ view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored(), _users=2)
126
+ bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1)
127
+ view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored())
128
+ div_Tensor = CallFunction(aten.div.Tensor, view_default_2, KeywordArg('inv_scale'))
129
+ convert_element_type_default = CallFunction(prims.convert_element_type.default, div_Tensor, Ignored(), _users=2)
130
+ amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True)
131
+ sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default)
132
+ exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2)
133
+ sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True)
134
+ div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList)
135
+ convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor_1, Ignored(), _users=2)
136
+ expand_default_2 = CallFunction(aten.expand.default, convert_element_type_default_1, Ignored())
137
+ view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored(), _users=2)
138
+ permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored())
139
+ expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored())
140
+ clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format)
141
+ view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored(), _users=2)
142
+ bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4)
143
+ view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored())
144
+ convert_element_type_default_2 = CallFunction(prims.convert_element_type.default, convert_element_type_default_1, Ignored(), _users=2)
145
+ neg_default = CallFunction(aten.neg.default, convert_element_type_default_2)
146
+ view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2)
147
+ permute_default_4 = CallFunction(aten.permute.default, view_default_4, Ignored())
148
+ bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_4)
149
+ view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored())
150
+ convert_element_type_default_3 = CallFunction(prims.convert_element_type.default, view_default_7, Ignored())
151
+ mul_Tensor = CallFunction(aten.mul.Tensor, convert_element_type_default_3, convert_element_type_default_2, _users=2)
152
+ sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor, Ignored(), True)
153
+ fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor)
154
+ convert_element_type_default_4 = CallFunction(prims.convert_element_type.default, fma_default, Ignored())
155
+ div_Tensor_2 = CallFunction(aten.div.Tensor, convert_element_type_default_4, KeywordArg('inv_scale'))
156
+ view_default_8 = CallFunction(aten.view.default, div_Tensor_2, Ignored(), _users=2)
157
+ permute_default_5 = CallFunction(aten.permute.default, view_default_1, Ignored())
158
+ bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_5)
159
+ view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored())
160
+ permute_default_6 = CallFunction(aten.permute.default, view_default_9, Ignored())
161
+ permute_default_7 = CallFunction(aten.permute.default, view_default, Ignored())
162
+ bmm_default_4 = CallFunction(aten.bmm.default, permute_default_7, view_default_8)
163
+ view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored())
164
+ permute_default_8 = CallFunction(aten.permute.default, view_default_10, Ignored())
165
+ permute_default_9 = CallFunction(aten.permute.default, permute_default_8, Ignored())
166
+ permute_default_10 = CallFunction(aten.permute.default, view_default_3, Ignored())
167
+ bmm_default_5 = CallFunction(aten.bmm.default, permute_default_10, view_default_6)
168
+ view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored())
169
+ permute_default_11 = CallFunction(aten.permute.default, view_default_11, Ignored())
170
+ _sfdp_pattern_11_half_training = MultiOutputPattern([view_default_5,
171
+ permute_default_6,
172
+ permute_default_9,
173
+ permute_default_11,
174
+ None
175
+ ])
176
+
177
+
178
+ permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored())
179
+ expand_default = CallFunction(aten.expand.default, permute_default, Ignored())
180
+ clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format)
181
+ view_default = CallFunction(aten.view.default, clone_default, Ignored())
182
+ permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored())
183
+ permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored())
184
+ expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored())
185
+ clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format)
186
+ view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored())
187
+ bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1)
188
+ view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored())
189
+ div_Tensor = CallFunction(aten.div.Tensor, view_default_2, KeywordArg('inv_scale'))
190
+ convert_element_type_default = CallFunction(prims.convert_element_type.default, div_Tensor, Ignored(), _users=2)
191
+ amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True)
192
+ sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default)
193
+ exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2)
194
+ sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True)
195
+ div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList)
196
+ convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor_1, Ignored())
197
+ expand_default_2 = CallFunction(aten.expand.default, convert_element_type_default_1, Ignored())
198
+ view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored())
199
+ permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored())
200
+ expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored())
201
+ clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format)
202
+ view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored())
203
+ bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4)
204
+ _sfdp_pattern_11_half_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0)
.venv/lib/python3.10/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_13.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: ignore-errors
2
+
3
+ # noqa: F401, E501
4
+ # This is an auto-generated file. Please do not modify it by hand.
5
+ # To re-generate, run:
6
+ # cd ~/pytorch && python torchgen/fuse/gen_patterns.py
7
+
8
+ import torch
9
+ import torch._inductor
10
+ import operator
11
+
12
+ aten = torch.ops.aten
13
+ prims = torch.ops.prims
14
+
15
+ from torch._inductor.pattern_matcher import (
16
+ Arg,
17
+ CallFunction,
18
+ CallFunctionVarArgs,
19
+ CallMethod,
20
+ CallMethodVarArgs,
21
+ CallModule,
22
+ CallModuleVarArgs,
23
+ ExclusiveKeywordArg,
24
+ Ignored,
25
+ KeywordArg,
26
+ ListOf,
27
+ MultiOutputPattern,
28
+ PatternExpr,
29
+ RepeatedExpr,
30
+ _TargetArgsExpr,
31
+ _TargetExpr,
32
+ _TargetExprVarArgs,
33
+ )
34
+ rand_default = CallFunction(aten.rand.default, Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False)
35
+ gt_Scalar = CallFunction(aten.gt.Scalar, rand_default, KeywordArg('dropout_p'), _users=2)
36
+ permute_default = CallFunction(aten.permute.default, KeywordArg('key'), Ignored(), _users=2)
37
+ bmm_default = CallFunction(aten.bmm.default, KeywordArg('query'), permute_default, _users=2)
38
+ amax_default = CallFunction(aten.amax.default, bmm_default, Ignored(), True)
39
+ sub_Tensor = CallFunction(aten.sub.Tensor, bmm_default, amax_default)
40
+ exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2)
41
+ sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True)
42
+ div_Tensor = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList, _users=3)
43
+ mul_Tensor = CallFunction(aten.mul.Tensor, gt_Scalar, div_Tensor)
44
+ mul_Tensor_1 = CallFunction(aten.mul.Tensor, mul_Tensor, Ignored(), _users=2)
45
+ bmm_default_1 = CallFunction(aten.bmm.default, mul_Tensor_1, KeywordArg('value'))
46
+ neg_default = CallFunction(aten.neg.default, div_Tensor)
47
+ permute_default_1 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored())
48
+ bmm_default_2 = CallFunction(aten.bmm.default, KeywordArg('tangents_1'), permute_default_1)
49
+ convert_element_type_default = CallFunction(prims.convert_element_type.default, gt_Scalar, Ignored())
50
+ mul_Tensor_2 = CallFunction(aten.mul.Tensor, convert_element_type_default, Ignored())
51
+ mul_Tensor_3 = CallFunction(aten.mul.Tensor, bmm_default_2, mul_Tensor_2)
52
+ mul_Tensor_4 = CallFunction(aten.mul.Tensor, mul_Tensor_3, div_Tensor, _users=2)
53
+ sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor_4, Ignored(), True)
54
+ fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor_4, _users=2)
55
+ permute_default_2 = CallFunction(aten.permute.default, permute_default, Ignored())
56
+ bmm_default_3 = CallFunction(aten.bmm.default, fma_default, permute_default_2)
57
+ permute_default_3 = CallFunction(aten.permute.default, KeywordArg('query'), Ignored())
58
+ bmm_default_4 = CallFunction(aten.bmm.default, permute_default_3, fma_default)
59
+ permute_default_4 = CallFunction(aten.permute.default, bmm_default_4, Ignored())
60
+ permute_default_5 = CallFunction(aten.permute.default, mul_Tensor_1, Ignored())
61
+ bmm_default_5 = CallFunction(aten.bmm.default, permute_default_5, KeywordArg('tangents_1'))
62
+ _sfdp_pattern_13_training = MultiOutputPattern([bmm_default_1,
63
+ bmm_default_3,
64
+ permute_default_4,
65
+ bmm_default_5,
66
+ None
67
+ ])
68
+
69
+
70
+ permute_default = CallFunction(aten.permute.default, KeywordArg('key'), Ignored())
71
+ bmm_default = CallFunction(aten.bmm.default, KeywordArg('query'), permute_default, _users=2)
72
+ amax_default = CallFunction(aten.amax.default, bmm_default, Ignored(), True)
73
+ sub_Tensor = CallFunction(aten.sub.Tensor, bmm_default, amax_default)
74
+ exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2)
75
+ sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True)
76
+ div_Tensor = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList)
77
+ _sfdp_pattern_13_inference = CallFunction(aten.bmm.default, div_Tensor, KeywordArg('value'), _users=0)
78
+
79
+
80
+ rand_default = CallFunction(aten.rand.default, Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False)
81
+ gt_Scalar = CallFunction(aten.gt.Scalar, rand_default, KeywordArg('dropout_p'), _users=2)
82
+ permute_default = CallFunction(aten.permute.default, KeywordArg('key'), Ignored(), _users=2)
83
+ bmm_default = CallFunction(aten.bmm.default, KeywordArg('query'), permute_default)
84
+ convert_element_type_default = CallFunction(prims.convert_element_type.default, bmm_default, Ignored(), _users=2)
85
+ amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True)
86
+ sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default)
87
+ exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2)
88
+ sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True)
89
+ div_Tensor = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList)
90
+ convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor, Ignored(), _users=2)
91
+ mul_Tensor = CallFunction(aten.mul.Tensor, gt_Scalar, convert_element_type_default_1)
92
+ mul_Tensor_1 = CallFunction(aten.mul.Tensor, mul_Tensor, Ignored(), _users=2)
93
+ bmm_default_1 = CallFunction(aten.bmm.default, mul_Tensor_1, KeywordArg('value'))
94
+ convert_element_type_default_2 = CallFunction(prims.convert_element_type.default, convert_element_type_default_1, Ignored(), _users=2)
95
+ neg_default = CallFunction(aten.neg.default, convert_element_type_default_2)
96
+ permute_default_1 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored())
97
+ bmm_default_2 = CallFunction(aten.bmm.default, KeywordArg('tangents_1'), permute_default_1)
98
+ convert_element_type_default_3 = CallFunction(prims.convert_element_type.default, gt_Scalar, Ignored())
99
+ mul_Tensor_2 = CallFunction(aten.mul.Tensor, convert_element_type_default_3, Ignored())
100
+ mul_Tensor_3 = CallFunction(aten.mul.Tensor, bmm_default_2, mul_Tensor_2)
101
+ convert_element_type_default_4 = CallFunction(prims.convert_element_type.default, mul_Tensor_3, Ignored())
102
+ mul_Tensor_4 = CallFunction(aten.mul.Tensor, convert_element_type_default_4, convert_element_type_default_2, _users=2)
103
+ sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor_4, Ignored(), True)
104
+ fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor_4)
105
+ convert_element_type_default_5 = CallFunction(prims.convert_element_type.default, fma_default, Ignored(), _users=2)
106
+ permute_default_2 = CallFunction(aten.permute.default, permute_default, Ignored())
107
+ bmm_default_3 = CallFunction(aten.bmm.default, convert_element_type_default_5, permute_default_2)
108
+ permute_default_3 = CallFunction(aten.permute.default, KeywordArg('query'), Ignored())
109
+ bmm_default_4 = CallFunction(aten.bmm.default, permute_default_3, convert_element_type_default_5)
110
+ permute_default_4 = CallFunction(aten.permute.default, bmm_default_4, Ignored())
111
+ permute_default_5 = CallFunction(aten.permute.default, mul_Tensor_1, Ignored())
112
+ bmm_default_5 = CallFunction(aten.bmm.default, permute_default_5, KeywordArg('tangents_1'))
113
+ _sfdp_pattern_13_half_training = MultiOutputPattern([bmm_default_1,
114
+ bmm_default_3,
115
+ permute_default_4,
116
+ bmm_default_5,
117
+ None
118
+ ])
119
+
120
+
121
+ permute_default = CallFunction(aten.permute.default, KeywordArg('key'), Ignored())
122
+ bmm_default = CallFunction(aten.bmm.default, KeywordArg('query'), permute_default)
123
+ convert_element_type_default = CallFunction(prims.convert_element_type.default, bmm_default, Ignored(), _users=2)
124
+ amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True)
125
+ sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default)
126
+ exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2)
127
+ sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True)
128
+ div_Tensor = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList)
129
+ convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor, Ignored())
130
+ _sfdp_pattern_13_half_inference = CallFunction(aten.bmm.default, convert_element_type_default_1, KeywordArg('value'), _users=0)
.venv/lib/python3.10/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_14.py ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: ignore-errors
2
+
3
+ # noqa: F401, E501
4
+ # This is an auto-generated file. Please do not modify it by hand.
5
+ # To re-generate, run:
6
+ # cd ~/pytorch && python torchgen/fuse/gen_patterns.py
7
+
8
+ import torch
9
+ import torch._inductor
10
+ import operator
11
+
12
+ aten = torch.ops.aten
13
+ prims = torch.ops.prims
14
+
15
+ from torch._inductor.pattern_matcher import (
16
+ Arg,
17
+ CallFunction,
18
+ CallFunctionVarArgs,
19
+ CallMethod,
20
+ CallMethodVarArgs,
21
+ CallModule,
22
+ CallModuleVarArgs,
23
+ ExclusiveKeywordArg,
24
+ Ignored,
25
+ KeywordArg,
26
+ ListOf,
27
+ MultiOutputPattern,
28
+ PatternExpr,
29
+ RepeatedExpr,
30
+ _TargetArgsExpr,
31
+ _TargetExpr,
32
+ _TargetExprVarArgs,
33
+ )
34
+ permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored())
35
+ expand_default = CallFunction(aten.expand.default, permute_default, Ignored())
36
+ clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format)
37
+ view_default = CallFunction(aten.view.default, clone_default, Ignored(), _users=2)
38
+ permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored())
39
+ permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored())
40
+ expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored())
41
+ clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format)
42
+ view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored(), _users=2)
43
+ bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1)
44
+ view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored())
45
+ div_Tensor = CallFunction(aten.div.Tensor, view_default_2, KeywordArg('inv_scale'))
46
+ add_Tensor = CallFunction(aten.add.Tensor, div_Tensor, KeywordArg('attn_mask'), _users=2)
47
+ amax_default = CallFunction(aten.amax.default, add_Tensor, Ignored(), True)
48
+ sub_Tensor = CallFunction(aten.sub.Tensor, add_Tensor, amax_default)
49
+ exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2)
50
+ sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True)
51
+ div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList, _users=3)
52
+ expand_default_2 = CallFunction(aten.expand.default, div_Tensor_1, Ignored())
53
+ view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored(), _users=2)
54
+ permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored())
55
+ expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored())
56
+ clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format)
57
+ view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored(), _users=2)
58
+ bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4)
59
+ view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored())
60
+ neg_default = CallFunction(aten.neg.default, div_Tensor_1)
61
+ view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2)
62
+ permute_default_4 = CallFunction(aten.permute.default, view_default_4, Ignored())
63
+ bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_4)
64
+ view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored())
65
+ mul_Tensor = CallFunction(aten.mul.Tensor, view_default_7, div_Tensor_1, _users=2)
66
+ sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor, Ignored(), True)
67
+ fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor)
68
+ div_Tensor_2 = CallFunction(aten.div.Tensor, fma_default, KeywordArg('inv_scale'))
69
+ view_default_8 = CallFunction(aten.view.default, div_Tensor_2, Ignored(), _users=2)
70
+ permute_default_5 = CallFunction(aten.permute.default, view_default_1, Ignored())
71
+ bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_5)
72
+ view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored())
73
+ permute_default_6 = CallFunction(aten.permute.default, view_default_9, Ignored())
74
+ permute_default_7 = CallFunction(aten.permute.default, view_default, Ignored())
75
+ bmm_default_4 = CallFunction(aten.bmm.default, permute_default_7, view_default_8)
76
+ view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored())
77
+ permute_default_8 = CallFunction(aten.permute.default, view_default_10, Ignored())
78
+ permute_default_9 = CallFunction(aten.permute.default, permute_default_8, Ignored())
79
+ permute_default_10 = CallFunction(aten.permute.default, view_default_3, Ignored())
80
+ bmm_default_5 = CallFunction(aten.bmm.default, permute_default_10, view_default_6)
81
+ view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored())
82
+ permute_default_11 = CallFunction(aten.permute.default, view_default_11, Ignored())
83
+ _sfdp_pattern_14_training = MultiOutputPattern([view_default_5,
84
+ permute_default_6,
85
+ permute_default_9,
86
+ permute_default_11,
87
+ None,
88
+ None
89
+ ])
90
+
91
+
92
+ permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored())
93
+ expand_default = CallFunction(aten.expand.default, permute_default, Ignored())
94
+ clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format)
95
+ view_default = CallFunction(aten.view.default, clone_default, Ignored())
96
+ permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored())
97
+ permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored())
98
+ expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored())
99
+ clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format)
100
+ view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored())
101
+ bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1)
102
+ view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored())
103
+ div_Tensor = CallFunction(aten.div.Tensor, view_default_2, KeywordArg('inv_scale'))
104
+ add_Tensor = CallFunction(aten.add.Tensor, div_Tensor, KeywordArg('attn_mask'), _users=2)
105
+ amax_default = CallFunction(aten.amax.default, add_Tensor, Ignored(), True)
106
+ sub_Tensor = CallFunction(aten.sub.Tensor, add_Tensor, amax_default)
107
+ exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2)
108
+ sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True)
109
+ div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList)
110
+ expand_default_2 = CallFunction(aten.expand.default, div_Tensor_1, Ignored())
111
+ view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored())
112
+ permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored())
113
+ expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored())
114
+ clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format)
115
+ view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored())
116
+ bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4)
117
+ _sfdp_pattern_14_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0)
118
+
119
+
120
+ permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored())
121
+ expand_default = CallFunction(aten.expand.default, permute_default, Ignored())
122
+ clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format)
123
+ view_default = CallFunction(aten.view.default, clone_default, Ignored(), _users=2)
124
+ permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored())
125
+ permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored())
126
+ expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored())
127
+ clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format)
128
+ view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored(), _users=2)
129
+ bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1)
130
+ view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored())
131
+ div_Tensor = CallFunction(aten.div.Tensor, view_default_2, KeywordArg('inv_scale'))
132
+ add_Tensor = CallFunction(aten.add.Tensor, div_Tensor, KeywordArg('attn_mask'))
133
+ convert_element_type_default = CallFunction(prims.convert_element_type.default, add_Tensor, Ignored(), _users=2)
134
+ amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True)
135
+ sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default)
136
+ exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2)
137
+ sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True)
138
+ div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList)
139
+ convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor_1, Ignored(), _users=2)
140
+ expand_default_2 = CallFunction(aten.expand.default, convert_element_type_default_1, Ignored())
141
+ view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored(), _users=2)
142
+ permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored())
143
+ expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored())
144
+ clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format)
145
+ view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored(), _users=2)
146
+ bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4)
147
+ view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored())
148
+ convert_element_type_default_2 = CallFunction(prims.convert_element_type.default, convert_element_type_default_1, Ignored(), _users=2)
149
+ neg_default = CallFunction(aten.neg.default, convert_element_type_default_2)
150
+ view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2)
151
+ permute_default_4 = CallFunction(aten.permute.default, view_default_4, Ignored())
152
+ bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_4)
153
+ view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored())
154
+ convert_element_type_default_3 = CallFunction(prims.convert_element_type.default, view_default_7, Ignored())
155
+ mul_Tensor = CallFunction(aten.mul.Tensor, convert_element_type_default_3, convert_element_type_default_2, _users=2)
156
+ sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor, Ignored(), True)
157
+ fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor)
158
+ convert_element_type_default_4 = CallFunction(prims.convert_element_type.default, fma_default, Ignored())
159
+ div_Tensor_2 = CallFunction(aten.div.Tensor, convert_element_type_default_4, KeywordArg('inv_scale'))
160
+ view_default_8 = CallFunction(aten.view.default, div_Tensor_2, Ignored(), _users=2)
161
+ permute_default_5 = CallFunction(aten.permute.default, view_default_1, Ignored())
162
+ bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_5)
163
+ view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored())
164
+ permute_default_6 = CallFunction(aten.permute.default, view_default_9, Ignored())
165
+ permute_default_7 = CallFunction(aten.permute.default, view_default, Ignored())
166
+ bmm_default_4 = CallFunction(aten.bmm.default, permute_default_7, view_default_8)
167
+ view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored())
168
+ permute_default_8 = CallFunction(aten.permute.default, view_default_10, Ignored())
169
+ permute_default_9 = CallFunction(aten.permute.default, permute_default_8, Ignored())
170
+ permute_default_10 = CallFunction(aten.permute.default, view_default_3, Ignored())
171
+ bmm_default_5 = CallFunction(aten.bmm.default, permute_default_10, view_default_6)
172
+ view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored())
173
+ permute_default_11 = CallFunction(aten.permute.default, view_default_11, Ignored())
174
+ _sfdp_pattern_14_half_training = MultiOutputPattern([view_default_5,
175
+ permute_default_6,
176
+ permute_default_9,
177
+ permute_default_11,
178
+ None,
179
+ None
180
+ ])
181
+
182
+
183
+ permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored())
184
+ expand_default = CallFunction(aten.expand.default, permute_default, Ignored())
185
+ clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format)
186
+ view_default = CallFunction(aten.view.default, clone_default, Ignored())
187
+ permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored())
188
+ permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored())
189
+ expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored())
190
+ clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format)
191
+ view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored())
192
+ bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1)
193
+ view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored())
194
+ div_Tensor = CallFunction(aten.div.Tensor, view_default_2, KeywordArg('inv_scale'))
195
+ add_Tensor = CallFunction(aten.add.Tensor, div_Tensor, KeywordArg('attn_mask'))
196
+ convert_element_type_default = CallFunction(prims.convert_element_type.default, add_Tensor, Ignored(), _users=2)
197
+ amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True)
198
+ sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default)
199
+ exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2)
200
+ sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True)
201
+ div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList)
202
+ convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor_1, Ignored())
203
+ expand_default_2 = CallFunction(aten.expand.default, convert_element_type_default_1, Ignored())
204
+ view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored())
205
+ permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored())
206
+ expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored())
207
+ clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format)
208
+ view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored())
209
+ bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4)
210
+ _sfdp_pattern_14_half_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0)
.venv/lib/python3.10/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_15.py ADDED
@@ -0,0 +1,230 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: ignore-errors
2
+
3
+ # noqa: F401, E501
4
+ # This is an auto-generated file. Please do not modify it by hand.
5
+ # To re-generate, run:
6
+ # cd ~/pytorch && python torchgen/fuse/gen_patterns.py
7
+
8
+ import torch
9
+ import torch._inductor
10
+ import operator
11
+
12
+ aten = torch.ops.aten
13
+ prims = torch.ops.prims
14
+
15
+ from torch._inductor.pattern_matcher import (
16
+ Arg,
17
+ CallFunction,
18
+ CallFunctionVarArgs,
19
+ CallMethod,
20
+ CallMethodVarArgs,
21
+ CallModule,
22
+ CallModuleVarArgs,
23
+ ExclusiveKeywordArg,
24
+ Ignored,
25
+ KeywordArg,
26
+ ListOf,
27
+ MultiOutputPattern,
28
+ PatternExpr,
29
+ RepeatedExpr,
30
+ _TargetArgsExpr,
31
+ _TargetExpr,
32
+ _TargetExprVarArgs,
33
+ )
34
+ eq_Scalar = CallFunction(aten.eq.Scalar, KeywordArg('attn_mask'), Ignored())
35
+ view_default = CallFunction(aten.view.default, eq_Scalar, Ignored())
36
+ expand_default = CallFunction(aten.expand.default, view_default, Ignored(), _users=2)
37
+ full_default = CallFunction(aten.full.default, [], Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False)
38
+ permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored())
39
+ expand_default_1 = CallFunction(aten.expand.default, permute_default, Ignored())
40
+ clone_default = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format)
41
+ view_default_1 = CallFunction(aten.view.default, clone_default, Ignored(), _users=2)
42
+ permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored())
43
+ permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored())
44
+ expand_default_2 = CallFunction(aten.expand.default, permute_default_2, Ignored())
45
+ clone_default_1 = CallFunction(aten.clone.default, expand_default_2, memory_format=torch.contiguous_format)
46
+ view_default_2 = CallFunction(aten.view.default, clone_default_1, Ignored(), _users=2)
47
+ bmm_default = CallFunction(aten.bmm.default, view_default_1, view_default_2)
48
+ view_default_3 = CallFunction(aten.view.default, bmm_default, Ignored())
49
+ div_Tensor = CallFunction(aten.div.Tensor, view_default_3, KeywordArg('inv_scale'))
50
+ where_self = CallFunction(aten.where.self, expand_default, full_default, div_Tensor, _users=2)
51
+ amax_default = CallFunction(aten.amax.default, where_self, Ignored(), True)
52
+ sub_Tensor = CallFunction(aten.sub.Tensor, where_self, amax_default)
53
+ exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2)
54
+ sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True)
55
+ div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList, _users=3)
56
+ expand_default_3 = CallFunction(aten.expand.default, div_Tensor_1, Ignored())
57
+ view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored(), _users=2)
58
+ permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored())
59
+ expand_default_4 = CallFunction(aten.expand.default, permute_default_3, Ignored())
60
+ clone_default_2 = CallFunction(aten.clone.default, expand_default_4, memory_format=torch.contiguous_format)
61
+ view_default_5 = CallFunction(aten.view.default, clone_default_2, Ignored(), _users=2)
62
+ bmm_default_1 = CallFunction(aten.bmm.default, view_default_4, view_default_5)
63
+ view_default_6 = CallFunction(aten.view.default, bmm_default_1, Ignored())
64
+ scalar_tensor_default = CallFunction(aten.scalar_tensor.default, Ignored(), dtype=Ignored(), layout=torch.strided, device=Ignored())
65
+ neg_default = CallFunction(aten.neg.default, div_Tensor_1)
66
+ view_default_7 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2)
67
+ permute_default_4 = CallFunction(aten.permute.default, view_default_5, Ignored())
68
+ bmm_default_2 = CallFunction(aten.bmm.default, view_default_7, permute_default_4)
69
+ view_default_8 = CallFunction(aten.view.default, bmm_default_2, Ignored())
70
+ mul_Tensor = CallFunction(aten.mul.Tensor, view_default_8, div_Tensor_1, _users=2)
71
+ sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor, Ignored(), True)
72
+ fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor)
73
+ where_self_1 = CallFunction(aten.where.self, expand_default, scalar_tensor_default, fma_default)
74
+ div_Tensor_2 = CallFunction(aten.div.Tensor, where_self_1, KeywordArg('inv_scale'))
75
+ view_default_9 = CallFunction(aten.view.default, div_Tensor_2, Ignored(), _users=2)
76
+ permute_default_5 = CallFunction(aten.permute.default, view_default_2, Ignored())
77
+ bmm_default_3 = CallFunction(aten.bmm.default, view_default_9, permute_default_5)
78
+ view_default_10 = CallFunction(aten.view.default, bmm_default_3, Ignored())
79
+ permute_default_6 = CallFunction(aten.permute.default, view_default_10, Ignored())
80
+ permute_default_7 = CallFunction(aten.permute.default, view_default_1, Ignored())
81
+ bmm_default_4 = CallFunction(aten.bmm.default, permute_default_7, view_default_9)
82
+ view_default_11 = CallFunction(aten.view.default, bmm_default_4, Ignored())
83
+ permute_default_8 = CallFunction(aten.permute.default, view_default_11, Ignored())
84
+ permute_default_9 = CallFunction(aten.permute.default, permute_default_8, Ignored())
85
+ permute_default_10 = CallFunction(aten.permute.default, view_default_4, Ignored())
86
+ bmm_default_5 = CallFunction(aten.bmm.default, permute_default_10, view_default_7)
87
+ view_default_12 = CallFunction(aten.view.default, bmm_default_5, Ignored())
88
+ permute_default_11 = CallFunction(aten.permute.default, view_default_12, Ignored())
89
+ _sfdp_pattern_15_training = MultiOutputPattern([view_default_6,
90
+ permute_default_6,
91
+ permute_default_9,
92
+ permute_default_11,
93
+ None,
94
+ None
95
+ ])
96
+
97
+
98
+ eq_Scalar = CallFunction(aten.eq.Scalar, KeywordArg('attn_mask'), Ignored())
99
+ view_default = CallFunction(aten.view.default, eq_Scalar, Ignored())
100
+ expand_default = CallFunction(aten.expand.default, view_default, Ignored())
101
+ full_default = CallFunction(aten.full.default, [], Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False)
102
+ permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored())
103
+ expand_default_1 = CallFunction(aten.expand.default, permute_default, Ignored())
104
+ clone_default = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format)
105
+ view_default_1 = CallFunction(aten.view.default, clone_default, Ignored())
106
+ permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored())
107
+ permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored())
108
+ expand_default_2 = CallFunction(aten.expand.default, permute_default_2, Ignored())
109
+ clone_default_1 = CallFunction(aten.clone.default, expand_default_2, memory_format=torch.contiguous_format)
110
+ view_default_2 = CallFunction(aten.view.default, clone_default_1, Ignored())
111
+ bmm_default = CallFunction(aten.bmm.default, view_default_1, view_default_2)
112
+ view_default_3 = CallFunction(aten.view.default, bmm_default, Ignored())
113
+ div_Tensor = CallFunction(aten.div.Tensor, view_default_3, KeywordArg('inv_scale'))
114
+ where_self = CallFunction(aten.where.self, expand_default, full_default, div_Tensor, _users=2)
115
+ amax_default = CallFunction(aten.amax.default, where_self, Ignored(), True)
116
+ sub_Tensor = CallFunction(aten.sub.Tensor, where_self, amax_default)
117
+ exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2)
118
+ sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True)
119
+ div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList)
120
+ expand_default_3 = CallFunction(aten.expand.default, div_Tensor_1, Ignored())
121
+ view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored())
122
+ permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored())
123
+ expand_default_4 = CallFunction(aten.expand.default, permute_default_3, Ignored())
124
+ clone_default_2 = CallFunction(aten.clone.default, expand_default_4, memory_format=torch.contiguous_format)
125
+ view_default_5 = CallFunction(aten.view.default, clone_default_2, Ignored())
126
+ bmm_default_1 = CallFunction(aten.bmm.default, view_default_4, view_default_5)
127
+ _sfdp_pattern_15_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0)
128
+
129
+
130
+ eq_Scalar = CallFunction(aten.eq.Scalar, KeywordArg('attn_mask'), Ignored())
131
+ view_default = CallFunction(aten.view.default, eq_Scalar, Ignored())
132
+ expand_default = CallFunction(aten.expand.default, view_default, Ignored(), _users=2)
133
+ full_default = CallFunction(aten.full.default, [], Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False)
134
+ permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored())
135
+ expand_default_1 = CallFunction(aten.expand.default, permute_default, Ignored())
136
+ clone_default = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format)
137
+ view_default_1 = CallFunction(aten.view.default, clone_default, Ignored(), _users=2)
138
+ permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored())
139
+ permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored())
140
+ expand_default_2 = CallFunction(aten.expand.default, permute_default_2, Ignored())
141
+ clone_default_1 = CallFunction(aten.clone.default, expand_default_2, memory_format=torch.contiguous_format)
142
+ view_default_2 = CallFunction(aten.view.default, clone_default_1, Ignored(), _users=2)
143
+ bmm_default = CallFunction(aten.bmm.default, view_default_1, view_default_2)
144
+ view_default_3 = CallFunction(aten.view.default, bmm_default, Ignored())
145
+ div_Tensor = CallFunction(aten.div.Tensor, view_default_3, KeywordArg('inv_scale'))
146
+ where_self = CallFunction(aten.where.self, expand_default, full_default, div_Tensor)
147
+ convert_element_type_default = CallFunction(prims.convert_element_type.default, where_self, Ignored(), _users=2)
148
+ amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True)
149
+ sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default)
150
+ exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2)
151
+ sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True)
152
+ div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList)
153
+ convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor_1, Ignored(), _users=2)
154
+ expand_default_3 = CallFunction(aten.expand.default, convert_element_type_default_1, Ignored())
155
+ view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored(), _users=2)
156
+ permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored())
157
+ expand_default_4 = CallFunction(aten.expand.default, permute_default_3, Ignored())
158
+ clone_default_2 = CallFunction(aten.clone.default, expand_default_4, memory_format=torch.contiguous_format)
159
+ view_default_5 = CallFunction(aten.view.default, clone_default_2, Ignored(), _users=2)
160
+ bmm_default_1 = CallFunction(aten.bmm.default, view_default_4, view_default_5)
161
+ view_default_6 = CallFunction(aten.view.default, bmm_default_1, Ignored())
162
+ scalar_tensor_default = CallFunction(aten.scalar_tensor.default, Ignored(), dtype=Ignored(), layout=torch.strided, device=Ignored())
163
+ convert_element_type_default_2 = CallFunction(prims.convert_element_type.default, convert_element_type_default_1, Ignored(), _users=2)
164
+ neg_default = CallFunction(aten.neg.default, convert_element_type_default_2)
165
+ view_default_7 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2)
166
+ permute_default_4 = CallFunction(aten.permute.default, view_default_5, Ignored())
167
+ bmm_default_2 = CallFunction(aten.bmm.default, view_default_7, permute_default_4)
168
+ view_default_8 = CallFunction(aten.view.default, bmm_default_2, Ignored())
169
+ convert_element_type_default_3 = CallFunction(prims.convert_element_type.default, view_default_8, Ignored())
170
+ mul_Tensor = CallFunction(aten.mul.Tensor, convert_element_type_default_3, convert_element_type_default_2, _users=2)
171
+ sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor, Ignored(), True)
172
+ fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor)
173
+ convert_element_type_default_4 = CallFunction(prims.convert_element_type.default, fma_default, Ignored())
174
+ where_self_1 = CallFunction(aten.where.self, expand_default, scalar_tensor_default, convert_element_type_default_4)
175
+ div_Tensor_2 = CallFunction(aten.div.Tensor, where_self_1, KeywordArg('inv_scale'))
176
+ view_default_9 = CallFunction(aten.view.default, div_Tensor_2, Ignored(), _users=2)
177
+ permute_default_5 = CallFunction(aten.permute.default, view_default_2, Ignored())
178
+ bmm_default_3 = CallFunction(aten.bmm.default, view_default_9, permute_default_5)
179
+ view_default_10 = CallFunction(aten.view.default, bmm_default_3, Ignored())
180
+ permute_default_6 = CallFunction(aten.permute.default, view_default_10, Ignored())
181
+ permute_default_7 = CallFunction(aten.permute.default, view_default_1, Ignored())
182
+ bmm_default_4 = CallFunction(aten.bmm.default, permute_default_7, view_default_9)
183
+ view_default_11 = CallFunction(aten.view.default, bmm_default_4, Ignored())
184
+ permute_default_8 = CallFunction(aten.permute.default, view_default_11, Ignored())
185
+ permute_default_9 = CallFunction(aten.permute.default, permute_default_8, Ignored())
186
+ permute_default_10 = CallFunction(aten.permute.default, view_default_4, Ignored())
187
+ bmm_default_5 = CallFunction(aten.bmm.default, permute_default_10, view_default_7)
188
+ view_default_12 = CallFunction(aten.view.default, bmm_default_5, Ignored())
189
+ permute_default_11 = CallFunction(aten.permute.default, view_default_12, Ignored())
190
+ _sfdp_pattern_15_half_training = MultiOutputPattern([view_default_6,
191
+ permute_default_6,
192
+ permute_default_9,
193
+ permute_default_11,
194
+ None,
195
+ None
196
+ ])
197
+
198
+
199
+ eq_Scalar = CallFunction(aten.eq.Scalar, KeywordArg('attn_mask'), Ignored())
200
+ view_default = CallFunction(aten.view.default, eq_Scalar, Ignored())
201
+ expand_default = CallFunction(aten.expand.default, view_default, Ignored())
202
+ full_default = CallFunction(aten.full.default, [], Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False)
203
+ permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored())
204
+ expand_default_1 = CallFunction(aten.expand.default, permute_default, Ignored())
205
+ clone_default = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format)
206
+ view_default_1 = CallFunction(aten.view.default, clone_default, Ignored())
207
+ permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored())
208
+ permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored())
209
+ expand_default_2 = CallFunction(aten.expand.default, permute_default_2, Ignored())
210
+ clone_default_1 = CallFunction(aten.clone.default, expand_default_2, memory_format=torch.contiguous_format)
211
+ view_default_2 = CallFunction(aten.view.default, clone_default_1, Ignored())
212
+ bmm_default = CallFunction(aten.bmm.default, view_default_1, view_default_2)
213
+ view_default_3 = CallFunction(aten.view.default, bmm_default, Ignored())
214
+ div_Tensor = CallFunction(aten.div.Tensor, view_default_3, KeywordArg('inv_scale'))
215
+ where_self = CallFunction(aten.where.self, expand_default, full_default, div_Tensor)
216
+ convert_element_type_default = CallFunction(prims.convert_element_type.default, where_self, Ignored(), _users=2)
217
+ amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True)
218
+ sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default)
219
+ exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2)
220
+ sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True)
221
+ div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList)
222
+ convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor_1, Ignored())
223
+ expand_default_3 = CallFunction(aten.expand.default, convert_element_type_default_1, Ignored())
224
+ view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored())
225
+ permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored())
226
+ expand_default_4 = CallFunction(aten.expand.default, permute_default_3, Ignored())
227
+ clone_default_2 = CallFunction(aten.clone.default, expand_default_4, memory_format=torch.contiguous_format)
228
+ view_default_5 = CallFunction(aten.view.default, clone_default_2, Ignored())
229
+ bmm_default_1 = CallFunction(aten.bmm.default, view_default_4, view_default_5)
230
+ _sfdp_pattern_15_half_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0)
.venv/lib/python3.10/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_16.py ADDED
@@ -0,0 +1,599 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: ignore-errors
2
+
3
+ # noqa: F401, E501
4
+ # This is an auto-generated file. Please do not modify it by hand.
5
+ # To re-generate, run:
6
+ # cd ~/pytorch && python torchgen/fuse/gen_patterns.py
7
+
8
+ import torch
9
+ import torch._inductor
10
+ import operator
11
+
12
+ aten = torch.ops.aten
13
+ prims = torch.ops.prims
14
+
15
+ from torch._inductor.pattern_matcher import (
16
+ Arg,
17
+ CallFunction,
18
+ CallFunctionVarArgs,
19
+ CallMethod,
20
+ CallMethodVarArgs,
21
+ CallModule,
22
+ CallModuleVarArgs,
23
+ ExclusiveKeywordArg,
24
+ Ignored,
25
+ KeywordArg,
26
+ ListOf,
27
+ MultiOutputPattern,
28
+ PatternExpr,
29
+ RepeatedExpr,
30
+ _TargetArgsExpr,
31
+ _TargetExpr,
32
+ _TargetExprVarArgs,
33
+ )
34
+ rand_default = CallFunction(aten.rand.default, Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False)
35
+ gt_Scalar = CallFunction(aten.gt.Scalar, rand_default, KeywordArg('dropout_p'), _users=2)
36
+ permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored())
37
+ expand_default = CallFunction(aten.expand.default, permute_default, Ignored())
38
+ clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format)
39
+ view_default = CallFunction(aten.view.default, clone_default, Ignored(), _users=2)
40
+ permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored())
41
+ permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored())
42
+ expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored())
43
+ clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format)
44
+ view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored(), _users=2)
45
+ bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1)
46
+ view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored())
47
+ div_Tensor = CallFunction(aten.div.Tensor, view_default_2, KeywordArg('inv_scale'))
48
+ add_Tensor = CallFunction(aten.add.Tensor, div_Tensor, KeywordArg('attn_mask'), _users=2)
49
+ amax_default = CallFunction(aten.amax.default, add_Tensor, Ignored(), True)
50
+ sub_Tensor = CallFunction(aten.sub.Tensor, add_Tensor, amax_default)
51
+ exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2)
52
+ sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True)
53
+ div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList, _users=3)
54
+ mul_Tensor = CallFunction(aten.mul.Tensor, gt_Scalar, div_Tensor_1)
55
+ mul_Tensor_1 = CallFunction(aten.mul.Tensor, mul_Tensor, Ignored())
56
+ expand_default_2 = CallFunction(aten.expand.default, mul_Tensor_1, Ignored())
57
+ view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored(), _users=2)
58
+ permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored())
59
+ expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored())
60
+ clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format)
61
+ view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored(), _users=2)
62
+ bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4)
63
+ view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored())
64
+ neg_default = CallFunction(aten.neg.default, div_Tensor_1)
65
+ view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2)
66
+ permute_default_4 = CallFunction(aten.permute.default, view_default_4, Ignored())
67
+ bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_4)
68
+ view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored())
69
+ convert_element_type_default = CallFunction(prims.convert_element_type.default, gt_Scalar, Ignored())
70
+ mul_Tensor_2 = CallFunction(aten.mul.Tensor, convert_element_type_default, Ignored())
71
+ mul_Tensor_3 = CallFunction(aten.mul.Tensor, view_default_7, mul_Tensor_2)
72
+ mul_Tensor_4 = CallFunction(aten.mul.Tensor, mul_Tensor_3, div_Tensor_1, _users=2)
73
+ sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor_4, Ignored(), True)
74
+ fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor_4)
75
+ div_Tensor_2 = CallFunction(aten.div.Tensor, fma_default, KeywordArg('inv_scale'))
76
+ view_default_8 = CallFunction(aten.view.default, div_Tensor_2, Ignored(), _users=2)
77
+ permute_default_5 = CallFunction(aten.permute.default, view_default_1, Ignored())
78
+ bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_5)
79
+ view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored())
80
+ permute_default_6 = CallFunction(aten.permute.default, view_default_9, Ignored())
81
+ permute_default_7 = CallFunction(aten.permute.default, view_default, Ignored())
82
+ bmm_default_4 = CallFunction(aten.bmm.default, permute_default_7, view_default_8)
83
+ view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored())
84
+ permute_default_8 = CallFunction(aten.permute.default, view_default_10, Ignored())
85
+ permute_default_9 = CallFunction(aten.permute.default, permute_default_8, Ignored())
86
+ permute_default_10 = CallFunction(aten.permute.default, view_default_3, Ignored())
87
+ bmm_default_5 = CallFunction(aten.bmm.default, permute_default_10, view_default_6)
88
+ view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored())
89
+ permute_default_11 = CallFunction(aten.permute.default, view_default_11, Ignored())
90
+ _sfdp_pattern_16_training = MultiOutputPattern([view_default_5,
91
+ permute_default_6,
92
+ permute_default_9,
93
+ permute_default_11,
94
+ None,
95
+ None,
96
+ None
97
+ ])
98
+
99
+
100
+ permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored())
101
+ expand_default = CallFunction(aten.expand.default, permute_default, Ignored())
102
+ clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format)
103
+ view_default = CallFunction(aten.view.default, clone_default, Ignored())
104
+ permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored())
105
+ permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored())
106
+ expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored())
107
+ clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format)
108
+ view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored())
109
+ bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1)
110
+ view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored())
111
+ div_Tensor = CallFunction(aten.div.Tensor, view_default_2, KeywordArg('inv_scale'))
112
+ add_Tensor = CallFunction(aten.add.Tensor, div_Tensor, KeywordArg('attn_mask'), _users=2)
113
+ amax_default = CallFunction(aten.amax.default, add_Tensor, Ignored(), True)
114
+ sub_Tensor = CallFunction(aten.sub.Tensor, add_Tensor, amax_default)
115
+ exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2)
116
+ sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True)
117
+ div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList)
118
+ expand_default_2 = CallFunction(aten.expand.default, div_Tensor_1, Ignored())
119
+ view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored())
120
+ permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored())
121
+ expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored())
122
+ clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format)
123
+ view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored())
124
+ bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4)
125
+ _sfdp_pattern_16_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0)
126
+
127
+
128
+ rand_default = CallFunction(aten.rand.default, Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False)
129
+ gt_Scalar = CallFunction(aten.gt.Scalar, rand_default, KeywordArg('dropout_p'), _users=2)
130
+ permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored())
131
+ expand_default = CallFunction(aten.expand.default, permute_default, Ignored())
132
+ view_default = CallFunction(aten.view.default, expand_default, Ignored(), _users=2)
133
+ permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored())
134
+ permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored())
135
+ expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored())
136
+ view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored(), _users=2)
137
+ bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1)
138
+ view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored())
139
+ div_Tensor = CallFunction(aten.div.Tensor, view_default_2, KeywordArg('inv_scale'))
140
+ add_Tensor = CallFunction(aten.add.Tensor, div_Tensor, KeywordArg('attn_mask'), _users=2)
141
+ amax_default = CallFunction(aten.amax.default, add_Tensor, Ignored(), True)
142
+ sub_Tensor = CallFunction(aten.sub.Tensor, add_Tensor, amax_default)
143
+ exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2)
144
+ sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True)
145
+ div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList, _users=3)
146
+ mul_Tensor = CallFunction(aten.mul.Tensor, gt_Scalar, div_Tensor_1)
147
+ mul_Tensor_1 = CallFunction(aten.mul.Tensor, mul_Tensor, Ignored())
148
+ expand_default_2 = CallFunction(aten.expand.default, mul_Tensor_1, Ignored())
149
+ view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored(), _users=2)
150
+ permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored())
151
+ expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored())
152
+ view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored(), _users=2)
153
+ bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4)
154
+ view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored())
155
+ neg_default = CallFunction(aten.neg.default, div_Tensor_1)
156
+ view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2)
157
+ permute_default_4 = CallFunction(aten.permute.default, view_default_4, Ignored())
158
+ bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_4)
159
+ view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored())
160
+ convert_element_type_default = CallFunction(prims.convert_element_type.default, gt_Scalar, Ignored())
161
+ mul_Tensor_2 = CallFunction(aten.mul.Tensor, convert_element_type_default, Ignored())
162
+ mul_Tensor_3 = CallFunction(aten.mul.Tensor, view_default_7, mul_Tensor_2)
163
+ mul_Tensor_4 = CallFunction(aten.mul.Tensor, mul_Tensor_3, div_Tensor_1, _users=2)
164
+ sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor_4, Ignored(), True)
165
+ fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor_4)
166
+ div_Tensor_2 = CallFunction(aten.div.Tensor, fma_default, KeywordArg('inv_scale'))
167
+ view_default_8 = CallFunction(aten.view.default, div_Tensor_2, Ignored(), _users=2)
168
+ permute_default_5 = CallFunction(aten.permute.default, view_default_1, Ignored())
169
+ bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_5)
170
+ view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored())
171
+ permute_default_6 = CallFunction(aten.permute.default, view_default_9, Ignored())
172
+ permute_default_7 = CallFunction(aten.permute.default, view_default, Ignored())
173
+ bmm_default_4 = CallFunction(aten.bmm.default, permute_default_7, view_default_8)
174
+ view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored())
175
+ permute_default_8 = CallFunction(aten.permute.default, view_default_10, Ignored())
176
+ permute_default_9 = CallFunction(aten.permute.default, permute_default_8, Ignored())
177
+ permute_default_10 = CallFunction(aten.permute.default, view_default_3, Ignored())
178
+ bmm_default_5 = CallFunction(aten.bmm.default, permute_default_10, view_default_6)
179
+ view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored())
180
+ permute_default_11 = CallFunction(aten.permute.default, view_default_11, Ignored())
181
+ _sfdp_pattern_16_bs1_training = MultiOutputPattern([view_default_5,
182
+ permute_default_6,
183
+ permute_default_9,
184
+ permute_default_11,
185
+ None,
186
+ None,
187
+ None
188
+ ])
189
+
190
+
191
+ permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored())
192
+ expand_default = CallFunction(aten.expand.default, permute_default, Ignored())
193
+ view_default = CallFunction(aten.view.default, expand_default, Ignored())
194
+ permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored())
195
+ permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored())
196
+ expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored())
197
+ view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored())
198
+ bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1)
199
+ view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored())
200
+ div_Tensor = CallFunction(aten.div.Tensor, view_default_2, KeywordArg('inv_scale'))
201
+ add_Tensor = CallFunction(aten.add.Tensor, div_Tensor, KeywordArg('attn_mask'), _users=2)
202
+ amax_default = CallFunction(aten.amax.default, add_Tensor, Ignored(), True)
203
+ sub_Tensor = CallFunction(aten.sub.Tensor, add_Tensor, amax_default)
204
+ exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2)
205
+ sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True)
206
+ div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList)
207
+ expand_default_2 = CallFunction(aten.expand.default, div_Tensor_1, Ignored())
208
+ view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored())
209
+ permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored())
210
+ expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored())
211
+ view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored())
212
+ bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4)
213
+ _sfdp_pattern_16_bs1_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0)
214
+
215
+
216
+ rand_default = CallFunction(aten.rand.default, Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False)
217
+ gt_Scalar = CallFunction(aten.gt.Scalar, rand_default, KeywordArg('dropout_p'), _users=2)
218
+ permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored())
219
+ expand_default = CallFunction(aten.expand.default, permute_default, Ignored())
220
+ clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format)
221
+ view_default = CallFunction(aten.view.default, clone_default, Ignored(), _users=2)
222
+ permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored())
223
+ permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored())
224
+ expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored())
225
+ clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format)
226
+ view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored(), _users=2)
227
+ bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1)
228
+ view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored())
229
+ div_Tensor = CallFunction(aten.div.Tensor, view_default_2, KeywordArg('inv_scale'))
230
+ add_Tensor = CallFunction(aten.add.Tensor, div_Tensor, KeywordArg('attn_mask'))
231
+ convert_element_type_default = CallFunction(prims.convert_element_type.default, add_Tensor, Ignored(), _users=2)
232
+ amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True)
233
+ sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default)
234
+ exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2)
235
+ sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True)
236
+ div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList)
237
+ convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor_1, Ignored(), _users=2)
238
+ mul_Tensor = CallFunction(aten.mul.Tensor, gt_Scalar, convert_element_type_default_1)
239
+ mul_Tensor_1 = CallFunction(aten.mul.Tensor, mul_Tensor, Ignored())
240
+ expand_default_2 = CallFunction(aten.expand.default, mul_Tensor_1, Ignored())
241
+ view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored(), _users=2)
242
+ permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored())
243
+ expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored())
244
+ clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format)
245
+ view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored(), _users=2)
246
+ bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4)
247
+ view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored())
248
+ convert_element_type_default_2 = CallFunction(prims.convert_element_type.default, convert_element_type_default_1, Ignored(), _users=2)
249
+ neg_default = CallFunction(aten.neg.default, convert_element_type_default_2)
250
+ view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2)
251
+ permute_default_4 = CallFunction(aten.permute.default, view_default_4, Ignored())
252
+ bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_4)
253
+ view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored())
254
+ convert_element_type_default_3 = CallFunction(prims.convert_element_type.default, gt_Scalar, Ignored())
255
+ mul_Tensor_2 = CallFunction(aten.mul.Tensor, convert_element_type_default_3, Ignored())
256
+ mul_Tensor_3 = CallFunction(aten.mul.Tensor, view_default_7, mul_Tensor_2)
257
+ convert_element_type_default_4 = CallFunction(prims.convert_element_type.default, mul_Tensor_3, Ignored())
258
+ mul_Tensor_4 = CallFunction(aten.mul.Tensor, convert_element_type_default_4, convert_element_type_default_2, _users=2)
259
+ sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor_4, Ignored(), True)
260
+ fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor_4)
261
+ convert_element_type_default_5 = CallFunction(prims.convert_element_type.default, fma_default, Ignored())
262
+ div_Tensor_2 = CallFunction(aten.div.Tensor, convert_element_type_default_5, KeywordArg('inv_scale'))
263
+ view_default_8 = CallFunction(aten.view.default, div_Tensor_2, Ignored(), _users=2)
264
+ permute_default_5 = CallFunction(aten.permute.default, view_default_1, Ignored())
265
+ bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_5)
266
+ view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored())
267
+ permute_default_6 = CallFunction(aten.permute.default, view_default_9, Ignored())
268
+ permute_default_7 = CallFunction(aten.permute.default, view_default, Ignored())
269
+ bmm_default_4 = CallFunction(aten.bmm.default, permute_default_7, view_default_8)
270
+ view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored())
271
+ permute_default_8 = CallFunction(aten.permute.default, view_default_10, Ignored())
272
+ permute_default_9 = CallFunction(aten.permute.default, permute_default_8, Ignored())
273
+ permute_default_10 = CallFunction(aten.permute.default, view_default_3, Ignored())
274
+ bmm_default_5 = CallFunction(aten.bmm.default, permute_default_10, view_default_6)
275
+ view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored())
276
+ permute_default_11 = CallFunction(aten.permute.default, view_default_11, Ignored())
277
+ _sfdp_pattern_16_half_training = MultiOutputPattern([view_default_5,
278
+ permute_default_6,
279
+ permute_default_9,
280
+ permute_default_11,
281
+ None,
282
+ None,
283
+ None
284
+ ])
285
+
286
+
287
+ permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored())
288
+ expand_default = CallFunction(aten.expand.default, permute_default, Ignored())
289
+ clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format)
290
+ view_default = CallFunction(aten.view.default, clone_default, Ignored())
291
+ permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored())
292
+ permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored())
293
+ expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored())
294
+ clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format)
295
+ view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored())
296
+ bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1)
297
+ view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored())
298
+ div_Tensor = CallFunction(aten.div.Tensor, view_default_2, KeywordArg('inv_scale'))
299
+ add_Tensor = CallFunction(aten.add.Tensor, div_Tensor, KeywordArg('attn_mask'))
300
+ convert_element_type_default = CallFunction(prims.convert_element_type.default, add_Tensor, Ignored(), _users=2)
301
+ amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True)
302
+ sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default)
303
+ exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2)
304
+ sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True)
305
+ div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList)
306
+ convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor_1, Ignored())
307
+ expand_default_2 = CallFunction(aten.expand.default, convert_element_type_default_1, Ignored())
308
+ view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored())
309
+ permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored())
310
+ expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored())
311
+ clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format)
312
+ view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored())
313
+ bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4)
314
+ _sfdp_pattern_16_half_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0)
315
+
316
+
317
+ rand_default = CallFunction(aten.rand.default, Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False)
318
+ gt_Scalar = CallFunction(aten.gt.Scalar, rand_default, KeywordArg('dropout_p'), _users=2)
319
+ permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored())
320
+ expand_default = CallFunction(aten.expand.default, permute_default, Ignored())
321
+ view_default = CallFunction(aten.view.default, expand_default, Ignored(), _users=2)
322
+ permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored())
323
+ permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored())
324
+ expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored())
325
+ view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored(), _users=2)
326
+ bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1)
327
+ view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored())
328
+ div_Tensor = CallFunction(aten.div.Tensor, view_default_2, KeywordArg('inv_scale'))
329
+ add_Tensor = CallFunction(aten.add.Tensor, div_Tensor, KeywordArg('attn_mask'))
330
+ convert_element_type_default = CallFunction(prims.convert_element_type.default, add_Tensor, Ignored(), _users=2)
331
+ amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True)
332
+ sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default)
333
+ exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2)
334
+ sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True)
335
+ div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList)
336
+ convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor_1, Ignored(), _users=2)
337
+ mul_Tensor = CallFunction(aten.mul.Tensor, gt_Scalar, convert_element_type_default_1)
338
+ mul_Tensor_1 = CallFunction(aten.mul.Tensor, mul_Tensor, Ignored())
339
+ expand_default_2 = CallFunction(aten.expand.default, mul_Tensor_1, Ignored())
340
+ view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored(), _users=2)
341
+ permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored())
342
+ expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored())
343
+ view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored(), _users=2)
344
+ bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4)
345
+ view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored())
346
+ convert_element_type_default_2 = CallFunction(prims.convert_element_type.default, convert_element_type_default_1, Ignored(), _users=2)
347
+ neg_default = CallFunction(aten.neg.default, convert_element_type_default_2)
348
+ view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2)
349
+ permute_default_4 = CallFunction(aten.permute.default, view_default_4, Ignored())
350
+ bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_4)
351
+ view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored())
352
+ convert_element_type_default_3 = CallFunction(prims.convert_element_type.default, gt_Scalar, Ignored())
353
+ mul_Tensor_2 = CallFunction(aten.mul.Tensor, convert_element_type_default_3, Ignored())
354
+ mul_Tensor_3 = CallFunction(aten.mul.Tensor, view_default_7, mul_Tensor_2)
355
+ convert_element_type_default_4 = CallFunction(prims.convert_element_type.default, mul_Tensor_3, Ignored())
356
+ mul_Tensor_4 = CallFunction(aten.mul.Tensor, convert_element_type_default_4, convert_element_type_default_2, _users=2)
357
+ sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor_4, Ignored(), True)
358
+ fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor_4)
359
+ convert_element_type_default_5 = CallFunction(prims.convert_element_type.default, fma_default, Ignored())
360
+ div_Tensor_2 = CallFunction(aten.div.Tensor, convert_element_type_default_5, KeywordArg('inv_scale'))
361
+ view_default_8 = CallFunction(aten.view.default, div_Tensor_2, Ignored(), _users=2)
362
+ permute_default_5 = CallFunction(aten.permute.default, view_default_1, Ignored())
363
+ bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_5)
364
+ view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored())
365
+ permute_default_6 = CallFunction(aten.permute.default, view_default_9, Ignored())
366
+ permute_default_7 = CallFunction(aten.permute.default, view_default, Ignored())
367
+ bmm_default_4 = CallFunction(aten.bmm.default, permute_default_7, view_default_8)
368
+ view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored())
369
+ permute_default_8 = CallFunction(aten.permute.default, view_default_10, Ignored())
370
+ permute_default_9 = CallFunction(aten.permute.default, permute_default_8, Ignored())
371
+ permute_default_10 = CallFunction(aten.permute.default, view_default_3, Ignored())
372
+ bmm_default_5 = CallFunction(aten.bmm.default, permute_default_10, view_default_6)
373
+ view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored())
374
+ permute_default_11 = CallFunction(aten.permute.default, view_default_11, Ignored())
375
+ _sfdp_pattern_16_half_bs1_training = MultiOutputPattern([view_default_5,
376
+ permute_default_6,
377
+ permute_default_9,
378
+ permute_default_11,
379
+ None,
380
+ None,
381
+ None
382
+ ])
383
+
384
+
385
+ permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored())
386
+ expand_default = CallFunction(aten.expand.default, permute_default, Ignored())
387
+ view_default = CallFunction(aten.view.default, expand_default, Ignored())
388
+ permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored())
389
+ permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored())
390
+ expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored())
391
+ view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored())
392
+ bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1)
393
+ view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored())
394
+ div_Tensor = CallFunction(aten.div.Tensor, view_default_2, KeywordArg('inv_scale'))
395
+ add_Tensor = CallFunction(aten.add.Tensor, div_Tensor, KeywordArg('attn_mask'))
396
+ convert_element_type_default = CallFunction(prims.convert_element_type.default, add_Tensor, Ignored(), _users=2)
397
+ amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True)
398
+ sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default)
399
+ exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2)
400
+ sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True)
401
+ div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList)
402
+ convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor_1, Ignored())
403
+ expand_default_2 = CallFunction(aten.expand.default, convert_element_type_default_1, Ignored())
404
+ view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored())
405
+ permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored())
406
+ expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored())
407
+ view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored())
408
+ bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4)
409
+ _sfdp_pattern_16_half_bs1_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0)
410
+
411
+
412
+ rand_default = CallFunction(aten.rand.default, Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False)
413
+ gt_Scalar = CallFunction(aten.gt.Scalar, rand_default, KeywordArg('dropout_p'), _users=2)
414
+ permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored())
415
+ expand_default = CallFunction(aten.expand.default, permute_default, Ignored())
416
+ clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format)
417
+ view_default = CallFunction(aten.view.default, clone_default, Ignored(), _users=2)
418
+ permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored())
419
+ permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored())
420
+ expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored())
421
+ clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format)
422
+ view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored(), _users=2)
423
+ bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1)
424
+ view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored())
425
+ div_Tensor = CallFunction(aten.div.Tensor, view_default_2, KeywordArg('inv_scale'))
426
+ add_Tensor = CallFunction(aten.add.Tensor, div_Tensor, KeywordArg('attn_mask'), _users=2)
427
+ amax_default = CallFunction(aten.amax.default, add_Tensor, Ignored(), True)
428
+ sub_Tensor = CallFunction(aten.sub.Tensor, add_Tensor, amax_default)
429
+ exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2)
430
+ sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True)
431
+ div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList, _users=3)
432
+ mul_Tensor = CallFunction(aten.mul.Tensor, gt_Scalar, div_Tensor_1)
433
+ mul_Tensor_1 = CallFunction(aten.mul.Tensor, mul_Tensor, Ignored())
434
+ convert_element_type_default = CallFunction(prims.convert_element_type.default, mul_Tensor_1, Ignored())
435
+ expand_default_2 = CallFunction(aten.expand.default, convert_element_type_default, Ignored())
436
+ view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored(), _users=2)
437
+ permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored())
438
+ expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored())
439
+ clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format)
440
+ view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored(), _users=2)
441
+ bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4)
442
+ view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored())
443
+ neg_default = CallFunction(aten.neg.default, div_Tensor_1)
444
+ view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2)
445
+ permute_default_4 = CallFunction(aten.permute.default, view_default_4, Ignored())
446
+ bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_4)
447
+ view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored())
448
+ convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, view_default_7, Ignored())
449
+ convert_element_type_default_2 = CallFunction(prims.convert_element_type.default, gt_Scalar, Ignored())
450
+ mul_Tensor_2 = CallFunction(aten.mul.Tensor, convert_element_type_default_2, Ignored())
451
+ mul_Tensor_3 = CallFunction(aten.mul.Tensor, convert_element_type_default_1, mul_Tensor_2)
452
+ mul_Tensor_4 = CallFunction(aten.mul.Tensor, mul_Tensor_3, div_Tensor_1, _users=2)
453
+ sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor_4, Ignored(), True)
454
+ fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor_4)
455
+ convert_element_type_default_3 = CallFunction(prims.convert_element_type.default, fma_default, Ignored())
456
+ div_Tensor_2 = CallFunction(aten.div.Tensor, convert_element_type_default_3, KeywordArg('inv_scale'))
457
+ view_default_8 = CallFunction(aten.view.default, div_Tensor_2, Ignored(), _users=2)
458
+ permute_default_5 = CallFunction(aten.permute.default, view_default_1, Ignored())
459
+ bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_5)
460
+ view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored())
461
+ permute_default_6 = CallFunction(aten.permute.default, view_default_9, Ignored())
462
+ permute_default_7 = CallFunction(aten.permute.default, view_default, Ignored())
463
+ bmm_default_4 = CallFunction(aten.bmm.default, permute_default_7, view_default_8)
464
+ view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored())
465
+ permute_default_8 = CallFunction(aten.permute.default, view_default_10, Ignored())
466
+ permute_default_9 = CallFunction(aten.permute.default, permute_default_8, Ignored())
467
+ permute_default_10 = CallFunction(aten.permute.default, view_default_3, Ignored())
468
+ bmm_default_5 = CallFunction(aten.bmm.default, permute_default_10, view_default_6)
469
+ view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored())
470
+ permute_default_11 = CallFunction(aten.permute.default, view_default_11, Ignored())
471
+ _sfdp_pattern_16_half_mask_fp32_training = MultiOutputPattern([view_default_5,
472
+ permute_default_6,
473
+ permute_default_9,
474
+ permute_default_11,
475
+ None,
476
+ None,
477
+ None
478
+ ])
479
+
480
+
481
+ permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored())
482
+ expand_default = CallFunction(aten.expand.default, permute_default, Ignored())
483
+ clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format)
484
+ view_default = CallFunction(aten.view.default, clone_default, Ignored())
485
+ permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored())
486
+ permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored())
487
+ expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored())
488
+ clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format)
489
+ view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored())
490
+ bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1)
491
+ view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored())
492
+ div_Tensor = CallFunction(aten.div.Tensor, view_default_2, KeywordArg('inv_scale'))
493
+ add_Tensor = CallFunction(aten.add.Tensor, div_Tensor, KeywordArg('attn_mask'), _users=2)
494
+ amax_default = CallFunction(aten.amax.default, add_Tensor, Ignored(), True)
495
+ sub_Tensor = CallFunction(aten.sub.Tensor, add_Tensor, amax_default)
496
+ exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2)
497
+ sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True)
498
+ div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList)
499
+ convert_element_type_default = CallFunction(prims.convert_element_type.default, div_Tensor_1, Ignored())
500
+ expand_default_2 = CallFunction(aten.expand.default, convert_element_type_default, Ignored())
501
+ view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored())
502
+ permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored())
503
+ expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored())
504
+ clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format)
505
+ view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored())
506
+ bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4)
507
+ _sfdp_pattern_16_half_mask_fp32_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0)
508
+
509
+
510
+ rand_default = CallFunction(aten.rand.default, Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False)
511
+ gt_Scalar = CallFunction(aten.gt.Scalar, rand_default, KeywordArg('dropout_p'), _users=2)
512
+ permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored())
513
+ expand_default = CallFunction(aten.expand.default, permute_default, Ignored())
514
+ view_default = CallFunction(aten.view.default, expand_default, Ignored(), _users=2)
515
+ permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored())
516
+ permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored())
517
+ expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored())
518
+ view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored(), _users=2)
519
+ bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1)
520
+ view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored())
521
+ div_Tensor = CallFunction(aten.div.Tensor, view_default_2, KeywordArg('inv_scale'))
522
+ add_Tensor = CallFunction(aten.add.Tensor, div_Tensor, KeywordArg('attn_mask'), _users=2)
523
+ amax_default = CallFunction(aten.amax.default, add_Tensor, Ignored(), True)
524
+ sub_Tensor = CallFunction(aten.sub.Tensor, add_Tensor, amax_default)
525
+ exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2)
526
+ sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True)
527
+ div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList, _users=3)
528
+ mul_Tensor = CallFunction(aten.mul.Tensor, gt_Scalar, div_Tensor_1)
529
+ mul_Tensor_1 = CallFunction(aten.mul.Tensor, mul_Tensor, Ignored())
530
+ convert_element_type_default = CallFunction(prims.convert_element_type.default, mul_Tensor_1, Ignored())
531
+ expand_default_2 = CallFunction(aten.expand.default, convert_element_type_default, Ignored())
532
+ view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored(), _users=2)
533
+ permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored())
534
+ expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored())
535
+ view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored(), _users=2)
536
+ bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4)
537
+ view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored())
538
+ neg_default = CallFunction(aten.neg.default, div_Tensor_1)
539
+ view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2)
540
+ permute_default_4 = CallFunction(aten.permute.default, view_default_4, Ignored())
541
+ bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_4)
542
+ view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored())
543
+ convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, view_default_7, Ignored())
544
+ convert_element_type_default_2 = CallFunction(prims.convert_element_type.default, gt_Scalar, Ignored())
545
+ mul_Tensor_2 = CallFunction(aten.mul.Tensor, convert_element_type_default_2, Ignored())
546
+ mul_Tensor_3 = CallFunction(aten.mul.Tensor, convert_element_type_default_1, mul_Tensor_2)
547
+ mul_Tensor_4 = CallFunction(aten.mul.Tensor, mul_Tensor_3, div_Tensor_1, _users=2)
548
+ sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor_4, Ignored(), True)
549
+ fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor_4)
550
+ convert_element_type_default_3 = CallFunction(prims.convert_element_type.default, fma_default, Ignored())
551
+ div_Tensor_2 = CallFunction(aten.div.Tensor, convert_element_type_default_3, KeywordArg('inv_scale'))
552
+ view_default_8 = CallFunction(aten.view.default, div_Tensor_2, Ignored(), _users=2)
553
+ permute_default_5 = CallFunction(aten.permute.default, view_default_1, Ignored())
554
+ bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_5)
555
+ view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored())
556
+ permute_default_6 = CallFunction(aten.permute.default, view_default_9, Ignored())
557
+ permute_default_7 = CallFunction(aten.permute.default, view_default, Ignored())
558
+ bmm_default_4 = CallFunction(aten.bmm.default, permute_default_7, view_default_8)
559
+ view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored())
560
+ permute_default_8 = CallFunction(aten.permute.default, view_default_10, Ignored())
561
+ permute_default_9 = CallFunction(aten.permute.default, permute_default_8, Ignored())
562
+ permute_default_10 = CallFunction(aten.permute.default, view_default_3, Ignored())
563
+ bmm_default_5 = CallFunction(aten.bmm.default, permute_default_10, view_default_6)
564
+ view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored())
565
+ permute_default_11 = CallFunction(aten.permute.default, view_default_11, Ignored())
566
+ _sfdp_pattern_16_half_mask_fp32_bs1_training = MultiOutputPattern([view_default_5,
567
+ permute_default_6,
568
+ permute_default_9,
569
+ permute_default_11,
570
+ None,
571
+ None,
572
+ None
573
+ ])
574
+
575
+
576
+ permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored())
577
+ expand_default = CallFunction(aten.expand.default, permute_default, Ignored())
578
+ view_default = CallFunction(aten.view.default, expand_default, Ignored())
579
+ permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored())
580
+ permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored())
581
+ expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored())
582
+ view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored())
583
+ bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1)
584
+ view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored())
585
+ div_Tensor = CallFunction(aten.div.Tensor, view_default_2, KeywordArg('inv_scale'))
586
+ add_Tensor = CallFunction(aten.add.Tensor, div_Tensor, KeywordArg('attn_mask'), _users=2)
587
+ amax_default = CallFunction(aten.amax.default, add_Tensor, Ignored(), True)
588
+ sub_Tensor = CallFunction(aten.sub.Tensor, add_Tensor, amax_default)
589
+ exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2)
590
+ sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True)
591
+ div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList)
592
+ convert_element_type_default = CallFunction(prims.convert_element_type.default, div_Tensor_1, Ignored())
593
+ expand_default_2 = CallFunction(aten.expand.default, convert_element_type_default, Ignored())
594
+ view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored())
595
+ permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored())
596
+ expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored())
597
+ view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored())
598
+ bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4)
599
+ _sfdp_pattern_16_half_mask_fp32_bs1_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0)
.venv/lib/python3.10/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_18.py ADDED
@@ -0,0 +1,453 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: ignore-errors
2
+
3
+ # noqa: F401, E501
4
+ # This is an auto-generated file. Please do not modify it by hand.
5
+ # To re-generate, run:
6
+ # cd ~/pytorch && python torchgen/fuse/gen_patterns.py
7
+
8
+ import torch
9
+ import torch._inductor
10
+ import operator
11
+
12
+ aten = torch.ops.aten
13
+ prims = torch.ops.prims
14
+
15
+ from torch._inductor.pattern_matcher import (
16
+ Arg,
17
+ CallFunction,
18
+ CallFunctionVarArgs,
19
+ CallMethod,
20
+ CallMethodVarArgs,
21
+ CallModule,
22
+ CallModuleVarArgs,
23
+ ExclusiveKeywordArg,
24
+ Ignored,
25
+ KeywordArg,
26
+ ListOf,
27
+ MultiOutputPattern,
28
+ PatternExpr,
29
+ RepeatedExpr,
30
+ _TargetArgsExpr,
31
+ _TargetExpr,
32
+ _TargetExprVarArgs,
33
+ )
34
+ rand_default = CallFunction(aten.rand.default, Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False)
35
+ gt_Scalar = CallFunction(aten.gt.Scalar, rand_default, KeywordArg('dropout_p'), _users=2)
36
+ permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored())
37
+ expand_default = CallFunction(aten.expand.default, permute_default, Ignored())
38
+ clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format)
39
+ view_default = CallFunction(aten.view.default, clone_default, Ignored(), _users=2)
40
+ permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored(), _users=2)
41
+ permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored())
42
+ expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored())
43
+ clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format)
44
+ view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored(), _users=2)
45
+ bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1)
46
+ view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored())
47
+ full_default = CallFunction(aten.full.default, [], Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False, _users=2)
48
+ div_Tensor = CallFunction(aten.div.Tensor, view_default_2, full_default)
49
+ full_default_1 = CallFunction(aten.full.default, [], Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False)
50
+ where_self = CallFunction(aten.where.self, KeywordArg('causal_mask'), div_Tensor, full_default_1, _users=2)
51
+ amax_default = CallFunction(aten.amax.default, where_self, Ignored(), True)
52
+ sub_Tensor = CallFunction(aten.sub.Tensor, where_self, amax_default)
53
+ exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2)
54
+ sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True)
55
+ div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList, _users=3)
56
+ mul_Tensor = CallFunction(aten.mul.Tensor, gt_Scalar, div_Tensor_1)
57
+ mul_Tensor_1 = CallFunction(aten.mul.Tensor, mul_Tensor, Ignored())
58
+ expand_default_2 = CallFunction(aten.expand.default, mul_Tensor_1, Ignored())
59
+ view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored(), _users=2)
60
+ permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored(), _users=2)
61
+ expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored())
62
+ clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format)
63
+ view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored(), _users=2)
64
+ bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4)
65
+ view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored())
66
+ neg_default = CallFunction(aten.neg.default, div_Tensor_1)
67
+ view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2)
68
+ permute_default_4 = CallFunction(aten.permute.default, view_default_4, Ignored())
69
+ bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_4)
70
+ view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored())
71
+ convert_element_type_default = CallFunction(prims.convert_element_type.default, gt_Scalar, Ignored())
72
+ mul_Tensor_2 = CallFunction(aten.mul.Tensor, convert_element_type_default, Ignored())
73
+ mul_Tensor_3 = CallFunction(aten.mul.Tensor, view_default_7, mul_Tensor_2)
74
+ mul_Tensor_4 = CallFunction(aten.mul.Tensor, mul_Tensor_3, div_Tensor_1, _users=2)
75
+ sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor_4, Ignored(), True)
76
+ fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor_4)
77
+ scalar_tensor_default = CallFunction(aten.scalar_tensor.default, Ignored(), dtype=Ignored(), layout=torch.strided, device=Ignored())
78
+ where_self_1 = CallFunction(aten.where.self, KeywordArg('causal_mask'), fma_default, scalar_tensor_default)
79
+ div_Tensor_2 = CallFunction(aten.div.Tensor, where_self_1, full_default)
80
+ view_default_8 = CallFunction(aten.view.default, div_Tensor_2, Ignored(), _users=2)
81
+ permute_default_5 = CallFunction(aten.permute.default, view_default_1, Ignored())
82
+ bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_5)
83
+ view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored())
84
+ permute_default_6 = CallFunction(aten.permute.default, view_default_9, Ignored())
85
+ permute_default_7 = CallFunction(aten.permute.default, view_default, Ignored())
86
+ bmm_default_4 = CallFunction(aten.bmm.default, permute_default_7, view_default_8)
87
+ view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored())
88
+ permute_default_8 = CallFunction(aten.permute.default, view_default_10, Ignored())
89
+ permute_default_9 = CallFunction(aten.permute.default, permute_default_8, Ignored())
90
+ permute_default_10 = CallFunction(aten.permute.default, view_default_3, Ignored())
91
+ bmm_default_5 = CallFunction(aten.bmm.default, permute_default_10, view_default_6)
92
+ view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored())
93
+ permute_default_11 = CallFunction(aten.permute.default, view_default_11, Ignored())
94
+ _sfdp_pattern_18_training = MultiOutputPattern([view_default_5,
95
+ permute_default_1,
96
+ permute_default_3,
97
+ permute_default_6,
98
+ permute_default_9,
99
+ permute_default_11,
100
+ None,
101
+ None
102
+ ])
103
+
104
+
105
+ permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored())
106
+ expand_default = CallFunction(aten.expand.default, permute_default, Ignored())
107
+ clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format)
108
+ view_default = CallFunction(aten.view.default, clone_default, Ignored())
109
+ permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored(), _users=2)
110
+ permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored())
111
+ expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored())
112
+ clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format)
113
+ view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored())
114
+ bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1)
115
+ view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored())
116
+ full_default = CallFunction(aten.full.default, [], Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False)
117
+ div_Tensor = CallFunction(aten.div.Tensor, view_default_2, full_default)
118
+ full_default_1 = CallFunction(aten.full.default, [], Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False)
119
+ where_self = CallFunction(aten.where.self, KeywordArg('causal_mask'), div_Tensor, full_default_1, _users=2)
120
+ amax_default = CallFunction(aten.amax.default, where_self, Ignored(), True)
121
+ sub_Tensor = CallFunction(aten.sub.Tensor, where_self, amax_default)
122
+ exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2)
123
+ sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True)
124
+ div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList)
125
+ expand_default_2 = CallFunction(aten.expand.default, div_Tensor_1, Ignored())
126
+ view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored())
127
+ permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored(), _users=2)
128
+ expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored())
129
+ clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format)
130
+ view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored())
131
+ bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4)
132
+ view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored())
133
+ _sfdp_pattern_18_inference = MultiOutputPattern([view_default_5,
134
+ permute_default_1,
135
+ permute_default_3
136
+ ])
137
+
138
+
139
+ rand_default = CallFunction(aten.rand.default, Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False)
140
+ gt_Scalar = CallFunction(aten.gt.Scalar, rand_default, KeywordArg('dropout_p'), _users=2)
141
+ permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored())
142
+ expand_default = CallFunction(aten.expand.default, permute_default, Ignored())
143
+ view_default = CallFunction(aten.view.default, expand_default, Ignored(), _users=2)
144
+ permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored(), _users=2)
145
+ permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored())
146
+ expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored())
147
+ view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored(), _users=2)
148
+ bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1)
149
+ view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored())
150
+ full_default = CallFunction(aten.full.default, [], Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False, _users=2)
151
+ div_Tensor = CallFunction(aten.div.Tensor, view_default_2, full_default)
152
+ full_default_1 = CallFunction(aten.full.default, [], Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False)
153
+ where_self = CallFunction(aten.where.self, KeywordArg('causal_mask'), div_Tensor, full_default_1, _users=2)
154
+ amax_default = CallFunction(aten.amax.default, where_self, Ignored(), True)
155
+ sub_Tensor = CallFunction(aten.sub.Tensor, where_self, amax_default)
156
+ exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2)
157
+ sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True)
158
+ div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList, _users=3)
159
+ mul_Tensor = CallFunction(aten.mul.Tensor, gt_Scalar, div_Tensor_1)
160
+ mul_Tensor_1 = CallFunction(aten.mul.Tensor, mul_Tensor, Ignored())
161
+ expand_default_2 = CallFunction(aten.expand.default, mul_Tensor_1, Ignored())
162
+ view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored(), _users=2)
163
+ permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored(), _users=2)
164
+ expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored())
165
+ view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored(), _users=2)
166
+ bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4)
167
+ view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored())
168
+ neg_default = CallFunction(aten.neg.default, div_Tensor_1)
169
+ view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2)
170
+ permute_default_4 = CallFunction(aten.permute.default, view_default_4, Ignored())
171
+ bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_4)
172
+ view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored())
173
+ convert_element_type_default = CallFunction(prims.convert_element_type.default, gt_Scalar, Ignored())
174
+ mul_Tensor_2 = CallFunction(aten.mul.Tensor, convert_element_type_default, Ignored())
175
+ mul_Tensor_3 = CallFunction(aten.mul.Tensor, view_default_7, mul_Tensor_2)
176
+ mul_Tensor_4 = CallFunction(aten.mul.Tensor, mul_Tensor_3, div_Tensor_1, _users=2)
177
+ sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor_4, Ignored(), True)
178
+ fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor_4)
179
+ scalar_tensor_default = CallFunction(aten.scalar_tensor.default, Ignored(), dtype=Ignored(), layout=torch.strided, device=Ignored())
180
+ where_self_1 = CallFunction(aten.where.self, KeywordArg('causal_mask'), fma_default, scalar_tensor_default)
181
+ div_Tensor_2 = CallFunction(aten.div.Tensor, where_self_1, full_default)
182
+ view_default_8 = CallFunction(aten.view.default, div_Tensor_2, Ignored(), _users=2)
183
+ permute_default_5 = CallFunction(aten.permute.default, view_default_1, Ignored())
184
+ bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_5)
185
+ view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored())
186
+ permute_default_6 = CallFunction(aten.permute.default, view_default_9, Ignored())
187
+ permute_default_7 = CallFunction(aten.permute.default, view_default, Ignored())
188
+ bmm_default_4 = CallFunction(aten.bmm.default, permute_default_7, view_default_8)
189
+ view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored())
190
+ permute_default_8 = CallFunction(aten.permute.default, view_default_10, Ignored())
191
+ permute_default_9 = CallFunction(aten.permute.default, permute_default_8, Ignored())
192
+ permute_default_10 = CallFunction(aten.permute.default, view_default_3, Ignored())
193
+ bmm_default_5 = CallFunction(aten.bmm.default, permute_default_10, view_default_6)
194
+ view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored())
195
+ permute_default_11 = CallFunction(aten.permute.default, view_default_11, Ignored())
196
+ _sfdp_pattern_18_bs1_training = MultiOutputPattern([view_default_5,
197
+ permute_default_1,
198
+ permute_default_3,
199
+ permute_default_6,
200
+ permute_default_9,
201
+ permute_default_11,
202
+ None,
203
+ None
204
+ ])
205
+
206
+
207
+ permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored())
208
+ expand_default = CallFunction(aten.expand.default, permute_default, Ignored())
209
+ view_default = CallFunction(aten.view.default, expand_default, Ignored())
210
+ permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored(), _users=2)
211
+ permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored())
212
+ expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored())
213
+ view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored())
214
+ bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1)
215
+ view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored())
216
+ full_default = CallFunction(aten.full.default, [], Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False)
217
+ div_Tensor = CallFunction(aten.div.Tensor, view_default_2, full_default)
218
+ full_default_1 = CallFunction(aten.full.default, [], Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False)
219
+ where_self = CallFunction(aten.where.self, KeywordArg('causal_mask'), div_Tensor, full_default_1, _users=2)
220
+ amax_default = CallFunction(aten.amax.default, where_self, Ignored(), True)
221
+ sub_Tensor = CallFunction(aten.sub.Tensor, where_self, amax_default)
222
+ exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2)
223
+ sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True)
224
+ div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList)
225
+ expand_default_2 = CallFunction(aten.expand.default, div_Tensor_1, Ignored())
226
+ view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored())
227
+ permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored(), _users=2)
228
+ expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored())
229
+ view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored())
230
+ bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4)
231
+ view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored())
232
+ _sfdp_pattern_18_bs1_inference = MultiOutputPattern([view_default_5,
233
+ permute_default_1,
234
+ permute_default_3
235
+ ])
236
+
237
+
238
+ rand_default = CallFunction(aten.rand.default, Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False)
239
+ gt_Scalar = CallFunction(aten.gt.Scalar, rand_default, KeywordArg('dropout_p'), _users=2)
240
+ permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored())
241
+ expand_default = CallFunction(aten.expand.default, permute_default, Ignored())
242
+ clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format)
243
+ view_default = CallFunction(aten.view.default, clone_default, Ignored(), _users=2)
244
+ permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored(), _users=2)
245
+ permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored())
246
+ expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored())
247
+ clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format)
248
+ view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored(), _users=2)
249
+ bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1)
250
+ view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored())
251
+ full_default = CallFunction(aten.full.default, [], Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False, _users=2)
252
+ div_Tensor = CallFunction(aten.div.Tensor, view_default_2, full_default)
253
+ full_default_1 = CallFunction(aten.full.default, [], Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False)
254
+ where_self = CallFunction(aten.where.self, KeywordArg('causal_mask'), div_Tensor, full_default_1)
255
+ convert_element_type_default = CallFunction(prims.convert_element_type.default, where_self, Ignored(), _users=2)
256
+ amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True)
257
+ sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default)
258
+ exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2)
259
+ sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True)
260
+ div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList)
261
+ convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor_1, Ignored(), _users=2)
262
+ mul_Tensor = CallFunction(aten.mul.Tensor, gt_Scalar, convert_element_type_default_1)
263
+ mul_Tensor_1 = CallFunction(aten.mul.Tensor, mul_Tensor, Ignored())
264
+ expand_default_2 = CallFunction(aten.expand.default, mul_Tensor_1, Ignored())
265
+ view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored(), _users=2)
266
+ permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored(), _users=2)
267
+ expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored())
268
+ clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format)
269
+ view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored(), _users=2)
270
+ bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4)
271
+ view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored())
272
+ convert_element_type_default_2 = CallFunction(prims.convert_element_type.default, convert_element_type_default_1, Ignored(), _users=2)
273
+ neg_default = CallFunction(aten.neg.default, convert_element_type_default_2)
274
+ view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2)
275
+ permute_default_4 = CallFunction(aten.permute.default, view_default_4, Ignored())
276
+ bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_4)
277
+ view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored())
278
+ convert_element_type_default_3 = CallFunction(prims.convert_element_type.default, gt_Scalar, Ignored())
279
+ mul_Tensor_2 = CallFunction(aten.mul.Tensor, convert_element_type_default_3, Ignored())
280
+ mul_Tensor_3 = CallFunction(aten.mul.Tensor, view_default_7, mul_Tensor_2)
281
+ convert_element_type_default_4 = CallFunction(prims.convert_element_type.default, mul_Tensor_3, Ignored())
282
+ mul_Tensor_4 = CallFunction(aten.mul.Tensor, convert_element_type_default_4, convert_element_type_default_2, _users=2)
283
+ sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor_4, Ignored(), True)
284
+ fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor_4)
285
+ convert_element_type_default_5 = CallFunction(prims.convert_element_type.default, fma_default, Ignored())
286
+ scalar_tensor_default = CallFunction(aten.scalar_tensor.default, Ignored(), dtype=Ignored(), layout=torch.strided, device=Ignored())
287
+ where_self_1 = CallFunction(aten.where.self, KeywordArg('causal_mask'), convert_element_type_default_5, scalar_tensor_default)
288
+ div_Tensor_2 = CallFunction(aten.div.Tensor, where_self_1, full_default)
289
+ view_default_8 = CallFunction(aten.view.default, div_Tensor_2, Ignored(), _users=2)
290
+ permute_default_5 = CallFunction(aten.permute.default, view_default_1, Ignored())
291
+ bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_5)
292
+ view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored())
293
+ permute_default_6 = CallFunction(aten.permute.default, view_default_9, Ignored())
294
+ permute_default_7 = CallFunction(aten.permute.default, view_default, Ignored())
295
+ bmm_default_4 = CallFunction(aten.bmm.default, permute_default_7, view_default_8)
296
+ view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored())
297
+ permute_default_8 = CallFunction(aten.permute.default, view_default_10, Ignored())
298
+ permute_default_9 = CallFunction(aten.permute.default, permute_default_8, Ignored())
299
+ permute_default_10 = CallFunction(aten.permute.default, view_default_3, Ignored())
300
+ bmm_default_5 = CallFunction(aten.bmm.default, permute_default_10, view_default_6)
301
+ view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored())
302
+ permute_default_11 = CallFunction(aten.permute.default, view_default_11, Ignored())
303
+ _sfdp_pattern_18_half_training = MultiOutputPattern([view_default_5,
304
+ permute_default_1,
305
+ permute_default_3,
306
+ permute_default_6,
307
+ permute_default_9,
308
+ permute_default_11,
309
+ None,
310
+ None
311
+ ])
312
+
313
+
314
+ permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored())
315
+ expand_default = CallFunction(aten.expand.default, permute_default, Ignored())
316
+ clone_default = CallFunction(aten.clone.default, expand_default, memory_format=torch.contiguous_format)
317
+ view_default = CallFunction(aten.view.default, clone_default, Ignored())
318
+ permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored(), _users=2)
319
+ permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored())
320
+ expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored())
321
+ clone_default_1 = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format)
322
+ view_default_1 = CallFunction(aten.view.default, clone_default_1, Ignored())
323
+ bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1)
324
+ view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored())
325
+ full_default = CallFunction(aten.full.default, [], Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False)
326
+ div_Tensor = CallFunction(aten.div.Tensor, view_default_2, full_default)
327
+ full_default_1 = CallFunction(aten.full.default, [], Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False)
328
+ where_self = CallFunction(aten.where.self, KeywordArg('causal_mask'), div_Tensor, full_default_1)
329
+ convert_element_type_default = CallFunction(prims.convert_element_type.default, where_self, Ignored(), _users=2)
330
+ amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True)
331
+ sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default)
332
+ exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2)
333
+ sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True)
334
+ div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList)
335
+ convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor_1, Ignored())
336
+ expand_default_2 = CallFunction(aten.expand.default, convert_element_type_default_1, Ignored())
337
+ view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored())
338
+ permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored(), _users=2)
339
+ expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored())
340
+ clone_default_2 = CallFunction(aten.clone.default, expand_default_3, memory_format=torch.contiguous_format)
341
+ view_default_4 = CallFunction(aten.view.default, clone_default_2, Ignored())
342
+ bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4)
343
+ view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored())
344
+ _sfdp_pattern_18_half_inference = MultiOutputPattern([view_default_5,
345
+ permute_default_1,
346
+ permute_default_3
347
+ ])
348
+
349
+
350
+ rand_default = CallFunction(aten.rand.default, Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False)
351
+ gt_Scalar = CallFunction(aten.gt.Scalar, rand_default, KeywordArg('dropout_p'), _users=2)
352
+ permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored())
353
+ expand_default = CallFunction(aten.expand.default, permute_default, Ignored())
354
+ view_default = CallFunction(aten.view.default, expand_default, Ignored(), _users=2)
355
+ permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored(), _users=2)
356
+ permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored())
357
+ expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored())
358
+ view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored(), _users=2)
359
+ bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1)
360
+ view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored())
361
+ full_default = CallFunction(aten.full.default, [], Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False, _users=2)
362
+ div_Tensor = CallFunction(aten.div.Tensor, view_default_2, full_default)
363
+ full_default_1 = CallFunction(aten.full.default, [], Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False)
364
+ where_self = CallFunction(aten.where.self, KeywordArg('causal_mask'), div_Tensor, full_default_1)
365
+ convert_element_type_default = CallFunction(prims.convert_element_type.default, where_self, Ignored(), _users=2)
366
+ amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True)
367
+ sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default)
368
+ exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2)
369
+ sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True)
370
+ div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList)
371
+ convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor_1, Ignored(), _users=2)
372
+ mul_Tensor = CallFunction(aten.mul.Tensor, gt_Scalar, convert_element_type_default_1)
373
+ mul_Tensor_1 = CallFunction(aten.mul.Tensor, mul_Tensor, Ignored())
374
+ expand_default_2 = CallFunction(aten.expand.default, mul_Tensor_1, Ignored())
375
+ view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored(), _users=2)
376
+ permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored(), _users=2)
377
+ expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored())
378
+ view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored(), _users=2)
379
+ bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4)
380
+ view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored())
381
+ convert_element_type_default_2 = CallFunction(prims.convert_element_type.default, convert_element_type_default_1, Ignored(), _users=2)
382
+ neg_default = CallFunction(aten.neg.default, convert_element_type_default_2)
383
+ view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2)
384
+ permute_default_4 = CallFunction(aten.permute.default, view_default_4, Ignored())
385
+ bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_4)
386
+ view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored())
387
+ convert_element_type_default_3 = CallFunction(prims.convert_element_type.default, gt_Scalar, Ignored())
388
+ mul_Tensor_2 = CallFunction(aten.mul.Tensor, convert_element_type_default_3, Ignored())
389
+ mul_Tensor_3 = CallFunction(aten.mul.Tensor, view_default_7, mul_Tensor_2)
390
+ convert_element_type_default_4 = CallFunction(prims.convert_element_type.default, mul_Tensor_3, Ignored())
391
+ mul_Tensor_4 = CallFunction(aten.mul.Tensor, convert_element_type_default_4, convert_element_type_default_2, _users=2)
392
+ sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor_4, Ignored(), True)
393
+ fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor_4)
394
+ convert_element_type_default_5 = CallFunction(prims.convert_element_type.default, fma_default, Ignored())
395
+ scalar_tensor_default = CallFunction(aten.scalar_tensor.default, Ignored(), dtype=Ignored(), layout=torch.strided, device=Ignored())
396
+ where_self_1 = CallFunction(aten.where.self, KeywordArg('causal_mask'), convert_element_type_default_5, scalar_tensor_default)
397
+ div_Tensor_2 = CallFunction(aten.div.Tensor, where_self_1, full_default)
398
+ view_default_8 = CallFunction(aten.view.default, div_Tensor_2, Ignored(), _users=2)
399
+ permute_default_5 = CallFunction(aten.permute.default, view_default_1, Ignored())
400
+ bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_5)
401
+ view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored())
402
+ permute_default_6 = CallFunction(aten.permute.default, view_default_9, Ignored())
403
+ permute_default_7 = CallFunction(aten.permute.default, view_default, Ignored())
404
+ bmm_default_4 = CallFunction(aten.bmm.default, permute_default_7, view_default_8)
405
+ view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored())
406
+ permute_default_8 = CallFunction(aten.permute.default, view_default_10, Ignored())
407
+ permute_default_9 = CallFunction(aten.permute.default, permute_default_8, Ignored())
408
+ permute_default_10 = CallFunction(aten.permute.default, view_default_3, Ignored())
409
+ bmm_default_5 = CallFunction(aten.bmm.default, permute_default_10, view_default_6)
410
+ view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored())
411
+ permute_default_11 = CallFunction(aten.permute.default, view_default_11, Ignored())
412
+ _sfdp_pattern_18_half_bs1_training = MultiOutputPattern([view_default_5,
413
+ permute_default_1,
414
+ permute_default_3,
415
+ permute_default_6,
416
+ permute_default_9,
417
+ permute_default_11,
418
+ None,
419
+ None
420
+ ])
421
+
422
+
423
+ permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored())
424
+ expand_default = CallFunction(aten.expand.default, permute_default, Ignored())
425
+ view_default = CallFunction(aten.view.default, expand_default, Ignored())
426
+ permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored(), _users=2)
427
+ permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored())
428
+ expand_default_1 = CallFunction(aten.expand.default, permute_default_2, Ignored())
429
+ view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored())
430
+ bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1)
431
+ view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored())
432
+ full_default = CallFunction(aten.full.default, [], Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False)
433
+ div_Tensor = CallFunction(aten.div.Tensor, view_default_2, full_default)
434
+ full_default_1 = CallFunction(aten.full.default, [], Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False)
435
+ where_self = CallFunction(aten.where.self, KeywordArg('causal_mask'), div_Tensor, full_default_1)
436
+ convert_element_type_default = CallFunction(prims.convert_element_type.default, where_self, Ignored(), _users=2)
437
+ amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True)
438
+ sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default)
439
+ exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2)
440
+ sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True)
441
+ div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList)
442
+ convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor_1, Ignored())
443
+ expand_default_2 = CallFunction(aten.expand.default, convert_element_type_default_1, Ignored())
444
+ view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored())
445
+ permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored(), _users=2)
446
+ expand_default_3 = CallFunction(aten.expand.default, permute_default_3, Ignored())
447
+ view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored())
448
+ bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4)
449
+ view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored())
450
+ _sfdp_pattern_18_half_bs1_inference = MultiOutputPattern([view_default_5,
451
+ permute_default_1,
452
+ permute_default_3
453
+ ])
.venv/lib/python3.10/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_19.py ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: ignore-errors
2
+
3
+ # noqa: F401, E501
4
+ # This is an auto-generated file. Please do not modify it by hand.
5
+ # To re-generate, run:
6
+ # cd ~/pytorch && python torchgen/fuse/gen_patterns.py
7
+
8
+ import torch
9
+ import torch._inductor
10
+ import operator
11
+
12
+ aten = torch.ops.aten
13
+ prims = torch.ops.prims
14
+
15
+ from torch._inductor.pattern_matcher import (
16
+ Arg,
17
+ CallFunction,
18
+ CallFunctionVarArgs,
19
+ CallMethod,
20
+ CallMethodVarArgs,
21
+ CallModule,
22
+ CallModuleVarArgs,
23
+ ExclusiveKeywordArg,
24
+ Ignored,
25
+ KeywordArg,
26
+ ListOf,
27
+ MultiOutputPattern,
28
+ PatternExpr,
29
+ RepeatedExpr,
30
+ _TargetArgsExpr,
31
+ _TargetExpr,
32
+ _TargetExprVarArgs,
33
+ )
34
+ rand_default = CallFunction(aten.rand.default, Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False)
35
+ gt_Scalar = CallFunction(aten.gt.Scalar, rand_default, KeywordArg('dropout_p'), _users=2)
36
+ expand_default = CallFunction(aten.expand.default, KeywordArg('query'), Ignored())
37
+ view_default = CallFunction(aten.view.default, expand_default, Ignored(), _users=2)
38
+ permute_default = CallFunction(aten.permute.default, KeywordArg('key'), Ignored())
39
+ expand_default_1 = CallFunction(aten.expand.default, permute_default, Ignored())
40
+ view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored(), _users=2)
41
+ bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1)
42
+ view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored())
43
+ full_default = CallFunction(aten.full.default, [], Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False, _users=2)
44
+ div_Tensor = CallFunction(aten.div.Tensor, view_default_2, full_default)
45
+ full_default_1 = CallFunction(aten.full.default, [], Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False)
46
+ where_self = CallFunction(aten.where.self, KeywordArg('causal_mask'), div_Tensor, full_default_1)
47
+ add_Tensor = CallFunction(aten.add.Tensor, where_self, KeywordArg('attn_mask'), _users=2)
48
+ amax_default = CallFunction(aten.amax.default, add_Tensor, Ignored(), True)
49
+ sub_Tensor = CallFunction(aten.sub.Tensor, add_Tensor, amax_default)
50
+ exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2)
51
+ sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True)
52
+ div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList, _users=3)
53
+ mul_Tensor = CallFunction(aten.mul.Tensor, gt_Scalar, div_Tensor_1)
54
+ mul_Tensor_1 = CallFunction(aten.mul.Tensor, mul_Tensor, Ignored())
55
+ expand_default_2 = CallFunction(aten.expand.default, mul_Tensor_1, Ignored())
56
+ view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored(), _users=2)
57
+ expand_default_3 = CallFunction(aten.expand.default, KeywordArg('value'), Ignored())
58
+ view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored(), _users=2)
59
+ bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4)
60
+ view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored())
61
+ neg_default = CallFunction(aten.neg.default, div_Tensor_1)
62
+ view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2)
63
+ permute_default_1 = CallFunction(aten.permute.default, view_default_4, Ignored())
64
+ bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_1)
65
+ view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored())
66
+ convert_element_type_default = CallFunction(prims.convert_element_type.default, gt_Scalar, Ignored())
67
+ mul_Tensor_2 = CallFunction(aten.mul.Tensor, convert_element_type_default, Ignored())
68
+ mul_Tensor_3 = CallFunction(aten.mul.Tensor, view_default_7, mul_Tensor_2)
69
+ mul_Tensor_4 = CallFunction(aten.mul.Tensor, mul_Tensor_3, div_Tensor_1, _users=2)
70
+ sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor_4, Ignored(), True)
71
+ fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor_4)
72
+ scalar_tensor_default = CallFunction(aten.scalar_tensor.default, Ignored(), dtype=Ignored(), layout=torch.strided, device=Ignored())
73
+ where_self_1 = CallFunction(aten.where.self, KeywordArg('causal_mask'), fma_default, scalar_tensor_default)
74
+ div_Tensor_2 = CallFunction(aten.div.Tensor, where_self_1, full_default)
75
+ view_default_8 = CallFunction(aten.view.default, div_Tensor_2, Ignored(), _users=2)
76
+ permute_default_2 = CallFunction(aten.permute.default, view_default_1, Ignored())
77
+ bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_2)
78
+ view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored())
79
+ permute_default_3 = CallFunction(aten.permute.default, view_default, Ignored())
80
+ bmm_default_4 = CallFunction(aten.bmm.default, permute_default_3, view_default_8)
81
+ view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored())
82
+ permute_default_4 = CallFunction(aten.permute.default, view_default_10, Ignored())
83
+ permute_default_5 = CallFunction(aten.permute.default, view_default_3, Ignored())
84
+ bmm_default_5 = CallFunction(aten.bmm.default, permute_default_5, view_default_6)
85
+ view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored())
86
+ _sfdp_pattern_19_training = MultiOutputPattern([view_default_5,
87
+ view_default_9,
88
+ permute_default_4,
89
+ view_default_11,
90
+ None,
91
+ None,
92
+ None
93
+ ])
94
+
95
+
96
+ expand_default = CallFunction(aten.expand.default, KeywordArg('query'), Ignored())
97
+ view_default = CallFunction(aten.view.default, expand_default, Ignored())
98
+ permute_default = CallFunction(aten.permute.default, KeywordArg('key'), Ignored())
99
+ expand_default_1 = CallFunction(aten.expand.default, permute_default, Ignored())
100
+ view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored())
101
+ bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1)
102
+ view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored())
103
+ full_default = CallFunction(aten.full.default, [], Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False)
104
+ div_Tensor = CallFunction(aten.div.Tensor, view_default_2, full_default)
105
+ full_default_1 = CallFunction(aten.full.default, [], Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False)
106
+ where_self = CallFunction(aten.where.self, KeywordArg('causal_mask'), div_Tensor, full_default_1)
107
+ add_Tensor = CallFunction(aten.add.Tensor, where_self, KeywordArg('attn_mask'), _users=2)
108
+ amax_default = CallFunction(aten.amax.default, add_Tensor, Ignored(), True)
109
+ sub_Tensor = CallFunction(aten.sub.Tensor, add_Tensor, amax_default)
110
+ exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2)
111
+ sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True)
112
+ div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList)
113
+ expand_default_2 = CallFunction(aten.expand.default, div_Tensor_1, Ignored())
114
+ view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored())
115
+ expand_default_3 = CallFunction(aten.expand.default, KeywordArg('value'), Ignored())
116
+ view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored())
117
+ bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4)
118
+ _sfdp_pattern_19_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0)
119
+
120
+
121
+ rand_default = CallFunction(aten.rand.default, Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False)
122
+ gt_Scalar = CallFunction(aten.gt.Scalar, rand_default, KeywordArg('dropout_p'), _users=2)
123
+ expand_default = CallFunction(aten.expand.default, KeywordArg('query'), Ignored())
124
+ view_default = CallFunction(aten.view.default, expand_default, Ignored(), _users=2)
125
+ permute_default = CallFunction(aten.permute.default, KeywordArg('key'), Ignored())
126
+ expand_default_1 = CallFunction(aten.expand.default, permute_default, Ignored())
127
+ view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored(), _users=2)
128
+ bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1)
129
+ view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored())
130
+ full_default = CallFunction(aten.full.default, [], Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False, _users=2)
131
+ div_Tensor = CallFunction(aten.div.Tensor, view_default_2, full_default)
132
+ full_default_1 = CallFunction(aten.full.default, [], Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False)
133
+ where_self = CallFunction(aten.where.self, KeywordArg('causal_mask'), div_Tensor, full_default_1)
134
+ add_Tensor = CallFunction(aten.add.Tensor, where_self, KeywordArg('attn_mask'), _users=2)
135
+ amax_default = CallFunction(aten.amax.default, add_Tensor, Ignored(), True)
136
+ sub_Tensor = CallFunction(aten.sub.Tensor, add_Tensor, amax_default)
137
+ exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2)
138
+ sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True)
139
+ div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList, _users=3)
140
+ convert_element_type_default = CallFunction(prims.convert_element_type.default, div_Tensor_1, Ignored())
141
+ mul_Tensor = CallFunction(aten.mul.Tensor, gt_Scalar, convert_element_type_default)
142
+ mul_Tensor_1 = CallFunction(aten.mul.Tensor, mul_Tensor, Ignored())
143
+ expand_default_2 = CallFunction(aten.expand.default, mul_Tensor_1, Ignored())
144
+ view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored(), _users=2)
145
+ expand_default_3 = CallFunction(aten.expand.default, KeywordArg('value'), Ignored())
146
+ view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored(), _users=2)
147
+ bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4)
148
+ view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored())
149
+ neg_default = CallFunction(aten.neg.default, div_Tensor_1)
150
+ view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2)
151
+ permute_default_1 = CallFunction(aten.permute.default, view_default_4, Ignored())
152
+ bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_1)
153
+ view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored())
154
+ convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, gt_Scalar, Ignored())
155
+ mul_Tensor_2 = CallFunction(aten.mul.Tensor, convert_element_type_default_1, Ignored())
156
+ mul_Tensor_3 = CallFunction(aten.mul.Tensor, view_default_7, mul_Tensor_2)
157
+ convert_element_type_default_2 = CallFunction(prims.convert_element_type.default, mul_Tensor_3, Ignored())
158
+ mul_Tensor_4 = CallFunction(aten.mul.Tensor, convert_element_type_default_2, div_Tensor_1, _users=2)
159
+ sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor_4, Ignored(), True)
160
+ fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor_4)
161
+ convert_element_type_default_3 = CallFunction(prims.convert_element_type.default, fma_default, Ignored())
162
+ scalar_tensor_default = CallFunction(aten.scalar_tensor.default, Ignored(), dtype=Ignored(), layout=torch.strided, device=Ignored())
163
+ where_self_1 = CallFunction(aten.where.self, KeywordArg('causal_mask'), convert_element_type_default_3, scalar_tensor_default)
164
+ div_Tensor_2 = CallFunction(aten.div.Tensor, where_self_1, full_default)
165
+ view_default_8 = CallFunction(aten.view.default, div_Tensor_2, Ignored(), _users=2)
166
+ permute_default_2 = CallFunction(aten.permute.default, view_default_1, Ignored())
167
+ bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_2)
168
+ view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored())
169
+ permute_default_3 = CallFunction(aten.permute.default, view_default, Ignored())
170
+ bmm_default_4 = CallFunction(aten.bmm.default, permute_default_3, view_default_8)
171
+ view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored())
172
+ permute_default_4 = CallFunction(aten.permute.default, view_default_10, Ignored())
173
+ permute_default_5 = CallFunction(aten.permute.default, view_default_3, Ignored())
174
+ bmm_default_5 = CallFunction(aten.bmm.default, permute_default_5, view_default_6)
175
+ view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored())
176
+ _sfdp_pattern_19_half_training = MultiOutputPattern([view_default_5,
177
+ view_default_9,
178
+ permute_default_4,
179
+ view_default_11,
180
+ None,
181
+ None,
182
+ None
183
+ ])
184
+
185
+
186
+ expand_default = CallFunction(aten.expand.default, KeywordArg('query'), Ignored())
187
+ view_default = CallFunction(aten.view.default, expand_default, Ignored())
188
+ permute_default = CallFunction(aten.permute.default, KeywordArg('key'), Ignored())
189
+ expand_default_1 = CallFunction(aten.expand.default, permute_default, Ignored())
190
+ view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored())
191
+ bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1)
192
+ view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored())
193
+ full_default = CallFunction(aten.full.default, [], Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False)
194
+ div_Tensor = CallFunction(aten.div.Tensor, view_default_2, full_default)
195
+ full_default_1 = CallFunction(aten.full.default, [], Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False)
196
+ where_self = CallFunction(aten.where.self, KeywordArg('causal_mask'), div_Tensor, full_default_1)
197
+ add_Tensor = CallFunction(aten.add.Tensor, where_self, KeywordArg('attn_mask'), _users=2)
198
+ amax_default = CallFunction(aten.amax.default, add_Tensor, Ignored(), True)
199
+ sub_Tensor = CallFunction(aten.sub.Tensor, add_Tensor, amax_default)
200
+ exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2)
201
+ sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True)
202
+ div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList)
203
+ convert_element_type_default = CallFunction(prims.convert_element_type.default, div_Tensor_1, Ignored())
204
+ expand_default_2 = CallFunction(aten.expand.default, convert_element_type_default, Ignored())
205
+ view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored())
206
+ expand_default_3 = CallFunction(aten.expand.default, KeywordArg('value'), Ignored())
207
+ view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored())
208
+ bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4)
209
+ _sfdp_pattern_19_half_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0)
.venv/lib/python3.10/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_2.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: ignore-errors
2
+
3
+ # noqa: F401, E501
4
+ # This is an auto-generated file. Please do not modify it by hand.
5
+ # To re-generate, run:
6
+ # cd ~/pytorch && python torchgen/fuse/gen_patterns.py
7
+
8
+ import torch
9
+ import torch._inductor
10
+ import operator
11
+
12
+ aten = torch.ops.aten
13
+ prims = torch.ops.prims
14
+
15
+ from torch._inductor.pattern_matcher import (
16
+ Arg,
17
+ CallFunction,
18
+ CallFunctionVarArgs,
19
+ CallMethod,
20
+ CallMethodVarArgs,
21
+ CallModule,
22
+ CallModuleVarArgs,
23
+ ExclusiveKeywordArg,
24
+ Ignored,
25
+ KeywordArg,
26
+ ListOf,
27
+ MultiOutputPattern,
28
+ PatternExpr,
29
+ RepeatedExpr,
30
+ _TargetArgsExpr,
31
+ _TargetExpr,
32
+ _TargetExprVarArgs,
33
+ )
34
+ expand_default = CallFunction(aten.expand.default, KeywordArg('query'), Ignored())
35
+ view_default = CallFunction(aten.view.default, expand_default, Ignored(), _users=2)
36
+ permute_default = CallFunction(aten.permute.default, KeywordArg('key'), Ignored())
37
+ expand_default_1 = CallFunction(aten.expand.default, permute_default, Ignored())
38
+ view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored(), _users=2)
39
+ bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1)
40
+ view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored())
41
+ mul_Tensor = CallFunction(aten.mul.Tensor, view_default_2, KeywordArg('scale_factor'), _users=2)
42
+ amax_default = CallFunction(aten.amax.default, mul_Tensor, Ignored(), True)
43
+ sub_Tensor = CallFunction(aten.sub.Tensor, mul_Tensor, amax_default)
44
+ exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2)
45
+ sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True)
46
+ div_Tensor = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList, _users=3)
47
+ expand_default_2 = CallFunction(aten.expand.default, div_Tensor, Ignored())
48
+ view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored(), _users=2)
49
+ expand_default_3 = CallFunction(aten.expand.default, KeywordArg('value'), Ignored())
50
+ view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored(), _users=2)
51
+ bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4)
52
+ view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored())
53
+ neg_default = CallFunction(aten.neg.default, div_Tensor)
54
+ view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2)
55
+ permute_default_1 = CallFunction(aten.permute.default, view_default_4, Ignored())
56
+ bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_1)
57
+ view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored())
58
+ mul_Tensor_1 = CallFunction(aten.mul.Tensor, view_default_7, div_Tensor, _users=2)
59
+ sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor_1, Ignored(), True)
60
+ fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor_1)
61
+ mul_Tensor_2 = CallFunction(aten.mul.Tensor, fma_default, KeywordArg('scale_factor'))
62
+ view_default_8 = CallFunction(aten.view.default, mul_Tensor_2, Ignored(), _users=2)
63
+ permute_default_2 = CallFunction(aten.permute.default, view_default_1, Ignored())
64
+ bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_2)
65
+ view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored())
66
+ permute_default_3 = CallFunction(aten.permute.default, view_default, Ignored())
67
+ bmm_default_4 = CallFunction(aten.bmm.default, permute_default_3, view_default_8)
68
+ view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored())
69
+ permute_default_4 = CallFunction(aten.permute.default, view_default_10, Ignored())
70
+ permute_default_5 = CallFunction(aten.permute.default, view_default_3, Ignored())
71
+ bmm_default_5 = CallFunction(aten.bmm.default, permute_default_5, view_default_6)
72
+ view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored())
73
+ _sfdp_pattern_2_training = MultiOutputPattern([view_default_5,
74
+ view_default_9,
75
+ permute_default_4,
76
+ view_default_11,
77
+ None
78
+ ])
79
+
80
+
81
+ expand_default = CallFunction(aten.expand.default, KeywordArg('query'), Ignored())
82
+ view_default = CallFunction(aten.view.default, expand_default, Ignored())
83
+ permute_default = CallFunction(aten.permute.default, KeywordArg('key'), Ignored())
84
+ expand_default_1 = CallFunction(aten.expand.default, permute_default, Ignored())
85
+ view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored())
86
+ bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1)
87
+ view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored())
88
+ mul_Tensor = CallFunction(aten.mul.Tensor, view_default_2, KeywordArg('scale_factor'), _users=2)
89
+ amax_default = CallFunction(aten.amax.default, mul_Tensor, Ignored(), True)
90
+ sub_Tensor = CallFunction(aten.sub.Tensor, mul_Tensor, amax_default)
91
+ exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2)
92
+ sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True)
93
+ div_Tensor = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList)
94
+ expand_default_2 = CallFunction(aten.expand.default, div_Tensor, Ignored())
95
+ view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored())
96
+ expand_default_3 = CallFunction(aten.expand.default, KeywordArg('value'), Ignored())
97
+ view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored())
98
+ bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4)
99
+ _sfdp_pattern_2_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0)
100
+
101
+
102
+ expand_default = CallFunction(aten.expand.default, KeywordArg('query'), Ignored())
103
+ view_default = CallFunction(aten.view.default, expand_default, Ignored(), _users=2)
104
+ permute_default = CallFunction(aten.permute.default, KeywordArg('key'), Ignored())
105
+ expand_default_1 = CallFunction(aten.expand.default, permute_default, Ignored())
106
+ view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored(), _users=2)
107
+ bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1)
108
+ view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored())
109
+ mul_Tensor = CallFunction(aten.mul.Tensor, view_default_2, KeywordArg('scale_factor'))
110
+ convert_element_type_default = CallFunction(prims.convert_element_type.default, mul_Tensor, Ignored(), _users=2)
111
+ amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True)
112
+ sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default)
113
+ exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2)
114
+ sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True)
115
+ div_Tensor = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList)
116
+ convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor, Ignored(), _users=2)
117
+ expand_default_2 = CallFunction(aten.expand.default, convert_element_type_default_1, Ignored())
118
+ view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored(), _users=2)
119
+ expand_default_3 = CallFunction(aten.expand.default, KeywordArg('value'), Ignored())
120
+ view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored(), _users=2)
121
+ bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4)
122
+ view_default_5 = CallFunction(aten.view.default, bmm_default_1, Ignored())
123
+ convert_element_type_default_2 = CallFunction(prims.convert_element_type.default, convert_element_type_default_1, Ignored(), _users=2)
124
+ neg_default = CallFunction(aten.neg.default, convert_element_type_default_2)
125
+ view_default_6 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2)
126
+ permute_default_1 = CallFunction(aten.permute.default, view_default_4, Ignored())
127
+ bmm_default_2 = CallFunction(aten.bmm.default, view_default_6, permute_default_1)
128
+ view_default_7 = CallFunction(aten.view.default, bmm_default_2, Ignored())
129
+ convert_element_type_default_3 = CallFunction(prims.convert_element_type.default, view_default_7, Ignored())
130
+ mul_Tensor_1 = CallFunction(aten.mul.Tensor, convert_element_type_default_3, convert_element_type_default_2, _users=2)
131
+ sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor_1, Ignored(), True)
132
+ fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor_1)
133
+ convert_element_type_default_4 = CallFunction(prims.convert_element_type.default, fma_default, Ignored())
134
+ mul_Tensor_2 = CallFunction(aten.mul.Tensor, convert_element_type_default_4, KeywordArg('scale_factor'))
135
+ view_default_8 = CallFunction(aten.view.default, mul_Tensor_2, Ignored(), _users=2)
136
+ permute_default_2 = CallFunction(aten.permute.default, view_default_1, Ignored())
137
+ bmm_default_3 = CallFunction(aten.bmm.default, view_default_8, permute_default_2)
138
+ view_default_9 = CallFunction(aten.view.default, bmm_default_3, Ignored())
139
+ permute_default_3 = CallFunction(aten.permute.default, view_default, Ignored())
140
+ bmm_default_4 = CallFunction(aten.bmm.default, permute_default_3, view_default_8)
141
+ view_default_10 = CallFunction(aten.view.default, bmm_default_4, Ignored())
142
+ permute_default_4 = CallFunction(aten.permute.default, view_default_10, Ignored())
143
+ permute_default_5 = CallFunction(aten.permute.default, view_default_3, Ignored())
144
+ bmm_default_5 = CallFunction(aten.bmm.default, permute_default_5, view_default_6)
145
+ view_default_11 = CallFunction(aten.view.default, bmm_default_5, Ignored())
146
+ _sfdp_pattern_2_half_training = MultiOutputPattern([view_default_5,
147
+ view_default_9,
148
+ permute_default_4,
149
+ view_default_11,
150
+ None
151
+ ])
152
+
153
+
154
+ expand_default = CallFunction(aten.expand.default, KeywordArg('query'), Ignored())
155
+ view_default = CallFunction(aten.view.default, expand_default, Ignored())
156
+ permute_default = CallFunction(aten.permute.default, KeywordArg('key'), Ignored())
157
+ expand_default_1 = CallFunction(aten.expand.default, permute_default, Ignored())
158
+ view_default_1 = CallFunction(aten.view.default, expand_default_1, Ignored())
159
+ bmm_default = CallFunction(aten.bmm.default, view_default, view_default_1)
160
+ view_default_2 = CallFunction(aten.view.default, bmm_default, Ignored())
161
+ mul_Tensor = CallFunction(aten.mul.Tensor, view_default_2, KeywordArg('scale_factor'))
162
+ convert_element_type_default = CallFunction(prims.convert_element_type.default, mul_Tensor, Ignored(), _users=2)
163
+ amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True)
164
+ sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default)
165
+ exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2)
166
+ sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True)
167
+ div_Tensor = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList)
168
+ convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor, Ignored())
169
+ expand_default_2 = CallFunction(aten.expand.default, convert_element_type_default_1, Ignored())
170
+ view_default_3 = CallFunction(aten.view.default, expand_default_2, Ignored())
171
+ expand_default_3 = CallFunction(aten.expand.default, KeywordArg('value'), Ignored())
172
+ view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored())
173
+ bmm_default_1 = CallFunction(aten.bmm.default, view_default_3, view_default_4)
174
+ _sfdp_pattern_2_half_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0)
.venv/lib/python3.10/site-packages/torch/_inductor/fx_passes/serialized_patterns/_sfdp_pattern_20.py ADDED
@@ -0,0 +1,244 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: ignore-errors
2
+
3
+ # noqa: F401, E501
4
+ # This is an auto-generated file. Please do not modify it by hand.
5
+ # To re-generate, run:
6
+ # cd ~/pytorch && python torchgen/fuse/gen_patterns.py
7
+
8
+ import torch
9
+ import torch._inductor
10
+ import operator
11
+
12
+ aten = torch.ops.aten
13
+ prims = torch.ops.prims
14
+
15
+ from torch._inductor.pattern_matcher import (
16
+ Arg,
17
+ CallFunction,
18
+ CallFunctionVarArgs,
19
+ CallMethod,
20
+ CallMethodVarArgs,
21
+ CallModule,
22
+ CallModuleVarArgs,
23
+ ExclusiveKeywordArg,
24
+ Ignored,
25
+ KeywordArg,
26
+ ListOf,
27
+ MultiOutputPattern,
28
+ PatternExpr,
29
+ RepeatedExpr,
30
+ _TargetArgsExpr,
31
+ _TargetExpr,
32
+ _TargetExprVarArgs,
33
+ )
34
+ rand_default = CallFunction(aten.rand.default, Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False)
35
+ gt_Scalar = CallFunction(aten.gt.Scalar, rand_default, KeywordArg('dropout_p'), _users=2)
36
+ eq_Scalar = CallFunction(aten.eq.Scalar, KeywordArg('attn_mask'), Ignored())
37
+ view_default = CallFunction(aten.view.default, eq_Scalar, Ignored())
38
+ expand_default = CallFunction(aten.expand.default, view_default, Ignored(), _users=2)
39
+ full_default = CallFunction(aten.full.default, [], Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False)
40
+ permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored())
41
+ div_Tensor = CallFunction(aten.div.Tensor, permute_default, Ignored())
42
+ expand_default_1 = CallFunction(aten.expand.default, div_Tensor, Ignored())
43
+ clone_default = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format)
44
+ view_default_1 = CallFunction(aten.view.default, clone_default, Ignored(), _users=2)
45
+ permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored())
46
+ permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored())
47
+ expand_default_2 = CallFunction(aten.expand.default, permute_default_2, Ignored())
48
+ clone_default_1 = CallFunction(aten.clone.default, expand_default_2, memory_format=torch.contiguous_format)
49
+ view_default_2 = CallFunction(aten.view.default, clone_default_1, Ignored(), _users=2)
50
+ bmm_default = CallFunction(aten.bmm.default, view_default_1, view_default_2)
51
+ view_default_3 = CallFunction(aten.view.default, bmm_default, Ignored())
52
+ where_self = CallFunction(aten.where.self, expand_default, full_default, view_default_3, _users=2)
53
+ amax_default = CallFunction(aten.amax.default, where_self, Ignored(), True)
54
+ sub_Tensor = CallFunction(aten.sub.Tensor, where_self, amax_default)
55
+ exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2)
56
+ sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True)
57
+ div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList, _users=3)
58
+ mul_Tensor = CallFunction(aten.mul.Tensor, gt_Scalar, div_Tensor_1)
59
+ mul_Tensor_1 = CallFunction(aten.mul.Tensor, mul_Tensor, Ignored())
60
+ expand_default_3 = CallFunction(aten.expand.default, mul_Tensor_1, Ignored())
61
+ view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored(), _users=2)
62
+ permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored())
63
+ expand_default_4 = CallFunction(aten.expand.default, permute_default_3, Ignored())
64
+ clone_default_2 = CallFunction(aten.clone.default, expand_default_4, memory_format=torch.contiguous_format)
65
+ view_default_5 = CallFunction(aten.view.default, clone_default_2, Ignored(), _users=2)
66
+ bmm_default_1 = CallFunction(aten.bmm.default, view_default_4, view_default_5)
67
+ view_default_6 = CallFunction(aten.view.default, bmm_default_1, Ignored())
68
+ scalar_tensor_default = CallFunction(aten.scalar_tensor.default, Ignored(), dtype=Ignored(), layout=torch.strided, device=Ignored())
69
+ neg_default = CallFunction(aten.neg.default, div_Tensor_1)
70
+ view_default_7 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2)
71
+ permute_default_4 = CallFunction(aten.permute.default, view_default_5, Ignored())
72
+ bmm_default_2 = CallFunction(aten.bmm.default, view_default_7, permute_default_4)
73
+ view_default_8 = CallFunction(aten.view.default, bmm_default_2, Ignored())
74
+ convert_element_type_default = CallFunction(prims.convert_element_type.default, gt_Scalar, Ignored())
75
+ mul_Tensor_2 = CallFunction(aten.mul.Tensor, convert_element_type_default, Ignored())
76
+ mul_Tensor_3 = CallFunction(aten.mul.Tensor, view_default_8, mul_Tensor_2)
77
+ mul_Tensor_4 = CallFunction(aten.mul.Tensor, mul_Tensor_3, div_Tensor_1, _users=2)
78
+ sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor_4, Ignored(), True)
79
+ fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor_4)
80
+ where_self_1 = CallFunction(aten.where.self, expand_default, scalar_tensor_default, fma_default)
81
+ view_default_9 = CallFunction(aten.view.default, where_self_1, Ignored(), _users=2)
82
+ permute_default_5 = CallFunction(aten.permute.default, view_default_2, Ignored())
83
+ bmm_default_3 = CallFunction(aten.bmm.default, view_default_9, permute_default_5)
84
+ view_default_10 = CallFunction(aten.view.default, bmm_default_3, Ignored())
85
+ div_Tensor_2 = CallFunction(aten.div.Tensor, view_default_10, Ignored())
86
+ permute_default_6 = CallFunction(aten.permute.default, div_Tensor_2, Ignored())
87
+ permute_default_7 = CallFunction(aten.permute.default, view_default_1, Ignored())
88
+ bmm_default_4 = CallFunction(aten.bmm.default, permute_default_7, view_default_9)
89
+ view_default_11 = CallFunction(aten.view.default, bmm_default_4, Ignored())
90
+ permute_default_8 = CallFunction(aten.permute.default, view_default_11, Ignored())
91
+ permute_default_9 = CallFunction(aten.permute.default, permute_default_8, Ignored())
92
+ permute_default_10 = CallFunction(aten.permute.default, view_default_4, Ignored())
93
+ bmm_default_5 = CallFunction(aten.bmm.default, permute_default_10, view_default_7)
94
+ view_default_12 = CallFunction(aten.view.default, bmm_default_5, Ignored())
95
+ permute_default_11 = CallFunction(aten.permute.default, view_default_12, Ignored())
96
+ _sfdp_pattern_20_training = MultiOutputPattern([view_default_6,
97
+ permute_default_6,
98
+ permute_default_9,
99
+ permute_default_11,
100
+ None,
101
+ None
102
+ ])
103
+
104
+
105
+ eq_Scalar = CallFunction(aten.eq.Scalar, KeywordArg('attn_mask'), Ignored())
106
+ view_default = CallFunction(aten.view.default, eq_Scalar, Ignored())
107
+ expand_default = CallFunction(aten.expand.default, view_default, Ignored())
108
+ full_default = CallFunction(aten.full.default, [], Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False)
109
+ permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored())
110
+ div_Tensor = CallFunction(aten.div.Tensor, permute_default, Ignored())
111
+ expand_default_1 = CallFunction(aten.expand.default, div_Tensor, Ignored())
112
+ clone_default = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format)
113
+ view_default_1 = CallFunction(aten.view.default, clone_default, Ignored())
114
+ permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored())
115
+ permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored())
116
+ expand_default_2 = CallFunction(aten.expand.default, permute_default_2, Ignored())
117
+ clone_default_1 = CallFunction(aten.clone.default, expand_default_2, memory_format=torch.contiguous_format)
118
+ view_default_2 = CallFunction(aten.view.default, clone_default_1, Ignored())
119
+ bmm_default = CallFunction(aten.bmm.default, view_default_1, view_default_2)
120
+ view_default_3 = CallFunction(aten.view.default, bmm_default, Ignored())
121
+ where_self = CallFunction(aten.where.self, expand_default, full_default, view_default_3, _users=2)
122
+ amax_default = CallFunction(aten.amax.default, where_self, Ignored(), True)
123
+ sub_Tensor = CallFunction(aten.sub.Tensor, where_self, amax_default)
124
+ exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2)
125
+ sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True)
126
+ div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList)
127
+ expand_default_3 = CallFunction(aten.expand.default, div_Tensor_1, Ignored())
128
+ view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored())
129
+ permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored())
130
+ expand_default_4 = CallFunction(aten.expand.default, permute_default_3, Ignored())
131
+ clone_default_2 = CallFunction(aten.clone.default, expand_default_4, memory_format=torch.contiguous_format)
132
+ view_default_5 = CallFunction(aten.view.default, clone_default_2, Ignored())
133
+ bmm_default_1 = CallFunction(aten.bmm.default, view_default_4, view_default_5)
134
+ _sfdp_pattern_20_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0)
135
+
136
+
137
+ rand_default = CallFunction(aten.rand.default, Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False)
138
+ gt_Scalar = CallFunction(aten.gt.Scalar, rand_default, KeywordArg('dropout_p'), _users=2)
139
+ eq_Scalar = CallFunction(aten.eq.Scalar, KeywordArg('attn_mask'), Ignored())
140
+ view_default = CallFunction(aten.view.default, eq_Scalar, Ignored())
141
+ expand_default = CallFunction(aten.expand.default, view_default, Ignored(), _users=2)
142
+ full_default = CallFunction(aten.full.default, [], Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False)
143
+ permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored())
144
+ div_Tensor = CallFunction(aten.div.Tensor, permute_default, Ignored())
145
+ expand_default_1 = CallFunction(aten.expand.default, div_Tensor, Ignored())
146
+ clone_default = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format)
147
+ view_default_1 = CallFunction(aten.view.default, clone_default, Ignored(), _users=2)
148
+ permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored())
149
+ permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored())
150
+ expand_default_2 = CallFunction(aten.expand.default, permute_default_2, Ignored())
151
+ clone_default_1 = CallFunction(aten.clone.default, expand_default_2, memory_format=torch.contiguous_format)
152
+ view_default_2 = CallFunction(aten.view.default, clone_default_1, Ignored(), _users=2)
153
+ bmm_default = CallFunction(aten.bmm.default, view_default_1, view_default_2)
154
+ view_default_3 = CallFunction(aten.view.default, bmm_default, Ignored())
155
+ where_self = CallFunction(aten.where.self, expand_default, full_default, view_default_3)
156
+ convert_element_type_default = CallFunction(prims.convert_element_type.default, where_self, Ignored(), _users=2)
157
+ amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True)
158
+ sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default)
159
+ exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2)
160
+ sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True)
161
+ div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList)
162
+ convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor_1, Ignored(), _users=2)
163
+ mul_Tensor = CallFunction(aten.mul.Tensor, gt_Scalar, convert_element_type_default_1)
164
+ mul_Tensor_1 = CallFunction(aten.mul.Tensor, mul_Tensor, Ignored())
165
+ expand_default_3 = CallFunction(aten.expand.default, mul_Tensor_1, Ignored())
166
+ view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored(), _users=2)
167
+ permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored())
168
+ expand_default_4 = CallFunction(aten.expand.default, permute_default_3, Ignored())
169
+ clone_default_2 = CallFunction(aten.clone.default, expand_default_4, memory_format=torch.contiguous_format)
170
+ view_default_5 = CallFunction(aten.view.default, clone_default_2, Ignored(), _users=2)
171
+ bmm_default_1 = CallFunction(aten.bmm.default, view_default_4, view_default_5)
172
+ view_default_6 = CallFunction(aten.view.default, bmm_default_1, Ignored())
173
+ scalar_tensor_default = CallFunction(aten.scalar_tensor.default, Ignored(), dtype=Ignored(), layout=torch.strided, device=Ignored())
174
+ convert_element_type_default_2 = CallFunction(prims.convert_element_type.default, convert_element_type_default_1, Ignored(), _users=2)
175
+ neg_default = CallFunction(aten.neg.default, convert_element_type_default_2)
176
+ view_default_7 = CallFunction(aten.view.default, KeywordArg('tangents_1'), Ignored(), _users=2)
177
+ permute_default_4 = CallFunction(aten.permute.default, view_default_5, Ignored())
178
+ bmm_default_2 = CallFunction(aten.bmm.default, view_default_7, permute_default_4)
179
+ view_default_8 = CallFunction(aten.view.default, bmm_default_2, Ignored())
180
+ convert_element_type_default_3 = CallFunction(prims.convert_element_type.default, gt_Scalar, Ignored())
181
+ mul_Tensor_2 = CallFunction(aten.mul.Tensor, convert_element_type_default_3, Ignored())
182
+ mul_Tensor_3 = CallFunction(aten.mul.Tensor, view_default_8, mul_Tensor_2)
183
+ convert_element_type_default_4 = CallFunction(prims.convert_element_type.default, mul_Tensor_3, Ignored())
184
+ mul_Tensor_4 = CallFunction(aten.mul.Tensor, convert_element_type_default_4, convert_element_type_default_2, _users=2)
185
+ sum_dim_IntList_1 = CallFunction(aten.sum.dim_IntList, mul_Tensor_4, Ignored(), True)
186
+ fma_default = CallFunction(prims.fma.default, neg_default, sum_dim_IntList_1, mul_Tensor_4)
187
+ convert_element_type_default_5 = CallFunction(prims.convert_element_type.default, fma_default, Ignored())
188
+ where_self_1 = CallFunction(aten.where.self, expand_default, scalar_tensor_default, convert_element_type_default_5)
189
+ view_default_9 = CallFunction(aten.view.default, where_self_1, Ignored(), _users=2)
190
+ permute_default_5 = CallFunction(aten.permute.default, view_default_2, Ignored())
191
+ bmm_default_3 = CallFunction(aten.bmm.default, view_default_9, permute_default_5)
192
+ view_default_10 = CallFunction(aten.view.default, bmm_default_3, Ignored())
193
+ div_Tensor_2 = CallFunction(aten.div.Tensor, view_default_10, Ignored())
194
+ permute_default_6 = CallFunction(aten.permute.default, div_Tensor_2, Ignored())
195
+ permute_default_7 = CallFunction(aten.permute.default, view_default_1, Ignored())
196
+ bmm_default_4 = CallFunction(aten.bmm.default, permute_default_7, view_default_9)
197
+ view_default_11 = CallFunction(aten.view.default, bmm_default_4, Ignored())
198
+ permute_default_8 = CallFunction(aten.permute.default, view_default_11, Ignored())
199
+ permute_default_9 = CallFunction(aten.permute.default, permute_default_8, Ignored())
200
+ permute_default_10 = CallFunction(aten.permute.default, view_default_4, Ignored())
201
+ bmm_default_5 = CallFunction(aten.bmm.default, permute_default_10, view_default_7)
202
+ view_default_12 = CallFunction(aten.view.default, bmm_default_5, Ignored())
203
+ permute_default_11 = CallFunction(aten.permute.default, view_default_12, Ignored())
204
+ _sfdp_pattern_20_half_training = MultiOutputPattern([view_default_6,
205
+ permute_default_6,
206
+ permute_default_9,
207
+ permute_default_11,
208
+ None,
209
+ None
210
+ ])
211
+
212
+
213
+ eq_Scalar = CallFunction(aten.eq.Scalar, KeywordArg('attn_mask'), Ignored())
214
+ view_default = CallFunction(aten.view.default, eq_Scalar, Ignored())
215
+ expand_default = CallFunction(aten.expand.default, view_default, Ignored())
216
+ full_default = CallFunction(aten.full.default, [], Ignored(), dtype=Ignored(), device=Ignored(), pin_memory=False)
217
+ permute_default = CallFunction(aten.permute.default, KeywordArg('query'), Ignored())
218
+ div_Tensor = CallFunction(aten.div.Tensor, permute_default, Ignored())
219
+ expand_default_1 = CallFunction(aten.expand.default, div_Tensor, Ignored())
220
+ clone_default = CallFunction(aten.clone.default, expand_default_1, memory_format=torch.contiguous_format)
221
+ view_default_1 = CallFunction(aten.view.default, clone_default, Ignored())
222
+ permute_default_1 = CallFunction(aten.permute.default, KeywordArg('key'), Ignored())
223
+ permute_default_2 = CallFunction(aten.permute.default, permute_default_1, Ignored())
224
+ expand_default_2 = CallFunction(aten.expand.default, permute_default_2, Ignored())
225
+ clone_default_1 = CallFunction(aten.clone.default, expand_default_2, memory_format=torch.contiguous_format)
226
+ view_default_2 = CallFunction(aten.view.default, clone_default_1, Ignored())
227
+ bmm_default = CallFunction(aten.bmm.default, view_default_1, view_default_2)
228
+ view_default_3 = CallFunction(aten.view.default, bmm_default, Ignored())
229
+ where_self = CallFunction(aten.where.self, expand_default, full_default, view_default_3)
230
+ convert_element_type_default = CallFunction(prims.convert_element_type.default, where_self, Ignored(), _users=2)
231
+ amax_default = CallFunction(aten.amax.default, convert_element_type_default, Ignored(), True)
232
+ sub_Tensor = CallFunction(aten.sub.Tensor, convert_element_type_default, amax_default)
233
+ exp_default = CallFunction(aten.exp.default, sub_Tensor, _users=2)
234
+ sum_dim_IntList = CallFunction(aten.sum.dim_IntList, exp_default, Ignored(), True)
235
+ div_Tensor_1 = CallFunction(aten.div.Tensor, exp_default, sum_dim_IntList)
236
+ convert_element_type_default_1 = CallFunction(prims.convert_element_type.default, div_Tensor_1, Ignored())
237
+ expand_default_3 = CallFunction(aten.expand.default, convert_element_type_default_1, Ignored())
238
+ view_default_4 = CallFunction(aten.view.default, expand_default_3, Ignored())
239
+ permute_default_3 = CallFunction(aten.permute.default, KeywordArg('value'), Ignored())
240
+ expand_default_4 = CallFunction(aten.expand.default, permute_default_3, Ignored())
241
+ clone_default_2 = CallFunction(aten.clone.default, expand_default_4, memory_format=torch.contiguous_format)
242
+ view_default_5 = CallFunction(aten.view.default, clone_default_2, Ignored())
243
+ bmm_default_1 = CallFunction(aten.bmm.default, view_default_4, view_default_5)
244
+ _sfdp_pattern_20_half_inference = CallFunction(aten.view.default, bmm_default_1, Ignored(), _users=0)